blob: 479f80f1dd4d4cddb7cb0b33243d0eb65faa2d34 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Douglas Gregor889ceb72009-02-03 19:21:40 +000015#include "clang/AST/DeclCXX.h"
Steve Naroffc4173fa2009-02-22 19:35:57 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregore362cea2009-05-10 22:57:19 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000018#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Stmt.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +000024#include "clang/AST/ASTMutationListener.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000026#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000027#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000028#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000029#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000030#include "llvm/Support/ErrorHandling.h"
Ted Kremenekce20e8f2008-05-20 00:43:19 +000031
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Chris Lattner88f70d62008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
Douglas Gregor1baf38f2011-03-26 12:10:19 +000040static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41 // If this declaration has an explicit visibility attribute, use it.
42 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43 switch (A->getVisibility()) {
44 case VisibilityAttr::Default:
45 return DefaultVisibility;
46 case VisibilityAttr::Hidden:
47 return HiddenVisibility;
48 case VisibilityAttr::Protected:
49 return ProtectedVisibility;
50 }
John McCall659a3372010-12-18 03:30:47 +000051
John McCall457a04e2010-10-22 21:05:15 +000052 return DefaultVisibility;
John McCall457a04e2010-10-22 21:05:15 +000053 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +000054
55 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
56 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +000057 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +000058 for (specific_attr_iterator<AvailabilityAttr>
59 A = D->specific_attr_begin<AvailabilityAttr>(),
60 AEnd = D->specific_attr_end<AvailabilityAttr>();
61 A != AEnd; ++A)
62 if ((*A)->getPlatform()->getName().equals("macosx"))
63 return DefaultVisibility;
64 }
65
66 return llvm::Optional<Visibility>();
John McCall457a04e2010-10-22 21:05:15 +000067}
68
John McCallc273f242010-10-30 11:50:40 +000069typedef NamedDecl::LinkageInfo LinkageInfo;
John McCall457a04e2010-10-22 21:05:15 +000070typedef std::pair<Linkage,Visibility> LVPair;
John McCallc273f242010-10-30 11:50:40 +000071
John McCall457a04e2010-10-22 21:05:15 +000072static LVPair merge(LVPair L, LVPair R) {
73 return LVPair(minLinkage(L.first, R.first),
74 minVisibility(L.second, R.second));
75}
76
John McCallc273f242010-10-30 11:50:40 +000077static LVPair merge(LVPair L, LinkageInfo R) {
78 return LVPair(minLinkage(L.first, R.linkage()),
79 minVisibility(L.second, R.visibility()));
80}
81
Benjamin Kramer396dcf32010-11-05 19:56:37 +000082namespace {
John McCall07072662010-11-02 01:45:15 +000083/// Flags controlling the computation of linkage and visibility.
84struct LVFlags {
85 bool ConsiderGlobalVisibility;
86 bool ConsiderVisibilityAttributes;
John McCall8bc6d5b2011-03-04 10:39:25 +000087 bool ConsiderTemplateParameterTypes;
John McCall07072662010-11-02 01:45:15 +000088
89 LVFlags() : ConsiderGlobalVisibility(true),
John McCall8bc6d5b2011-03-04 10:39:25 +000090 ConsiderVisibilityAttributes(true),
91 ConsiderTemplateParameterTypes(true) {
John McCall07072662010-11-02 01:45:15 +000092 }
93
Douglas Gregorbf62d642010-12-06 18:36:25 +000094 /// \brief Returns a set of flags that is only useful for computing the
95 /// linkage, not the visibility, of a declaration.
96 static LVFlags CreateOnlyDeclLinkage() {
97 LVFlags F;
98 F.ConsiderGlobalVisibility = false;
99 F.ConsiderVisibilityAttributes = false;
John McCall8bc6d5b2011-03-04 10:39:25 +0000100 F.ConsiderTemplateParameterTypes = false;
Douglas Gregorbf62d642010-12-06 18:36:25 +0000101 return F;
102 }
103
John McCall07072662010-11-02 01:45:15 +0000104 /// Returns a set of flags, otherwise based on these, which ignores
105 /// off all sources of visibility except template arguments.
106 LVFlags onlyTemplateVisibility() const {
107 LVFlags F = *this;
108 F.ConsiderGlobalVisibility = false;
109 F.ConsiderVisibilityAttributes = false;
John McCall8bc6d5b2011-03-04 10:39:25 +0000110 F.ConsiderTemplateParameterTypes = false;
John McCall07072662010-11-02 01:45:15 +0000111 return F;
112 }
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000113};
Benjamin Kramer396dcf32010-11-05 19:56:37 +0000114} // end anonymous namespace
John McCall07072662010-11-02 01:45:15 +0000115
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000116/// \brief Get the most restrictive linkage for the types in the given
117/// template parameter list.
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000118static LVPair
John McCall457a04e2010-10-22 21:05:15 +0000119getLVForTemplateParameterList(const TemplateParameterList *Params) {
120 LVPair LV(ExternalLinkage, DefaultVisibility);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000121 for (TemplateParameterList::const_iterator P = Params->begin(),
122 PEnd = Params->end();
123 P != PEnd; ++P) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000124 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 if (NTTP->isExpandedParameterPack()) {
126 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
127 QualType T = NTTP->getExpansionType(I);
128 if (!T->isDependentType())
129 LV = merge(LV, T->getLinkageAndVisibility());
130 }
131 continue;
132 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000133
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000134 if (!NTTP->getType()->isDependentType()) {
John McCall457a04e2010-10-22 21:05:15 +0000135 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000136 continue;
137 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000138 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000139
140 if (TemplateTemplateParmDecl *TTP
141 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
John McCallc273f242010-10-30 11:50:40 +0000142 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000143 }
144 }
145
John McCall457a04e2010-10-22 21:05:15 +0000146 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000147}
148
Douglas Gregorbf62d642010-12-06 18:36:25 +0000149/// getLVForDecl - Get the linkage and visibility for the given declaration.
150static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
151
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000152/// \brief Get the most restrictive linkage for the types and
153/// declarations in the given template argument list.
John McCall457a04e2010-10-22 21:05:15 +0000154static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
Douglas Gregorbf62d642010-12-06 18:36:25 +0000155 unsigned NumArgs,
156 LVFlags &F) {
John McCall457a04e2010-10-22 21:05:15 +0000157 LVPair LV(ExternalLinkage, DefaultVisibility);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000158
159 for (unsigned I = 0; I != NumArgs; ++I) {
160 switch (Args[I].getKind()) {
161 case TemplateArgument::Null:
162 case TemplateArgument::Integral:
163 case TemplateArgument::Expression:
164 break;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000165
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000166 case TemplateArgument::Type:
John McCall457a04e2010-10-22 21:05:15 +0000167 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000168 break;
169
170 case TemplateArgument::Declaration:
John McCall457a04e2010-10-22 21:05:15 +0000171 // The decl can validly be null as the representation of nullptr
172 // arguments, valid only in C++0x.
173 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000174 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
175 LV = merge(LV, getLVForDecl(ND, F));
John McCall457a04e2010-10-22 21:05:15 +0000176 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000177 break;
178
179 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000180 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000181 if (TemplateDecl *Template
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000182 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000183 LV = merge(LV, getLVForDecl(Template, F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000184 break;
185
186 case TemplateArgument::Pack:
John McCall457a04e2010-10-22 21:05:15 +0000187 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
Douglas Gregorbf62d642010-12-06 18:36:25 +0000188 Args[I].pack_size(),
189 F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000190 break;
191 }
192 }
193
John McCall457a04e2010-10-22 21:05:15 +0000194 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000195}
196
John McCallc273f242010-10-30 11:50:40 +0000197static LVPair
Douglas Gregorbf62d642010-12-06 18:36:25 +0000198getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
199 LVFlags &F) {
200 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
John McCall8823c652010-08-13 08:35:10 +0000201}
202
John McCallb8c604a2011-06-27 23:06:04 +0000203static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
204 const FunctionTemplateSpecializationInfo *spec) {
205 return !(spec->isExplicitSpecialization() &&
206 fn->hasAttr<VisibilityAttr>());
207}
208
209static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
210 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
211}
212
John McCall07072662010-11-02 01:45:15 +0000213static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000214 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000215 "Not a name having namespace scope");
216 ASTContext &Context = D->getASTContext();
217
218 // C++ [basic.link]p3:
219 // A name having namespace scope (3.3.6) has internal linkage if it
220 // is the name of
221 // - an object, reference, function or function template that is
222 // explicitly declared static; or,
223 // (This bullet corresponds to C99 6.2.2p3.)
224 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
225 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000226 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000227 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000228
229 // - an object or reference that is explicitly declared const
230 // and neither explicitly declared extern nor previously
231 // declared to have external linkage; or
232 // (there is no equivalent in C99)
233 if (Context.getLangOptions().CPlusPlus &&
Eli Friedmanf873c2f2009-11-26 03:04:01 +0000234 Var->getType().isConstant(Context) &&
John McCall8e7d6562010-08-26 03:08:43 +0000235 Var->getStorageClass() != SC_Extern &&
236 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000237 bool FoundExtern = false;
238 for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
239 PrevVar && !FoundExtern;
240 PrevVar = PrevVar->getPreviousDeclaration())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000241 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000242 FoundExtern = true;
243
244 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000245 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000246 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000247 if (Var->getStorageClass() == SC_None) {
248 const VarDecl *PrevVar = Var->getPreviousDeclaration();
249 for (; PrevVar; PrevVar = PrevVar->getPreviousDeclaration())
250 if (PrevVar->getStorageClass() == SC_PrivateExtern)
251 break;
252 if (PrevVar)
253 return PrevVar->getLinkageAndVisibility();
254 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000255 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000256 // C++ [temp]p4:
257 // A non-member function template can have internal linkage; any
258 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000259 const FunctionDecl *Function = 0;
260 if (const FunctionTemplateDecl *FunTmpl
261 = dyn_cast<FunctionTemplateDecl>(D))
262 Function = FunTmpl->getTemplatedDecl();
263 else
264 Function = cast<FunctionDecl>(D);
265
266 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000267 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000268 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000269 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
270 // - a data member of an anonymous union.
271 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000272 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000273 }
274
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000275 if (D->isInAnonymousNamespace()) {
276 const VarDecl *Var = dyn_cast<VarDecl>(D);
277 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
278 if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
279 return LinkageInfo::uniqueExternal();
280 }
John McCallb7139c42010-10-28 04:18:25 +0000281
John McCall457a04e2010-10-22 21:05:15 +0000282 // Set up the defaults.
283
284 // C99 6.2.2p5:
285 // If the declaration of an identifier for an object has file
286 // scope and no storage-class specifier, its linkage is
287 // external.
John McCallc273f242010-10-30 11:50:40 +0000288 LinkageInfo LV;
289
John McCall07072662010-11-02 01:45:15 +0000290 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000291 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
292 LV.setVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000293 F.ConsiderGlobalVisibility = false;
John McCall2faf32c2010-12-10 02:59:44 +0000294 } else {
295 // If we're declared in a namespace with a visibility attribute,
296 // use that namespace's visibility, but don't call it explicit.
297 for (const DeclContext *DC = D->getDeclContext();
298 !isa<TranslationUnitDecl>(DC);
299 DC = DC->getParent()) {
Rafael Espindola09593a32012-01-01 17:48:19 +0000300 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
301 if (!ND) continue;
302 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
Rafael Espindola0f960a02012-01-01 18:06:40 +0000303 LV.setVisibility(*Vis, true);
John McCall2faf32c2010-12-10 02:59:44 +0000304 F.ConsiderGlobalVisibility = false;
305 break;
306 }
307 }
John McCall07072662010-11-02 01:45:15 +0000308 }
John McCallc273f242010-10-30 11:50:40 +0000309 }
John McCall457a04e2010-10-22 21:05:15 +0000310
Douglas Gregorf73b2822009-11-25 22:24:25 +0000311 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000312
Douglas Gregorf73b2822009-11-25 22:24:25 +0000313 // A name having namespace scope has external linkage if it is the
314 // name of
315 //
316 // - an object or reference, unless it has internal linkage; or
317 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000318 // GCC applies the following optimization to variables and static
319 // data members, but not to functions:
320 //
John McCall457a04e2010-10-22 21:05:15 +0000321 // Modify the variable's LV by the LV of its type unless this is
322 // C or extern "C". This follows from [basic.link]p9:
323 // A type without linkage shall not be used as the type of a
324 // variable or function with external linkage unless
325 // - the entity has C language linkage, or
326 // - the entity is declared within an unnamed namespace, or
327 // - the entity is not used or is defined in the same
328 // translation unit.
329 // and [basic.link]p10:
330 // ...the types specified by all declarations referring to a
331 // given variable or function shall be identical...
332 // C does not have an equivalent rule.
333 //
John McCall5fe84122010-10-26 04:59:26 +0000334 // Ignore this if we've got an explicit attribute; the user
335 // probably knows what they're doing.
336 //
John McCall457a04e2010-10-22 21:05:15 +0000337 // Note that we don't want to make the variable non-external
338 // because of this, but unique-external linkage suits us.
John McCall36cd5cc2010-10-30 09:18:49 +0000339 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
John McCall457a04e2010-10-22 21:05:15 +0000340 LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
341 if (TypeLV.first != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000342 return LinkageInfo::uniqueExternal();
343 if (!LV.visibilityExplicit())
344 LV.mergeVisibility(TypeLV.second);
John McCall37bb6c92010-10-29 22:22:43 +0000345 }
346
John McCall23032652010-11-02 18:38:13 +0000347 if (Var->getStorageClass() == SC_PrivateExtern)
348 LV.setVisibility(HiddenVisibility, true);
349
Douglas Gregorf73b2822009-11-25 22:24:25 +0000350 if (!Context.getLangOptions().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000351 (Var->getStorageClass() == SC_Extern ||
352 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall457a04e2010-10-22 21:05:15 +0000353
Douglas Gregorf73b2822009-11-25 22:24:25 +0000354 // C99 6.2.2p4:
355 // For an identifier declared with the storage-class specifier
356 // extern in a scope in which a prior declaration of that
357 // identifier is visible, if the prior declaration specifies
358 // internal or external linkage, the linkage of the identifier
359 // at the later declaration is the same as the linkage
360 // specified at the prior declaration. If no prior declaration
361 // is visible, or if the prior declaration specifies no
362 // linkage, then the identifier has external linkage.
363 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000364 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
John McCallc273f242010-10-30 11:50:40 +0000365 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
366 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000367 }
368 }
369
Douglas Gregorf73b2822009-11-25 22:24:25 +0000370 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000371 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000372 // In theory, we can modify the function's LV by the LV of its
373 // type unless it has C linkage (see comment above about variables
374 // for justification). In practice, GCC doesn't do this, so it's
375 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000376
John McCall23032652010-11-02 18:38:13 +0000377 if (Function->getStorageClass() == SC_PrivateExtern)
378 LV.setVisibility(HiddenVisibility, true);
379
Douglas Gregorf73b2822009-11-25 22:24:25 +0000380 // C99 6.2.2p5:
381 // If the declaration of an identifier for a function has no
382 // storage-class specifier, its linkage is determined exactly
383 // as if it were declared with the storage-class specifier
384 // extern.
385 if (!Context.getLangOptions().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000386 (Function->getStorageClass() == SC_Extern ||
387 Function->getStorageClass() == SC_PrivateExtern ||
388 Function->getStorageClass() == SC_None)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000389 // C99 6.2.2p4:
390 // For an identifier declared with the storage-class specifier
391 // extern in a scope in which a prior declaration of that
392 // identifier is visible, if the prior declaration specifies
393 // internal or external linkage, the linkage of the identifier
394 // at the later declaration is the same as the linkage
395 // specified at the prior declaration. If no prior declaration
396 // is visible, or if the prior declaration specifies no
397 // linkage, then the identifier has external linkage.
398 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000399 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
John McCallc273f242010-10-30 11:50:40 +0000400 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
401 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000402 }
403 }
404
John McCallf768aa72011-02-10 06:50:24 +0000405 // In C++, then if the type of the function uses a type with
406 // unique-external linkage, it's not legally usable from outside
407 // this translation unit. However, we should use the C linkage
408 // rules instead for extern "C" declarations.
409 if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
410 Function->getType()->getLinkage() == UniqueExternalLinkage)
411 return LinkageInfo::uniqueExternal();
412
John McCallb8c604a2011-06-27 23:06:04 +0000413 // Consider LV from the template and the template arguments unless
414 // this is an explicit specialization with a visibility attribute.
415 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000416 = Function->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000417 if (shouldConsiderTemplateLV(Function, specInfo)) {
418 LV.merge(getLVForDecl(specInfo->getTemplate(),
419 F.onlyTemplateVisibility()));
420 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
421 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
422 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000423 }
424
Douglas Gregorf73b2822009-11-25 22:24:25 +0000425 // - a named class (Clause 9), or an unnamed class defined in a
426 // typedef declaration in which the class has the typedef name
427 // for linkage purposes (7.1.3); or
428 // - a named enumeration (7.2), or an unnamed enumeration
429 // defined in a typedef declaration in which the enumeration
430 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000431 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
432 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000433 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000434 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000435
John McCall457a04e2010-10-22 21:05:15 +0000436 // If this is a class template specialization, consider the
437 // linkage of the template and template arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000438 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000439 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCallb8c604a2011-06-27 23:06:04 +0000440 if (shouldConsiderTemplateLV(spec)) {
441 // From the template.
442 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
443 F.onlyTemplateVisibility()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000444
John McCallb8c604a2011-06-27 23:06:04 +0000445 // The arguments at which the template was instantiated.
446 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
447 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
448 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000449 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000450
John McCall5fe84122010-10-26 04:59:26 +0000451 // Consider -fvisibility unless the type has C linkage.
John McCall07072662010-11-02 01:45:15 +0000452 if (F.ConsiderGlobalVisibility)
453 F.ConsiderGlobalVisibility =
John McCall5fe84122010-10-26 04:59:26 +0000454 (Context.getLangOptions().CPlusPlus &&
455 !Tag->getDeclContext()->isExternCContext());
John McCall457a04e2010-10-22 21:05:15 +0000456
Douglas Gregorf73b2822009-11-25 22:24:25 +0000457 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000458 } else if (isa<EnumConstantDecl>(D)) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000459 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
John McCallc273f242010-10-30 11:50:40 +0000460 if (!isExternalLinkage(EnumLV.linkage()))
461 return LinkageInfo::none();
462 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000463
464 // - a template, unless it is a function template that has
465 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000466 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
467 if (F.ConsiderTemplateParameterTypes)
468 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000469
Douglas Gregorf73b2822009-11-25 22:24:25 +0000470 // - a namespace (7.3), unless it is declared within an unnamed
471 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000472 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
473 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000474
John McCall457a04e2010-10-22 21:05:15 +0000475 // By extension, we assign external linkage to Objective-C
476 // interfaces.
477 } else if (isa<ObjCInterfaceDecl>(D)) {
478 // fallout
479
480 // Everything not covered here has no linkage.
481 } else {
John McCallc273f242010-10-30 11:50:40 +0000482 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000483 }
484
485 // If we ended up with non-external linkage, visibility should
486 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000487 if (LV.linkage() != ExternalLinkage)
488 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000489
490 // If we didn't end up with hidden visibility, consider attributes
491 // and -fvisibility.
John McCall07072662010-11-02 01:45:15 +0000492 if (F.ConsiderGlobalVisibility)
John McCallc273f242010-10-30 11:50:40 +0000493 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
John McCall457a04e2010-10-22 21:05:15 +0000494
495 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000496}
497
John McCall07072662010-11-02 01:45:15 +0000498static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
John McCall457a04e2010-10-22 21:05:15 +0000499 // Only certain class members have linkage. Note that fields don't
500 // really have linkage, but it's convenient to say they do for the
501 // purposes of calculating linkage of pointer-to-data-member
502 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000503 if (!(isa<CXXMethodDecl>(D) ||
504 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000505 isa<FieldDecl>(D) ||
John McCall8823c652010-08-13 08:35:10 +0000506 (isa<TagDecl>(D) &&
Richard Smithdda56e42011-04-15 14:24:37 +0000507 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallc273f242010-10-30 11:50:40 +0000508 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000509
John McCall07072662010-11-02 01:45:15 +0000510 LinkageInfo LV;
511
512 // The flags we're going to use to compute the class's visibility.
513 LVFlags ClassF = F;
514
515 // If we have an explicit visibility attribute, merge that in.
516 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000517 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
518 LV.mergeVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000519
520 // Ignore global visibility later, but not this attribute.
521 F.ConsiderGlobalVisibility = false;
522
523 // Ignore both global visibility and attributes when computing our
524 // parent's visibility.
525 ClassF = F.onlyTemplateVisibility();
526 }
527 }
John McCallc273f242010-10-30 11:50:40 +0000528
529 // Class members only have linkage if their class has external
John McCall07072662010-11-02 01:45:15 +0000530 // linkage.
531 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
532 if (!isExternalLinkage(LV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000533 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000534
535 // If the class already has unique-external linkage, we can't improve.
John McCall07072662010-11-02 01:45:15 +0000536 if (LV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000537 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000538
John McCall8823c652010-08-13 08:35:10 +0000539 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000540 // If the type of the function uses a type with unique-external
541 // linkage, it's not legally usable from outside this translation unit.
542 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
543 return LinkageInfo::uniqueExternal();
544
John McCall37bb6c92010-10-29 22:22:43 +0000545 TemplateSpecializationKind TSK = TSK_Undeclared;
546
John McCall457a04e2010-10-22 21:05:15 +0000547 // If this is a method template specialization, use the linkage for
548 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000549 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000550 = MD->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000551 if (shouldConsiderTemplateLV(MD, spec)) {
552 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
553 if (F.ConsiderTemplateParameterTypes)
554 LV.merge(getLVForTemplateParameterList(
555 spec->getTemplate()->getTemplateParameters()));
556 }
John McCall37bb6c92010-10-29 22:22:43 +0000557
John McCallb8c604a2011-06-27 23:06:04 +0000558 TSK = spec->getTemplateSpecializationKind();
John McCall37bb6c92010-10-29 22:22:43 +0000559 } else if (MemberSpecializationInfo *MSI =
560 MD->getMemberSpecializationInfo()) {
561 TSK = MSI->getTemplateSpecializationKind();
John McCall8823c652010-08-13 08:35:10 +0000562 }
563
John McCall37bb6c92010-10-29 22:22:43 +0000564 // If we're paying attention to global visibility, apply
565 // -finline-visibility-hidden if this is an inline method.
566 //
John McCallc273f242010-10-30 11:50:40 +0000567 // Note that ConsiderGlobalVisibility doesn't yet have information
568 // about whether containing classes have visibility attributes,
569 // and that's intentional.
570 if (TSK != TSK_ExplicitInstantiationDeclaration &&
Rafael Espindola0b790462011-12-27 21:15:28 +0000571 TSK != TSK_ExplicitInstantiationDefinition &&
John McCall07072662010-11-02 01:45:15 +0000572 F.ConsiderGlobalVisibility &&
John McCalle6e622e2010-11-01 01:29:57 +0000573 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
574 // InlineVisibilityHidden only applies to definitions, and
575 // isInlined() only gives meaningful answers on definitions
576 // anyway.
577 const FunctionDecl *Def = 0;
578 if (MD->hasBody(Def) && Def->isInlined())
579 LV.setVisibility(HiddenVisibility);
580 }
John McCall457a04e2010-10-22 21:05:15 +0000581
John McCall37bb6c92010-10-29 22:22:43 +0000582 // Note that in contrast to basically every other situation, we
583 // *do* apply -fvisibility to method declarations.
584
585 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000586 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000587 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCallb8c604a2011-06-27 23:06:04 +0000588 if (shouldConsiderTemplateLV(spec)) {
589 // Merge template argument/parameter information for member
590 // class template specializations.
591 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
John McCall8bc6d5b2011-03-04 10:39:25 +0000592 if (F.ConsiderTemplateParameterTypes)
593 LV.merge(getLVForTemplateParameterList(
John McCallb8c604a2011-06-27 23:06:04 +0000594 spec->getSpecializedTemplate()->getTemplateParameters()));
595 }
John McCall37bb6c92010-10-29 22:22:43 +0000596 }
597
John McCall37bb6c92010-10-29 22:22:43 +0000598 // Static data members.
599 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000600 // Modify the variable's linkage by its type, but ignore the
601 // type's visibility unless it's a definition.
602 LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
603 if (TypeLV.first != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000604 LV.mergeLinkage(UniqueExternalLinkage);
605 if (!LV.visibilityExplicit())
606 LV.mergeVisibility(TypeLV.second);
John McCall37bb6c92010-10-29 22:22:43 +0000607 }
608
John McCall07072662010-11-02 01:45:15 +0000609 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
John McCall37bb6c92010-10-29 22:22:43 +0000610
611 // Apply -fvisibility if desired.
John McCall07072662010-11-02 01:45:15 +0000612 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
John McCallc273f242010-10-30 11:50:40 +0000613 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
John McCall8823c652010-08-13 08:35:10 +0000614 }
615
John McCall457a04e2010-10-22 21:05:15 +0000616 return LV;
John McCall8823c652010-08-13 08:35:10 +0000617}
618
John McCalld396b972011-02-08 19:01:05 +0000619static void clearLinkageForClass(const CXXRecordDecl *record) {
620 for (CXXRecordDecl::decl_iterator
621 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
622 Decl *child = *i;
623 if (isa<NamedDecl>(child))
624 cast<NamedDecl>(child)->ClearLinkageCache();
625 }
626}
627
David Blaikie68e081d2011-12-20 02:48:34 +0000628void NamedDecl::anchor() { }
629
John McCalld396b972011-02-08 19:01:05 +0000630void NamedDecl::ClearLinkageCache() {
631 // Note that we can't skip clearing the linkage of children just
632 // because the parent doesn't have cached linkage: we don't cache
633 // when computing linkage for parent contexts.
634
635 HasCachedLinkage = 0;
636
637 // If we're changing the linkage of a class, we need to reset the
638 // linkage of child declarations, too.
639 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
640 clearLinkageForClass(record);
641
John McCall83779672011-02-19 02:53:41 +0000642 if (ClassTemplateDecl *temp =
643 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCalld396b972011-02-08 19:01:05 +0000644 // Clear linkage for the template pattern.
645 CXXRecordDecl *record = temp->getTemplatedDecl();
646 record->HasCachedLinkage = 0;
647 clearLinkageForClass(record);
648
John McCall83779672011-02-19 02:53:41 +0000649 // We need to clear linkage for specializations, too.
650 for (ClassTemplateDecl::spec_iterator
651 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
652 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000653 }
John McCall83779672011-02-19 02:53:41 +0000654
655 // Clear cached linkage for function template decls, too.
656 if (FunctionTemplateDecl *temp =
John McCall8f9a4292011-03-22 06:58:49 +0000657 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
658 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000659 for (FunctionTemplateDecl::spec_iterator
660 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
661 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000662 }
John McCall83779672011-02-19 02:53:41 +0000663
John McCalld396b972011-02-08 19:01:05 +0000664}
665
Douglas Gregorbf62d642010-12-06 18:36:25 +0000666Linkage NamedDecl::getLinkage() const {
667 if (HasCachedLinkage) {
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000668 assert(Linkage(CachedLinkage) ==
669 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000670 return Linkage(CachedLinkage);
671 }
672
673 CachedLinkage = getLVForDecl(this,
674 LVFlags::CreateOnlyDeclLinkage()).linkage();
675 HasCachedLinkage = 1;
676 return Linkage(CachedLinkage);
677}
678
John McCallc273f242010-10-30 11:50:40 +0000679LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000680 LinkageInfo LI = getLVForDecl(this, LVFlags());
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000681 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000682 HasCachedLinkage = 1;
683 CachedLinkage = LI.linkage();
684 return LI;
John McCall033caa52010-10-29 00:29:13 +0000685}
Ted Kremenek926d8602010-04-20 23:15:35 +0000686
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000687llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
688 // Use the most recent declaration of a variable.
689 if (const VarDecl *var = dyn_cast<VarDecl>(this))
690 return getVisibilityOf(var->getMostRecentDeclaration());
691
692 // Use the most recent declaration of a function, and also handle
693 // function template specializations.
694 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
695 if (llvm::Optional<Visibility> V
696 = getVisibilityOf(fn->getMostRecentDeclaration()))
697 return V;
698
699 // If the function is a specialization of a template with an
700 // explicit visibility attribute, use that.
701 if (FunctionTemplateSpecializationInfo *templateInfo
702 = fn->getTemplateSpecializationInfo())
703 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
704
705 return llvm::Optional<Visibility>();
706 }
707
708 // Otherwise, just check the declaration itself first.
709 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
710 return V;
711
712 // If there wasn't explicit visibility there, and this is a
713 // specialization of a class template, check for visibility
714 // on the pattern.
715 if (const ClassTemplateSpecializationDecl *spec
716 = dyn_cast<ClassTemplateSpecializationDecl>(this))
717 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
718
719 return llvm::Optional<Visibility>();
720}
721
John McCall07072662010-11-02 01:45:15 +0000722static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000723 // Objective-C: treat all Objective-C declarations as having external
724 // linkage.
John McCall033caa52010-10-29 00:29:13 +0000725 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000726 default:
727 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +0000728 case Decl::ParmVar:
729 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000730 case Decl::TemplateTemplateParm: // count these as external
731 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +0000732 case Decl::ObjCAtDefsField:
733 case Decl::ObjCCategory:
734 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +0000735 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +0000736 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +0000737 case Decl::ObjCMethod:
738 case Decl::ObjCProperty:
739 case Decl::ObjCPropertyImpl:
740 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +0000741 return LinkageInfo::external();
Ted Kremenek926d8602010-04-20 23:15:35 +0000742 }
743
Douglas Gregorf73b2822009-11-25 22:24:25 +0000744 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +0000745 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall07072662010-11-02 01:45:15 +0000746 return getLVForNamespaceScopeDecl(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000747
748 // C++ [basic.link]p5:
749 // In addition, a member function, static data member, a named
750 // class or enumeration of class scope, or an unnamed class or
751 // enumeration defined in a class-scope typedef declaration such
752 // that the class or enumeration has the typedef name for linkage
753 // purposes (7.1.3), has external linkage if the name of the class
754 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +0000755 if (D->getDeclContext()->isRecord())
John McCall07072662010-11-02 01:45:15 +0000756 return getLVForClassMember(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000757
758 // C++ [basic.link]p6:
759 // The name of a function declared in block scope and the name of
760 // an object declared by a block scope extern declaration have
761 // linkage. If there is a visible declaration of an entity with
762 // linkage having the same name and type, ignoring entities
763 // declared outside the innermost enclosing namespace scope, the
764 // block scope declaration declares that same entity and receives
765 // the linkage of the previous declaration. If there is more than
766 // one such matching entity, the program is ill-formed. Otherwise,
767 // if no matching entity is found, the block scope entity receives
768 // external linkage.
John McCall033caa52010-10-29 00:29:13 +0000769 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
770 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Chandler Carruth4322a282011-02-25 00:05:02 +0000771 if (Function->isInAnonymousNamespace() && !Function->isExternC())
John McCallc273f242010-10-30 11:50:40 +0000772 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000773
John McCallc273f242010-10-30 11:50:40 +0000774 LinkageInfo LV;
Douglas Gregorbf62d642010-12-06 18:36:25 +0000775 if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000776 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
777 LV.setVisibility(*Vis);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000778 }
779
John McCall457a04e2010-10-22 21:05:15 +0000780 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000781 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000782 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
783 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000784 }
785
786 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000787 }
788
John McCall033caa52010-10-29 00:29:13 +0000789 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCall8e7d6562010-08-26 03:08:43 +0000790 if (Var->getStorageClass() == SC_Extern ||
791 Var->getStorageClass() == SC_PrivateExtern) {
Chandler Carruth4322a282011-02-25 00:05:02 +0000792 if (Var->isInAnonymousNamespace() && !Var->isExternC())
John McCallc273f242010-10-30 11:50:40 +0000793 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000794
John McCallc273f242010-10-30 11:50:40 +0000795 LinkageInfo LV;
John McCall457a04e2010-10-22 21:05:15 +0000796 if (Var->getStorageClass() == SC_PrivateExtern)
John McCallc273f242010-10-30 11:50:40 +0000797 LV.setVisibility(HiddenVisibility);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000798 else if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000799 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
800 LV.setVisibility(*Vis);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000801 }
802
John McCall457a04e2010-10-22 21:05:15 +0000803 if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000804 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000805 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
806 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000807 }
808
809 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000810 }
811 }
812
813 // C++ [basic.link]p6:
814 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +0000815 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000816}
Douglas Gregorf73b2822009-11-25 22:24:25 +0000817
Douglas Gregor2ada0482009-02-04 17:27:36 +0000818std::string NamedDecl::getQualifiedNameAsString() const {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000819 return getQualifiedNameAsString(getASTContext().getLangOptions());
820}
821
822std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000823 const DeclContext *Ctx = getDeclContext();
824
825 if (Ctx->isFunctionOrMethod())
826 return getNameAsString();
827
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000828 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000829 ContextsTy Contexts;
830
831 // Collect contexts.
832 while (Ctx && isa<NamedDecl>(Ctx)) {
833 Contexts.push_back(Ctx);
834 Ctx = Ctx->getParent();
835 };
836
837 std::string QualName;
838 llvm::raw_string_ostream OS(QualName);
839
840 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
841 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000842 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000843 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +0000844 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
845 std::string TemplateArgsStr
846 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +0000847 TemplateArgs.data(),
848 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +0000849 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000850 OS << Spec->getName() << TemplateArgsStr;
851 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +0000852 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000853 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +0000854 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000855 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000856 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
857 if (!RD->getIdentifier())
858 OS << "<anonymous " << RD->getKindName() << '>';
859 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000860 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000861 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +0000862 const FunctionProtoType *FT = 0;
863 if (FD->hasWrittenPrototype())
864 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
865
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000866 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +0000867 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +0000868 unsigned NumParams = FD->getNumParams();
869 for (unsigned i = 0; i < NumParams; ++i) {
870 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000871 OS << ", ";
Sam Weinigb999f682009-12-28 03:19:38 +0000872 std::string Param;
873 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000874 OS << Param;
Sam Weinigb999f682009-12-28 03:19:38 +0000875 }
876
877 if (FT->isVariadic()) {
878 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000879 OS << ", ";
880 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +0000881 }
882 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000883 OS << ')';
884 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000885 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000886 }
887 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000888 }
889
John McCalla2a3f7d2010-03-16 21:48:18 +0000890 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000891 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +0000892 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000893 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000894
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000895 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +0000896}
897
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000898bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000899 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
900
Douglas Gregor889ceb72009-02-03 19:21:40 +0000901 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
902 // We want to keep it, unless it nominates same namespace.
903 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +0000904 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
905 ->getOriginalNamespace() ==
906 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
907 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000910 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
911 // For function declarations, we keep track of redeclarations.
912 return FD->getPreviousDeclaration() == OldD;
913
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000914 // For function templates, the underlying function declarations are linked.
915 if (const FunctionTemplateDecl *FunctionTemplate
916 = dyn_cast<FunctionTemplateDecl>(this))
917 if (const FunctionTemplateDecl *OldFunctionTemplate
918 = dyn_cast<FunctionTemplateDecl>(OldD))
919 return FunctionTemplate->getTemplatedDecl()
920 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000921
Steve Naroffc4173fa2009-02-22 19:35:57 +0000922 // For method declarations, we keep track of redeclarations.
923 if (isa<ObjCMethodDecl>(this))
924 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000925
John McCall9f3059a2009-10-09 21:13:30 +0000926 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
927 return true;
928
John McCall3f746822009-11-17 05:59:44 +0000929 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
930 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
931 cast<UsingShadowDecl>(OldD)->getTargetDecl();
932
Douglas Gregora9d87bc2011-02-25 00:36:19 +0000933 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
934 ASTContext &Context = getASTContext();
935 return Context.getCanonicalNestedNameSpecifier(
936 cast<UsingDecl>(this)->getQualifier()) ==
937 Context.getCanonicalNestedNameSpecifier(
938 cast<UsingDecl>(OldD)->getQualifier());
939 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +0000940
Douglas Gregorb59643b2012-01-03 23:26:26 +0000941 // A typedef of an Objective-C class type can replace an Objective-C class
942 // declaration or definition, and vice versa.
943 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
944 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
945 return true;
946
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000947 // For non-function declarations, if the declarations are of the
948 // same kind then this must be a redeclaration, or semantic analysis
949 // would not have given us the new declaration.
950 return this->getKind() == OldD->getKind();
951}
952
Douglas Gregoreddf4332009-02-24 20:03:32 +0000953bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000954 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000955}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000956
Anders Carlsson6915bf62009-06-26 06:29:23 +0000957NamedDecl *NamedDecl::getUnderlyingDecl() {
958 NamedDecl *ND = this;
959 while (true) {
John McCall3f746822009-11-17 05:59:44 +0000960 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
Anders Carlsson6915bf62009-06-26 06:29:23 +0000961 ND = UD->getTargetDecl();
962 else if (ObjCCompatibleAliasDecl *AD
963 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
964 return AD->getClassInterface();
965 else
966 return ND;
967 }
968}
969
John McCalla8ae2222010-04-06 21:38:20 +0000970bool NamedDecl::isCXXInstanceMember() const {
971 assert(isCXXClassMember() &&
972 "checking whether non-member is instance member");
973
974 const NamedDecl *D = this;
975 if (isa<UsingShadowDecl>(D))
976 D = cast<UsingShadowDecl>(D)->getTargetDecl();
977
Francois Pichet783dd6e2010-11-21 06:08:52 +0000978 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +0000979 return true;
980 if (isa<CXXMethodDecl>(D))
981 return cast<CXXMethodDecl>(D)->isInstance();
982 if (isa<FunctionTemplateDecl>(D))
983 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
984 ->getTemplatedDecl())->isInstance();
985 return false;
986}
987
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000988//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000989// DeclaratorDecl Implementation
990//===----------------------------------------------------------------------===//
991
Douglas Gregorec9c6ae2010-07-06 18:42:40 +0000992template <typename DeclT>
993static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
994 if (decl->getNumTemplateParameterLists() > 0)
995 return decl->getTemplateParameterList(0)->getTemplateLoc();
996 else
997 return decl->getInnerLocStart();
998}
999
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001000SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001001 TypeSourceInfo *TSI = getTypeSourceInfo();
1002 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001003 return SourceLocation();
1004}
1005
Douglas Gregor14454802011-02-25 02:25:35 +00001006void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1007 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001008 // Make sure the extended decl info is allocated.
1009 if (!hasExtInfo()) {
1010 // Save (non-extended) type source info pointer.
1011 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1012 // Allocate external info struct.
1013 DeclInfo = new (getASTContext()) ExtInfo;
1014 // Restore savedTInfo into (extended) decl info.
1015 getExtInfo()->TInfo = savedTInfo;
1016 }
1017 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001018 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001019 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001020 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001021 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001022 if (getExtInfo()->NumTemplParamLists == 0) {
1023 // Save type source info pointer.
1024 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1025 // Deallocate the extended decl info.
1026 getASTContext().Deallocate(getExtInfo());
1027 // Restore savedTInfo into (non-extended) decl info.
1028 DeclInfo = savedTInfo;
1029 }
1030 else
1031 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001032 }
1033 }
1034}
1035
Abramo Bagnara60804e12011-03-18 15:16:37 +00001036void
1037DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1038 unsigned NumTPLists,
1039 TemplateParameterList **TPLists) {
1040 assert(NumTPLists > 0);
1041 // Make sure the extended decl info is allocated.
1042 if (!hasExtInfo()) {
1043 // Save (non-extended) type source info pointer.
1044 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1045 // Allocate external info struct.
1046 DeclInfo = new (getASTContext()) ExtInfo;
1047 // Restore savedTInfo into (extended) decl info.
1048 getExtInfo()->TInfo = savedTInfo;
1049 }
1050 // Set the template parameter lists info.
1051 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1052}
1053
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001054SourceLocation DeclaratorDecl::getOuterLocStart() const {
1055 return getTemplateOrInnerLocStart(this);
1056}
1057
Abramo Bagnaraea947882011-03-08 16:41:52 +00001058namespace {
1059
1060// Helper function: returns true if QT is or contains a type
1061// having a postfix component.
1062bool typeIsPostfix(clang::QualType QT) {
1063 while (true) {
1064 const Type* T = QT.getTypePtr();
1065 switch (T->getTypeClass()) {
1066 default:
1067 return false;
1068 case Type::Pointer:
1069 QT = cast<PointerType>(T)->getPointeeType();
1070 break;
1071 case Type::BlockPointer:
1072 QT = cast<BlockPointerType>(T)->getPointeeType();
1073 break;
1074 case Type::MemberPointer:
1075 QT = cast<MemberPointerType>(T)->getPointeeType();
1076 break;
1077 case Type::LValueReference:
1078 case Type::RValueReference:
1079 QT = cast<ReferenceType>(T)->getPointeeType();
1080 break;
1081 case Type::PackExpansion:
1082 QT = cast<PackExpansionType>(T)->getPattern();
1083 break;
1084 case Type::Paren:
1085 case Type::ConstantArray:
1086 case Type::DependentSizedArray:
1087 case Type::IncompleteArray:
1088 case Type::VariableArray:
1089 case Type::FunctionProto:
1090 case Type::FunctionNoProto:
1091 return true;
1092 }
1093 }
1094}
1095
1096} // namespace
1097
1098SourceRange DeclaratorDecl::getSourceRange() const {
1099 SourceLocation RangeEnd = getLocation();
1100 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1101 if (typeIsPostfix(TInfo->getType()))
1102 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1103 }
1104 return SourceRange(getOuterLocStart(), RangeEnd);
1105}
1106
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001107void
Douglas Gregor20527e22010-06-15 17:44:38 +00001108QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1109 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001110 TemplateParameterList **TPLists) {
1111 assert((NumTPLists == 0 || TPLists != 0) &&
1112 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001113
1114 // Free previous template parameters (if any).
1115 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001116 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001117 TemplParamLists = 0;
1118 NumTemplParamLists = 0;
1119 }
1120 // Set info on matched template parameter lists (if any).
1121 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001122 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001123 NumTemplParamLists = NumTPLists;
1124 for (unsigned i = NumTPLists; i-- > 0; )
1125 TemplParamLists[i] = TPLists[i];
1126 }
1127}
1128
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001129//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001130// VarDecl Implementation
1131//===----------------------------------------------------------------------===//
1132
Sebastian Redl833ef452010-01-26 22:01:41 +00001133const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1134 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001135 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001136 case SC_Auto: return "auto";
1137 case SC_Extern: return "extern";
1138 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1139 case SC_PrivateExtern: return "__private_extern__";
1140 case SC_Register: return "register";
1141 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001142 }
1143
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001144 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001145 return 0;
1146}
1147
Abramo Bagnaradff19302011-03-08 08:55:46 +00001148VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1149 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001150 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001151 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001152 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001153}
1154
Douglas Gregorbf62d642010-12-06 18:36:25 +00001155void VarDecl::setStorageClass(StorageClass SC) {
1156 assert(isLegalForVariable(SC));
1157 if (getStorageClass() != SC)
1158 ClearLinkageCache();
1159
John McCallbeaa11c2011-05-01 02:13:58 +00001160 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001161}
1162
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001163SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001164 if (getInit())
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001165 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00001166 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001167}
1168
Sebastian Redl833ef452010-01-26 22:01:41 +00001169bool VarDecl::isExternC() const {
1170 ASTContext &Context = getASTContext();
1171 if (!Context.getLangOptions().CPlusPlus)
1172 return (getDeclContext()->isTranslationUnit() &&
John McCall8e7d6562010-08-26 03:08:43 +00001173 getStorageClass() != SC_Static) ||
Sebastian Redl833ef452010-01-26 22:01:41 +00001174 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
1175
Chandler Carruth4322a282011-02-25 00:05:02 +00001176 const DeclContext *DC = getDeclContext();
1177 if (DC->isFunctionOrMethod())
1178 return false;
1179
1180 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001181 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1182 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
John McCall8e7d6562010-08-26 03:08:43 +00001183 return getStorageClass() != SC_Static;
Sebastian Redl833ef452010-01-26 22:01:41 +00001184
1185 break;
1186 }
1187
Sebastian Redl833ef452010-01-26 22:01:41 +00001188 }
1189
1190 return false;
1191}
1192
1193VarDecl *VarDecl::getCanonicalDecl() {
1194 return getFirstDeclaration();
1195}
1196
Sebastian Redl35351a92010-01-31 22:27:38 +00001197VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1198 // C++ [basic.def]p2:
1199 // A declaration is a definition unless [...] it contains the 'extern'
1200 // specifier or a linkage-specification and neither an initializer [...],
1201 // it declares a static data member in a class declaration [...].
1202 // C++ [temp.expl.spec]p15:
1203 // An explicit specialization of a static data member of a template is a
1204 // definition if the declaration includes an initializer; otherwise, it is
1205 // a declaration.
1206 if (isStaticDataMember()) {
1207 if (isOutOfLine() && (hasInit() ||
1208 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1209 return Definition;
1210 else
1211 return DeclarationOnly;
1212 }
1213 // C99 6.7p5:
1214 // A definition of an identifier is a declaration for that identifier that
1215 // [...] causes storage to be reserved for that object.
1216 // Note: that applies for all non-file-scope objects.
1217 // C99 6.9.2p1:
1218 // If the declaration of an identifier for an object has file scope and an
1219 // initializer, the declaration is an external definition for the identifier
1220 if (hasInit())
1221 return Definition;
1222 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1223 if (hasExternalStorage())
1224 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001225
John McCall8e7d6562010-08-26 03:08:43 +00001226 if (getStorageClassAsWritten() == SC_Extern ||
1227 getStorageClassAsWritten() == SC_PrivateExtern) {
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001228 for (const VarDecl *PrevVar = getPreviousDeclaration();
1229 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
1230 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1231 return DeclarationOnly;
1232 }
1233 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001234 // C99 6.9.2p2:
1235 // A declaration of an object that has file scope without an initializer,
1236 // and without a storage class specifier or the scs 'static', constitutes
1237 // a tentative definition.
1238 // No such thing in C++.
1239 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1240 return TentativeDefinition;
1241
1242 // What's left is (in C, block-scope) declarations without initializers or
1243 // external storage. These are definitions.
1244 return Definition;
1245}
1246
Sebastian Redl35351a92010-01-31 22:27:38 +00001247VarDecl *VarDecl::getActingDefinition() {
1248 DefinitionKind Kind = isThisDeclarationADefinition();
1249 if (Kind != TentativeDefinition)
1250 return 0;
1251
Chris Lattner48eb14d2010-06-14 18:31:46 +00001252 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001253 VarDecl *First = getFirstDeclaration();
1254 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1255 I != E; ++I) {
1256 Kind = (*I)->isThisDeclarationADefinition();
1257 if (Kind == Definition)
1258 return 0;
1259 else if (Kind == TentativeDefinition)
1260 LastTentative = *I;
1261 }
1262 return LastTentative;
1263}
1264
1265bool VarDecl::isTentativeDefinitionNow() const {
1266 DefinitionKind Kind = isThisDeclarationADefinition();
1267 if (Kind != TentativeDefinition)
1268 return false;
1269
1270 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1271 if ((*I)->isThisDeclarationADefinition() == Definition)
1272 return false;
1273 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001274 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001275}
1276
Sebastian Redl5ca79842010-02-01 20:16:42 +00001277VarDecl *VarDecl::getDefinition() {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001278 VarDecl *First = getFirstDeclaration();
1279 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1280 I != E; ++I) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001281 if ((*I)->isThisDeclarationADefinition() == Definition)
1282 return *I;
1283 }
1284 return 0;
1285}
1286
John McCall37bb6c92010-10-29 22:22:43 +00001287VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1288 DefinitionKind Kind = DeclarationOnly;
1289
1290 const VarDecl *First = getFirstDeclaration();
1291 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1292 I != E; ++I)
1293 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1294
1295 return Kind;
1296}
1297
Sebastian Redl5ca79842010-02-01 20:16:42 +00001298const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001299 redecl_iterator I = redecls_begin(), E = redecls_end();
1300 while (I != E && !I->getInit())
1301 ++I;
1302
1303 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001304 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001305 return I->getInit();
1306 }
1307 return 0;
1308}
1309
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001310bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001311 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001312 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001313
1314 if (!isStaticDataMember())
1315 return false;
1316
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001317 // If this static data member was instantiated from a static data member of
1318 // a class template, check whether that static data member was defined
1319 // out-of-line.
1320 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1321 return VD->isOutOfLine();
1322
1323 return false;
1324}
1325
Douglas Gregor1d957a32009-10-27 18:42:08 +00001326VarDecl *VarDecl::getOutOfLineDefinition() {
1327 if (!isStaticDataMember())
1328 return 0;
1329
1330 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1331 RD != RDEnd; ++RD) {
1332 if (RD->getLexicalDeclContext()->isFileContext())
1333 return *RD;
1334 }
1335
1336 return 0;
1337}
1338
Douglas Gregord5058122010-02-11 01:19:42 +00001339void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001340 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1341 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001342 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001343 }
1344
1345 Init = I;
1346}
1347
Richard Smith242ad892011-12-21 02:55:12 +00001348bool VarDecl::isUsableInConstantExpressions() const {
1349 const LangOptions &Lang = getASTContext().getLangOptions();
1350
1351 // Only const variables can be used in constant expressions in C++. C++98 does
1352 // not require the variable to be non-volatile, but we consider this to be a
1353 // defect.
1354 if (!Lang.CPlusPlus ||
1355 !getType().isConstQualified() || getType().isVolatileQualified())
1356 return false;
1357
1358 // In C++, const, non-volatile variables of integral or enumeration types
1359 // can be used in constant expressions.
1360 if (getType()->isIntegralOrEnumerationType())
1361 return true;
1362
1363 // Additionally, in C++11, non-volatile constexpr variables and references can
1364 // be used in constant expressions.
1365 return Lang.CPlusPlus0x && (isConstexpr() || getType()->isReferenceType());
1366}
1367
Richard Smithd0b4dd62011-12-19 06:19:21 +00001368/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1369/// form, which contains extra information on the evaluated value of the
1370/// initializer.
1371EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1372 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1373 if (!Eval) {
1374 Stmt *S = Init.get<Stmt *>();
1375 Eval = new (getASTContext()) EvaluatedStmt;
1376 Eval->Value = S;
1377 Init = Eval;
1378 }
1379 return Eval;
1380}
1381
1382bool VarDecl::evaluateValue(
1383 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1384 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1385
1386 // We only produce notes indicating why an initializer is non-constant the
1387 // first time it is evaluated. FIXME: The notes won't always be emitted the
1388 // first time we try evaluation, so might not be produced at all.
1389 if (Eval->WasEvaluated)
1390 return !Eval->Evaluated.isUninit();
1391
1392 const Expr *Init = cast<Expr>(Eval->Value);
1393 assert(!Init->isValueDependent());
1394
1395 if (Eval->IsEvaluating) {
1396 // FIXME: Produce a diagnostic for self-initialization.
1397 Eval->CheckedICE = true;
1398 Eval->IsICE = false;
1399 return false;
1400 }
1401
1402 Eval->IsEvaluating = true;
1403
1404 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1405 this, Notes);
1406
1407 // Ensure the result is an uninitialized APValue if evaluation fails.
1408 if (!Result)
1409 Eval->Evaluated = APValue();
1410
1411 Eval->IsEvaluating = false;
1412 Eval->WasEvaluated = true;
1413
1414 // In C++11, we have determined whether the initializer was a constant
1415 // expression as a side-effect.
1416 if (getASTContext().getLangOptions().CPlusPlus0x && !Eval->CheckedICE) {
1417 Eval->CheckedICE = true;
1418 Eval->IsICE = Notes.empty();
1419 }
1420
1421 return Result;
1422}
1423
1424bool VarDecl::checkInitIsICE() const {
1425 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1426 if (Eval->CheckedICE)
1427 // We have already checked whether this subexpression is an
1428 // integral constant expression.
1429 return Eval->IsICE;
1430
1431 const Expr *Init = cast<Expr>(Eval->Value);
1432 assert(!Init->isValueDependent());
1433
1434 // In C++11, evaluate the initializer to check whether it's a constant
1435 // expression.
1436 if (getASTContext().getLangOptions().CPlusPlus0x) {
1437 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1438 evaluateValue(Notes);
1439 return Eval->IsICE;
1440 }
1441
1442 // It's an ICE whether or not the definition we found is
1443 // out-of-line. See DR 721 and the discussion in Clang PR
1444 // 6206 for details.
1445
1446 if (Eval->CheckingICE)
1447 return false;
1448 Eval->CheckingICE = true;
1449
1450 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1451 Eval->CheckingICE = false;
1452 Eval->CheckedICE = true;
1453 return Eval->IsICE;
1454}
1455
Douglas Gregorfe314812011-06-21 17:03:29 +00001456bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001457 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001458
1459 const Expr *E = getInit();
1460 if (!E)
1461 return false;
1462
1463 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1464 E = Cleanups->getSubExpr();
1465
1466 return isa<MaterializeTemporaryExpr>(E);
1467}
1468
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001469VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001470 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001471 return cast<VarDecl>(MSI->getInstantiatedFrom());
1472
1473 return 0;
1474}
1475
Douglas Gregor3c74d412009-10-14 20:14:33 +00001476TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001477 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001478 return MSI->getTemplateSpecializationKind();
1479
1480 return TSK_Undeclared;
1481}
1482
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001483MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001484 return getASTContext().getInstantiatedFromStaticDataMember(this);
1485}
1486
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001487void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1488 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001489 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001490 assert(MSI && "Not an instantiated static data member?");
1491 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001492 if (TSK != TSK_ExplicitSpecialization &&
1493 PointOfInstantiation.isValid() &&
1494 MSI->getPointOfInstantiation().isInvalid())
1495 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001496}
1497
Sebastian Redl833ef452010-01-26 22:01:41 +00001498//===----------------------------------------------------------------------===//
1499// ParmVarDecl Implementation
1500//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001501
Sebastian Redl833ef452010-01-26 22:01:41 +00001502ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001503 SourceLocation StartLoc,
1504 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001505 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001506 StorageClass S, StorageClass SCAsWritten,
1507 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001508 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001509 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001510}
1511
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001512SourceRange ParmVarDecl::getSourceRange() const {
1513 if (!hasInheritedDefaultArg()) {
1514 SourceRange ArgRange = getDefaultArgRange();
1515 if (ArgRange.isValid())
1516 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1517 }
1518
1519 return DeclaratorDecl::getSourceRange();
1520}
1521
Sebastian Redl833ef452010-01-26 22:01:41 +00001522Expr *ParmVarDecl::getDefaultArg() {
1523 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1524 assert(!hasUninstantiatedDefaultArg() &&
1525 "Default argument is not yet instantiated!");
1526
1527 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001528 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001529 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001530
Sebastian Redl833ef452010-01-26 22:01:41 +00001531 return Arg;
1532}
1533
Sebastian Redl833ef452010-01-26 22:01:41 +00001534SourceRange ParmVarDecl::getDefaultArgRange() const {
1535 if (const Expr *E = getInit())
1536 return E->getSourceRange();
1537
1538 if (hasUninstantiatedDefaultArg())
1539 return getUninstantiatedDefaultArg()->getSourceRange();
1540
1541 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001542}
1543
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001544bool ParmVarDecl::isParameterPack() const {
1545 return isa<PackExpansionType>(getType());
1546}
1547
Ted Kremenek540017e2011-10-06 05:00:56 +00001548void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1549 getASTContext().setParameterIndex(this, parameterIndex);
1550 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1551}
1552
1553unsigned ParmVarDecl::getParameterIndexLarge() const {
1554 return getASTContext().getParameterIndex(this);
1555}
1556
Nuno Lopes394ec982008-12-17 23:39:55 +00001557//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001558// FunctionDecl Implementation
1559//===----------------------------------------------------------------------===//
1560
Douglas Gregorb11aad82011-02-19 18:51:44 +00001561void FunctionDecl::getNameForDiagnostic(std::string &S,
1562 const PrintingPolicy &Policy,
1563 bool Qualified) const {
1564 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1565 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1566 if (TemplateArgs)
1567 S += TemplateSpecializationType::PrintTemplateArgumentList(
1568 TemplateArgs->data(),
1569 TemplateArgs->size(),
1570 Policy);
1571
1572}
1573
Ted Kremenek186a0742010-04-29 16:49:01 +00001574bool FunctionDecl::isVariadic() const {
1575 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1576 return FT->isVariadic();
1577 return false;
1578}
1579
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001580bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1581 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001582 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001583 Definition = *I;
1584 return true;
1585 }
1586 }
1587
1588 return false;
1589}
1590
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001591bool FunctionDecl::hasTrivialBody() const
1592{
1593 Stmt *S = getBody();
1594 if (!S) {
1595 // Since we don't have a body for this function, we don't know if it's
1596 // trivial or not.
1597 return false;
1598 }
1599
1600 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1601 return true;
1602 return false;
1603}
1604
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001605bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1606 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001607 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001608 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1609 return true;
1610 }
1611 }
1612
1613 return false;
1614}
1615
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001616Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001617 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1618 if (I->Body) {
1619 Definition = *I;
1620 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001621 } else if (I->IsLateTemplateParsed) {
1622 Definition = *I;
1623 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001624 }
1625 }
1626
1627 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001628}
1629
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001630void FunctionDecl::setBody(Stmt *B) {
1631 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00001632 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001633 EndRangeLoc = B->getLocEnd();
1634}
1635
Douglas Gregor7d9120c2010-09-28 21:55:22 +00001636void FunctionDecl::setPure(bool P) {
1637 IsPure = P;
1638 if (P)
1639 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1640 Parent->markedVirtualFunctionPure();
1641}
1642
Douglas Gregor16618f22009-09-12 00:17:51 +00001643bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00001644 const TranslationUnitDecl *tunit =
1645 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1646 return tunit &&
Alexis Huntf9933e82011-05-15 20:59:31 +00001647 !tunit->getASTContext().getLangOptions().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00001648 getIdentifier() &&
1649 getIdentifier()->isStr("main");
1650}
1651
1652bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1653 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1654 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1655 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1656 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1657 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1658
1659 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1660 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1661
1662 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1663 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1664
1665 ASTContext &Context =
1666 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1667 ->getASTContext();
1668
1669 // The result type and first argument type are constant across all
1670 // these operators. The second argument must be exactly void*.
1671 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001672}
1673
Douglas Gregor16618f22009-09-12 00:17:51 +00001674bool FunctionDecl::isExternC() const {
1675 ASTContext &Context = getASTContext();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001676 // In C, any non-static, non-overloadable function has external
1677 // linkage.
1678 if (!Context.getLangOptions().CPlusPlus)
John McCall8e7d6562010-08-26 03:08:43 +00001679 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001680
Chandler Carruth4322a282011-02-25 00:05:02 +00001681 const DeclContext *DC = getDeclContext();
1682 if (DC->isRecord())
1683 return false;
1684
1685 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001686 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1687 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
John McCall8e7d6562010-08-26 03:08:43 +00001688 return getStorageClass() != SC_Static &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001689 !getAttr<OverloadableAttr>();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001690
1691 break;
1692 }
1693 }
1694
Douglas Gregorbff62032010-10-21 16:57:46 +00001695 return isMain();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001696}
1697
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001698bool FunctionDecl::isGlobal() const {
1699 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1700 return Method->isStatic();
1701
John McCall8e7d6562010-08-26 03:08:43 +00001702 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001703 return false;
1704
Mike Stump11289f42009-09-09 15:08:12 +00001705 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001706 DC->isNamespace();
1707 DC = DC->getParent()) {
1708 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1709 if (!Namespace->getDeclName())
1710 return false;
1711 break;
1712 }
1713 }
1714
1715 return true;
1716}
1717
Sebastian Redl833ef452010-01-26 22:01:41 +00001718void
1719FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1720 redeclarable_base::setPreviousDeclaration(PrevDecl);
1721
1722 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1723 FunctionTemplateDecl *PrevFunTmpl
1724 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1725 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1726 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1727 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00001728
Axel Naumannfbc7b982011-11-08 18:21:06 +00001729 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00001730 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00001731}
1732
1733const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1734 return getFirstDeclaration();
1735}
1736
1737FunctionDecl *FunctionDecl::getCanonicalDecl() {
1738 return getFirstDeclaration();
1739}
1740
Douglas Gregorbf62d642010-12-06 18:36:25 +00001741void FunctionDecl::setStorageClass(StorageClass SC) {
1742 assert(isLegalForFunction(SC));
1743 if (getStorageClass() != SC)
1744 ClearLinkageCache();
1745
1746 SClass = SC;
1747}
1748
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001749/// \brief Returns a value indicating whether this function
1750/// corresponds to a builtin function.
1751///
1752/// The function corresponds to a built-in function if it is
1753/// declared at translation scope or within an extern "C" block and
1754/// its name matches with the name of a builtin. The returned value
1755/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00001756/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001757/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001758unsigned FunctionDecl::getBuiltinID() const {
1759 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00001760 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1761 return 0;
1762
1763 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1764 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1765 return BuiltinID;
1766
1767 // This function has the name of a known C library
1768 // function. Determine whether it actually refers to the C library
1769 // function or whether it just has the same name.
1770
Douglas Gregora908e7f2009-02-17 03:23:10 +00001771 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00001772 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00001773 return 0;
1774
Douglas Gregore711f702009-02-14 18:57:46 +00001775 // If this function is at translation-unit scope and we're not in
1776 // C++, it refers to the C library function.
1777 if (!Context.getLangOptions().CPlusPlus &&
1778 getDeclContext()->isTranslationUnit())
1779 return BuiltinID;
1780
1781 // If the function is in an extern "C" linkage specification and is
1782 // not marked "overloadable", it's the real function.
1783 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001784 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00001785 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001786 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00001787 return BuiltinID;
1788
1789 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001790 return 0;
1791}
1792
1793
Chris Lattner47c0d002009-04-25 06:03:53 +00001794/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00001795/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00001796/// after it has been created.
1797unsigned FunctionDecl::getNumParams() const {
John McCall9dd450b2009-09-21 23:43:11 +00001798 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001799 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00001800 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001801 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00001802
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001803}
1804
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00001805void FunctionDecl::setParams(ASTContext &C,
David Blaikie9c70e042011-09-21 18:16:56 +00001806 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001807 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00001808 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00001809
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001810 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00001811 if (!NewParamInfo.empty()) {
1812 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1813 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001814 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001815}
Chris Lattner41943152007-01-25 04:52:46 +00001816
Chris Lattner58258242008-04-10 02:22:51 +00001817/// getMinRequiredArguments - Returns the minimum number of arguments
1818/// needed to call this function. This may be fewer than the number of
1819/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00001820/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00001821unsigned FunctionDecl::getMinRequiredArguments() const {
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001822 if (!getASTContext().getLangOptions().CPlusPlus)
1823 return getNumParams();
1824
Douglas Gregor7825bf32011-01-06 22:09:01 +00001825 unsigned NumRequiredArgs = getNumParams();
1826
1827 // If the last parameter is a parameter pack, we don't need an argument for
1828 // it.
1829 if (NumRequiredArgs > 0 &&
1830 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1831 --NumRequiredArgs;
1832
1833 // If this parameter has a default argument, we don't need an argument for
1834 // it.
1835 while (NumRequiredArgs > 0 &&
1836 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00001837 --NumRequiredArgs;
1838
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001839 // We might have parameter packs before the end. These can't be deduced,
1840 // but they can still handle multiple arguments.
1841 unsigned ArgIdx = NumRequiredArgs;
1842 while (ArgIdx > 0) {
1843 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1844 NumRequiredArgs = ArgIdx;
1845
1846 --ArgIdx;
1847 }
1848
Chris Lattner58258242008-04-10 02:22:51 +00001849 return NumRequiredArgs;
1850}
1851
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001852bool FunctionDecl::isInlined() const {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001853 if (IsInline)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001854 return true;
Anders Carlssoncfb65d72009-12-04 22:35:50 +00001855
1856 if (isa<CXXMethodDecl>(this)) {
1857 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1858 return true;
1859 }
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001860
1861 switch (getTemplateSpecializationKind()) {
1862 case TSK_Undeclared:
1863 case TSK_ExplicitSpecialization:
1864 return false;
1865
1866 case TSK_ImplicitInstantiation:
1867 case TSK_ExplicitInstantiationDeclaration:
1868 case TSK_ExplicitInstantiationDefinition:
1869 // Handle below.
1870 break;
1871 }
1872
1873 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001874 bool HasPattern = false;
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001875 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001876 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001877
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001878 if (HasPattern && PatternDecl)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001879 return PatternDecl->isInlined();
1880
1881 return false;
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001882}
1883
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001884/// \brief For a function declaration in C or C++, determine whether this
1885/// declaration causes the definition to be externally visible.
1886///
1887/// Determines whether this is the first non-inline redeclaration of an inline
1888/// function in a language where "inline" does not normally require an
1889/// externally visible definition.
1890bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1891 assert(!doesThisDeclarationHaveABody() &&
1892 "Must have a declaration without a body.");
1893
1894 ASTContext &Context = getASTContext();
1895
1896 // In C99 mode, a function may have an inline definition (causing it to
1897 // be deferred) then redeclared later. As a special case, "extern inline"
1898 // is not required to produce an external symbol.
1899 if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
1900 Context.getLangOptions().CPlusPlus)
1901 return false;
1902 if (getLinkage() != ExternalLinkage || isInlineSpecified())
1903 return false;
Nick Lewyckyba4cc012011-07-18 07:11:55 +00001904 const FunctionDecl *Definition = 0;
1905 if (hasBody(Definition))
1906 return Definition->isInlined() &&
1907 Definition->isInlineDefinitionExternallyVisible();
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001908 return false;
1909}
1910
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001911/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001912/// definition will be externally visible.
1913///
1914/// Inline function definitions are always available for inlining optimizations.
1915/// However, depending on the language dialect, declaration specifiers, and
1916/// attributes, the definition of an inline function may or may not be
1917/// "externally" visible to other translation units in the program.
1918///
1919/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00001920/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001921/// inline definition becomes externally visible (C99 6.7.4p6).
1922///
1923/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1924/// definition, we use the GNU semantics for inline, which are nearly the
1925/// opposite of C99 semantics. In particular, "inline" by itself will create
1926/// an externally visible symbol, but "extern inline" will not create an
1927/// externally visible symbol.
1928bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001929 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001930 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001931 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00001932
Rafael Espindolafb2af642011-06-02 16:13:27 +00001933 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001934 // If it's not the case that both 'inline' and 'extern' are
1935 // specified on the definition, then this inline definition is
1936 // externally visible.
1937 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1938 return true;
1939
1940 // If any declaration is 'inline' but not 'extern', then this definition
1941 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00001942 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1943 Redecl != RedeclEnd;
1944 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001945 if (Redecl->isInlineSpecified() &&
1946 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00001947 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00001948 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00001949
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001950 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00001951 }
1952
1953 // C99 6.7.4p6:
1954 // [...] If all of the file scope declarations for a function in a
1955 // translation unit include the inline function specifier without extern,
1956 // then the definition in that translation unit is an inline definition.
1957 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1958 Redecl != RedeclEnd;
1959 ++Redecl) {
1960 // Only consider file-scope declarations in this test.
1961 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1962 continue;
Eli Friedman94ab9302011-10-11 22:09:24 +00001963
1964 // Only consider explicit declarations; the presence of a builtin for a
1965 // libcall shouldn't affect whether a definition is externally visible.
1966 if (Redecl->isImplicit())
1967 continue;
1968
John McCall8e7d6562010-08-26 03:08:43 +00001969 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00001970 return true; // Not an inline definition
1971 }
1972
1973 // C99 6.7.4p6:
1974 // An inline definition does not provide an external definition for the
1975 // function, and does not forbid an external definition in another
1976 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001977 return false;
1978}
1979
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001980/// getOverloadedOperator - Which C++ overloaded operator this
1981/// function represents, if any.
1982OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00001983 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1984 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001985 else
1986 return OO_None;
1987}
1988
Alexis Huntc88db062010-01-13 09:01:02 +00001989/// getLiteralIdentifier - The literal suffix identifier this function
1990/// represents, if any.
1991const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1992 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1993 return getDeclName().getCXXLiteralIdentifier();
1994 else
1995 return 0;
1996}
1997
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00001998FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1999 if (TemplateOrSpecialization.isNull())
2000 return TK_NonTemplate;
2001 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2002 return TK_FunctionTemplate;
2003 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2004 return TK_MemberSpecialization;
2005 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2006 return TK_FunctionTemplateSpecialization;
2007 if (TemplateOrSpecialization.is
2008 <DependentFunctionTemplateSpecializationInfo*>())
2009 return TK_DependentFunctionTemplateSpecialization;
2010
David Blaikie83d382b2011-09-23 05:06:16 +00002011 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002012}
2013
Douglas Gregord801b062009-10-07 23:56:10 +00002014FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002015 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002016 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2017
2018 return 0;
2019}
2020
Douglas Gregor06db9f52009-10-12 20:18:28 +00002021MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2022 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2023}
2024
Douglas Gregord801b062009-10-07 23:56:10 +00002025void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002026FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2027 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002028 TemplateSpecializationKind TSK) {
2029 assert(TemplateOrSpecialization.isNull() &&
2030 "Member function is already a specialization");
2031 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002032 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002033 TemplateOrSpecialization = Info;
2034}
2035
Douglas Gregorafca3b42009-10-27 20:53:28 +00002036bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002037 // If the function is invalid, it can't be implicitly instantiated.
2038 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002039 return false;
2040
2041 switch (getTemplateSpecializationKind()) {
2042 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002043 case TSK_ExplicitInstantiationDefinition:
2044 return false;
2045
2046 case TSK_ImplicitInstantiation:
2047 return true;
2048
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002049 // It is possible to instantiate TSK_ExplicitSpecialization kind
2050 // if the FunctionDecl has a class scope specialization pattern.
2051 case TSK_ExplicitSpecialization:
2052 return getClassScopeSpecializationPattern() != 0;
2053
Douglas Gregorafca3b42009-10-27 20:53:28 +00002054 case TSK_ExplicitInstantiationDeclaration:
2055 // Handled below.
2056 break;
2057 }
2058
2059 // Find the actual template from which we will instantiate.
2060 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002061 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002062 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002063 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002064
2065 // C++0x [temp.explicit]p9:
2066 // Except for inline functions, other explicit instantiation declarations
2067 // have the effect of suppressing the implicit instantiation of the entity
2068 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002069 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002070 return true;
2071
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002072 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002073}
2074
2075bool FunctionDecl::isTemplateInstantiation() const {
2076 switch (getTemplateSpecializationKind()) {
2077 case TSK_Undeclared:
2078 case TSK_ExplicitSpecialization:
2079 return false;
2080 case TSK_ImplicitInstantiation:
2081 case TSK_ExplicitInstantiationDeclaration:
2082 case TSK_ExplicitInstantiationDefinition:
2083 return true;
2084 }
2085 llvm_unreachable("All TSK values handled.");
2086}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002087
2088FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002089 // Handle class scope explicit specialization special case.
2090 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2091 return getClassScopeSpecializationPattern();
2092
Douglas Gregorafca3b42009-10-27 20:53:28 +00002093 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2094 while (Primary->getInstantiatedFromMemberTemplate()) {
2095 // If we have hit a point where the user provided a specialization of
2096 // this template, we're done looking.
2097 if (Primary->isMemberSpecialization())
2098 break;
2099
2100 Primary = Primary->getInstantiatedFromMemberTemplate();
2101 }
2102
2103 return Primary->getTemplatedDecl();
2104 }
2105
2106 return getInstantiatedFromMemberFunction();
2107}
2108
Douglas Gregor70d83e22009-06-29 17:30:29 +00002109FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002110 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002111 = TemplateOrSpecialization
2112 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002113 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002114 }
2115 return 0;
2116}
2117
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002118FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2119 return getASTContext().getClassScopeSpecializationPattern(this);
2120}
2121
Douglas Gregor70d83e22009-06-29 17:30:29 +00002122const TemplateArgumentList *
2123FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002124 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002125 = TemplateOrSpecialization
2126 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002127 return Info->TemplateArguments;
2128 }
2129 return 0;
2130}
2131
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002132const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002133FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2134 if (FunctionTemplateSpecializationInfo *Info
2135 = TemplateOrSpecialization
2136 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2137 return Info->TemplateArgumentsAsWritten;
2138 }
2139 return 0;
2140}
2141
Mike Stump11289f42009-09-09 15:08:12 +00002142void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002143FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2144 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002145 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002146 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002147 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002148 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2149 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002150 assert(TSK != TSK_Undeclared &&
2151 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002152 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002153 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002154 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002155 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2156 TemplateArgs,
2157 TemplateArgsAsWritten,
2158 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002159 TemplateOrSpecialization = Info;
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002161 // Insert this function template specialization into the set of known
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002162 // function template specializations.
2163 if (InsertPos)
Sebastian Redl9ab988f2011-04-14 14:07:59 +00002164 Template->addSpecialization(Info, InsertPos);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002165 else {
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002166 // Try to insert the new node. If there is an existing node, leave it, the
2167 // set will contain the canonical decls while
2168 // FunctionTemplateDecl::findSpecialization will return
2169 // the most recent redeclarations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002170 FunctionTemplateSpecializationInfo *Existing
2171 = Template->getSpecializations().GetOrInsertNode(Info);
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002172 (void)Existing;
2173 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
2174 "Set is supposed to only contain canonical decls");
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002175 }
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002176}
2177
John McCallb9c78482010-04-08 09:05:18 +00002178void
2179FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2180 const UnresolvedSetImpl &Templates,
2181 const TemplateArgumentListInfo &TemplateArgs) {
2182 assert(TemplateOrSpecialization.isNull());
2183 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2184 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002185 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002186 void *Buffer = Context.Allocate(Size);
2187 DependentFunctionTemplateSpecializationInfo *Info =
2188 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2189 TemplateArgs);
2190 TemplateOrSpecialization = Info;
2191}
2192
2193DependentFunctionTemplateSpecializationInfo::
2194DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2195 const TemplateArgumentListInfo &TArgs)
2196 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2197
2198 d.NumTemplates = Ts.size();
2199 d.NumArgs = TArgs.size();
2200
2201 FunctionTemplateDecl **TsArray =
2202 const_cast<FunctionTemplateDecl**>(getTemplates());
2203 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2204 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2205
2206 TemplateArgumentLoc *ArgsArray =
2207 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2208 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2209 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2210}
2211
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002212TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002213 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002214 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002215 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002216 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002217 if (FTSInfo)
2218 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002219
Douglas Gregord801b062009-10-07 23:56:10 +00002220 MemberSpecializationInfo *MSInfo
2221 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2222 if (MSInfo)
2223 return MSInfo->getTemplateSpecializationKind();
2224
2225 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002226}
2227
Mike Stump11289f42009-09-09 15:08:12 +00002228void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002229FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2230 SourceLocation PointOfInstantiation) {
2231 if (FunctionTemplateSpecializationInfo *FTSInfo
2232 = TemplateOrSpecialization.dyn_cast<
2233 FunctionTemplateSpecializationInfo*>()) {
2234 FTSInfo->setTemplateSpecializationKind(TSK);
2235 if (TSK != TSK_ExplicitSpecialization &&
2236 PointOfInstantiation.isValid() &&
2237 FTSInfo->getPointOfInstantiation().isInvalid())
2238 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2239 } else if (MemberSpecializationInfo *MSInfo
2240 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2241 MSInfo->setTemplateSpecializationKind(TSK);
2242 if (TSK != TSK_ExplicitSpecialization &&
2243 PointOfInstantiation.isValid() &&
2244 MSInfo->getPointOfInstantiation().isInvalid())
2245 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2246 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002247 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002248}
2249
2250SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002251 if (FunctionTemplateSpecializationInfo *FTSInfo
2252 = TemplateOrSpecialization.dyn_cast<
2253 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002254 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002255 else if (MemberSpecializationInfo *MSInfo
2256 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002257 return MSInfo->getPointOfInstantiation();
2258
2259 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002260}
2261
Douglas Gregor6411b922009-09-11 20:15:17 +00002262bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002263 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002264 return true;
2265
2266 // If this function was instantiated from a member function of a
2267 // class template, check whether that member function was defined out-of-line.
2268 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2269 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002270 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002271 return Definition->isOutOfLine();
2272 }
2273
2274 // If this function was instantiated from a function template,
2275 // check whether that function template was defined out-of-line.
2276 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2277 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002278 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002279 return Definition->isOutOfLine();
2280 }
2281
2282 return false;
2283}
2284
Abramo Bagnaraea947882011-03-08 16:41:52 +00002285SourceRange FunctionDecl::getSourceRange() const {
2286 return SourceRange(getOuterLocStart(), EndRangeLoc);
2287}
2288
Chris Lattner59a25942008-03-31 00:36:02 +00002289//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002290// FieldDecl Implementation
2291//===----------------------------------------------------------------------===//
2292
Jay Foad39c79802011-01-12 09:06:06 +00002293FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002294 SourceLocation StartLoc, SourceLocation IdLoc,
2295 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002296 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2297 bool HasInit) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002298 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002299 BW, Mutable, HasInit);
Sebastian Redl833ef452010-01-26 22:01:41 +00002300}
2301
2302bool FieldDecl::isAnonymousStructOrUnion() const {
2303 if (!isImplicit() || getDeclName())
2304 return false;
2305
2306 if (const RecordType *Record = getType()->getAs<RecordType>())
2307 return Record->getDecl()->isAnonymousStructOrUnion();
2308
2309 return false;
2310}
2311
Richard Smithcaf33902011-10-10 18:28:20 +00002312unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2313 assert(isBitField() && "not a bitfield");
2314 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2315 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2316}
2317
John McCall4e819612011-01-20 07:57:12 +00002318unsigned FieldDecl::getFieldIndex() const {
2319 if (CachedFieldIndex) return CachedFieldIndex - 1;
2320
Richard Smithd62306a2011-11-10 06:34:14 +00002321 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002322 const RecordDecl *RD = getParent();
2323 const FieldDecl *LastFD = 0;
2324 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smithd62306a2011-11-10 06:34:14 +00002325
2326 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2327 I != E; ++I, ++Index) {
2328 (*I)->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002329
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002330 if (IsMsStruct) {
2331 // Zero-length bitfields following non-bitfield members are ignored.
Richard Smithd62306a2011-11-10 06:34:14 +00002332 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2333 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002334 continue;
2335 }
Richard Smithd62306a2011-11-10 06:34:14 +00002336 LastFD = (*I);
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002337 }
John McCall4e819612011-01-20 07:57:12 +00002338 }
2339
Richard Smithd62306a2011-11-10 06:34:14 +00002340 assert(CachedFieldIndex && "failed to find field in parent");
2341 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002342}
2343
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002344SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002345 if (const Expr *E = InitializerOrBitWidth.getPointer())
2346 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002347 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002348}
2349
Richard Smith938f40b2011-06-11 17:19:42 +00002350void FieldDecl::setInClassInitializer(Expr *Init) {
2351 assert(!InitializerOrBitWidth.getPointer() &&
2352 "bit width or initializer already set");
2353 InitializerOrBitWidth.setPointer(Init);
2354 InitializerOrBitWidth.setInt(0);
2355}
2356
Sebastian Redl833ef452010-01-26 22:01:41 +00002357//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002358// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002359//===----------------------------------------------------------------------===//
2360
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002361SourceLocation TagDecl::getOuterLocStart() const {
2362 return getTemplateOrInnerLocStart(this);
2363}
2364
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002365SourceRange TagDecl::getSourceRange() const {
2366 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002367 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002368}
2369
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002370TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002371 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002372}
2373
Richard Smithdda56e42011-04-15 14:24:37 +00002374void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2375 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002376 if (TypeForDecl)
John McCall424cec92011-01-19 06:33:43 +00002377 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002378 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002379}
2380
Douglas Gregordee1be82009-01-17 00:42:38 +00002381void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002382 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002383
2384 if (isa<CXXRecordDecl>(this)) {
2385 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2386 struct CXXRecordDecl::DefinitionData *Data =
2387 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002388 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2389 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002390 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002391}
2392
2393void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002394 assert((!isa<CXXRecordDecl>(this) ||
2395 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2396 "definition completed but not started");
2397
John McCallf937c022011-10-07 06:10:15 +00002398 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002399 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002400
2401 if (ASTMutationListener *L = getASTMutationListener())
2402 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002403}
2404
John McCallf937c022011-10-07 06:10:15 +00002405TagDecl *TagDecl::getDefinition() const {
2406 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002407 return const_cast<TagDecl *>(this);
Andrew Trickba266ee2010-10-19 21:54:32 +00002408 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2409 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002410
2411 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002412 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002413 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002414 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002415
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002416 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002417}
2418
Douglas Gregor14454802011-02-25 02:25:35 +00002419void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2420 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002421 // Make sure the extended qualifier info is allocated.
2422 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002423 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002424 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002425 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002426 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002427 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002428 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002429 if (getExtInfo()->NumTemplParamLists == 0) {
2430 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002431 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002432 }
2433 else
2434 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002435 }
2436 }
2437}
2438
Abramo Bagnara60804e12011-03-18 15:16:37 +00002439void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2440 unsigned NumTPLists,
2441 TemplateParameterList **TPLists) {
2442 assert(NumTPLists > 0);
2443 // Make sure the extended decl info is allocated.
2444 if (!hasExtInfo())
2445 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002446 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002447 // Set the template parameter lists info.
2448 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2449}
2450
Ted Kremenek21475702008-09-05 17:16:31 +00002451//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002452// EnumDecl Implementation
2453//===----------------------------------------------------------------------===//
2454
David Blaikie68e081d2011-12-20 02:48:34 +00002455void EnumDecl::anchor() { }
2456
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002457EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2458 SourceLocation StartLoc, SourceLocation IdLoc,
2459 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002460 EnumDecl *PrevDecl, bool IsScoped,
2461 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002462 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002463 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl833ef452010-01-26 22:01:41 +00002464 C.getTypeDeclType(Enum, PrevDecl);
2465 return Enum;
2466}
2467
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002468EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002469 return new (C) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002470 false, false, false);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002471}
2472
Douglas Gregord5058122010-02-11 01:19:42 +00002473void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002474 QualType NewPromotionType,
2475 unsigned NumPositiveBits,
2476 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002477 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002478 if (!IntegerType)
2479 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002480 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002481 setNumPositiveBits(NumPositiveBits);
2482 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002483 TagDecl::completeDefinition();
2484}
2485
2486//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002487// RecordDecl Implementation
2488//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002489
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002490RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2491 SourceLocation StartLoc, SourceLocation IdLoc,
2492 IdentifierInfo *Id, RecordDecl *PrevDecl)
2493 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00002494 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002495 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002496 HasObjectMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002497 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00002498 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00002499}
2500
Jay Foad39c79802011-01-12 09:06:06 +00002501RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002502 SourceLocation StartLoc, SourceLocation IdLoc,
2503 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2504 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2505 PrevDecl);
Ted Kremenek21475702008-09-05 17:16:31 +00002506 C.getTypeDeclType(R, PrevDecl);
2507 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00002508}
2509
Jay Foad39c79802011-01-12 09:06:06 +00002510RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002511 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2512 SourceLocation(), 0, 0);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002513}
2514
Douglas Gregordfcad112009-03-25 15:59:44 +00002515bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00002516 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00002517 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2518}
2519
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002520RecordDecl::field_iterator RecordDecl::field_begin() const {
2521 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2522 LoadFieldsFromExternalStorage();
2523
2524 return field_iterator(decl_iterator(FirstDecl));
2525}
2526
Douglas Gregorb11aad82011-02-19 18:51:44 +00002527/// completeDefinition - Notes that the definition of this type is now
2528/// complete.
2529void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00002530 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00002531 TagDecl::completeDefinition();
2532}
2533
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002534void RecordDecl::LoadFieldsFromExternalStorage() const {
2535 ExternalASTSource *Source = getASTContext().getExternalSource();
2536 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2537
2538 // Notify that we have a RecordDecl doing some initialization.
2539 ExternalASTSource::Deserializing TheFields(Source);
2540
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002541 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002542 LoadedFieldsFromExternalStorage = true;
2543 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2544 case ELR_Success:
2545 break;
2546
2547 case ELR_AlreadyLoaded:
2548 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002549 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002550 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002551
2552#ifndef NDEBUG
2553 // Check that all decls we got were FieldDecls.
2554 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2555 assert(isa<FieldDecl>(Decls[i]));
2556#endif
2557
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002558 if (Decls.empty())
2559 return;
2560
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00002561 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2562 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002563}
2564
Steve Naroff415d3d52008-10-08 17:01:13 +00002565//===----------------------------------------------------------------------===//
2566// BlockDecl Implementation
2567//===----------------------------------------------------------------------===//
2568
David Blaikie9c70e042011-09-21 18:16:56 +00002569void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00002570 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00002571
Steve Naroffc4b30e52009-03-13 16:56:44 +00002572 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002573 if (!NewParamInfo.empty()) {
2574 NumParams = NewParamInfo.size();
2575 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2576 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002577 }
2578}
2579
John McCall351762c2011-02-07 10:33:21 +00002580void BlockDecl::setCaptures(ASTContext &Context,
2581 const Capture *begin,
2582 const Capture *end,
2583 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00002584 CapturesCXXThis = capturesCXXThis;
2585
2586 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00002587 NumCaptures = 0;
2588 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00002589 return;
2590 }
2591
John McCall351762c2011-02-07 10:33:21 +00002592 NumCaptures = end - begin;
2593
2594 // Avoid new Capture[] because we don't want to provide a default
2595 // constructor.
2596 size_t allocationSize = NumCaptures * sizeof(Capture);
2597 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2598 memcpy(buffer, begin, allocationSize);
2599 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002600}
Sebastian Redl833ef452010-01-26 22:01:41 +00002601
John McCallce45f882011-06-15 22:51:16 +00002602bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2603 for (capture_const_iterator
2604 i = capture_begin(), e = capture_end(); i != e; ++i)
2605 // Only auto vars can be captured, so no redeclaration worries.
2606 if (i->getVariable() == variable)
2607 return true;
2608
2609 return false;
2610}
2611
Douglas Gregor70226da2010-12-21 16:27:07 +00002612SourceRange BlockDecl::getSourceRange() const {
2613 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2614}
Sebastian Redl833ef452010-01-26 22:01:41 +00002615
2616//===----------------------------------------------------------------------===//
2617// Other Decl Allocation/Deallocation Method Implementations
2618//===----------------------------------------------------------------------===//
2619
David Blaikie68e081d2011-12-20 02:48:34 +00002620void TranslationUnitDecl::anchor() { }
2621
Sebastian Redl833ef452010-01-26 22:01:41 +00002622TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2623 return new (C) TranslationUnitDecl(C);
2624}
2625
David Blaikie68e081d2011-12-20 02:48:34 +00002626void LabelDecl::anchor() { }
2627
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002628LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002629 SourceLocation IdentL, IdentifierInfo *II) {
2630 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2631}
2632
2633LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2634 SourceLocation IdentL, IdentifierInfo *II,
2635 SourceLocation GnuLabelL) {
2636 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2637 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002638}
2639
David Blaikie68e081d2011-12-20 02:48:34 +00002640void NamespaceDecl::anchor() { }
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002641
Sebastian Redl833ef452010-01-26 22:01:41 +00002642NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00002643 SourceLocation StartLoc,
2644 SourceLocation IdLoc, IdentifierInfo *Id) {
2645 return new (C) NamespaceDecl(DC, StartLoc, IdLoc, Id);
Sebastian Redl833ef452010-01-26 22:01:41 +00002646}
2647
Douglas Gregor417e87c2010-10-27 19:49:05 +00002648NamespaceDecl *NamespaceDecl::getNextNamespace() {
2649 return dyn_cast_or_null<NamespaceDecl>(
2650 NextNamespace.get(getASTContext().getExternalSource()));
2651}
2652
David Blaikie68e081d2011-12-20 02:48:34 +00002653void ValueDecl::anchor() { }
2654
2655void ImplicitParamDecl::anchor() { }
2656
Sebastian Redl833ef452010-01-26 22:01:41 +00002657ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002658 SourceLocation IdLoc,
2659 IdentifierInfo *Id,
2660 QualType Type) {
2661 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00002662}
2663
2664FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002665 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002666 const DeclarationNameInfo &NameInfo,
2667 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002668 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00002669 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00002670 bool hasWrittenPrototype,
2671 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002672 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2673 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00002674 isInlineSpecified,
2675 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00002676 New->HasWrittenPrototype = hasWrittenPrototype;
2677 return New;
2678}
2679
2680BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2681 return new (C) BlockDecl(DC, L);
2682}
2683
2684EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2685 SourceLocation L,
2686 IdentifierInfo *Id, QualType T,
2687 Expr *E, const llvm::APSInt &V) {
2688 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2689}
2690
David Blaikie68e081d2011-12-20 02:48:34 +00002691void IndirectFieldDecl::anchor() { }
2692
Benjamin Kramer39593702010-11-21 14:11:41 +00002693IndirectFieldDecl *
2694IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2695 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2696 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00002697 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2698}
2699
Douglas Gregorbe996932010-09-01 20:41:53 +00002700SourceRange EnumConstantDecl::getSourceRange() const {
2701 SourceLocation End = getLocation();
2702 if (Init)
2703 End = Init->getLocEnd();
2704 return SourceRange(getLocation(), End);
2705}
2706
David Blaikie68e081d2011-12-20 02:48:34 +00002707void TypeDecl::anchor() { }
2708
Sebastian Redl833ef452010-01-26 22:01:41 +00002709TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00002710 SourceLocation StartLoc, SourceLocation IdLoc,
2711 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2712 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00002713}
2714
David Blaikie68e081d2011-12-20 02:48:34 +00002715void TypedefNameDecl::anchor() { }
2716
Richard Smithdda56e42011-04-15 14:24:37 +00002717TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2718 SourceLocation StartLoc,
2719 SourceLocation IdLoc, IdentifierInfo *Id,
2720 TypeSourceInfo *TInfo) {
2721 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2722}
2723
Abramo Bagnaraea947882011-03-08 16:41:52 +00002724SourceRange TypedefDecl::getSourceRange() const {
2725 SourceLocation RangeEnd = getLocation();
2726 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2727 if (typeIsPostfix(TInfo->getType()))
2728 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2729 }
2730 return SourceRange(getLocStart(), RangeEnd);
2731}
2732
Richard Smithdda56e42011-04-15 14:24:37 +00002733SourceRange TypeAliasDecl::getSourceRange() const {
2734 SourceLocation RangeEnd = getLocStart();
2735 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2736 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2737 return SourceRange(getLocStart(), RangeEnd);
2738}
2739
David Blaikie68e081d2011-12-20 02:48:34 +00002740void FileScopeAsmDecl::anchor() { }
2741
Sebastian Redl833ef452010-01-26 22:01:41 +00002742FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00002743 StringLiteral *Str,
2744 SourceLocation AsmLoc,
2745 SourceLocation RParenLoc) {
2746 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00002747}
Douglas Gregorba345522011-12-02 23:23:56 +00002748
2749//===----------------------------------------------------------------------===//
2750// ImportDecl Implementation
2751//===----------------------------------------------------------------------===//
2752
2753/// \brief Retrieve the number of module identifiers needed to name the given
2754/// module.
2755static unsigned getNumModuleIdentifiers(Module *Mod) {
2756 unsigned Result = 1;
2757 while (Mod->Parent) {
2758 Mod = Mod->Parent;
2759 ++Result;
2760 }
2761 return Result;
2762}
2763
Douglas Gregor22d09742012-01-03 18:04:46 +00002764ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002765 Module *Imported,
2766 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00002767 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002768 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002769{
2770 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
2771 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
2772 memcpy(StoredLocs, IdentifierLocs.data(),
2773 IdentifierLocs.size() * sizeof(SourceLocation));
2774}
2775
Douglas Gregor22d09742012-01-03 18:04:46 +00002776ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002777 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00002778 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002779 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002780{
2781 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
2782}
2783
2784ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00002785 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00002786 ArrayRef<SourceLocation> IdentifierLocs) {
2787 void *Mem = C.Allocate(sizeof(ImportDecl) +
2788 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00002789 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00002790}
2791
2792ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00002793 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002794 Module *Imported,
2795 SourceLocation EndLoc) {
2796 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00002797 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00002798 Import->setImplicit();
2799 return Import;
2800}
2801
2802ImportDecl *ImportDecl::CreateEmpty(ASTContext &C, unsigned NumLocations) {
2803 void *Mem = C.Allocate(sizeof(ImportDecl) +
2804 NumLocations * sizeof(SourceLocation));
2805 return new (Mem) ImportDecl(EmptyShell());
2806}
2807
2808ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
2809 if (!ImportedAndComplete.getInt())
2810 return ArrayRef<SourceLocation>();
2811
2812 const SourceLocation *StoredLocs
2813 = reinterpret_cast<const SourceLocation *>(this + 1);
2814 return ArrayRef<SourceLocation>(StoredLocs,
2815 getNumModuleIdentifiers(getImportedModule()));
2816}
2817
2818SourceRange ImportDecl::getSourceRange() const {
2819 if (!ImportedAndComplete.getInt())
2820 return SourceRange(getLocation(),
2821 *reinterpret_cast<const SourceLocation *>(this + 1));
2822
2823 return SourceRange(getLocation(), getIdentifierLocs().back());
2824}