blob: ed80dd8fca21ccc06533ce3de41fec6a453602ef [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"
Jordan Rose1e879d82018-03-23 00:07:18 +000030#include "clang/AST/PrettyDeclStackTrace.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000031#include "clang/AST/PrettyPrinter.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000032#include "clang/AST/Redeclarable.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000033#include "clang/AST/Stmt.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000034#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000036#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000037#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000038#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000039#include "clang/Basic/LLVM.h"
40#include "clang/Basic/LangOptions.h"
41#include "clang/Basic/Linkage.h"
Douglas Gregorba345522011-12-02 23:23:56 +000042#include "clang/Basic/Module.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000043#include "clang/Basic/PartialDiagnostic.h"
44#include "clang/Basic/SanitizerBlacklist.h"
45#include "clang/Basic/Sanitizers.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000048#include "clang/Basic/Specifiers.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000049#include "clang/Basic/TargetCXXABI.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000050#include "clang/Basic/TargetInfo.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000051#include "clang/Basic/Visibility.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000052#include "clang/Frontend/FrontendDiagnostic.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000053#include "llvm/ADT/APSInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/None.h"
56#include "llvm/ADT/Optional.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/StringSwitch.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Triple.h"
62#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000063#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000064#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000065#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000066#include <cassert>
67#include <cstddef>
68#include <cstring>
69#include <memory>
70#include <string>
71#include <tuple>
72#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000073
Chris Lattner6d9a6852006-10-25 05:11:20 +000074using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000075
Richard Smith0b87e072013-10-07 08:02:11 +000076Decl *clang::getPrimaryMergedDecl(Decl *D) {
77 return D->getASTContext().getPrimaryMergedDecl(D);
78}
79
Jordan Rose1e879d82018-03-23 00:07:18 +000080void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81 SourceLocation Loc = this->Loc;
82 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83 if (Loc.isValid()) {
84 Loc.print(OS, Context.getSourceManager());
85 OS << ": ";
86 }
87 OS << Message;
88
89 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
90 OS << " '";
91 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92 OS << "'";
93 }
94
95 OS << '\n';
96}
97
Richard Smith73b21d82014-09-03 02:33:22 +000098// Defined here so that it can be inlined into its direct callers.
99bool Decl::isOutOfLine() const {
100 return !getLexicalDeclContext()->Equals(getDeclContext());
101}
102
Richard Smith42413142015-05-15 20:05:43 +0000103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +0000105 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +0000106
Chris Lattner88f70d62008-03-15 05:43:15 +0000107//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000108// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000109//===----------------------------------------------------------------------===//
110
John McCalldf25c432013-02-16 00:17:33 +0000111// Visibility rules aren't rigorously externally specified, but here
112// are the basic principles behind what we implement:
113//
114// 1. An explicit visibility attribute is generally a direct expression
115// of the user's intent and should be honored. Only the innermost
116// visibility attribute applies. If no visibility attribute applies,
117// global visibility settings are considered.
118//
119// 2. There is one caveat to the above: on or in a template pattern,
120// an explicit visibility attribute is just a default rule, and
121// visibility can be decreased by the visibility of template
122// arguments. But this, too, has an exception: an attribute on an
123// explicit specialization or instantiation causes all the visibility
124// restrictions of the template arguments to be ignored.
125//
126// 3. A variable that does not otherwise have explicit visibility can
127// be restricted by the visibility of its type.
128//
129// 4. A visibility restriction is explicit if it comes from an
130// attribute (or something like it), not a global visibility setting.
131// When emitting a reference to an external symbol, visibility
132// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000133//
134// 5. When computing the visibility of a non-type, including a
135// non-type member of a class, only non-type visibility restrictions
136// are considered: the 'visibility' attribute, global value-visibility
137// settings, and a few special cases like __private_extern.
138//
139// 6. When computing the visibility of a type, including a type member
140// of a class, only type visibility restrictions are considered:
141// the 'type_visibility' attribute and global type-visibility settings.
142// However, a 'visibility' attribute counts as a 'type_visibility'
143// attribute on any declaration that only has the former.
144//
145// The visibility of a "secondary" entity, like a template argument,
146// is computed using the kind of that entity, not the kind of the
147// primary entity for which we are computing visibility. For example,
148// the visibility of a specialization of either of these templates:
149// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150// template <class T, bool (&compare)(T, X)> class matcher;
151// is restricted according to the type visibility of the argument 'T',
152// the type visibility of 'bool(&)(T,X)', and the value visibility of
153// the argument function 'compare'. That 'has_match' is a value
154// and 'matcher' is a type only matters when looking for attributes
155// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000156
John McCalld041a9b2013-02-20 01:54:26 +0000157/// Does this computation kind permit us to consider additional
158/// visibility settings from attributes and the like?
159static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000160 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000161}
162
163/// Given an LVComputationKind, return one of the same type/value sort
164/// that records that it already has explicit visibility.
165static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000166withExplicitVisibilityAlready(LVComputationKind Kind) {
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000169}
170
David Blaikie05785d12013-02-20 22:23:23 +0000171static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000173 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000174 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000175 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000176}
177
John McCalldf25c432013-02-16 00:17:33 +0000178/// Is the given declaration a "type" or a "value" for the purposes of
179/// visibility computation?
180static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000181 return isa<TypeDecl>(D) ||
182 isa<ClassTemplateDecl>(D) ||
183 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000184}
185
John McCall5f46c482013-02-21 23:42:58 +0000186/// Does the given declaration have member specialization information,
187/// and if so, is it an explicit specialization?
188template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000189std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000190isExplicitMemberSpecialization(const T *D) {
191 if (const MemberSpecializationInfo *member =
192 D->getMemberSpecializationInfo()) {
193 return member->isExplicitSpecialization();
194 }
195 return false;
196}
197
198/// For templates, this question is easier: a member template can't be
199/// explicitly instantiated, so there's a single bit indicating whether
200/// or not this is an explicit member specialization.
201static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202 return D->isMemberSpecialization();
203}
204
John McCalld041a9b2013-02-20 01:54:26 +0000205/// Given a visibility attribute, return the explicit visibility
206/// associated with it.
207template <class T>
208static Visibility getVisibilityFromAttr(const T *attr) {
209 switch (attr->getVisibility()) {
210 case T::Default:
211 return DefaultVisibility;
212 case T::Hidden:
213 return HiddenVisibility;
214 case T::Protected:
215 return ProtectedVisibility;
216 }
217 llvm_unreachable("bad visibility kind");
218}
219
John McCalldf25c432013-02-16 00:17:33 +0000220/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000221static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000222 NamedDecl::ExplicitVisibilityKind kind) {
223 // If we're ultimately computing the visibility of a type, look for
224 // a 'type_visibility' attribute before looking for 'visibility'.
225 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000226 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000227 return getVisibilityFromAttr(A);
228 }
229 }
230
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000231 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000232 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000233 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000234 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000235
David Blaikie7a30dc52013-02-21 01:47:18 +0000236 return None;
John McCall457a04e2010-10-22 21:05:15 +0000237}
238
George Burgess IV99db3ea2017-08-09 04:02:49 +0000239LinkageInfo LinkageComputer::getLVForType(const Type &T,
240 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000241 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000242 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000243 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000244}
245
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000246/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000247/// template parameter list. For visibility purposes, template
248/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000249LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000251 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000252 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000253 // Template type parameters are the most common and never
254 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000255 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000256 continue;
257
258 // Non-type template parameters can be restricted by the value type, e.g.
259 // template <enum X> class A { ... };
260 // We have to be careful here, though, because we can be dealing with
261 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000262 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000263 // Handle the non-pack case first.
264 if (!NTTP->isExpandedParameterPack()) {
265 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000266 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000267 }
268 continue;
269 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000270
John McCalldf25c432013-02-16 00:17:33 +0000271 // Look at all the types in an expanded pack.
272 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273 QualType type = NTTP->getExpansionType(i);
274 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000275 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276 }
John McCalldf25c432013-02-16 00:17:33 +0000277 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000278 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279
John McCalldf25c432013-02-16 00:17:33 +0000280 // Template template parameters can be restricted by their
281 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000282 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000283
284 // Handle the non-pack case first.
285 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000286 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287 computation));
John McCalldf25c432013-02-16 00:17:33 +0000288 continue;
289 }
290
291 // Look at all expansions in an expanded pack.
292 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293 i != n; ++i) {
294 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000295 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000296 }
297 }
298
John McCall457a04e2010-10-22 21:05:15 +0000299 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300}
301
Eli Friedman7e346a82013-07-01 20:22:57 +0000302static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000303 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000304 const DeclContext *DC = D->getDeclContext();
305 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000306 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000308 DC = DC->getParent();
309 }
310 return Ret;
311}
312
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313/// \brief Get the most restrictive linkage for the types and
314/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000315///
316/// Note that we don't take an LVComputationKind because we always
317/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000318LinkageInfo
319LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000321 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000322
David Majnemerc7b85c42014-04-23 05:16:48 +0000323 for (const TemplateArgument &Arg : Args) {
324 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 case TemplateArgument::Null:
326 case TemplateArgument::Integral:
327 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000328 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000329
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000331 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000332 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000333
George Burgess IV00f70bd2018-03-01 05:43:23 +0000334 case TemplateArgument::Declaration: {
335 const NamedDecl *ND = Arg.getAsDecl();
336 assert(!usesTypeVisibility(ND));
337 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
George Burgess IV00f70bd2018-03-01 05:43:23 +0000339 }
Eli Friedmanb826a002012-09-26 02:36:12 +0000340
341 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000342 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000343 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000344
345 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000346 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000347 if (TemplateDecl *Template =
348 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000349 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000350 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351
352 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000353 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000354 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000355 }
John McCalldf25c432013-02-16 00:17:33 +0000356 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000357 }
358
John McCall457a04e2010-10-22 21:05:15 +0000359 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000360}
361
George Burgess IV99db3ea2017-08-09 04:02:49 +0000362LinkageInfo
363LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000365 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000366}
367
John McCall5f46c482013-02-21 23:42:58 +0000368static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
369 const FunctionTemplateSpecializationInfo *specInfo) {
370 // Include visibility from the template parameters and arguments
371 // only if this is not an explicit instantiation or specialization
372 // with direct explicit visibility. (Implicit instantiations won't
373 // have a direct attribute.)
374 if (!specInfo->isExplicitInstantiationOrSpecialization())
375 return true;
376
377 return !fn->hasAttr<VisibilityAttr>();
378}
379
John McCalldf25c432013-02-16 00:17:33 +0000380/// Merge in template-related linkage and visibility for the given
381/// function template specialization.
382///
383/// We don't need a computation kind here because we can assume
384/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000385///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000386/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000387void LinkageComputer::mergeTemplateLV(
388 LinkageInfo &LV, const FunctionDecl *fn,
389 const FunctionTemplateSpecializationInfo *specInfo,
390 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000391 bool considerVisibility =
392 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000393
394 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000395 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000396 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000397 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000398 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
399
400 // Merge information from the template arguments.
401 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000402 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000403 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000404}
405
John McCall5f46c482013-02-21 23:42:58 +0000406/// Does the given declaration have a direct visibility attribute
407/// that would match the given rules?
408static bool hasDirectVisibilityAttribute(const NamedDecl *D,
409 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000410 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000411 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000412
413 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
414 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000415}
416
John McCalld041a9b2013-02-20 01:54:26 +0000417/// Should we consider visibility associated with the template
418/// arguments and parameters of the given class template specialization?
419static bool shouldConsiderTemplateVisibility(
420 const ClassTemplateSpecializationDecl *spec,
421 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000422 // Include visibility from the template parameters and arguments
423 // only if this is not an explicit instantiation or specialization
424 // with direct explicit visibility (and note that implicit
425 // instantiations won't have a direct attribute).
426 //
427 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000428 // for an explicit specialization when computing the visibility of a
429 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000430 //
431 // This is a bit complex; let's unpack it.
432 //
433 // An explicit class specialization is an independent, top-level
434 // declaration. As such, if it or any of its members has an
435 // explicit visibility attribute, that must directly express the
436 // user's intent, and we should honor it. The same logic applies to
437 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000438
439 // Fast path: if this is not an explicit instantiation or
440 // specialization, we always want to consider template-related
441 // visibility restrictions.
442 if (!spec->isExplicitInstantiationOrSpecialization())
443 return true;
444
445 // This is the 'member thereof' check.
446 if (spec->isExplicitSpecialization() &&
447 hasExplicitVisibilityAlready(computation))
448 return false;
449
John McCall5f46c482013-02-21 23:42:58 +0000450 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000451}
452
453/// Merge in template-related linkage and visibility for the given
454/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000455void LinkageComputer::mergeTemplateLV(
456 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
457 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000458 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000459
460 // Merge information from the template parameters, but ignore
461 // visibility if we're only considering template arguments.
462
John McCalld041a9b2013-02-20 01:54:26 +0000463 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000464 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000465 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000466 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000467 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000468
469 // Merge information from the template arguments. We ignore
470 // template-argument visibility if we've got an explicit
471 // instantiation with a visibility attribute.
472 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000473 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000474 if (considerVisibility)
475 LV.mergeVisibility(argsLV);
476 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000477}
478
Larisse Voufo5899e192014-07-02 23:08:34 +0000479/// Should we consider visibility associated with the template
480/// arguments and parameters of the given variable template
481/// specialization? As usual, follow class template specialization
482/// logic up to initialization.
483static bool shouldConsiderTemplateVisibility(
484 const VarTemplateSpecializationDecl *spec,
485 LVComputationKind computation) {
486 // Include visibility from the template parameters and arguments
487 // only if this is not an explicit instantiation or specialization
488 // with direct explicit visibility (and note that implicit
489 // instantiations won't have a direct attribute).
490 if (!spec->isExplicitInstantiationOrSpecialization())
491 return true;
492
493 // An explicit variable specialization is an independent, top-level
494 // declaration. As such, if it has an explicit visibility attribute,
495 // that must directly express the user's intent, and we should honor
496 // it.
497 if (spec->isExplicitSpecialization() &&
498 hasExplicitVisibilityAlready(computation))
499 return false;
500
501 return !hasDirectVisibilityAttribute(spec, computation);
502}
503
504/// Merge in template-related linkage and visibility for the given
505/// variable template specialization. As usual, follow class template
506/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000507void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
508 const VarTemplateSpecializationDecl *spec,
509 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000510 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511
512 // Merge information from the template parameters, but ignore
513 // visibility if we're only considering template arguments.
514
515 VarTemplateDecl *temp = spec->getSpecializedTemplate();
516 LinkageInfo tempLV =
517 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518 LV.mergeMaybeWithVisibility(tempLV,
519 considerVisibility && !hasExplicitVisibilityAlready(computation));
520
521 // Merge information from the template arguments. We ignore
522 // template-argument visibility if we've got an explicit
523 // instantiation with a visibility attribute.
524 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526 if (considerVisibility)
527 LV.mergeVisibility(argsLV);
528 LV.mergeExternalVisibility(argsLV);
529}
530
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000531static bool useInlineVisibilityHidden(const NamedDecl *D) {
532 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000533 const LangOptions &Opts = D->getASTContext().getLangOpts();
534 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000535 return false;
536
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000537 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000538 if (!FD)
539 return false;
540
541 TemplateSpecializationKind TSK = TSK_Undeclared;
542 if (FunctionTemplateSpecializationInfo *spec
543 = FD->getTemplateSpecializationInfo()) {
544 TSK = spec->getTemplateSpecializationKind();
545 } else if (MemberSpecializationInfo *MSI =
546 FD->getMemberSpecializationInfo()) {
547 TSK = MSI->getTemplateSpecializationKind();
548 }
549
Craig Topper36250ad2014-05-12 05:36:57 +0000550 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000551 // InlineVisibilityHidden only applies to definitions, and
552 // isInlined() only gives meaningful answers on definitions
553 // anyway.
554 return TSK != TSK_ExplicitInstantiationDeclaration &&
555 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000556 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557}
558
Rafael Espindola593537a2013-05-05 20:15:21 +0000559template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000560 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000561 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000562}
563
Richard Smith03c05032014-02-17 23:34:47 +0000564static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000565 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000566 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000567 return true;
568 return false;
569}
570
Richard Smith1283e982017-07-07 20:04:28 +0000571static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000572 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000573 switch (D->getModuleOwnershipKind()) {
574 case Decl::ModuleOwnershipKind::Unowned:
575 case Decl::ModuleOwnershipKind::ModulePrivate:
576 return false;
577 case Decl::ModuleOwnershipKind::Visible:
578 case Decl::ModuleOwnershipKind::VisibleWhenImported:
579 if (auto *M = D->getOwningModule())
580 return M->Kind == Module::ModuleInterfaceUnit;
581 }
582 llvm_unreachable("unexpected module ownership kind");
583}
584
585static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
586 // Internal linkage declarations within a module interface unit are modeled
587 // as "module-internal linkage", which means that they have internal linkage
588 // formally but can be indirectly accessed from outside the module via inline
589 // functions and templates defined within the module.
590 if (auto *M = D->getOwningModule())
591 if (M->Kind == Module::ModuleInterfaceUnit)
592 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
593
594 return LinkageInfo::internal();
595}
596
597static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
598 // C++ Modules TS [basic.link]/6.8:
599 // - A name declared at namespace scope that does not have internal linkage
600 // by the previous rules and that is introduced by a non-exported
601 // declaration has module linkage.
602 if (auto *M = D->getOwningModule())
603 if (M->Kind == Module::ModuleInterfaceUnit)
Richard Smithbecb92d2017-10-10 22:33:17 +0000604 if (!isExportedFromModuleIntefaceUnit(
605 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smith1283e982017-07-07 20:04:28 +0000606 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
607
608 return LinkageInfo::external();
609}
610
George Burgess IV99db3ea2017-08-09 04:02:49 +0000611LinkageInfo
612LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000613 LVComputationKind computation,
614 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000615 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000616 "Not a name having namespace scope");
617 ASTContext &Context = D->getASTContext();
618
619 // C++ [basic.link]p3:
620 // A name having namespace scope (3.3.6) has internal linkage if it
621 // is the name of
622 // - an object, reference, function or function template that is
623 // explicitly declared static; or,
624 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000625 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000626 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000627 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000628 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000629
Richard Smith62f19e72016-06-25 00:15:56 +0000630 // - a non-inline, non-volatile object or reference that is explicitly
631 // declared const or constexpr and neither explicitly declared extern
632 // nor previously declared to have external linkage; or (there is no
633 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000634 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000636 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000637 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000638 !Var->isInline() &&
639 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000640 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000641 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000642 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000643
644 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000645 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000646 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000647 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000648 }
649
650 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
651 PrevVar = PrevVar->getPreviousDecl()) {
652 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
653 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000654 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000655 // Explicitly declared static.
656 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000657 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000658 }
Alp Tokera2794f92014-01-22 07:29:52 +0000659 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000660 // C++ [temp]p4:
661 // A non-member function template can have internal linkage; any
662 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000663
664 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000665 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000666 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000667 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
668 // - a data member of an anonymous union.
669 const VarDecl *VD = IFD->getVarDecl();
670 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000671 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000672 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000673 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000674
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000675 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000676 const auto *Var = dyn_cast<VarDecl>(D);
677 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000678 // FIXME: The check for extern "C" here is not justified by the standard
679 // wording, but we retain it from the pre-DR1113 model to avoid breaking
680 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000681 //
682 // C++11 [basic.link]p4:
683 // An unnamed namespace or a namespace declared directly or indirectly
684 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000685 if ((!Var || !isFirstInExternCContext(Var)) &&
686 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000687 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000688 }
John McCallb7139c42010-10-28 04:18:25 +0000689
John McCall457a04e2010-10-22 21:05:15 +0000690 // Set up the defaults.
691
692 // C99 6.2.2p5:
693 // If the declaration of an identifier for an object has file
694 // scope and no storage-class specifier, its linkage is
695 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000696 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000697
John McCalld041a9b2013-02-20 01:54:26 +0000698 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000699 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000700 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000701 } else {
702 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000703 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000704 for (const DeclContext *DC = D->getDeclContext();
705 !isa<TranslationUnitDecl>(DC);
706 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000707 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000708 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000709 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000710 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000711 break;
712 }
713 }
714 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000715
John McCalldf25c432013-02-16 00:17:33 +0000716 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000717 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000718 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000719 Visibility globalVisibility =
720 computation.isValueVisibility()
721 ? Context.getLangOpts().getValueVisibilityMode()
722 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000723 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000724
725 // If we're paying attention to global visibility, apply
726 // -finline-visibility-hidden if this is an inline method.
727 if (useInlineVisibilityHidden(D))
728 LV.mergeVisibility(HiddenVisibility, true);
729 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000730 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000731
Douglas Gregorf73b2822009-11-25 22:24:25 +0000732 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000733
Douglas Gregorf73b2822009-11-25 22:24:25 +0000734 // A name having namespace scope has external linkage if it is the
735 // name of
736 //
737 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000738 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000739 // GCC applies the following optimization to variables and static
740 // data members, but not to functions:
741 //
John McCall457a04e2010-10-22 21:05:15 +0000742 // Modify the variable's LV by the LV of its type unless this is
743 // C or extern "C". This follows from [basic.link]p9:
744 // A type without linkage shall not be used as the type of a
745 // variable or function with external linkage unless
746 // - the entity has C language linkage, or
747 // - the entity is declared within an unnamed namespace, or
748 // - the entity is not used or is defined in the same
749 // translation unit.
750 // and [basic.link]p10:
751 // ...the types specified by all declarations referring to a
752 // given variable or function shall be identical...
753 // C does not have an equivalent rule.
754 //
John McCall5fe84122010-10-26 04:59:26 +0000755 // Ignore this if we've got an explicit attribute; the user
756 // probably knows what they're doing.
757 //
John McCall457a04e2010-10-22 21:05:15 +0000758 // Note that we don't want to make the variable non-external
759 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000760 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
761 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000762 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000763 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000764 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000765 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000766 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000767 }
768
John McCall23032652010-11-02 18:38:13 +0000769 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000770 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000771
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000772 // Note that Sema::MergeVarDecl already takes care of implementing
773 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
774 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000775
Larisse Voufo5899e192014-07-02 23:08:34 +0000776 // As per function and class template specializations (below),
777 // consider LV for the template and template arguments. We're at file
778 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000779 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000780 mergeTemplateLV(LV, spec, computation);
781 }
782
Douglas Gregorf73b2822009-11-25 22:24:25 +0000783 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000784 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000785 // In theory, we can modify the function's LV by the LV of its
786 // type unless it has C linkage (see comment above about variables
787 // for justification). In practice, GCC doesn't do this, so it's
788 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000789
John McCall23032652010-11-02 18:38:13 +0000790 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000791 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000792
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000793 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
794 // merging storage classes and visibility attributes, so we don't have to
795 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000796
John McCallf768aa72011-02-10 06:50:24 +0000797 // In C++, then if the type of the function uses a type with
798 // unique-external linkage, it's not legally usable from outside
799 // this translation unit. However, we should use the C linkage
800 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000801 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000802 // Only look at the type-as-written. Otherwise, deducing the return type
803 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000804 QualType TypeAsWritten = Function->getType();
805 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
806 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000807 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000808 return LinkageInfo::uniqueExternal();
809 }
John McCallf768aa72011-02-10 06:50:24 +0000810
John McCall5f46c482013-02-21 23:42:58 +0000811 // Consider LV from the template and the template arguments.
812 // We're at file scope, so we do not need to worry about nested
813 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000814 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000815 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000816 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000817 }
818
Douglas Gregorf73b2822009-11-25 22:24:25 +0000819 // - a named class (Clause 9), or an unnamed class defined in a
820 // typedef declaration in which the class has the typedef name
821 // for linkage purposes (7.1.3); or
822 // - a named enumeration (7.2), or an unnamed enumeration
823 // defined in a typedef declaration in which the enumeration
824 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000825 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000826 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000827 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000828 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000829
John McCall457a04e2010-10-22 21:05:15 +0000830 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000831 // linkage of the template and template arguments. We're at file
832 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000833 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000834 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000835 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000836
837 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000838 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000839 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000840 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000841 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000842 return LinkageInfo::none();
843 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000844
845 // - a template, unless it is a function template that has
846 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000847 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000848 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000849 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000850 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000851 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
852
Douglas Gregorf73b2822009-11-25 22:24:25 +0000853 // - a namespace (7.3), unless it is declared within an unnamed
854 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000855 //
856 // We handled names in anonymous namespaces above.
857 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000858 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000859
John McCall457a04e2010-10-22 21:05:15 +0000860 // By extension, we assign external linkage to Objective-C
861 // interfaces.
862 } else if (isa<ObjCInterfaceDecl>(D)) {
863 // fallout
864
Richard Smith97135cc2015-11-12 22:19:45 +0000865 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
866 // A typedef declaration has linkage if it gives a type a name for
867 // linkage purposes.
868 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
869 return LinkageInfo::none();
870
John McCall457a04e2010-10-22 21:05:15 +0000871 // Everything not covered here has no linkage.
872 } else {
John McCallc273f242010-10-30 11:50:40 +0000873 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000874 }
875
Richard Smithc445d5d2017-10-03 01:58:15 +0000876 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000877 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000878 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000879 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000880
John McCall457a04e2010-10-22 21:05:15 +0000881 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000882}
883
George Burgess IV99db3ea2017-08-09 04:02:49 +0000884LinkageInfo
885LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000886 LVComputationKind computation,
887 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000888 // Only certain class members have linkage. Note that fields don't
889 // really have linkage, but it's convenient to say they do for the
890 // purposes of calculating linkage of pointer-to-data-member
891 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000892 //
893 // Templates also don't officially have linkage, but since we ignore
894 // the C++ standard and look at template arguments when determining
895 // linkage and visibility of a template specialization, we might hit
896 // a template template argument that way. If we do, we need to
897 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000898 if (!(isa<CXXMethodDecl>(D) ||
899 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000900 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000901 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000902 isa<TagDecl>(D) ||
903 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000904 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000905
John McCall07072662010-11-02 01:45:15 +0000906 LinkageInfo LV;
907
John McCall07072662010-11-02 01:45:15 +0000908 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000909 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000910 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000911 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000912 // If we're paying attention to global visibility, apply
913 // -finline-visibility-hidden if this is an inline method.
914 //
915 // Note that we do this before merging information about
916 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000917 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000918 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000919 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000920
921 // If this class member has an explicit visibility attribute, the only
922 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000923 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000924 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000925 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000926 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000927
John McCall5f46c482013-02-21 23:42:58 +0000928 LinkageInfo classLV =
929 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000930 // The member has the same linkage as the class. If that's not externally
931 // visible, we don't need to compute anything about the linkage.
932 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000933 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000934 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000935
936
John McCall5f46c482013-02-21 23:42:58 +0000937 // Otherwise, don't merge in classLV yet, because in certain cases
938 // we need to completely ignore the visibility from it.
939
940 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000941 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000942
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000943 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000944 // Only look at the type-as-written. Otherwise, deducing the return type
945 // of a function could change its linkage.
946 QualType TypeAsWritten = MD->getType();
947 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
948 TypeAsWritten = TSI->getType();
949 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
950 return LinkageInfo::uniqueExternal();
951
John McCall457a04e2010-10-22 21:05:15 +0000952 // If this is a method template specialization, use the linkage for
953 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000954 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000955 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000956 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000957 if (spec->isExplicitSpecialization()) {
958 explicitSpecSuppressor = MD;
959 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
960 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
961 }
962 } else if (isExplicitMemberSpecialization(MD)) {
963 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000964 }
John McCall457a04e2010-10-22 21:05:15 +0000965
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000966 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
967 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000968 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000969 if (spec->isExplicitSpecialization()) {
970 explicitSpecSuppressor = spec;
971 } else {
972 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
973 if (isExplicitMemberSpecialization(temp)) {
974 explicitSpecSuppressor = temp->getTemplatedDecl();
975 }
976 }
977 } else if (isExplicitMemberSpecialization(RD)) {
978 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000979 }
980
John McCall37bb6c92010-10-29 22:22:43 +0000981 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000982 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
983 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000984 mergeTemplateLV(LV, spec, computation);
985
John McCall36cd5cc2010-10-30 09:18:49 +0000986 // Modify the variable's linkage by its type, but ignore the
987 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +0000988 if (!IgnoreVarTypeLinkage) {
989 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
990 // FIXME: If the type's linkage is not externally visible, we can
991 // give this static data member UniqueExternalLinkage.
992 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
993 LV.mergeVisibility(typeLV);
994 LV.mergeExternalVisibility(typeLV);
995 }
John McCall5f46c482013-02-21 23:42:58 +0000996
997 if (isExplicitMemberSpecialization(VD)) {
998 explicitSpecSuppressor = VD;
999 }
John McCalldf25c432013-02-16 00:17:33 +00001000
1001 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001002 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001003 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +00001004 (!LV.isVisibilityExplicit() &&
1005 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +00001006 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +00001007 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001008 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +00001009 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +00001010
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001011 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +00001012 if (isExplicitMemberSpecialization(redeclTemp)) {
1013 explicitSpecSuppressor = temp->getTemplatedDecl();
1014 }
1015 }
John McCall37bb6c92010-10-29 22:22:43 +00001016 }
1017
John McCall5f46c482013-02-21 23:42:58 +00001018 // We should never be looking for an attribute directly on a template.
1019 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1020
1021 // If this member is an explicit member specialization, and it has
1022 // an explicit attribute, ignore visibility from the parent.
1023 bool considerClassVisibility = true;
1024 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001025 // optimization: hasDVA() is true only with explicit visibility.
1026 LV.isVisibilityExplicit() &&
1027 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001028 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1029 considerClassVisibility = false;
1030 }
1031
1032 // Finally, merge in information from the class.
1033 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001034 return LV;
John McCall8823c652010-08-13 08:35:10 +00001035}
1036
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001037void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001038
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001039bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001040 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001041 return true;
John McCalld396b972011-02-08 19:01:05 +00001042
Richard Smithfbe7b462017-09-22 02:22:32 +00001043 Linkage L = LinkageComputer{}
1044 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1045 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001046 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001047}
1048
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001049ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1050 StringRef name = getName();
1051 if (name.empty()) return SFF_None;
1052
1053 if (name.front() == 'C')
1054 if (name == "CFStringCreateWithFormat" ||
1055 name == "CFStringCreateWithFormatAndArguments" ||
1056 name == "CFStringAppendFormat" ||
1057 name == "CFStringAppendFormatAndArguments")
1058 return SFF_CFString;
1059 return SFF_None;
1060}
1061
Rafael Espindola3ae00052013-05-13 00:12:11 +00001062Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001063 // We don't care about visibility here, so ask for the cheapest
1064 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001065 return LinkageComputer{}
1066 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1067 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001068}
1069
John McCallc273f242010-10-30 11:50:40 +00001070LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001071 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001072}
Ted Kremenek926d8602010-04-20 23:15:35 +00001073
Rafael Espindola9ad61122013-11-26 16:09:08 +00001074static Optional<Visibility>
1075getExplicitVisibilityAux(const NamedDecl *ND,
1076 NamedDecl::ExplicitVisibilityKind kind,
1077 bool IsMostRecent) {
1078 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1079
Rafael Espindola3a52c442013-02-26 19:33:14 +00001080 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001081 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001082 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001083
Rafael Espindola3a52c442013-02-26 19:33:14 +00001084 // If this is a member class of a specialization of a class template
1085 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001086 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001087 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1088 if (InstantiatedFrom)
1089 return getVisibilityOf(InstantiatedFrom, kind);
1090 }
1091
1092 // If there wasn't explicit visibility there, and this is a
1093 // specialization of a class template, check for visibility
1094 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001095 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001096 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1097 kind);
1098
1099 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001100 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001101 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1102 if (MostRecent != ND)
1103 return getExplicitVisibilityAux(MostRecent, kind, true);
1104 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001105
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001106 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001107 if (Var->isStaticDataMember()) {
1108 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1109 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001110 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001111 }
1112
David Majnemer35b02bc2014-04-29 07:32:26 +00001113 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1114 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1115 kind);
1116
David Blaikie7a30dc52013-02-21 01:47:18 +00001117 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001118 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001119 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001120 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001121 // If the function is a specialization of a template with an
1122 // explicit visibility attribute, use that.
1123 if (FunctionTemplateSpecializationInfo *templateInfo
1124 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001125 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1126 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001127
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001128 // If the function is a member of a specialization of a class template
1129 // and the corresponding decl has explicit visibility, use that.
1130 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1131 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001132 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001133
David Blaikie7a30dc52013-02-21 01:47:18 +00001134 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001135 }
1136
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001137 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001138 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001139 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001140
David Blaikie7a30dc52013-02-21 01:47:18 +00001141 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001142}
1143
Rafael Espindola9ad61122013-11-26 16:09:08 +00001144Optional<Visibility>
1145NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1146 return getExplicitVisibilityAux(this, kind, false);
1147}
1148
George Burgess IV99db3ea2017-08-09 04:02:49 +00001149LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1150 Decl *ContextDecl,
1151 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001152 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001153 const NamedDecl *Owner;
1154 if (!ContextDecl)
1155 Owner = dyn_cast<NamedDecl>(DC);
1156 else if (isa<ParmVarDecl>(ContextDecl))
1157 Owner =
1158 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1159 else
1160 Owner = cast<NamedDecl>(ContextDecl);
1161
Richard Smithc95d2c52017-09-22 04:25:05 +00001162 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001163 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001164
1165 // If the owner has a deduced type, we need to skip querying the linkage and
1166 // visibility of that type, because it might involve this closure type. The
1167 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1168 // than NoLinkage when we don't strictly need to, which is benign.
1169 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001170 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001171 VD && VD->getType()->getContainedDeducedType()
1172 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1173 : getLVForDecl(Owner, computation);
1174
Richard Smith7ff83042017-09-22 04:33:20 +00001175 // A lambda never formally has linkage. But if the owner is externally
1176 // visible, then the lambda is too. We apply the same rules to blocks.
1177 if (!isExternallyVisible(OwnerLV.getLinkage()))
1178 return LinkageInfo::none();
1179 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1180 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001181}
1182
George Burgess IV99db3ea2017-08-09 04:02:49 +00001183LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1184 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001185 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001186 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001187 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001188 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001189
1190 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001191 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001192 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001193
1194 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001195 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001196 if (Optional<Visibility> Vis =
1197 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001198 LV.mergeVisibility(*Vis, true);
1199 }
1200
1201 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1202 // merging storage classes and visibility attributes, so we don't have to
1203 // look at previous decls in here.
1204
1205 return LV;
1206 }
1207
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001208 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001209 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001210 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001211 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001212
John McCalldf25c432013-02-16 00:17:33 +00001213 LinkageInfo LV;
1214 if (Var->getStorageClass() == SC_PrivateExtern)
1215 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001216 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001217 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001218 LV.mergeVisibility(*Vis, true);
1219 }
1220
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001221 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1222 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1223 if (PrevLV.getLinkage())
1224 LV.setLinkage(PrevLV.getLinkage());
1225 LV.mergeVisibility(PrevLV);
1226 }
1227
John McCalldf25c432013-02-16 00:17:33 +00001228 return LV;
1229 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001230
1231 if (!Var->isStaticLocal())
1232 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001233 }
1234
Rafael Espindolaa4184182013-06-17 20:04:51 +00001235 ASTContext &Context = D->getASTContext();
1236 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001237 return LinkageInfo::none();
1238
Eli Friedman7e346a82013-07-01 20:22:57 +00001239 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001240 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001241 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001242
Eli Friedman7e346a82013-07-01 20:22:57 +00001243 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001244 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001245 if (!BD->getBlockManglingNumber())
1246 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001247
Eli Friedman7e346a82013-07-01 20:22:57 +00001248 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1249 BD->getBlockManglingContextDecl(), computation);
1250 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001251 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001252 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001253 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001254 return LinkageInfo::none();
1255
1256 LV = getLVForDecl(FD, computation);
1257 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001258 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001259 return LinkageInfo::none();
1260 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1261 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001262}
1263
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001264static inline const CXXRecordDecl*
1265getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1266 const CXXRecordDecl *Ret = Record;
1267 while (Record && Record->isLambda()) {
1268 Ret = Record;
1269 if (!Record->getParent()) break;
1270 // Get the Containing Class of this Lambda Class
1271 Record = dyn_cast_or_null<CXXRecordDecl>(
1272 Record->getParent()->getParent());
1273 }
1274 return Ret;
1275}
1276
George Burgess IV99db3ea2017-08-09 04:02:49 +00001277LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001278 LVComputationKind computation,
1279 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001280 // Internal_linkage attribute overrides other considerations.
1281 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001282 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001283
Ted Kremenek926d8602010-04-20 23:15:35 +00001284 // Objective-C: treat all Objective-C declarations as having external
1285 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001286 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001287 default:
1288 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001289
1290 // Per C++ [basic.link]p2, only the names of objects, references,
1291 // functions, types, templates, namespaces, and values ever have linkage.
1292 //
1293 // Note that the name of a typedef, namespace alias, using declaration,
1294 // and so on are not the name of the corresponding type, namespace, or
1295 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001296 case Decl::ImplicitParam:
1297 case Decl::Label:
1298 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001299 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001300 case Decl::Using:
1301 case Decl::UsingShadow:
1302 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001303 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001304
Richard Smith26210db2015-11-13 03:52:13 +00001305 case Decl::EnumConstant:
1306 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001307 if (D->getASTContext().getLangOpts().CPlusPlus)
1308 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1309 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001310
Richard Smith97135cc2015-11-12 22:19:45 +00001311 case Decl::Typedef:
1312 case Decl::TypeAlias:
1313 // A typedef declaration has linkage if it gives a type a name for
1314 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001315 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001316 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1317 return LinkageInfo::none();
1318 break;
1319
John McCall457a04e2010-10-22 21:05:15 +00001320 case Decl::TemplateTemplateParm: // count these as external
1321 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001322 case Decl::ObjCAtDefsField:
1323 case Decl::ObjCCategory:
1324 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001325 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001326 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001327 case Decl::ObjCMethod:
1328 case Decl::ObjCProperty:
1329 case Decl::ObjCPropertyImpl:
1330 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001331 return getExternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001332
1333 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001334 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001335 if (Record->isLambda()) {
1336 if (!Record->getLambdaManglingNumber()) {
1337 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001338 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001339 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001340
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001341 // This lambda has its linkage/visibility determined:
1342 // - either by the outermost lambda if that lambda has no mangling
1343 // number.
1344 // - or by the parent of the outer most lambda
1345 // This prevents infinite recursion in settings such as nested lambdas
1346 // used in NSDMI's, for e.g.
1347 // struct L {
1348 // int t{};
1349 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1350 // };
1351 const CXXRecordDecl *OuterMostLambda =
1352 getOutermostEnclosingLambda(Record);
1353 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001354 return getInternalLinkageFor(D);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001355
1356 return getLVForClosure(
1357 OuterMostLambda->getDeclContext()->getRedeclContext(),
1358 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001359 }
1360
1361 break;
1362 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001363 }
1364
Douglas Gregorf73b2822009-11-25 22:24:25 +00001365 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001366 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001367 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001368
1369 // C++ [basic.link]p5:
1370 // In addition, a member function, static data member, a named
1371 // class or enumeration of class scope, or an unnamed class or
1372 // enumeration defined in a class-scope typedef declaration such
1373 // that the class or enumeration has the typedef name for linkage
1374 // purposes (7.1.3), has external linkage if the name of the class
1375 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001376 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001377 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001378
1379 // C++ [basic.link]p6:
1380 // The name of a function declared in block scope and the name of
1381 // an object declared by a block scope extern declaration have
1382 // linkage. If there is a visible declaration of an entity with
1383 // linkage having the same name and type, ignoring entities
1384 // declared outside the innermost enclosing namespace scope, the
1385 // block scope declaration declares that same entity and receives
1386 // the linkage of the previous declaration. If there is more than
1387 // one such matching entity, the program is ill-formed. Otherwise,
1388 // if no matching entity is found, the block scope entity receives
1389 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001390 if (D->getDeclContext()->isFunctionOrMethod())
1391 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001392
1393 // C++ [basic.link]p6:
1394 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001395 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001396}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001397
George Burgess IV99db3ea2017-08-09 04:02:49 +00001398/// getLVForDecl - Get the linkage and visibility for the given declaration.
1399LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1400 LVComputationKind computation) {
1401 // Internal_linkage attribute overrides other considerations.
1402 if (D->hasAttr<InternalLinkageAttr>())
1403 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001404
Richard Smithfbe7b462017-09-22 02:22:32 +00001405 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001406 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001407
George Burgess IV35cb4f82017-08-09 04:12:17 +00001408 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1409 return *LI;
1410
George Burgess IV99db3ea2017-08-09 04:02:49 +00001411 LinkageInfo LV = computeLVForDecl(D, computation);
1412 if (D->hasCachedLinkage())
1413 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001414
George Burgess IV99db3ea2017-08-09 04:02:49 +00001415 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001416 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001417
1418#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001419 // In C (because of gnu inline) and in c++ with microsoft extensions an
1420 // static can follow an extern, so we can have two decls with different
1421 // linkages.
1422 const LangOptions &Opts = D->getASTContext().getLangOpts();
1423 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1424 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001425
George Burgess IV99db3ea2017-08-09 04:02:49 +00001426 // We have just computed the linkage for this decl. By induction we know
1427 // that all other computed linkages match, check that the one we just
1428 // computed also does.
1429 NamedDecl *Old = nullptr;
1430 for (auto I : D->redecls()) {
1431 auto *T = cast<NamedDecl>(I);
1432 if (T == D)
1433 continue;
1434 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1435 Old = T;
1436 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001437 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001438 }
1439 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001440#endif
1441
George Burgess IV99db3ea2017-08-09 04:02:49 +00001442 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001443}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001444
George Burgess IV99db3ea2017-08-09 04:02:49 +00001445LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001446 return getLVForDecl(D,
1447 LVComputationKind(usesTypeVisibility(D)
1448 ? NamedDecl::VisibilityForType
1449 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001450}
1451
Richard Smithbecb92d2017-10-10 22:33:17 +00001452Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001453 Module *M = getOwningModule();
1454 if (!M)
1455 return nullptr;
1456
1457 switch (M->Kind) {
1458 case Module::ModuleMapModule:
1459 // Module map modules have no special linkage semantics.
1460 return nullptr;
1461
1462 case Module::ModuleInterfaceUnit:
1463 return M;
1464
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001465 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001466 // External linkage declarations in the global module have no owning module
1467 // for linkage purposes. But internal linkage declarations in the global
1468 // module fragment of a particular module are owned by that module for
1469 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001470 if (IgnoreLinkage)
1471 return nullptr;
1472 bool InternalLinkage;
1473 if (auto *ND = dyn_cast<NamedDecl>(this))
1474 InternalLinkage = !ND->hasExternalFormalLinkage();
1475 else {
1476 auto *NSD = dyn_cast<NamespaceDecl>(this);
1477 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1478 isInAnonymousNamespace();
1479 }
1480 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001481 }
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001482 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001483
1484 llvm_unreachable("unknown module kind");
1485}
1486
Richard Smith7873de02016-08-11 22:25:46 +00001487void NamedDecl::printName(raw_ostream &os) const {
1488 os << Name;
1489}
1490
Douglas Gregor2ada0482009-02-04 17:27:36 +00001491std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001492 std::string QualName;
1493 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001494 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001495 return OS.str();
1496}
1497
1498void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1499 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1500}
1501
1502void NamedDecl::printQualifiedName(raw_ostream &OS,
1503 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001504 const DeclContext *Ctx = getDeclContext();
1505
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001506 // For ObjC methods, look through categories and use the interface as context.
1507 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1508 if (auto *ID = MD->getClassInterface())
1509 Ctx = ID;
1510
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001511 if (Ctx->isFunctionOrMethod()) {
1512 printName(OS);
1513 return;
1514 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001515
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001516 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001517 ContextsTy Contexts;
1518
Sam McCall34f9d3f2018-02-02 13:34:47 +00001519 // Collect named contexts.
1520 while (Ctx) {
1521 if (isa<NamedDecl>(Ctx))
1522 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001523 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001524 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001525
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001526 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001527 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001528 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001529 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001530 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001531 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001532 if (P.SuppressUnwrittenScope &&
1533 (ND->isAnonymousNamespace() || ND->isInline()))
1534 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001535 if (ND->isAnonymousNamespace()) {
1536 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1537 : "(anonymous namespace)");
1538 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001539 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001540 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001541 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001542 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001543 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001544 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001545 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001546 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001547 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001548 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001549 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001550
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001551 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001552 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001553 unsigned NumParams = FD->getNumParams();
1554 for (unsigned i = 0; i < NumParams; ++i) {
1555 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001556 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001557 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001558 }
1559
1560 if (FT->isVariadic()) {
1561 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001562 OS << ", ";
1563 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001564 }
1565 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001566 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001567 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001568 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1569 // enumerator is declared in the scope that immediately contains
1570 // the enum-specifier. Each scoped enumerator is declared in the
1571 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001572 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001573 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001574 // is global.
1575 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001576 OS << *ED;
1577 else
1578 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001579 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001580 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001581 }
1582 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001583 }
1584
Richard Smith7873de02016-08-11 22:25:46 +00001585 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001586 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001587 else
David Blaikieabe1a392014-04-02 05:58:29 +00001588 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001589}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001590
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001591void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1592 const PrintingPolicy &Policy,
1593 bool Qualified) const {
1594 if (Qualified)
1595 printQualifiedName(OS, Policy);
1596 else
1597 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001598}
1599
Richard Smithe8292b12015-02-10 03:28:10 +00001600template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1601 return true;
1602}
1603static bool isRedeclarableImpl(...) { return false; }
1604static bool isRedeclarable(Decl::Kind K) {
1605 switch (K) {
1606#define DECL(Type, Base) \
1607 case Decl::Type: \
1608 return isRedeclarableImpl((Type##Decl *)nullptr);
1609#define ABSTRACT_DECL(DECL)
1610#include "clang/AST/DeclNodes.inc"
1611 }
1612 llvm_unreachable("unknown decl kind");
1613}
1614
1615bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001616 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1617
Richard Smithfe620d22015-03-05 23:24:12 +00001618 // Never replace one imported declaration with another; we need both results
1619 // when re-exporting.
1620 if (OldD->isFromASTFile() && isFromASTFile())
1621 return false;
1622
Richard Smith5cd86f82015-11-03 03:13:11 +00001623 // A kind mismatch implies that the declaration is not replaced.
1624 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001625 return false;
1626
Richard Smith5cd86f82015-11-03 03:13:11 +00001627 // For method declarations, we never replace. (Why?)
1628 if (isa<ObjCMethodDecl>(this))
1629 return false;
1630
1631 // For parameters, pick the newer one. This is either an error or (in
1632 // Objective-C) permitted as an extension.
1633 if (isa<ParmVarDecl>(this))
1634 return true;
1635
Richard Smithe8292b12015-02-10 03:28:10 +00001636 // Inline namespaces can give us two declarations with the same
1637 // name and kind in the same scope but different contexts; we should
1638 // keep both declarations in this case.
1639 if (!this->getDeclContext()->getRedeclContext()->Equals(
1640 OldD->getDeclContext()->getRedeclContext()))
1641 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001642
Richard Smith5cd86f82015-11-03 03:13:11 +00001643 // Using declarations can be replaced if they import the same name from the
1644 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001645 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001646 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001647 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001648 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001649 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001650 }
Richard Smithe8292b12015-02-10 03:28:10 +00001651 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001652 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001653 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001654 Context.getCanonicalNestedNameSpecifier(
1655 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1656 }
1657
Richard Smith5cd86f82015-11-03 03:13:11 +00001658 if (isRedeclarable(getKind())) {
1659 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1660 return false;
1661
1662 if (IsKnownNewer)
1663 return true;
1664
Richard Smithe8292b12015-02-10 03:28:10 +00001665 // Check whether this is actually newer than OldD. We want to keep the
1666 // newer declaration. This loop will usually only iterate once, because
1667 // OldD is usually the previous declaration.
1668 for (auto D : redecls()) {
1669 if (D == OldD)
1670 break;
1671
1672 // If we reach the canonical declaration, then OldD is not actually older
1673 // than this one.
1674 //
1675 // FIXME: In this case, we should not add this decl to the lookup table.
1676 if (D->isCanonicalDecl())
1677 return false;
1678 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001679
1680 // It's a newer declaration of the same kind of declaration in the same
1681 // scope: we want this decl instead of the existing one.
1682 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001683 }
1684
Richard Smith5cd86f82015-11-03 03:13:11 +00001685 // In all other cases, we need to keep both declarations in case they have
1686 // different visibility. Any attempt to use the name will result in an
1687 // ambiguity if more than one is visible.
1688 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001689}
1690
Douglas Gregoreddf4332009-02-24 20:03:32 +00001691bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001692 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001693}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001694
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001695NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001696 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001697 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001698 ND = UD->getTargetDecl();
1699
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001700 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001701 return AD->getClassInterface();
1702
Richard Smithf2005d32015-12-29 23:34:32 +00001703 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1704 return AD->getNamespace();
1705
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001706 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001707}
1708
John McCalla8ae2222010-04-06 21:38:20 +00001709bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001710 if (!isCXXClassMember())
1711 return false;
1712
John McCalla8ae2222010-04-06 21:38:20 +00001713 const NamedDecl *D = this;
1714 if (isa<UsingShadowDecl>(D))
1715 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1716
John McCall5e77d762013-04-16 07:28:30 +00001717 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001718 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001719 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001720 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001721 return false;
1722}
1723
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001724//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001725// DeclaratorDecl Implementation
1726//===----------------------------------------------------------------------===//
1727
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001728template <typename DeclT>
1729static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1730 if (decl->getNumTemplateParameterLists() > 0)
1731 return decl->getTemplateParameterList(0)->getTemplateLoc();
1732 else
1733 return decl->getInnerLocStart();
1734}
1735
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001736SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001737 TypeSourceInfo *TSI = getTypeSourceInfo();
1738 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001739 return SourceLocation();
1740}
1741
Douglas Gregor14454802011-02-25 02:25:35 +00001742void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1743 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001744 // Make sure the extended decl info is allocated.
1745 if (!hasExtInfo()) {
1746 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001747 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001748 // Allocate external info struct.
1749 DeclInfo = new (getASTContext()) ExtInfo;
1750 // Restore savedTInfo into (extended) decl info.
1751 getExtInfo()->TInfo = savedTInfo;
1752 }
1753 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001754 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001755 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001756 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001757 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001758 if (getExtInfo()->NumTemplParamLists == 0) {
1759 // Save type source info pointer.
1760 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1761 // Deallocate the extended decl info.
1762 getASTContext().Deallocate(getExtInfo());
1763 // Restore savedTInfo into (non-extended) decl info.
1764 DeclInfo = savedTInfo;
1765 }
1766 else
1767 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001768 }
1769 }
1770}
1771
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001772void DeclaratorDecl::setTemplateParameterListsInfo(
1773 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1774 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001775 // Make sure the extended decl info is allocated.
1776 if (!hasExtInfo()) {
1777 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001778 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001779 // Allocate external info struct.
1780 DeclInfo = new (getASTContext()) ExtInfo;
1781 // Restore savedTInfo into (extended) decl info.
1782 getExtInfo()->TInfo = savedTInfo;
1783 }
1784 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001785 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001786}
1787
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001788SourceLocation DeclaratorDecl::getOuterLocStart() const {
1789 return getTemplateOrInnerLocStart(this);
1790}
1791
Abramo Bagnaraea947882011-03-08 16:41:52 +00001792// Helper function: returns true if QT is or contains a type
1793// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001794static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001795 while (true) {
1796 const Type* T = QT.getTypePtr();
1797 switch (T->getTypeClass()) {
1798 default:
1799 return false;
1800 case Type::Pointer:
1801 QT = cast<PointerType>(T)->getPointeeType();
1802 break;
1803 case Type::BlockPointer:
1804 QT = cast<BlockPointerType>(T)->getPointeeType();
1805 break;
1806 case Type::MemberPointer:
1807 QT = cast<MemberPointerType>(T)->getPointeeType();
1808 break;
1809 case Type::LValueReference:
1810 case Type::RValueReference:
1811 QT = cast<ReferenceType>(T)->getPointeeType();
1812 break;
1813 case Type::PackExpansion:
1814 QT = cast<PackExpansionType>(T)->getPattern();
1815 break;
1816 case Type::Paren:
1817 case Type::ConstantArray:
1818 case Type::DependentSizedArray:
1819 case Type::IncompleteArray:
1820 case Type::VariableArray:
1821 case Type::FunctionProto:
1822 case Type::FunctionNoProto:
1823 return true;
1824 }
1825 }
1826}
1827
Abramo Bagnaraea947882011-03-08 16:41:52 +00001828SourceRange DeclaratorDecl::getSourceRange() const {
1829 SourceLocation RangeEnd = getLocation();
1830 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001831 // If the declaration has no name or the type extends past the name take the
1832 // end location of the type.
1833 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001834 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1835 }
1836 return SourceRange(getOuterLocStart(), RangeEnd);
1837}
1838
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001839void QualifierInfo::setTemplateParameterListsInfo(
1840 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001841 // Free previous template parameters (if any).
1842 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001843 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001844 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001845 NumTemplParamLists = 0;
1846 }
1847 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001848 if (!TPLists.empty()) {
1849 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1850 NumTemplParamLists = TPLists.size();
1851 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001852 }
1853}
1854
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001855//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001856// VarDecl Implementation
1857//===----------------------------------------------------------------------===//
1858
Sebastian Redl833ef452010-01-26 22:01:41 +00001859const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1860 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001861 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001862 case SC_Auto: return "auto";
1863 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001864 case SC_PrivateExtern: return "__private_extern__";
1865 case SC_Register: return "register";
1866 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001867 }
1868
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001869 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001870}
1871
Richard Smith053f6c62014-05-16 23:01:30 +00001872VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1873 SourceLocation StartLoc, SourceLocation IdLoc,
1874 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1875 StorageClass SC)
1876 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001877 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001878 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1879 "VarDeclBitfields too large!");
1880 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1881 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001882 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1883 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001884 AllBits = 0;
1885 VarDeclBits.SClass = SC;
1886 // Everything else is implicitly initialized to false.
1887}
1888
Abramo Bagnaradff19302011-03-08 08:55:46 +00001889VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1890 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001891 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001892 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001893 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001894}
1895
Douglas Gregor72172e92012-01-05 21:55:30 +00001896VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001897 return new (C, ID)
1898 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1899 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001900}
1901
Douglas Gregorbf62d642010-12-06 18:36:25 +00001902void VarDecl::setStorageClass(StorageClass SC) {
1903 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001904 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001905}
1906
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001907VarDecl::TLSKind VarDecl::getTLSKind() const {
1908 switch (VarDeclBits.TSCSpec) {
1909 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001910 if (!hasAttr<ThreadAttr>() &&
1911 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1912 getASTContext().getTargetInfo().isTLSSupported() &&
1913 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001914 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001915 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1916 LangOptions::MSVC2015)) ||
1917 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001918 ? TLS_Dynamic
1919 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001920 case TSCS___thread: // Fall through.
1921 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001922 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001923 case TSCS_thread_local:
1924 return TLS_Dynamic;
1925 }
1926 llvm_unreachable("Unknown thread storage class specifier!");
1927}
1928
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001929SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001930 if (const Expr *Init = getInit()) {
1931 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001932 // If Init is implicit, ignore its source range and fallback on
1933 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1934 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001935 return SourceRange(getOuterLocStart(), InitEnd);
1936 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001937 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001938}
1939
Rafael Espindola88510672013-01-04 21:18:45 +00001940template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001941static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001942 // C++ [dcl.link]p1: All function types, function names with external linkage,
1943 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001944 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001945 return NoLanguageLinkage;
1946
1947 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001948 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001949 ASTContext &Context = D.getASTContext();
1950 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001951 return CLanguageLinkage;
1952
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001953 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1954 // language linkage of the names of class members and the function type of
1955 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001956 const DeclContext *DC = D.getDeclContext();
1957 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001958 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001959
1960 // If the first decl is in an extern "C" context, any other redeclaration
1961 // will have C language linkage. If the first one is not in an extern "C"
1962 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001963 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001964 return CLanguageLinkage;
1965 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001966}
1967
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001968template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001969static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001970 // Since the context is ignored for class members, they can only have C++
1971 // language linkage or no language linkage.
1972 const DeclContext *DC = D.getDeclContext();
1973 if (DC->isRecord()) {
1974 assert(D.getASTContext().getLangOpts().CPlusPlus);
1975 return false;
1976 }
1977
1978 return D.getLanguageLinkage() == CLanguageLinkage;
1979}
1980
Rafael Espindolaf4187652013-02-14 01:18:37 +00001981LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001982 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001983}
1984
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001985bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001986 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001987}
1988
Rafael Espindola593537a2013-05-05 20:15:21 +00001989bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001990 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001991}
1992
1993bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001994 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001995}
1996
Rafael Espindola8db352d2013-10-17 15:37:26 +00001997VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001998
Nico Weber7f5015a2015-04-15 21:53:00 +00001999VarDecl::DefinitionKind
2000VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00002001 if (isThisDeclarationADemotedDefinition())
2002 return DeclarationOnly;
2003
Sebastian Redl35351a92010-01-31 22:27:38 +00002004 // C++ [basic.def]p2:
2005 // A declaration is a definition unless [...] it contains the 'extern'
2006 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00002007 // it declares a non-inline static data member in a class declaration [...],
2008 // it declares a static data member outside a class definition and the variable
2009 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00002010 // C++1y [temp.expl.spec]p15:
2011 // An explicit specialization of a static data member or an explicit
2012 // specialization of a static data member template is a definition if the
2013 // declaration includes an initializer; otherwise, it is a declaration.
2014 //
2015 // FIXME: How do you declare (but not define) a partial specialization of
2016 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00002017 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002018 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002019 !(getCanonicalDecl()->isInline() &&
2020 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002021 (hasInit() ||
2022 // If the first declaration is out-of-line, this may be an
2023 // instantiation of an out-of-line partial specialization of a variable
2024 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002025 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002026 ? getTemplateSpecializationKind() == TSK_Undeclared
2027 : getTemplateSpecializationKind() !=
2028 TSK_ExplicitSpecialization) ||
2029 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002030 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002031 else if (!isOutOfLine() && isInline())
2032 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002033 else
2034 return DeclarationOnly;
2035 }
2036 // C99 6.7p5:
2037 // A definition of an identifier is a declaration for that identifier that
2038 // [...] causes storage to be reserved for that object.
2039 // Note: that applies for all non-file-scope objects.
2040 // C99 6.9.2p1:
2041 // If the declaration of an identifier for an object has file scope and an
2042 // initializer, the declaration is an external definition for the identifier
2043 if (hasInit())
2044 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002045
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002046 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002047 return Definition;
2048
David Majnemerdd0bed12015-05-14 05:19:20 +00002049 if (const auto *SAA = getAttr<SelectAnyAttr>())
2050 if (!SAA->isInherited())
2051 return Definition;
2052
Richard Smith8809a0c2013-09-27 20:14:12 +00002053 // A variable template specialization (other than a static data member
2054 // template or an explicit specialization) is a declaration until we
2055 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002056 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2057 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2058 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2059 !VTSD->IsCompleteDefinition)
2060 return DeclarationOnly;
2061 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002062
Nico Weber608e7682015-04-15 23:04:24 +00002063 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002064 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002065
Rafael Espindolabff59562013-04-25 12:11:36 +00002066 // [dcl.link] p7:
2067 // A declaration directly contained in a linkage-specification is treated
2068 // as if it contains the extern specifier for the purpose of determining
2069 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002070 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002071 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002072
Sebastian Redl35351a92010-01-31 22:27:38 +00002073 // C99 6.9.2p2:
2074 // A declaration of an object that has file scope without an initializer,
2075 // and without a storage class specifier or the scs 'static', constitutes
2076 // a tentative definition.
2077 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002078 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002079 return TentativeDefinition;
2080
2081 // What's left is (in C, block-scope) declarations without initializers or
2082 // external storage. These are definitions.
2083 return Definition;
2084}
2085
Sebastian Redl35351a92010-01-31 22:27:38 +00002086VarDecl *VarDecl::getActingDefinition() {
2087 DefinitionKind Kind = isThisDeclarationADefinition();
2088 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002089 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002090
Craig Topper36250ad2014-05-12 05:36:57 +00002091 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002092 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002093 for (auto I : First->redecls()) {
2094 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002095 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002096 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002097 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002098 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002099 }
2100 return LastTentative;
2101}
2102
Daniel Dunbar9d355812012-03-09 01:51:51 +00002103VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002104 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002105 for (auto I : First->redecls()) {
2106 if (I->isThisDeclarationADefinition(C) == Definition)
2107 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002108 }
Craig Topper36250ad2014-05-12 05:36:57 +00002109 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002110}
2111
Daniel Dunbar9d355812012-03-09 01:51:51 +00002112VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002113 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002114
Rafael Espindola8db352d2013-10-17 15:37:26 +00002115 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002116 for (auto I : First->redecls()) {
2117 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002118 if (Kind == Definition)
2119 break;
2120 }
John McCall37bb6c92010-10-29 22:22:43 +00002121
2122 return Kind;
2123}
2124
Sebastian Redl5ca79842010-02-01 20:16:42 +00002125const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002126 for (auto I : redecls()) {
2127 if (auto Expr = I->getInit()) {
2128 D = I;
2129 return Expr;
2130 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002131 }
Craig Topper36250ad2014-05-12 05:36:57 +00002132 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002133}
2134
Chandler Carruth813faed2015-12-30 02:51:00 +00002135bool VarDecl::hasInit() const {
2136 if (auto *P = dyn_cast<ParmVarDecl>(this))
2137 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2138 return false;
2139
2140 return !Init.isNull();
2141}
2142
2143Expr *VarDecl::getInit() {
2144 if (!hasInit())
2145 return nullptr;
2146
2147 if (auto *S = Init.dyn_cast<Stmt *>())
2148 return cast<Expr>(S);
2149
2150 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2151}
2152
2153Stmt **VarDecl::getInitAddress() {
2154 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2155 return &ES->Value;
2156
2157 return Init.getAddrOfPtr1();
2158}
2159
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002160bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002161 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002162 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002163
2164 if (!isStaticDataMember())
2165 return false;
2166
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002167 // If this static data member was instantiated from a static data member of
2168 // a class template, check whether that static data member was defined
2169 // out-of-line.
2170 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2171 return VD->isOutOfLine();
2172
2173 return false;
2174}
2175
Douglas Gregord5058122010-02-11 01:19:42 +00002176void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002177 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002178 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002179 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002180 }
2181
2182 Init = I;
2183}
2184
Daniel Dunbar9d355812012-03-09 01:51:51 +00002185bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002186 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002187
Richard Smith35ecb362012-03-02 04:14:40 +00002188 if (!Lang.CPlusPlus)
2189 return false;
2190
2191 // In C++11, any variable of reference type can be used in a constant
2192 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002193 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002194 return true;
2195
2196 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002197 // not require the variable to be non-volatile, but we consider this to be a
2198 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002199 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002200 return false;
2201
2202 // In C++, const, non-volatile variables of integral or enumeration types
2203 // can be used in constant expressions.
2204 if (getType()->isIntegralOrEnumerationType())
2205 return true;
2206
Richard Smith35ecb362012-03-02 04:14:40 +00002207 // Additionally, in C++11, non-volatile constexpr variables can be used in
2208 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002209 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002210}
2211
Richard Smithd0b4dd62011-12-19 06:19:21 +00002212/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2213/// form, which contains extra information on the evaluated value of the
2214/// initializer.
2215EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002216 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002217 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002218 // Note: EvaluatedStmt contains an APValue, which usually holds
2219 // resources not allocated from the ASTContext. We need to do some
2220 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2221 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002222 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002223 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002224 Init = Eval;
2225 }
2226 return Eval;
2227}
2228
Richard Smithdafff942012-01-14 04:30:29 +00002229APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002230 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002231 return evaluateValue(Notes);
2232}
2233
2234APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002235 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002236 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2237
2238 // We only produce notes indicating why an initializer is non-constant the
2239 // first time it is evaluated. FIXME: The notes won't always be emitted the
2240 // first time we try evaluation, so might not be produced at all.
2241 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002242 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002243
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002244 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002245 assert(!Init->isValueDependent());
2246
2247 if (Eval->IsEvaluating) {
2248 // FIXME: Produce a diagnostic for self-initialization.
2249 Eval->CheckedICE = true;
2250 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002251 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002252 }
2253
2254 Eval->IsEvaluating = true;
2255
2256 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2257 this, Notes);
2258
Manuel Klimeka7328992013-06-03 13:51:33 +00002259 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2260 // or that it's empty (so that there's nothing to clean up) if evaluation
2261 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002262 if (!Result)
2263 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002264 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002265 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002266
2267 Eval->IsEvaluating = false;
2268 Eval->WasEvaluated = true;
2269
2270 // In C++11, we have determined whether the initializer was a constant
2271 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002272 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002273 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002274 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002275 }
2276
Craig Topper36250ad2014-05-12 05:36:57 +00002277 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002278}
2279
Chandler Carruth813faed2015-12-30 02:51:00 +00002280APValue *VarDecl::getEvaluatedValue() const {
2281 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2282 if (Eval->WasEvaluated)
2283 return &Eval->Evaluated;
2284
2285 return nullptr;
2286}
2287
2288bool VarDecl::isInitKnownICE() const {
2289 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2290 return Eval->CheckedICE;
2291
2292 return false;
2293}
2294
2295bool VarDecl::isInitICE() const {
2296 assert(isInitKnownICE() &&
2297 "Check whether we already know that the initializer is an ICE");
2298 return Init.get<EvaluatedStmt *>()->IsICE;
2299}
2300
Richard Smithd0b4dd62011-12-19 06:19:21 +00002301bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002302 // Initializers of weak variables are never ICEs.
2303 if (isWeak())
2304 return false;
2305
Richard Smithd0b4dd62011-12-19 06:19:21 +00002306 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2307 if (Eval->CheckedICE)
2308 // We have already checked whether this subexpression is an
2309 // integral constant expression.
2310 return Eval->IsICE;
2311
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002312 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002313 assert(!Init->isValueDependent());
2314
2315 // In C++11, evaluate the initializer to check whether it's a constant
2316 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002317 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002318 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002319 evaluateValue(Notes);
2320 return Eval->IsICE;
2321 }
2322
2323 // It's an ICE whether or not the definition we found is
2324 // out-of-line. See DR 721 and the discussion in Clang PR
2325 // 6206 for details.
2326
2327 if (Eval->CheckingICE)
2328 return false;
2329 Eval->CheckingICE = true;
2330
2331 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2332 Eval->CheckingICE = false;
2333 Eval->CheckedICE = true;
2334 return Eval->IsICE;
2335}
2336
Richard Smith2195ec92017-04-21 01:15:13 +00002337template<typename DeclT>
2338static DeclT *getDefinitionOrSelf(DeclT *D) {
2339 assert(D);
2340 if (auto *Def = D->getDefinition())
2341 return Def;
2342 return D;
2343}
2344
Richard Smithedbc6e92016-10-14 21:41:24 +00002345VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2346 // If it's a variable template specialization, find the template or partial
2347 // specialization from which it was instantiated.
2348 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2349 auto From = VDTemplSpec->getInstantiatedFrom();
2350 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2351 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2352 if (NewVTD->isMemberSpecialization())
2353 break;
2354 VTD = NewVTD;
2355 }
Richard Smith2195ec92017-04-21 01:15:13 +00002356 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002357 }
2358 if (auto *VTPSD =
2359 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2360 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2361 if (NewVTPSD->isMemberSpecialization())
2362 break;
2363 VTPSD = NewVTPSD;
2364 }
Richard Smith2195ec92017-04-21 01:15:13 +00002365 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002366 }
2367 }
2368
2369 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2370 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2371 VarDecl *VD = getInstantiatedFromStaticDataMember();
2372 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2373 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002374 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002375 }
2376 }
2377
2378 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002379 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2380 if (VarTemplate->isMemberSpecialization())
2381 break;
2382 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2383 }
2384
Richard Smith2195ec92017-04-21 01:15:13 +00002385 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002386 }
2387 return nullptr;
2388}
2389
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002390VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002391 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002392 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002393
2394 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002395}
2396
Douglas Gregor3c74d412009-10-14 20:14:33 +00002397TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002398 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002399 return Spec->getSpecializationKind();
2400
Sebastian Redl35351a92010-01-31 22:27:38 +00002401 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002402 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002403
Douglas Gregor86d142a2009-10-08 07:24:58 +00002404 return TSK_Undeclared;
2405}
2406
Richard Smith8809a0c2013-09-27 20:14:12 +00002407SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002408 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002409 return Spec->getPointOfInstantiation();
2410
2411 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2412 return MSI->getPointOfInstantiation();
2413
2414 return SourceLocation();
2415}
2416
Larisse Voufo39a1e502013-08-06 01:03:05 +00002417VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2418 return getASTContext().getTemplateOrSpecializationInfo(this)
2419 .dyn_cast<VarTemplateDecl *>();
2420}
2421
2422void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2423 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2424}
2425
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002426MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002427 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002428 // FIXME: Remove ?
2429 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2430 return getASTContext().getTemplateOrSpecializationInfo(this)
2431 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002432 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002433}
2434
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002435void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2436 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002437 assert((isa<VarTemplateSpecializationDecl>(this) ||
2438 getMemberSpecializationInfo()) &&
2439 "not a variable or static data member template specialization");
2440
Larisse Voufo39a1e502013-08-06 01:03:05 +00002441 if (VarTemplateSpecializationDecl *Spec =
2442 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2443 Spec->setSpecializationKind(TSK);
2444 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002445 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002446 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002447 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2448 L->InstantiationRequested(this);
2449 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002450 }
2451
2452 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2453 MSI->setTemplateSpecializationKind(TSK);
2454 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002455 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002456 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002457 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2458 L->InstantiationRequested(this);
2459 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002460 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002461}
2462
2463void
2464VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2465 TemplateSpecializationKind TSK) {
2466 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2467 "Previous template or instantiation?");
2468 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002469}
2470
Sebastian Redl833ef452010-01-26 22:01:41 +00002471//===----------------------------------------------------------------------===//
2472// ParmVarDecl Implementation
2473//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002474
Sebastian Redl833ef452010-01-26 22:01:41 +00002475ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002476 SourceLocation StartLoc,
2477 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002478 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002479 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002480 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002481 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002482}
2483
Reid Kleckner8a365022013-06-24 17:51:48 +00002484QualType ParmVarDecl::getOriginalType() const {
2485 TypeSourceInfo *TSI = getTypeSourceInfo();
2486 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002487 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002488 return DT->getOriginalType();
2489 return T;
2490}
2491
Douglas Gregor72172e92012-01-05 21:55:30 +00002492ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002493 return new (C, ID)
2494 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2495 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002496}
2497
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002498SourceRange ParmVarDecl::getSourceRange() const {
2499 if (!hasInheritedDefaultArg()) {
2500 SourceRange ArgRange = getDefaultArgRange();
2501 if (ArgRange.isValid())
2502 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2503 }
2504
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002505 // DeclaratorDecl considers the range of postfix types as overlapping with the
2506 // declaration name, but this is not the case with parameters in ObjC methods.
2507 if (isa<ObjCMethodDecl>(getDeclContext()))
2508 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2509
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002510 return DeclaratorDecl::getSourceRange();
2511}
2512
Sebastian Redl833ef452010-01-26 22:01:41 +00002513Expr *ParmVarDecl::getDefaultArg() {
2514 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2515 assert(!hasUninstantiatedDefaultArg() &&
2516 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002517
Sebastian Redl833ef452010-01-26 22:01:41 +00002518 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002519 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002520 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002521
Sebastian Redl833ef452010-01-26 22:01:41 +00002522 return Arg;
2523}
2524
Chandler Carruth813faed2015-12-30 02:51:00 +00002525void ParmVarDecl::setDefaultArg(Expr *defarg) {
2526 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2527 Init = defarg;
2528}
Sebastian Redl833ef452010-01-26 22:01:41 +00002529
Chandler Carruth813faed2015-12-30 02:51:00 +00002530SourceRange ParmVarDecl::getDefaultArgRange() const {
2531 switch (ParmVarDeclBits.DefaultArgKind) {
2532 case DAK_None:
2533 case DAK_Unparsed:
2534 // Nothing we can do here.
2535 return SourceRange();
2536
2537 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002538 return getUninstantiatedDefaultArg()->getSourceRange();
2539
Chandler Carruth813faed2015-12-30 02:51:00 +00002540 case DAK_Normal:
2541 if (const Expr *E = getInit())
2542 return E->getSourceRange();
2543
2544 // Missing an actual expression, may be invalid.
2545 return SourceRange();
2546 }
2547 llvm_unreachable("Invalid default argument kind.");
2548}
2549
2550void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2551 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2552 Init = arg;
2553}
2554
2555Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2556 assert(hasUninstantiatedDefaultArg() &&
2557 "Wrong kind of initialization expression!");
2558 return cast_or_null<Expr>(Init.get<Stmt *>());
2559}
2560
2561bool ParmVarDecl::hasDefaultArg() const {
2562 // FIXME: We should just return false for DAK_None here once callers are
2563 // prepared for the case that we encountered an invalid default argument and
2564 // were unable to even build an invalid expression.
2565 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2566 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002567}
2568
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002569bool ParmVarDecl::isParameterPack() const {
2570 return isa<PackExpansionType>(getType());
2571}
2572
Ted Kremenek540017e2011-10-06 05:00:56 +00002573void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2574 getASTContext().setParameterIndex(this, parameterIndex);
2575 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2576}
2577
2578unsigned ParmVarDecl::getParameterIndexLarge() const {
2579 return getASTContext().getParameterIndex(this);
2580}
2581
Nuno Lopes394ec982008-12-17 23:39:55 +00002582//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002583// FunctionDecl Implementation
2584//===----------------------------------------------------------------------===//
2585
Benjamin Kramer9170e912013-02-22 15:46:01 +00002586void FunctionDecl::getNameForDiagnostic(
2587 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2588 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002589 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2590 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002591 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002592}
2593
Ted Kremenek186a0742010-04-29 16:49:01 +00002594bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002595 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002596 return FT->isVariadic();
2597 return false;
2598}
2599
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002600bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002601 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002602 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002603 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002604 return true;
2605 }
2606 }
2607
2608 return false;
2609}
2610
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002611bool FunctionDecl::hasTrivialBody() const
2612{
2613 Stmt *S = getBody();
2614 if (!S) {
2615 // Since we don't have a body for this function, we don't know if it's
2616 // trivial or not.
2617 return false;
2618 }
2619
2620 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2621 return true;
2622 return false;
2623}
2624
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002625bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002626 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002627 if (I->isThisDeclarationADefinition()) {
2628 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002629 return true;
2630 }
2631 }
2632
2633 return false;
2634}
2635
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002636Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002637 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002638 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002639
2640 if (Definition->Body)
2641 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002642
Craig Topper36250ad2014-05-12 05:36:57 +00002643 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002644}
2645
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002646void FunctionDecl::setBody(Stmt *B) {
2647 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002648 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002649 EndRangeLoc = B->getLocEnd();
2650}
2651
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002652void FunctionDecl::setPure(bool P) {
2653 IsPure = P;
2654 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002655 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002656 Parent->markedVirtualFunctionPure();
2657}
2658
Richard Smith8d0dc312013-07-21 23:12:18 +00002659template<std::size_t Len>
2660static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2661 IdentifierInfo *II = ND->getIdentifier();
2662 return II && II->isStr(Str);
2663}
2664
Douglas Gregor16618f22009-09-12 00:17:51 +00002665bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002666 const TranslationUnitDecl *tunit =
2667 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2668 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002669 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002670 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002671}
2672
David Majnemerc729b0b2013-09-16 22:44:20 +00002673bool FunctionDecl::isMSVCRTEntryPoint() const {
2674 const TranslationUnitDecl *TUnit =
2675 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2676 if (!TUnit)
2677 return false;
2678
2679 // Even though we aren't really targeting MSVCRT if we are freestanding,
2680 // semantic analysis for these functions remains the same.
2681
2682 // MSVCRT entry points only exist on MSVCRT targets.
2683 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2684 return false;
2685
2686 // Nameless functions like constructors cannot be entry points.
2687 if (!getIdentifier())
2688 return false;
2689
2690 return llvm::StringSwitch<bool>(getName())
2691 .Cases("main", // an ANSI console app
2692 "wmain", // a Unicode console App
2693 "WinMain", // an ANSI GUI app
2694 "wWinMain", // a Unicode GUI app
2695 "DllMain", // a DLL
2696 true)
2697 .Default(false);
2698}
2699
John McCall53ffd372011-05-15 17:49:20 +00002700bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2701 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2702 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2703 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2704 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2705 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2706
Richard Smithf6004412014-01-19 23:25:37 +00002707 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2708 return false;
John McCall53ffd372011-05-15 17:49:20 +00002709
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002710 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002711 if (proto->getNumParams() != 2 || proto->isVariadic())
2712 return false;
John McCall53ffd372011-05-15 17:49:20 +00002713
2714 ASTContext &Context =
2715 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2716 ->getASTContext();
2717
2718 // The result type and first argument type are constant across all
2719 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002720 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002721}
2722
Akira Hatanakacae83f72017-06-29 18:48:40 +00002723bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002724 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2725 return false;
2726 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2727 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2728 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2729 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2730 return false;
2731
2732 if (isa<CXXRecordDecl>(getDeclContext()))
2733 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002734
2735 // This can only fail for an invalid 'operator new' declaration.
2736 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2737 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002738
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002739 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002740 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002741 return false;
2742
2743 // If this is a single-parameter function, it must be a replaceable global
2744 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002745 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002746 return true;
2747
Richard Smithb2f0f052016-10-10 18:54:32 +00002748 unsigned Params = 1;
2749 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002750 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002751
2752 auto Consume = [&] {
2753 ++Params;
2754 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2755 };
2756
2757 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2758 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002759 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002760 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2761 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2762 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2763 IsSizedDelete = true;
2764 Consume();
2765 }
2766
2767 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2768 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002769 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2770 if (IsAligned)
2771 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002772 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002773 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002774
2775 // Finally, if this is not a sized delete, the final parameter can
2776 // be a 'const std::nothrow_t&'.
2777 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2778 Ty = Ty->getPointeeType();
2779 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2780 return false;
2781 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2782 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2783 Consume();
2784 }
2785
2786 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002787}
2788
Richard Smith5b349582017-10-13 01:55:36 +00002789bool FunctionDecl::isDestroyingOperatorDelete() const {
2790 // C++ P0722:
2791 // Within a class C, a single object deallocation function with signature
2792 // (T, std::destroying_delete_t, <more params>)
2793 // is a destroying operator delete.
2794 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2795 getNumParams() < 2)
2796 return false;
2797
2798 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2799 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2800 RD->getIdentifier()->isStr("destroying_delete_t");
2801}
2802
Rafael Espindolaf4187652013-02-14 01:18:37 +00002803LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002804 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002805}
2806
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002807bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002808 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002809}
2810
Rafael Espindola593537a2013-05-05 20:15:21 +00002811bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002812 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002813}
2814
2815bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002816 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002817}
2818
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002819bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002820 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002821 return Method->isStatic();
2822
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002823 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002824 return false;
2825
Mike Stump11289f42009-09-09 15:08:12 +00002826 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002827 DC->isNamespace();
2828 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002829 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002830 if (!Namespace->getDeclName())
2831 return false;
2832 break;
2833 }
2834 }
2835
2836 return true;
2837}
2838
Richard Smith10876ef2013-01-17 01:30:42 +00002839bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002840 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2841 hasAttr<C11NoReturnAttr>())
2842 return true;
2843
2844 if (auto *FnTy = getType()->getAs<FunctionType>())
2845 return FnTy->getNoReturnAttr();
2846
2847 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002848}
2849
Sebastian Redl833ef452010-01-26 22:01:41 +00002850void
2851FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002852 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002853
2854 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2855 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002856 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002857 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002858 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002859 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002860
Axel Naumannfbc7b982011-11-08 18:21:06 +00002861 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002862 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002863}
2864
Rafael Espindola8db352d2013-10-17 15:37:26 +00002865FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002866
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002867/// \brief Returns a value indicating whether this function
2868/// corresponds to a builtin function.
2869///
2870/// The function corresponds to a built-in function if it is
2871/// declared at translation scope or within an extern "C" block and
2872/// its name matches with the name of a builtin. The returned value
2873/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002874/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002875/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002876unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002877 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002878 return 0;
2879
2880 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002881 if (!BuiltinID)
2882 return 0;
2883
2884 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002885 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002886 const auto *LinkageDecl =
2887 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002888 // In C++, the first declaration of a builtin is always inside an implicit
2889 // extern "C".
2890 // FIXME: A recognised library function may not be directly in an extern "C"
2891 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002892 if (!LinkageDecl) {
2893 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002894 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002895 return Builtin::BI__GetExceptionInfo;
2896 return 0;
2897 }
2898 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002899 return 0;
2900 }
2901
2902 // If the function is marked "overloadable", it has a different mangled name
2903 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002904 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002905 return 0;
2906
Douglas Gregore711f702009-02-14 18:57:46 +00002907 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2908 return BuiltinID;
2909
2910 // This function has the name of a known C library
2911 // function. Determine whether it actually refers to the C library
2912 // function or whether it just has the same name.
2913
Douglas Gregora908e7f2009-02-17 03:23:10 +00002914 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002915 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002916 return 0;
2917
Anastasia Stulova1202de32016-02-12 12:07:04 +00002918 // OpenCL v1.2 s6.9.f - The library functions defined in
2919 // the C99 standard headers are not available.
2920 if (Context.getLangOpts().OpenCL &&
2921 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2922 return 0;
2923
Artem Belevich5ecdb942018-01-23 19:08:18 +00002924 // CUDA does not have device-side standard library. printf and malloc are the
2925 // only special cases that are supported by device-side runtime.
2926 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
2927 !hasAttr<CUDAHostAttr>() &&
2928 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
2929 return 0;
2930
Warren Hunt445d83e2013-11-01 23:46:51 +00002931 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002932}
2933
Chris Lattner47c0d002009-04-25 06:03:53 +00002934/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002935/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002936/// after it has been created.
2937unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002938 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002939 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002940}
2941
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002942void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002943 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002944 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002945 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002946
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002947 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002948 if (!NewParamInfo.empty()) {
2949 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2950 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002951 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002952}
Chris Lattner41943152007-01-25 04:52:46 +00002953
Chris Lattner58258242008-04-10 02:22:51 +00002954/// getMinRequiredArguments - Returns the minimum number of arguments
2955/// needed to call this function. This may be fewer than the number of
2956/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002957/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002958unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002959 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002960 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002961
Richard Smith91151782014-04-01 19:18:16 +00002962 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002963 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002964 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2965 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002966 return NumRequiredArgs;
2967}
2968
David Majnemer54e3ba52014-04-02 23:17:29 +00002969/// \brief The combination of the extern and inline keywords under MSVC forces
2970/// the function to be required.
2971///
2972/// Note: This function assumes that we will only get called when isInlined()
2973/// would return true for this FunctionDecl.
2974bool FunctionDecl::isMSExternInline() const {
2975 assert(isInlined() && "expected to get called on an inlined function!");
2976
2977 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002978 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2979 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002980 return false;
2981
David Majnemer73768702015-03-20 00:02:27 +00002982 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2983 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002984 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002985 return true;
2986
2987 return false;
2988}
2989
2990static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2991 if (Redecl->getStorageClass() != SC_Extern)
2992 return false;
2993
2994 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2995 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002996 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002997 return false;
2998
2999 return true;
3000}
3001
Eli Friedman1b125c32012-02-07 03:50:18 +00003002static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3003 // Only consider file-scope declarations in this test.
3004 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3005 return false;
3006
3007 // Only consider explicit declarations; the presence of a builtin for a
3008 // libcall shouldn't affect whether a definition is externally visible.
3009 if (Redecl->isImplicit())
3010 return false;
3011
3012 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3013 return true; // Not an inline definition
3014
3015 return false;
3016}
3017
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003018/// \brief For a function declaration in C or C++, determine whether this
3019/// declaration causes the definition to be externally visible.
3020///
David Majnemer54e3ba52014-04-02 23:17:29 +00003021/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003022/// of redeclarations of the given functions causes
3023/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003024bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003025 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003026 "Must have a declaration without a body.");
3027
3028 ASTContext &Context = getASTContext();
3029
David Majnemer54e3ba52014-04-02 23:17:29 +00003030 if (Context.getLangOpts().MSVCCompat) {
3031 const FunctionDecl *Definition;
3032 if (hasBody(Definition) && Definition->isInlined() &&
3033 redeclForcesDefMSVC(this))
3034 return true;
3035 }
3036
David Blaikiebbafb8a2012-03-11 07:00:24 +00003037 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003038 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3039 // an externally visible definition.
3040 //
3041 // FIXME: What happens if gnu_inline gets added on after the first
3042 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003043 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003044 return false;
3045
3046 const FunctionDecl *Prev = this;
3047 bool FoundBody = false;
3048 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003049 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003050
3051 if (Prev->Body) {
3052 // If it's not the case that both 'inline' and 'extern' are
3053 // specified on the definition, then it is always externally visible.
3054 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003055 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003056 return false;
3057 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003058 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003059 return false;
3060 }
3061 }
3062 return FoundBody;
3063 }
3064
David Blaikiebbafb8a2012-03-11 07:00:24 +00003065 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003066 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003067
3068 // C99 6.7.4p6:
3069 // [...] If all of the file scope declarations for a function in a
3070 // translation unit include the inline function specifier without extern,
3071 // then the definition in that translation unit is an inline definition.
3072 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003073 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003074 const FunctionDecl *Prev = this;
3075 bool FoundBody = false;
3076 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003077 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003078 if (RedeclForcesDefC99(Prev))
3079 return false;
3080 }
3081 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003082}
3083
Alp Tokerd0787eb2014-07-02 01:47:15 +00003084SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3085 const TypeSourceInfo *TSI = getTypeSourceInfo();
3086 if (!TSI)
3087 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00003088 FunctionTypeLoc FTL =
3089 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3090 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003091 return SourceRange();
3092
Alp Tokerf5b10792014-07-02 12:55:58 +00003093 // Skip self-referential return types.
3094 const SourceManager &SM = getASTContext().getSourceManager();
3095 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3096 SourceLocation Boundary = getNameInfo().getLocStart();
3097 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3098 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3099 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003100
Alp Tokerf5b10792014-07-02 12:55:58 +00003101 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003102}
3103
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003104SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3105 const TypeSourceInfo *TSI = getTypeSourceInfo();
3106 if (!TSI)
3107 return SourceRange();
3108 FunctionTypeLoc FTL =
3109 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3110 if (!FTL)
3111 return SourceRange();
3112
3113 return FTL.getExceptionSpecRange();
3114}
3115
Aaron Ballmane7964782016-03-07 22:44:55 +00003116const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003117 QualType RetType = getReturnType();
3118 if (RetType->isRecordType()) {
Aaron Ballman35713eb2017-10-17 20:33:35 +00003119 if (const auto *Ret =
3120 dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) {
Aaron Ballmane7964782016-03-07 22:44:55 +00003121 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3122 return R;
3123 }
3124 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3125 if (const EnumDecl *ED = ET->getDecl()) {
3126 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3127 return R;
3128 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003129 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003130 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003131}
3132
Richard Smithf3814ad2013-01-25 00:08:28 +00003133/// \brief For an inline function definition in C, or for a gnu_inline function
3134/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003135///
3136/// Inline function definitions are always available for inlining optimizations.
3137/// However, depending on the language dialect, declaration specifiers, and
3138/// attributes, the definition of an inline function may or may not be
3139/// "externally" visible to other translation units in the program.
3140///
3141/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003142/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003143/// inline definition becomes externally visible (C99 6.7.4p6).
3144///
3145/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3146/// definition, we use the GNU semantics for inline, which are nearly the
3147/// opposite of C99 semantics. In particular, "inline" by itself will create
3148/// an externally visible symbol, but "extern inline" will not create an
3149/// externally visible symbol.
3150bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003151 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3152 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003153 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003154 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003155
David Blaikiebbafb8a2012-03-11 07:00:24 +00003156 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003157 // Note: If you change the logic here, please change
3158 // doesDeclarationForceExternallyVisibleDefinition as well.
3159 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003160 // If it's not the case that both 'inline' and 'extern' are
3161 // specified on the definition, then this inline definition is
3162 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003163 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003164 return true;
3165
3166 // If any declaration is 'inline' but not 'extern', then this definition
3167 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003168 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003169 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003170 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003171 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003172 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003173
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003174 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003175 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003176
Richard Smithf3814ad2013-01-25 00:08:28 +00003177 // The rest of this function is C-only.
3178 assert(!Context.getLangOpts().CPlusPlus &&
3179 "should not use C inline rules in C++");
3180
Douglas Gregor299d76e2009-09-13 07:46:26 +00003181 // C99 6.7.4p6:
3182 // [...] If all of the file scope declarations for a function in a
3183 // translation unit include the inline function specifier without extern,
3184 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003185 for (auto Redecl : redecls()) {
3186 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003187 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003188 }
3189
3190 // C99 6.7.4p6:
3191 // An inline definition does not provide an external definition for the
3192 // function, and does not forbid an external definition in another
3193 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003194 return false;
3195}
3196
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003197/// getOverloadedOperator - Which C++ overloaded operator this
3198/// function represents, if any.
3199OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003200 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3201 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003202 else
3203 return OO_None;
3204}
3205
Alexis Huntc88db062010-01-13 09:01:02 +00003206/// getLiteralIdentifier - The literal suffix identifier this function
3207/// represents, if any.
3208const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3209 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3210 return getDeclName().getCXXLiteralIdentifier();
3211 else
Craig Topper36250ad2014-05-12 05:36:57 +00003212 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003213}
3214
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003215FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3216 if (TemplateOrSpecialization.isNull())
3217 return TK_NonTemplate;
3218 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3219 return TK_FunctionTemplate;
3220 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3221 return TK_MemberSpecialization;
3222 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3223 return TK_FunctionTemplateSpecialization;
3224 if (TemplateOrSpecialization.is
3225 <DependentFunctionTemplateSpecializationInfo*>())
3226 return TK_DependentFunctionTemplateSpecialization;
3227
David Blaikie83d382b2011-09-23 05:06:16 +00003228 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003229}
3230
Douglas Gregord801b062009-10-07 23:56:10 +00003231FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003232 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003233 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003234
3235 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003236}
3237
Chandler Carruth21c90602015-12-30 03:24:14 +00003238MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3239 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3240}
3241
Douglas Gregord801b062009-10-07 23:56:10 +00003242void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003243FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3244 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003245 TemplateSpecializationKind TSK) {
3246 assert(TemplateOrSpecialization.isNull() &&
3247 "Member function is already a specialization");
3248 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003249 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003250 TemplateOrSpecialization = Info;
3251}
3252
Chandler Carruth21c90602015-12-30 03:24:14 +00003253FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3254 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3255}
3256
3257void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3258 TemplateOrSpecialization = Template;
3259}
3260
Douglas Gregorafca3b42009-10-27 20:53:28 +00003261bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003262 // If the function is invalid, it can't be implicitly instantiated.
3263 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003264 return false;
3265
3266 switch (getTemplateSpecializationKind()) {
3267 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003268 case TSK_ExplicitInstantiationDefinition:
3269 return false;
3270
3271 case TSK_ImplicitInstantiation:
3272 return true;
3273
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003274 // It is possible to instantiate TSK_ExplicitSpecialization kind
3275 // if the FunctionDecl has a class scope specialization pattern.
3276 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003277 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003278
Douglas Gregorafca3b42009-10-27 20:53:28 +00003279 case TSK_ExplicitInstantiationDeclaration:
3280 // Handled below.
3281 break;
3282 }
3283
3284 // Find the actual template from which we will instantiate.
3285 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003286 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003287 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003288 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003289
3290 // C++0x [temp.explicit]p9:
3291 // Except for inline functions, other explicit instantiation declarations
3292 // have the effect of suppressing the implicit instantiation of the entity
3293 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003294 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003295 return true;
3296
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003297 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003298}
3299
3300bool FunctionDecl::isTemplateInstantiation() const {
3301 switch (getTemplateSpecializationKind()) {
3302 case TSK_Undeclared:
3303 case TSK_ExplicitSpecialization:
3304 return false;
3305 case TSK_ImplicitInstantiation:
3306 case TSK_ExplicitInstantiationDeclaration:
3307 case TSK_ExplicitInstantiationDefinition:
3308 return true;
3309 }
3310 llvm_unreachable("All TSK values handled.");
3311}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003312
3313FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003314 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003315 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3316 if (auto *Spec = getClassScopeSpecializationPattern())
3317 return getDefinitionOrSelf(Spec);
3318 return nullptr;
3319 }
3320
Faisal Valib90b2112014-04-03 16:32:21 +00003321 // If this is a generic lambda call operator specialization, its
3322 // instantiation pattern is always its primary template's pattern
3323 // even if its primary template was instantiated from another
3324 // member template (which happens with nested generic lambdas).
3325 // Since a lambda's call operator's body is transformed eagerly,
3326 // we don't have to go hunting for a prototype definition template
3327 // (i.e. instantiated-from-member-template) to use as an instantiation
3328 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003329
Faisal Valib90b2112014-04-03 16:32:21 +00003330 if (isGenericLambdaCallOperatorSpecialization(
3331 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003332 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3333 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003334 }
Richard Smith2195ec92017-04-21 01:15:13 +00003335
Douglas Gregorafca3b42009-10-27 20:53:28 +00003336 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3337 while (Primary->getInstantiatedFromMemberTemplate()) {
3338 // If we have hit a point where the user provided a specialization of
3339 // this template, we're done looking.
3340 if (Primary->isMemberSpecialization())
3341 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003342 Primary = Primary->getInstantiatedFromMemberTemplate();
3343 }
Richard Smith2195ec92017-04-21 01:15:13 +00003344
3345 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003346 }
Richard Smith2195ec92017-04-21 01:15:13 +00003347
3348 if (auto *MFD = getInstantiatedFromMemberFunction())
3349 return getDefinitionOrSelf(MFD);
3350
3351 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003352}
3353
Douglas Gregor70d83e22009-06-29 17:30:29 +00003354FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003355 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003356 = TemplateOrSpecialization
3357 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003358 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003359 }
Craig Topper36250ad2014-05-12 05:36:57 +00003360 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003361}
3362
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003363FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3364 return getASTContext().getClassScopeSpecializationPattern(this);
3365}
3366
Chandler Carruth21c90602015-12-30 03:24:14 +00003367FunctionTemplateSpecializationInfo *
3368FunctionDecl::getTemplateSpecializationInfo() const {
3369 return TemplateOrSpecialization
3370 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3371}
3372
Douglas Gregor70d83e22009-06-29 17:30:29 +00003373const TemplateArgumentList *
3374FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003375 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003376 = TemplateOrSpecialization
3377 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003378 return Info->TemplateArguments;
3379 }
Craig Topper36250ad2014-05-12 05:36:57 +00003380 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003381}
3382
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003383const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003384FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3385 if (FunctionTemplateSpecializationInfo *Info
3386 = TemplateOrSpecialization
3387 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3388 return Info->TemplateArgumentsAsWritten;
3389 }
Craig Topper36250ad2014-05-12 05:36:57 +00003390 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003391}
3392
Mike Stump11289f42009-09-09 15:08:12 +00003393void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003394FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3395 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003396 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003397 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003398 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003399 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3400 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003401 assert(TSK != TSK_Undeclared &&
3402 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003403 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003404 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003405 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003406 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3407 TemplateArgs,
3408 TemplateArgsAsWritten,
3409 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003410 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003411 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003412}
3413
John McCallb9c78482010-04-08 09:05:18 +00003414void
3415FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3416 const UnresolvedSetImpl &Templates,
3417 const TemplateArgumentListInfo &TemplateArgs) {
3418 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003419 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003420 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3421 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003422 TemplateOrSpecialization = Info;
3423}
3424
James Y Knight7a22b242015-08-06 20:26:32 +00003425DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003426FunctionDecl::getDependentSpecializationInfo() const {
3427 return TemplateOrSpecialization
3428 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3429}
3430
3431DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003432DependentFunctionTemplateSpecializationInfo::Create(
3433 ASTContext &Context, const UnresolvedSetImpl &Ts,
3434 const TemplateArgumentListInfo &TArgs) {
3435 void *Buffer = Context.Allocate(
3436 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3437 TArgs.size(), Ts.size()));
3438 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3439}
3440
John McCallb9c78482010-04-08 09:05:18 +00003441DependentFunctionTemplateSpecializationInfo::
3442DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3443 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003444 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003445 NumTemplates = Ts.size();
3446 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003447
James Y Knight7a22b242015-08-06 20:26:32 +00003448 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003449 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3450 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3451
James Y Knight7a22b242015-08-06 20:26:32 +00003452 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003453 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3454 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3455}
3456
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003457TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003458 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003459 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003460 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003461 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003462 if (FTSInfo)
3463 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003464
Douglas Gregord801b062009-10-07 23:56:10 +00003465 MemberSpecializationInfo *MSInfo
3466 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3467 if (MSInfo)
3468 return MSInfo->getTemplateSpecializationKind();
3469
3470 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003471}
3472
Mike Stump11289f42009-09-09 15:08:12 +00003473void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003474FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3475 SourceLocation PointOfInstantiation) {
3476 if (FunctionTemplateSpecializationInfo *FTSInfo
3477 = TemplateOrSpecialization.dyn_cast<
3478 FunctionTemplateSpecializationInfo*>()) {
3479 FTSInfo->setTemplateSpecializationKind(TSK);
3480 if (TSK != TSK_ExplicitSpecialization &&
3481 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003482 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003483 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003484 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3485 L->InstantiationRequested(this);
3486 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003487 } else if (MemberSpecializationInfo *MSInfo
3488 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3489 MSInfo->setTemplateSpecializationKind(TSK);
3490 if (TSK != TSK_ExplicitSpecialization &&
3491 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003492 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003493 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003494 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3495 L->InstantiationRequested(this);
3496 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003497 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003498 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003499}
3500
3501SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003502 if (FunctionTemplateSpecializationInfo *FTSInfo
3503 = TemplateOrSpecialization.dyn_cast<
3504 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003505 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003506 else if (MemberSpecializationInfo *MSInfo
3507 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003508 return MSInfo->getPointOfInstantiation();
3509
3510 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003511}
3512
Douglas Gregor6411b922009-09-11 20:15:17 +00003513bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003514 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003515 return true;
3516
3517 // If this function was instantiated from a member function of a
3518 // class template, check whether that member function was defined out-of-line.
3519 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3520 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003521 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003522 return Definition->isOutOfLine();
3523 }
3524
3525 // If this function was instantiated from a function template,
3526 // check whether that function template was defined out-of-line.
3527 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3528 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003529 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003530 return Definition->isOutOfLine();
3531 }
3532
3533 return false;
3534}
3535
Abramo Bagnaraea947882011-03-08 16:41:52 +00003536SourceRange FunctionDecl::getSourceRange() const {
3537 return SourceRange(getOuterLocStart(), EndRangeLoc);
3538}
3539
Anna Zaks28db7ce2012-01-18 02:45:01 +00003540unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003541 IdentifierInfo *FnInfo = getIdentifier();
3542
3543 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003544 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003545
3546 // Builtin handling.
3547 switch (getBuiltinID()) {
3548 case Builtin::BI__builtin_memset:
3549 case Builtin::BI__builtin___memset_chk:
3550 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003551 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003552
3553 case Builtin::BI__builtin_memcpy:
3554 case Builtin::BI__builtin___memcpy_chk:
3555 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003556 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003557
3558 case Builtin::BI__builtin_memmove:
3559 case Builtin::BI__builtin___memmove_chk:
3560 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003561 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003562
3563 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003564 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003565 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003566
Anna Zaks201d4892012-01-13 21:52:01 +00003567 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003568 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003569 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003570
3571 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003572 case Builtin::BImemcmp:
3573 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003574
3575 case Builtin::BI__builtin_strncpy:
3576 case Builtin::BI__builtin___strncpy_chk:
3577 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003578 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003579
3580 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003581 case Builtin::BIstrncmp:
3582 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003583
3584 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003585 case Builtin::BIstrncasecmp:
3586 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003587
3588 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003589 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003590 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003591 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003592
3593 case Builtin::BI__builtin_strndup:
3594 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003595 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003596
Anna Zaks314cd092012-02-01 19:08:57 +00003597 case Builtin::BI__builtin_strlen:
3598 case Builtin::BIstrlen:
3599 return Builtin::BIstrlen;
3600
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003601 case Builtin::BI__builtin_bzero:
3602 case Builtin::BIbzero:
3603 return Builtin::BIbzero;
3604
Anna Zaks201d4892012-01-13 21:52:01 +00003605 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003606 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003607 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003608 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003609 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003610 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003611 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003612 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003613 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003614 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003615 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003616 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003617 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003618 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003619 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003620 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003621 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003622 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003623 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003624 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003625 else if (FnInfo->isStr("strlen"))
3626 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003627 else if (FnInfo->isStr("bzero"))
3628 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003629 }
3630 break;
3631 }
Anna Zaks22122702012-01-17 00:37:07 +00003632 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003633}
3634
Richard Trieue6caa262017-12-23 00:41:01 +00003635unsigned FunctionDecl::getODRHash() {
3636 if (HasODRHash)
3637 return ODRHash;
3638
3639 if (FunctionDecl *Definition = getDefinition()) {
3640 if (Definition != this) {
3641 HasODRHash = true;
3642 ODRHash = Definition->getODRHash();
3643 return ODRHash;
3644 }
3645 }
3646
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003647 if (auto *FT = getInstantiatedFromMemberFunction()) {
3648 HasODRHash = true;
3649 ODRHash = FT->getODRHash();
3650 return ODRHash;
3651 }
3652
Richard Trieue6caa262017-12-23 00:41:01 +00003653 class ODRHash Hash;
3654 Hash.AddFunctionDecl(this);
3655 HasODRHash = true;
3656 ODRHash = Hash.CalculateHash();
3657 return ODRHash;
3658}
3659
Chris Lattner59a25942008-03-31 00:36:02 +00003660//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003661// FieldDecl Implementation
3662//===----------------------------------------------------------------------===//
3663
Jay Foad39c79802011-01-12 09:06:06 +00003664FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003665 SourceLocation StartLoc, SourceLocation IdLoc,
3666 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003667 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003668 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003669 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3670 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003671}
3672
Douglas Gregor72172e92012-01-05 21:55:30 +00003673FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003674 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3675 SourceLocation(), nullptr, QualType(), nullptr,
3676 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003677}
3678
Sebastian Redl833ef452010-01-26 22:01:41 +00003679bool FieldDecl::isAnonymousStructOrUnion() const {
3680 if (!isImplicit() || getDeclName())
3681 return false;
3682
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003683 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003684 return Record->getDecl()->isAnonymousStructOrUnion();
3685
3686 return false;
3687}
3688
Richard Smithcaf33902011-10-10 18:28:20 +00003689unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3690 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003691 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003692}
3693
John McCall4e819612011-01-20 07:57:12 +00003694unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003695 const FieldDecl *Canonical = getCanonicalDecl();
3696 if (Canonical != this)
3697 return Canonical->getFieldIndex();
3698
John McCall4e819612011-01-20 07:57:12 +00003699 if (CachedFieldIndex) return CachedFieldIndex - 1;
3700
Richard Smithd62306a2011-11-10 06:34:14 +00003701 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00003702 const RecordDecl *RD = getParent()->getDefinition();
3703 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00003704
Hans Wennborga302cd92014-08-21 16:06:57 +00003705 for (auto *Field : RD->fields()) {
3706 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3707 ++Index;
3708 }
John McCall4e819612011-01-20 07:57:12 +00003709
Richard Smithd62306a2011-11-10 06:34:14 +00003710 assert(CachedFieldIndex && "failed to find field in parent");
3711 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003712}
3713
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003714SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003715 const Expr *FinalExpr = getInClassInitializer();
3716 if (!FinalExpr)
3717 FinalExpr = getBitWidth();
3718 if (FinalExpr)
3719 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3720 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003721}
3722
3723void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003724 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003725 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003726 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003727 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003728 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003729 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3730 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003731}
3732
Sebastian Redl833ef452010-01-26 22:01:41 +00003733//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003734// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003735//===----------------------------------------------------------------------===//
3736
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003737SourceLocation TagDecl::getOuterLocStart() const {
3738 return getTemplateOrInnerLocStart(this);
3739}
3740
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003741SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003742 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003743 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003744 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003745}
3746
Rafael Espindola8db352d2013-10-17 15:37:26 +00003747TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003748
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003749void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003750 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003751 if (const Type *T = getTypeForDecl()) {
3752 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003753 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003754 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003755 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003756}
3757
Douglas Gregordee1be82009-01-17 00:42:38 +00003758void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003759 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003760
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003761 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003762 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003763 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003764 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003765 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003766 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003767}
3768
3769void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003770 assert((!isa<CXXRecordDecl>(this) ||
3771 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3772 "definition completed but not started");
3773
John McCallf937c022011-10-07 06:10:15 +00003774 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003775 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003776
3777 if (ASTMutationListener *L = getASTMutationListener())
3778 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003779}
3780
John McCallf937c022011-10-07 06:10:15 +00003781TagDecl *TagDecl::getDefinition() const {
3782 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003783 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003784
3785 // If it's possible for us to have an out-of-date definition, check now.
3786 if (MayHaveOutOfDateDef) {
3787 if (IdentifierInfo *II = getIdentifier()) {
3788 if (II->isOutOfDate()) {
3789 updateOutOfDate(*II);
3790 }
3791 }
3792 }
3793
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003794 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003795 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003796
Aaron Ballman86c93902014-03-06 23:45:36 +00003797 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003798 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003799 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003800
Craig Topper36250ad2014-05-12 05:36:57 +00003801 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003802}
3803
Douglas Gregor14454802011-02-25 02:25:35 +00003804void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3805 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003806 // Make sure the extended qualifier info is allocated.
3807 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003808 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003809 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003810 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003811 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003812 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003813 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003814 if (getExtInfo()->NumTemplParamLists == 0) {
3815 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003816 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003817 }
3818 else
3819 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003820 }
3821 }
3822}
3823
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003824void TagDecl::setTemplateParameterListsInfo(
3825 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3826 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003827 // Make sure the extended decl info is allocated.
3828 if (!hasExtInfo())
3829 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003830 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003831 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003832 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003833}
3834
Ted Kremenek21475702008-09-05 17:16:31 +00003835//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003836// EnumDecl Implementation
3837//===----------------------------------------------------------------------===//
3838
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003839void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00003840
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003841EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3842 SourceLocation StartLoc, SourceLocation IdLoc,
3843 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003844 EnumDecl *PrevDecl, bool IsScoped,
3845 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003846 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3847 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003848 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003849 C.getTypeDeclType(Enum, PrevDecl);
3850 return Enum;
3851}
3852
Douglas Gregor72172e92012-01-05 21:55:30 +00003853EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003854 EnumDecl *Enum =
3855 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3856 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003857 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3858 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003859}
3860
Alp Tokerb9fa5122014-01-06 11:31:18 +00003861SourceRange EnumDecl::getIntegerTypeRange() const {
3862 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3863 return TI->getTypeLoc().getSourceRange();
3864 return SourceRange();
3865}
3866
Douglas Gregord5058122010-02-11 01:19:42 +00003867void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003868 QualType NewPromotionType,
3869 unsigned NumPositiveBits,
3870 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003871 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003872 if (!IntegerType)
3873 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003874 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003875 setNumPositiveBits(NumPositiveBits);
3876 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003877 TagDecl::completeDefinition();
3878}
3879
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003880bool EnumDecl::isClosed() const {
3881 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3882 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3883 return true;
3884}
3885
3886bool EnumDecl::isClosedFlag() const {
3887 return isClosed() && hasAttr<FlagEnumAttr>();
3888}
3889
3890bool EnumDecl::isClosedNonFlag() const {
3891 return isClosed() && !hasAttr<FlagEnumAttr>();
3892}
3893
Richard Smith7d137e32012-03-23 03:33:32 +00003894TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3895 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3896 return MSI->getTemplateSpecializationKind();
3897
3898 return TSK_Undeclared;
3899}
3900
3901void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3902 SourceLocation PointOfInstantiation) {
3903 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3904 assert(MSI && "Not an instantiated member enumeration?");
3905 MSI->setTemplateSpecializationKind(TSK);
3906 if (TSK != TSK_ExplicitSpecialization &&
3907 PointOfInstantiation.isValid() &&
3908 MSI->getPointOfInstantiation().isInvalid())
3909 MSI->setPointOfInstantiation(PointOfInstantiation);
3910}
3911
Richard Smith6739a102016-05-05 00:56:12 +00003912EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3913 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3914 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3915 EnumDecl *ED = getInstantiatedFromMemberEnum();
3916 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3917 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003918 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003919 }
3920 }
3921
3922 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3923 "couldn't find pattern for enum instantiation");
3924 return nullptr;
3925}
3926
Richard Smith4b38ded2012-03-14 23:13:10 +00003927EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3928 if (SpecializationInfo)
3929 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3930
Craig Topper36250ad2014-05-12 05:36:57 +00003931 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003932}
3933
3934void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3935 TemplateSpecializationKind TSK) {
3936 assert(!SpecializationInfo && "Member enum is already a specialization");
3937 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3938}
3939
Sebastian Redl833ef452010-01-26 22:01:41 +00003940//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003941// RecordDecl Implementation
3942//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003943
Richard Smith053f6c62014-05-16 23:01:30 +00003944RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3945 DeclContext *DC, SourceLocation StartLoc,
3946 SourceLocation IdLoc, IdentifierInfo *Id,
3947 RecordDecl *PrevDecl)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003948 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3949 HasFlexibleArrayMember(false), AnonymousStructOrUnion(false),
3950 HasObjectMember(false), HasVolatileMember(false),
Akira Hatanaka7275da02018-02-28 07:15:55 +00003951 LoadedFieldsFromExternalStorage(false),
3952 NonTrivialToPrimitiveDefaultInitialize(false),
Akira Hatanakad791e922018-03-19 17:38:40 +00003953 NonTrivialToPrimitiveCopy(false), NonTrivialToPrimitiveDestroy(false),
3954 CanPassInRegisters(true) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003955 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003956}
3957
Jay Foad39c79802011-01-12 09:06:06 +00003958RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003959 SourceLocation StartLoc, SourceLocation IdLoc,
3960 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003961 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3962 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003963 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3964
Ted Kremenek21475702008-09-05 17:16:31 +00003965 C.getTypeDeclType(R, PrevDecl);
3966 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003967}
3968
Douglas Gregor72172e92012-01-05 21:55:30 +00003969RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003970 RecordDecl *R =
3971 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3972 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003973 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3974 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003975}
3976
Douglas Gregordfcad112009-03-25 15:59:44 +00003977bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003978 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003979 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3980}
3981
Alexey Bataev39c81e22014-08-28 04:28:19 +00003982bool RecordDecl::isLambda() const {
3983 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3984 return RD->isLambda();
3985 return false;
3986}
3987
Alexey Bataev330de032014-10-29 12:21:55 +00003988bool RecordDecl::isCapturedRecord() const {
3989 return hasAttr<CapturedRecordAttr>();
3990}
3991
3992void RecordDecl::setCapturedRecord() {
3993 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3994}
3995
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003996RecordDecl::field_iterator RecordDecl::field_begin() const {
3997 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3998 LoadFieldsFromExternalStorage();
3999
4000 return field_iterator(decl_iterator(FirstDecl));
4001}
4002
Douglas Gregorb11aad82011-02-19 18:51:44 +00004003/// completeDefinition - Notes that the definition of this type is now
4004/// complete.
4005void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00004006 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00004007 TagDecl::completeDefinition();
4008}
4009
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004010/// isMsStruct - Get whether or not this record uses ms_struct layout.
4011/// This which can be turned on with an attribute, pragma, or the
4012/// -mms-bitfields command-line option.
4013bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00004014 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004015}
4016
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004017void RecordDecl::LoadFieldsFromExternalStorage() const {
4018 ExternalASTSource *Source = getASTContext().getExternalSource();
4019 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4020
4021 // Notify that we have a RecordDecl doing some initialization.
4022 ExternalASTSource::Deserializing TheFields(Source);
4023
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004024 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00004025 LoadedFieldsFromExternalStorage = true;
4026 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4027 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4028 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004029
4030#ifndef NDEBUG
4031 // Check that all decls we got were FieldDecls.
4032 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004033 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004034#endif
4035
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004036 if (Decls.empty())
4037 return;
4038
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004039 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004040 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004041}
4042
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004043bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4044 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004045 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4046 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4047 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004048 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004049 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004050 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004051 // We may be able to relax some of these requirements.
4052 int ReasonToReject = -1;
4053 if (!CXXRD || CXXRD->isExternCContext())
4054 ReasonToReject = 0; // is not C++.
4055 else if (CXXRD->hasAttr<PackedAttr>())
4056 ReasonToReject = 1; // is packed.
4057 else if (CXXRD->isUnion())
4058 ReasonToReject = 2; // is a union.
4059 else if (CXXRD->isTriviallyCopyable())
4060 ReasonToReject = 3; // is trivially copyable.
4061 else if (CXXRD->hasTrivialDestructor())
4062 ReasonToReject = 4; // has trivial destructor.
4063 else if (CXXRD->isStandardLayout())
4064 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004065 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4066 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004067 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004068 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4069 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004070 "field-padding"))
4071 ReasonToReject = 7; // is blacklisted.
4072
4073 if (EmitRemark) {
4074 if (ReasonToReject >= 0)
4075 Context.getDiagnostics().Report(
4076 getLocation(),
4077 diag::remark_sanitize_address_insert_extra_padding_rejected)
4078 << getQualifiedNameAsString() << ReasonToReject;
4079 else
4080 Context.getDiagnostics().Report(
4081 getLocation(),
4082 diag::remark_sanitize_address_insert_extra_padding_accepted)
4083 << getQualifiedNameAsString();
4084 }
4085 return ReasonToReject < 0;
4086}
4087
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004088const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4089 for (const auto *I : fields()) {
4090 if (I->getIdentifier())
4091 return I;
4092
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004093 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004094 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004095 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004096 return NamedDataMember;
4097 }
4098
4099 // We didn't find a named data member.
4100 return nullptr;
4101}
4102
Steve Naroff415d3d52008-10-08 17:01:13 +00004103//===----------------------------------------------------------------------===//
4104// BlockDecl Implementation
4105//===----------------------------------------------------------------------===//
4106
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004107void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004108 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004109
Steve Naroffc4b30e52009-03-13 16:56:44 +00004110 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004111 if (!NewParamInfo.empty()) {
4112 NumParams = NewParamInfo.size();
4113 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4114 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004115 }
4116}
4117
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004118void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4119 bool CapturesCXXThis) {
4120 this->CapturesCXXThis = CapturesCXXThis;
4121 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004122
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004123 if (Captures.empty()) {
4124 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004125 return;
4126 }
4127
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004128 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004129}
Sebastian Redl833ef452010-01-26 22:01:41 +00004130
John McCallce45f882011-06-15 22:51:16 +00004131bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004132 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004133 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004134 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004135 return true;
4136
4137 return false;
4138}
4139
Douglas Gregor70226da2010-12-21 16:27:07 +00004140SourceRange BlockDecl::getSourceRange() const {
4141 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4142}
Sebastian Redl833ef452010-01-26 22:01:41 +00004143
4144//===----------------------------------------------------------------------===//
4145// Other Decl Allocation/Deallocation Method Implementations
4146//===----------------------------------------------------------------------===//
4147
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004148void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004149
Sebastian Redl833ef452010-01-26 22:01:41 +00004150TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004151 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004152}
4153
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004154void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004155
4156PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4157 TranslationUnitDecl *DC,
4158 SourceLocation CommentLoc,
4159 PragmaMSCommentKind CommentKind,
4160 StringRef Arg) {
4161 PragmaCommentDecl *PCD =
4162 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4163 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4164 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4165 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4166 return PCD;
4167}
4168
4169PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4170 unsigned ID,
4171 unsigned ArgSize) {
4172 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4173 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4174}
4175
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004176void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004177
4178PragmaDetectMismatchDecl *
4179PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4180 SourceLocation Loc, StringRef Name,
4181 StringRef Value) {
4182 size_t ValueStart = Name.size() + 1;
4183 PragmaDetectMismatchDecl *PDMD =
4184 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4185 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4186 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4187 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4188 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4189 Value.size());
4190 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4191 return PDMD;
4192}
4193
4194PragmaDetectMismatchDecl *
4195PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4196 unsigned NameValueSize) {
4197 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4198 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4199}
Nico Weber66220292016-03-02 17:28:48 +00004200
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004201void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004202
4203ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4204 TranslationUnitDecl *DC) {
4205 return new (C, DC) ExternCContextDecl(DC);
4206}
4207
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004208void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004209
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004210LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004211 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004212 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004213}
4214
4215LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4216 SourceLocation IdentL, IdentifierInfo *II,
4217 SourceLocation GnuLabelL) {
4218 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004219 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004220}
4221
Douglas Gregor72172e92012-01-05 21:55:30 +00004222LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004223 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4224 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004225}
4226
Ehsan Akhgari31097582014-09-22 02:21:54 +00004227void LabelDecl::setMSAsmLabel(StringRef Name) {
4228 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4229 memcpy(Buffer, Name.data(), Name.size());
4230 Buffer[Name.size()] = '\0';
4231 MSAsmName = Buffer;
4232}
4233
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004234void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004235
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004236bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004237 for (const auto *I : attrs())
4238 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004239 return true;
4240
4241 return isWeakImported();
4242}
4243
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004244void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004245
Sebastian Redl833ef452010-01-26 22:01:41 +00004246ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004247 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004248 IdentifierInfo *Id, QualType Type,
4249 ImplicitParamKind ParamKind) {
4250 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4251}
4252
4253ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4254 ImplicitParamKind ParamKind) {
4255 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004256}
4257
Richard Smithf7981722013-11-22 09:01:48 +00004258ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004259 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004260 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004261}
4262
Sebastian Redl833ef452010-01-26 22:01:41 +00004263FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004264 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004265 const DeclarationNameInfo &NameInfo,
4266 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004267 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004268 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004269 bool hasWrittenPrototype,
4270 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004271 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004272 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4273 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004274 New->HasWrittenPrototype = hasWrittenPrototype;
4275 return New;
4276}
4277
Douglas Gregor72172e92012-01-05 21:55:30 +00004278FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004279 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004280 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004281 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004282}
4283
Sebastian Redl833ef452010-01-26 22:01:41 +00004284BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004285 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004286}
4287
Douglas Gregor72172e92012-01-05 21:55:30 +00004288BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004289 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004290}
4291
Chandler Carruth21c90602015-12-30 03:24:14 +00004292CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4293 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4294 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4295
Ben Langmuir37943a72013-05-03 19:00:33 +00004296CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4297 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004298 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004299 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004300}
4301
Ben Langmuirce914fc2013-05-03 19:20:19 +00004302CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004303 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004304 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004305 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004306}
4307
Chandler Carruth21c90602015-12-30 03:24:14 +00004308Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4309void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4310
4311bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4312void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4313
Sebastian Redl833ef452010-01-26 22:01:41 +00004314EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4315 SourceLocation L,
4316 IdentifierInfo *Id, QualType T,
4317 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004318 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004319}
4320
Douglas Gregor72172e92012-01-05 21:55:30 +00004321EnumConstantDecl *
4322EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004323 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4324 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004325}
4326
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004327void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004328
Richard Smith9f951822016-01-06 22:49:11 +00004329IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4330 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004331 QualType T,
4332 MutableArrayRef<NamedDecl *> CH)
4333 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4334 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004335 // In C++, indirect field declarations conflict with tag declarations in the
4336 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4337 if (C.getLangOpts().CPlusPlus)
4338 IdentifierNamespace |= IDNS_Tag;
4339}
4340
Benjamin Kramer39593702010-11-21 14:11:41 +00004341IndirectFieldDecl *
4342IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004343 IdentifierInfo *Id, QualType T,
4344 llvm::MutableArrayRef<NamedDecl *> CH) {
4345 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004346}
4347
Douglas Gregor72172e92012-01-05 21:55:30 +00004348IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4349 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004350 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004351 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004352}
4353
Douglas Gregorbe996932010-09-01 20:41:53 +00004354SourceRange EnumConstantDecl::getSourceRange() const {
4355 SourceLocation End = getLocation();
4356 if (Init)
4357 End = Init->getLocEnd();
4358 return SourceRange(getLocation(), End);
4359}
4360
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004361void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004362
Sebastian Redl833ef452010-01-26 22:01:41 +00004363TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004364 SourceLocation StartLoc, SourceLocation IdLoc,
4365 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004366 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004367}
4368
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004369void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004370
Richard Smith42413142015-05-15 20:05:43 +00004371TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4372 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4373 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4374 auto *ThisTypedef = this;
4375 if (AnyRedecl && OwningTypedef) {
4376 OwningTypedef = OwningTypedef->getCanonicalDecl();
4377 ThisTypedef = ThisTypedef->getCanonicalDecl();
4378 }
4379 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004380 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004381 }
Richard Smitha5230222015-03-27 01:37:43 +00004382
4383 return nullptr;
4384}
4385
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004386bool TypedefNameDecl::isTransparentTagSlow() const {
4387 auto determineIsTransparent = [&]() {
4388 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4389 if (auto *TD = TT->getDecl()) {
4390 if (TD->getName() != getName())
4391 return false;
4392 SourceLocation TTLoc = getLocation();
4393 SourceLocation TDLoc = TD->getLocation();
4394 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4395 return false;
4396 SourceManager &SM = getASTContext().getSourceManager();
4397 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4398 }
4399 }
4400 return false;
4401 };
4402
4403 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004404 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004405 return isTransparent;
4406}
4407
Douglas Gregor72172e92012-01-05 21:55:30 +00004408TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004409 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004410 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004411}
4412
Richard Smithdda56e42011-04-15 14:24:37 +00004413TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4414 SourceLocation StartLoc,
4415 SourceLocation IdLoc, IdentifierInfo *Id,
4416 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004417 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004418}
4419
Douglas Gregor72172e92012-01-05 21:55:30 +00004420TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004421 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4422 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004423}
4424
Abramo Bagnaraea947882011-03-08 16:41:52 +00004425SourceRange TypedefDecl::getSourceRange() const {
4426 SourceLocation RangeEnd = getLocation();
4427 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4428 if (typeIsPostfix(TInfo->getType()))
4429 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4430 }
4431 return SourceRange(getLocStart(), RangeEnd);
4432}
4433
Richard Smithdda56e42011-04-15 14:24:37 +00004434SourceRange TypeAliasDecl::getSourceRange() const {
4435 SourceLocation RangeEnd = getLocStart();
4436 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4437 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4438 return SourceRange(getLocStart(), RangeEnd);
4439}
4440
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004441void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004442
Sebastian Redl833ef452010-01-26 22:01:41 +00004443FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004444 StringLiteral *Str,
4445 SourceLocation AsmLoc,
4446 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004447 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004448}
Douglas Gregorba345522011-12-02 23:23:56 +00004449
Richard Smithf7981722013-11-22 09:01:48 +00004450FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004451 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004452 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4453 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004454}
4455
Michael Han84324352013-02-22 17:15:32 +00004456void EmptyDecl::anchor() {}
4457
4458EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004459 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004460}
4461
4462EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004463 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004464}
4465
Douglas Gregorba345522011-12-02 23:23:56 +00004466//===----------------------------------------------------------------------===//
4467// ImportDecl Implementation
4468//===----------------------------------------------------------------------===//
4469
4470/// \brief Retrieve the number of module identifiers needed to name the given
4471/// module.
4472static unsigned getNumModuleIdentifiers(Module *Mod) {
4473 unsigned Result = 1;
4474 while (Mod->Parent) {
4475 Mod = Mod->Parent;
4476 ++Result;
4477 }
4478 return Result;
4479}
4480
Douglas Gregor22d09742012-01-03 18:04:46 +00004481ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004482 Module *Imported,
4483 ArrayRef<SourceLocation> IdentifierLocs)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004484 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004485 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004486 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004487 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4488 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004489}
4490
Douglas Gregor22d09742012-01-03 18:04:46 +00004491ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004492 Module *Imported, SourceLocation EndLoc)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004493 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004494 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004495}
4496
Richard Smithf7981722013-11-22 09:01:48 +00004497ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004498 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004499 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004500 return new (C, DC,
4501 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004502 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004503}
4504
Richard Smithf7981722013-11-22 09:01:48 +00004505ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004506 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004507 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004508 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004509 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4510 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004511 Import->setImplicit();
4512 return Import;
4513}
4514
Douglas Gregor72172e92012-01-05 21:55:30 +00004515ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4516 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004517 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004518 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004519}
4520
4521ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4522 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004523 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004524
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004525 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004526 return llvm::makeArrayRef(StoredLocs,
4527 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004528}
4529
4530SourceRange ImportDecl::getSourceRange() const {
4531 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004532 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4533
Douglas Gregorba345522011-12-02 23:23:56 +00004534 return SourceRange(getLocation(), getIdentifierLocs().back());
4535}
Richard Smith8df390f2016-09-08 23:14:54 +00004536
4537//===----------------------------------------------------------------------===//
4538// ExportDecl Implementation
4539//===----------------------------------------------------------------------===//
4540
4541void ExportDecl::anchor() {}
4542
4543ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4544 SourceLocation ExportLoc) {
4545 return new (C, DC) ExportDecl(DC, ExportLoc);
4546}
4547
4548ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4549 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4550}