xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision 7bd78a91)
1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Decl subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include <algorithm>
33 
34 using namespace clang;
35 
36 Decl *clang::getPrimaryMergedDecl(Decl *D) {
37   return D->getASTContext().getPrimaryMergedDecl(D);
38 }
39 
40 //===----------------------------------------------------------------------===//
41 // NamedDecl Implementation
42 //===----------------------------------------------------------------------===//
43 
44 // Visibility rules aren't rigorously externally specified, but here
45 // are the basic principles behind what we implement:
46 //
47 // 1. An explicit visibility attribute is generally a direct expression
48 // of the user's intent and should be honored.  Only the innermost
49 // visibility attribute applies.  If no visibility attribute applies,
50 // global visibility settings are considered.
51 //
52 // 2. There is one caveat to the above: on or in a template pattern,
53 // an explicit visibility attribute is just a default rule, and
54 // visibility can be decreased by the visibility of template
55 // arguments.  But this, too, has an exception: an attribute on an
56 // explicit specialization or instantiation causes all the visibility
57 // restrictions of the template arguments to be ignored.
58 //
59 // 3. A variable that does not otherwise have explicit visibility can
60 // be restricted by the visibility of its type.
61 //
62 // 4. A visibility restriction is explicit if it comes from an
63 // attribute (or something like it), not a global visibility setting.
64 // When emitting a reference to an external symbol, visibility
65 // restrictions are ignored unless they are explicit.
66 //
67 // 5. When computing the visibility of a non-type, including a
68 // non-type member of a class, only non-type visibility restrictions
69 // are considered: the 'visibility' attribute, global value-visibility
70 // settings, and a few special cases like __private_extern.
71 //
72 // 6. When computing the visibility of a type, including a type member
73 // of a class, only type visibility restrictions are considered:
74 // the 'type_visibility' attribute and global type-visibility settings.
75 // However, a 'visibility' attribute counts as a 'type_visibility'
76 // attribute on any declaration that only has the former.
77 //
78 // The visibility of a "secondary" entity, like a template argument,
79 // is computed using the kind of that entity, not the kind of the
80 // primary entity for which we are computing visibility.  For example,
81 // the visibility of a specialization of either of these templates:
82 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
83 //   template <class T, bool (&compare)(T, X)> class matcher;
84 // is restricted according to the type visibility of the argument 'T',
85 // the type visibility of 'bool(&)(T,X)', and the value visibility of
86 // the argument function 'compare'.  That 'has_match' is a value
87 // and 'matcher' is a type only matters when looking for attributes
88 // and settings from the immediate context.
89 
90 const unsigned IgnoreExplicitVisibilityBit = 2;
91 const unsigned IgnoreAllVisibilityBit = 4;
92 
93 /// Kinds of LV computation.  The linkage side of the computation is
94 /// always the same, but different things can change how visibility is
95 /// computed.
96 enum LVComputationKind {
97   /// Do an LV computation for, ultimately, a type.
98   /// Visibility may be restricted by type visibility settings and
99   /// the visibility of template arguments.
100   LVForType = NamedDecl::VisibilityForType,
101 
102   /// Do an LV computation for, ultimately, a non-type declaration.
103   /// Visibility may be restricted by value visibility settings and
104   /// the visibility of template arguments.
105   LVForValue = NamedDecl::VisibilityForValue,
106 
107   /// Do an LV computation for, ultimately, a type that already has
108   /// some sort of explicit visibility.  Visibility may only be
109   /// restricted by the visibility of template arguments.
110   LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
111 
112   /// Do an LV computation for, ultimately, a non-type declaration
113   /// that already has some sort of explicit visibility.  Visibility
114   /// may only be restricted by the visibility of template arguments.
115   LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
116 
117   /// Do an LV computation when we only care about the linkage.
118   LVForLinkageOnly =
119       LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
120 };
121 
122 /// Does this computation kind permit us to consider additional
123 /// visibility settings from attributes and the like?
124 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
125   return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
126 }
127 
128 /// Given an LVComputationKind, return one of the same type/value sort
129 /// that records that it already has explicit visibility.
130 static LVComputationKind
131 withExplicitVisibilityAlready(LVComputationKind oldKind) {
132   LVComputationKind newKind =
133     static_cast<LVComputationKind>(unsigned(oldKind) |
134                                    IgnoreExplicitVisibilityBit);
135   assert(oldKind != LVForType          || newKind == LVForExplicitType);
136   assert(oldKind != LVForValue         || newKind == LVForExplicitValue);
137   assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
138   assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
139   return newKind;
140 }
141 
142 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
143                                                   LVComputationKind kind) {
144   assert(!hasExplicitVisibilityAlready(kind) &&
145          "asking for explicit visibility when we shouldn't be");
146   return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
147 }
148 
149 /// Is the given declaration a "type" or a "value" for the purposes of
150 /// visibility computation?
151 static bool usesTypeVisibility(const NamedDecl *D) {
152   return isa<TypeDecl>(D) ||
153          isa<ClassTemplateDecl>(D) ||
154          isa<ObjCInterfaceDecl>(D);
155 }
156 
157 /// Does the given declaration have member specialization information,
158 /// and if so, is it an explicit specialization?
159 template <class T> static typename
160 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
161 isExplicitMemberSpecialization(const T *D) {
162   if (const MemberSpecializationInfo *member =
163         D->getMemberSpecializationInfo()) {
164     return member->isExplicitSpecialization();
165   }
166   return false;
167 }
168 
169 /// For templates, this question is easier: a member template can't be
170 /// explicitly instantiated, so there's a single bit indicating whether
171 /// or not this is an explicit member specialization.
172 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
173   return D->isMemberSpecialization();
174 }
175 
176 /// Given a visibility attribute, return the explicit visibility
177 /// associated with it.
178 template <class T>
179 static Visibility getVisibilityFromAttr(const T *attr) {
180   switch (attr->getVisibility()) {
181   case T::Default:
182     return DefaultVisibility;
183   case T::Hidden:
184     return HiddenVisibility;
185   case T::Protected:
186     return ProtectedVisibility;
187   }
188   llvm_unreachable("bad visibility kind");
189 }
190 
191 /// Return the explicit visibility of the given declaration.
192 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
193                                     NamedDecl::ExplicitVisibilityKind kind) {
194   // If we're ultimately computing the visibility of a type, look for
195   // a 'type_visibility' attribute before looking for 'visibility'.
196   if (kind == NamedDecl::VisibilityForType) {
197     if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
198       return getVisibilityFromAttr(A);
199     }
200   }
201 
202   // If this declaration has an explicit visibility attribute, use it.
203   if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
204     return getVisibilityFromAttr(A);
205   }
206 
207   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
208   // implies visibility(default).
209   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
210     for (const auto *A : D->specific_attrs<AvailabilityAttr>())
211       if (A->getPlatform()->getName().equals("macosx"))
212         return DefaultVisibility;
213   }
214 
215   return None;
216 }
217 
218 static LinkageInfo
219 getLVForType(const Type &T, LVComputationKind computation) {
220   if (computation == LVForLinkageOnly)
221     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
222   return T.getLinkageAndVisibility();
223 }
224 
225 /// \brief Get the most restrictive linkage for the types in the given
226 /// template parameter list.  For visibility purposes, template
227 /// parameters are part of the signature of a template.
228 static LinkageInfo
229 getLVForTemplateParameterList(const TemplateParameterList *params,
230                               LVComputationKind computation) {
231   LinkageInfo LV;
232   for (TemplateParameterList::const_iterator P = params->begin(),
233                                           PEnd = params->end();
234        P != PEnd; ++P) {
235 
236     // Template type parameters are the most common and never
237     // contribute to visibility, pack or not.
238     if (isa<TemplateTypeParmDecl>(*P))
239       continue;
240 
241     // Non-type template parameters can be restricted by the value type, e.g.
242     //   template <enum X> class A { ... };
243     // We have to be careful here, though, because we can be dealing with
244     // dependent types.
245     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
246       // Handle the non-pack case first.
247       if (!NTTP->isExpandedParameterPack()) {
248         if (!NTTP->getType()->isDependentType()) {
249           LV.merge(getLVForType(*NTTP->getType(), computation));
250         }
251         continue;
252       }
253 
254       // Look at all the types in an expanded pack.
255       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
256         QualType type = NTTP->getExpansionType(i);
257         if (!type->isDependentType())
258           LV.merge(type->getLinkageAndVisibility());
259       }
260       continue;
261     }
262 
263     // Template template parameters can be restricted by their
264     // template parameters, recursively.
265     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
266 
267     // Handle the non-pack case first.
268     if (!TTP->isExpandedParameterPack()) {
269       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
270                                              computation));
271       continue;
272     }
273 
274     // Look at all expansions in an expanded pack.
275     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
276            i != n; ++i) {
277       LV.merge(getLVForTemplateParameterList(
278           TTP->getExpansionTemplateParameters(i), computation));
279     }
280   }
281 
282   return LV;
283 }
284 
285 /// getLVForDecl - Get the linkage and visibility for the given declaration.
286 static LinkageInfo getLVForDecl(const NamedDecl *D,
287                                 LVComputationKind computation);
288 
289 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
290   const Decl *Ret = NULL;
291   const DeclContext *DC = D->getDeclContext();
292   while (DC->getDeclKind() != Decl::TranslationUnit) {
293     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
294       Ret = cast<Decl>(DC);
295     DC = DC->getParent();
296   }
297   return Ret;
298 }
299 
300 /// \brief Get the most restrictive linkage for the types and
301 /// declarations in the given template argument list.
302 ///
303 /// Note that we don't take an LVComputationKind because we always
304 /// want to honor the visibility of template arguments in the same way.
305 static LinkageInfo
306 getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
307                              LVComputationKind computation) {
308   LinkageInfo LV;
309 
310   for (unsigned i = 0, e = args.size(); i != e; ++i) {
311     const TemplateArgument &arg = args[i];
312     switch (arg.getKind()) {
313     case TemplateArgument::Null:
314     case TemplateArgument::Integral:
315     case TemplateArgument::Expression:
316       continue;
317 
318     case TemplateArgument::Type:
319       LV.merge(getLVForType(*arg.getAsType(), computation));
320       continue;
321 
322     case TemplateArgument::Declaration:
323       if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
324         assert(!usesTypeVisibility(ND));
325         LV.merge(getLVForDecl(ND, computation));
326       }
327       continue;
328 
329     case TemplateArgument::NullPtr:
330       LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
331       continue;
332 
333     case TemplateArgument::Template:
334     case TemplateArgument::TemplateExpansion:
335       if (TemplateDecl *Template
336                 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
337         LV.merge(getLVForDecl(Template, computation));
338       continue;
339 
340     case TemplateArgument::Pack:
341       LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
342       continue;
343     }
344     llvm_unreachable("bad template argument kind");
345   }
346 
347   return LV;
348 }
349 
350 static LinkageInfo
351 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
352                              LVComputationKind computation) {
353   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
354 }
355 
356 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
357                         const FunctionTemplateSpecializationInfo *specInfo) {
358   // Include visibility from the template parameters and arguments
359   // only if this is not an explicit instantiation or specialization
360   // with direct explicit visibility.  (Implicit instantiations won't
361   // have a direct attribute.)
362   if (!specInfo->isExplicitInstantiationOrSpecialization())
363     return true;
364 
365   return !fn->hasAttr<VisibilityAttr>();
366 }
367 
368 /// Merge in template-related linkage and visibility for the given
369 /// function template specialization.
370 ///
371 /// We don't need a computation kind here because we can assume
372 /// LVForValue.
373 ///
374 /// \param[out] LV the computation to use for the parent
375 static void
376 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
377                 const FunctionTemplateSpecializationInfo *specInfo,
378                 LVComputationKind computation) {
379   bool considerVisibility =
380     shouldConsiderTemplateVisibility(fn, specInfo);
381 
382   // Merge information from the template parameters.
383   FunctionTemplateDecl *temp = specInfo->getTemplate();
384   LinkageInfo tempLV =
385     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
386   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
387 
388   // Merge information from the template arguments.
389   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
390   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
391   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
392 }
393 
394 /// Does the given declaration have a direct visibility attribute
395 /// that would match the given rules?
396 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
397                                          LVComputationKind computation) {
398   switch (computation) {
399   case LVForType:
400   case LVForExplicitType:
401     if (D->hasAttr<TypeVisibilityAttr>())
402       return true;
403     // fallthrough
404   case LVForValue:
405   case LVForExplicitValue:
406     if (D->hasAttr<VisibilityAttr>())
407       return true;
408     return false;
409   case LVForLinkageOnly:
410     return false;
411   }
412   llvm_unreachable("bad visibility computation kind");
413 }
414 
415 /// Should we consider visibility associated with the template
416 /// arguments and parameters of the given class template specialization?
417 static bool shouldConsiderTemplateVisibility(
418                                  const ClassTemplateSpecializationDecl *spec,
419                                  LVComputationKind computation) {
420   // Include visibility from the template parameters and arguments
421   // only if this is not an explicit instantiation or specialization
422   // with direct explicit visibility (and note that implicit
423   // instantiations won't have a direct attribute).
424   //
425   // Furthermore, we want to ignore template parameters and arguments
426   // for an explicit specialization when computing the visibility of a
427   // member thereof with explicit visibility.
428   //
429   // This is a bit complex; let's unpack it.
430   //
431   // An explicit class specialization is an independent, top-level
432   // declaration.  As such, if it or any of its members has an
433   // explicit visibility attribute, that must directly express the
434   // user's intent, and we should honor it.  The same logic applies to
435   // an explicit instantiation of a member of such a thing.
436 
437   // Fast path: if this is not an explicit instantiation or
438   // specialization, we always want to consider template-related
439   // visibility restrictions.
440   if (!spec->isExplicitInstantiationOrSpecialization())
441     return true;
442 
443   // This is the 'member thereof' check.
444   if (spec->isExplicitSpecialization() &&
445       hasExplicitVisibilityAlready(computation))
446     return false;
447 
448   return !hasDirectVisibilityAttribute(spec, computation);
449 }
450 
451 /// Merge in template-related linkage and visibility for the given
452 /// class template specialization.
453 static void mergeTemplateLV(LinkageInfo &LV,
454                             const ClassTemplateSpecializationDecl *spec,
455                             LVComputationKind computation) {
456   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
457 
458   // Merge information from the template parameters, but ignore
459   // visibility if we're only considering template arguments.
460 
461   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
462   LinkageInfo tempLV =
463     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
464   LV.mergeMaybeWithVisibility(tempLV,
465            considerVisibility && !hasExplicitVisibilityAlready(computation));
466 
467   // Merge information from the template arguments.  We ignore
468   // template-argument visibility if we've got an explicit
469   // instantiation with a visibility attribute.
470   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
471   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
472   if (considerVisibility)
473     LV.mergeVisibility(argsLV);
474   LV.mergeExternalVisibility(argsLV);
475 }
476 
477 static bool useInlineVisibilityHidden(const NamedDecl *D) {
478   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
479   const LangOptions &Opts = D->getASTContext().getLangOpts();
480   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
481     return false;
482 
483   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
484   if (!FD)
485     return false;
486 
487   TemplateSpecializationKind TSK = TSK_Undeclared;
488   if (FunctionTemplateSpecializationInfo *spec
489       = FD->getTemplateSpecializationInfo()) {
490     TSK = spec->getTemplateSpecializationKind();
491   } else if (MemberSpecializationInfo *MSI =
492              FD->getMemberSpecializationInfo()) {
493     TSK = MSI->getTemplateSpecializationKind();
494   }
495 
496   const FunctionDecl *Def = 0;
497   // InlineVisibilityHidden only applies to definitions, and
498   // isInlined() only gives meaningful answers on definitions
499   // anyway.
500   return TSK != TSK_ExplicitInstantiationDeclaration &&
501     TSK != TSK_ExplicitInstantiationDefinition &&
502     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
503 }
504 
505 template <typename T> static bool isFirstInExternCContext(T *D) {
506   const T *First = D->getFirstDecl();
507   return First->isInExternCContext();
508 }
509 
510 static bool isSingleLineLanguageLinkage(const Decl &D) {
511   if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
512     if (!SD->hasBraces())
513       return true;
514   return false;
515 }
516 
517 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
518                                               LVComputationKind computation) {
519   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
520          "Not a name having namespace scope");
521   ASTContext &Context = D->getASTContext();
522 
523   // C++ [basic.link]p3:
524   //   A name having namespace scope (3.3.6) has internal linkage if it
525   //   is the name of
526   //     - an object, reference, function or function template that is
527   //       explicitly declared static; or,
528   // (This bullet corresponds to C99 6.2.2p3.)
529   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
530     // Explicitly declared static.
531     if (Var->getStorageClass() == SC_Static)
532       return LinkageInfo::internal();
533 
534     // - a non-volatile object or reference that is explicitly declared const
535     //   or constexpr and neither explicitly declared extern nor previously
536     //   declared to have external linkage; or (there is no equivalent in C99)
537     if (Context.getLangOpts().CPlusPlus &&
538         Var->getType().isConstQualified() &&
539         !Var->getType().isVolatileQualified()) {
540       const VarDecl *PrevVar = Var->getPreviousDecl();
541       if (PrevVar)
542         return getLVForDecl(PrevVar, computation);
543 
544       if (Var->getStorageClass() != SC_Extern &&
545           Var->getStorageClass() != SC_PrivateExtern &&
546           !isSingleLineLanguageLinkage(*Var))
547         return LinkageInfo::internal();
548     }
549 
550     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
551          PrevVar = PrevVar->getPreviousDecl()) {
552       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
553           Var->getStorageClass() == SC_None)
554         return PrevVar->getLinkageAndVisibility();
555       // Explicitly declared static.
556       if (PrevVar->getStorageClass() == SC_Static)
557         return LinkageInfo::internal();
558     }
559   } else if (const FunctionDecl *Function = D->getAsFunction()) {
560     // C++ [temp]p4:
561     //   A non-member function template can have internal linkage; any
562     //   other template name shall have external linkage.
563 
564     // Explicitly declared static.
565     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
566       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
567   }
568   //   - a data member of an anonymous union.
569   assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
570   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
571 
572   if (D->isInAnonymousNamespace()) {
573     const VarDecl *Var = dyn_cast<VarDecl>(D);
574     const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
575     if ((!Var || !isFirstInExternCContext(Var)) &&
576         (!Func || !isFirstInExternCContext(Func)))
577       return LinkageInfo::uniqueExternal();
578   }
579 
580   // Set up the defaults.
581 
582   // C99 6.2.2p5:
583   //   If the declaration of an identifier for an object has file
584   //   scope and no storage-class specifier, its linkage is
585   //   external.
586   LinkageInfo LV;
587 
588   if (!hasExplicitVisibilityAlready(computation)) {
589     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
590       LV.mergeVisibility(*Vis, true);
591     } else {
592       // If we're declared in a namespace with a visibility attribute,
593       // use that namespace's visibility, and it still counts as explicit.
594       for (const DeclContext *DC = D->getDeclContext();
595            !isa<TranslationUnitDecl>(DC);
596            DC = DC->getParent()) {
597         const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
598         if (!ND) continue;
599         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
600           LV.mergeVisibility(*Vis, true);
601           break;
602         }
603       }
604     }
605 
606     // Add in global settings if the above didn't give us direct visibility.
607     if (!LV.isVisibilityExplicit()) {
608       // Use global type/value visibility as appropriate.
609       Visibility globalVisibility;
610       if (computation == LVForValue) {
611         globalVisibility = Context.getLangOpts().getValueVisibilityMode();
612       } else {
613         assert(computation == LVForType);
614         globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
615       }
616       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
617 
618       // If we're paying attention to global visibility, apply
619       // -finline-visibility-hidden if this is an inline method.
620       if (useInlineVisibilityHidden(D))
621         LV.mergeVisibility(HiddenVisibility, true);
622     }
623   }
624 
625   // C++ [basic.link]p4:
626 
627   //   A name having namespace scope has external linkage if it is the
628   //   name of
629   //
630   //     - an object or reference, unless it has internal linkage; or
631   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
632     // GCC applies the following optimization to variables and static
633     // data members, but not to functions:
634     //
635     // Modify the variable's LV by the LV of its type unless this is
636     // C or extern "C".  This follows from [basic.link]p9:
637     //   A type without linkage shall not be used as the type of a
638     //   variable or function with external linkage unless
639     //    - the entity has C language linkage, or
640     //    - the entity is declared within an unnamed namespace, or
641     //    - the entity is not used or is defined in the same
642     //      translation unit.
643     // and [basic.link]p10:
644     //   ...the types specified by all declarations referring to a
645     //   given variable or function shall be identical...
646     // C does not have an equivalent rule.
647     //
648     // Ignore this if we've got an explicit attribute;  the user
649     // probably knows what they're doing.
650     //
651     // Note that we don't want to make the variable non-external
652     // because of this, but unique-external linkage suits us.
653     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
654       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
655       if (TypeLV.getLinkage() != ExternalLinkage)
656         return LinkageInfo::uniqueExternal();
657       if (!LV.isVisibilityExplicit())
658         LV.mergeVisibility(TypeLV);
659     }
660 
661     if (Var->getStorageClass() == SC_PrivateExtern)
662       LV.mergeVisibility(HiddenVisibility, true);
663 
664     // Note that Sema::MergeVarDecl already takes care of implementing
665     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
666     // to do it here.
667 
668   //     - a function, unless it has internal linkage; or
669   } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
670     // In theory, we can modify the function's LV by the LV of its
671     // type unless it has C linkage (see comment above about variables
672     // for justification).  In practice, GCC doesn't do this, so it's
673     // just too painful to make work.
674 
675     if (Function->getStorageClass() == SC_PrivateExtern)
676       LV.mergeVisibility(HiddenVisibility, true);
677 
678     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
679     // merging storage classes and visibility attributes, so we don't have to
680     // look at previous decls in here.
681 
682     // In C++, then if the type of the function uses a type with
683     // unique-external linkage, it's not legally usable from outside
684     // this translation unit.  However, we should use the C linkage
685     // rules instead for extern "C" declarations.
686     if (Context.getLangOpts().CPlusPlus &&
687         !Function->isInExternCContext()) {
688       // Only look at the type-as-written. If this function has an auto-deduced
689       // return type, we can't compute the linkage of that type because it could
690       // require looking at the linkage of this function, and we don't need this
691       // for correctness because the type is not part of the function's
692       // signature.
693       // FIXME: This is a hack. We should be able to solve this circularity and
694       // the one in getLVForClassMember for Functions some other way.
695       QualType TypeAsWritten = Function->getType();
696       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
697         TypeAsWritten = TSI->getType();
698       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
699         return LinkageInfo::uniqueExternal();
700     }
701 
702     // Consider LV from the template and the template arguments.
703     // We're at file scope, so we do not need to worry about nested
704     // specializations.
705     if (FunctionTemplateSpecializationInfo *specInfo
706                                = Function->getTemplateSpecializationInfo()) {
707       mergeTemplateLV(LV, Function, specInfo, computation);
708     }
709 
710   //     - a named class (Clause 9), or an unnamed class defined in a
711   //       typedef declaration in which the class has the typedef name
712   //       for linkage purposes (7.1.3); or
713   //     - a named enumeration (7.2), or an unnamed enumeration
714   //       defined in a typedef declaration in which the enumeration
715   //       has the typedef name for linkage purposes (7.1.3); or
716   } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
717     // Unnamed tags have no linkage.
718     if (!Tag->hasNameForLinkage())
719       return LinkageInfo::none();
720 
721     // If this is a class template specialization, consider the
722     // linkage of the template and template arguments.  We're at file
723     // scope, so we do not need to worry about nested specializations.
724     if (const ClassTemplateSpecializationDecl *spec
725           = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
726       mergeTemplateLV(LV, spec, computation);
727     }
728 
729   //     - an enumerator belonging to an enumeration with external linkage;
730   } else if (isa<EnumConstantDecl>(D)) {
731     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
732                                       computation);
733     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
734       return LinkageInfo::none();
735     LV.merge(EnumLV);
736 
737   //     - a template, unless it is a function template that has
738   //       internal linkage (Clause 14);
739   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
740     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
741     LinkageInfo tempLV =
742       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
743     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
744 
745   //     - a namespace (7.3), unless it is declared within an unnamed
746   //       namespace.
747   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
748     return LV;
749 
750   // By extension, we assign external linkage to Objective-C
751   // interfaces.
752   } else if (isa<ObjCInterfaceDecl>(D)) {
753     // fallout
754 
755   // Everything not covered here has no linkage.
756   } else {
757     return LinkageInfo::none();
758   }
759 
760   // If we ended up with non-external linkage, visibility should
761   // always be default.
762   if (LV.getLinkage() != ExternalLinkage)
763     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
764 
765   return LV;
766 }
767 
768 static LinkageInfo getLVForClassMember(const NamedDecl *D,
769                                        LVComputationKind computation) {
770   // Only certain class members have linkage.  Note that fields don't
771   // really have linkage, but it's convenient to say they do for the
772   // purposes of calculating linkage of pointer-to-data-member
773   // template arguments.
774   //
775   // Templates also don't officially have linkage, but since we ignore
776   // the C++ standard and look at template arguments when determining
777   // linkage and visibility of a template specialization, we might hit
778   // a template template argument that way. If we do, we need to
779   // consider its linkage.
780   if (!(isa<CXXMethodDecl>(D) ||
781         isa<VarDecl>(D) ||
782         isa<FieldDecl>(D) ||
783         isa<IndirectFieldDecl>(D) ||
784         isa<TagDecl>(D) ||
785         isa<TemplateDecl>(D)))
786     return LinkageInfo::none();
787 
788   LinkageInfo LV;
789 
790   // If we have an explicit visibility attribute, merge that in.
791   if (!hasExplicitVisibilityAlready(computation)) {
792     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
793       LV.mergeVisibility(*Vis, true);
794     // If we're paying attention to global visibility, apply
795     // -finline-visibility-hidden if this is an inline method.
796     //
797     // Note that we do this before merging information about
798     // the class visibility.
799     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
800       LV.mergeVisibility(HiddenVisibility, true);
801   }
802 
803   // If this class member has an explicit visibility attribute, the only
804   // thing that can change its visibility is the template arguments, so
805   // only look for them when processing the class.
806   LVComputationKind classComputation = computation;
807   if (LV.isVisibilityExplicit())
808     classComputation = withExplicitVisibilityAlready(computation);
809 
810   LinkageInfo classLV =
811     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
812   // If the class already has unique-external linkage, we can't improve.
813   if (classLV.getLinkage() == UniqueExternalLinkage)
814     return LinkageInfo::uniqueExternal();
815 
816   if (!isExternallyVisible(classLV.getLinkage()))
817     return LinkageInfo::none();
818 
819 
820   // Otherwise, don't merge in classLV yet, because in certain cases
821   // we need to completely ignore the visibility from it.
822 
823   // Specifically, if this decl exists and has an explicit attribute.
824   const NamedDecl *explicitSpecSuppressor = 0;
825 
826   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
827     // If the type of the function uses a type with unique-external
828     // linkage, it's not legally usable from outside this translation unit.
829     // But only look at the type-as-written. If this function has an auto-deduced
830     // return type, we can't compute the linkage of that type because it could
831     // require looking at the linkage of this function, and we don't need this
832     // for correctness because the type is not part of the function's
833     // signature.
834     // FIXME: This is a hack. We should be able to solve this circularity and the
835     // one in getLVForNamespaceScopeDecl for Functions some other way.
836     {
837       QualType TypeAsWritten = MD->getType();
838       if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
839         TypeAsWritten = TSI->getType();
840       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
841         return LinkageInfo::uniqueExternal();
842     }
843     // If this is a method template specialization, use the linkage for
844     // the template parameters and arguments.
845     if (FunctionTemplateSpecializationInfo *spec
846            = MD->getTemplateSpecializationInfo()) {
847       mergeTemplateLV(LV, MD, spec, computation);
848       if (spec->isExplicitSpecialization()) {
849         explicitSpecSuppressor = MD;
850       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
851         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
852       }
853     } else if (isExplicitMemberSpecialization(MD)) {
854       explicitSpecSuppressor = MD;
855     }
856 
857   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
858     if (const ClassTemplateSpecializationDecl *spec
859         = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
860       mergeTemplateLV(LV, spec, computation);
861       if (spec->isExplicitSpecialization()) {
862         explicitSpecSuppressor = spec;
863       } else {
864         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
865         if (isExplicitMemberSpecialization(temp)) {
866           explicitSpecSuppressor = temp->getTemplatedDecl();
867         }
868       }
869     } else if (isExplicitMemberSpecialization(RD)) {
870       explicitSpecSuppressor = RD;
871     }
872 
873   // Static data members.
874   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
875     // Modify the variable's linkage by its type, but ignore the
876     // type's visibility unless it's a definition.
877     LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
878     if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
879       LV.mergeVisibility(typeLV);
880     LV.mergeExternalVisibility(typeLV);
881 
882     if (isExplicitMemberSpecialization(VD)) {
883       explicitSpecSuppressor = VD;
884     }
885 
886   // Template members.
887   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
888     bool considerVisibility =
889       (!LV.isVisibilityExplicit() &&
890        !classLV.isVisibilityExplicit() &&
891        !hasExplicitVisibilityAlready(computation));
892     LinkageInfo tempLV =
893       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
894     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
895 
896     if (const RedeclarableTemplateDecl *redeclTemp =
897           dyn_cast<RedeclarableTemplateDecl>(temp)) {
898       if (isExplicitMemberSpecialization(redeclTemp)) {
899         explicitSpecSuppressor = temp->getTemplatedDecl();
900       }
901     }
902   }
903 
904   // We should never be looking for an attribute directly on a template.
905   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
906 
907   // If this member is an explicit member specialization, and it has
908   // an explicit attribute, ignore visibility from the parent.
909   bool considerClassVisibility = true;
910   if (explicitSpecSuppressor &&
911       // optimization: hasDVA() is true only with explicit visibility.
912       LV.isVisibilityExplicit() &&
913       classLV.getVisibility() != DefaultVisibility &&
914       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
915     considerClassVisibility = false;
916   }
917 
918   // Finally, merge in information from the class.
919   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
920   return LV;
921 }
922 
923 void NamedDecl::anchor() { }
924 
925 static LinkageInfo computeLVForDecl(const NamedDecl *D,
926                                     LVComputationKind computation);
927 
928 bool NamedDecl::isLinkageValid() const {
929   if (!hasCachedLinkage())
930     return true;
931 
932   return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
933          getCachedLinkage();
934 }
935 
936 Linkage NamedDecl::getLinkageInternal() const {
937   // We don't care about visibility here, so ask for the cheapest
938   // possible visibility analysis.
939   return getLVForDecl(this, LVForLinkageOnly).getLinkage();
940 }
941 
942 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
943   LVComputationKind computation =
944     (usesTypeVisibility(this) ? LVForType : LVForValue);
945   return getLVForDecl(this, computation);
946 }
947 
948 static Optional<Visibility>
949 getExplicitVisibilityAux(const NamedDecl *ND,
950                          NamedDecl::ExplicitVisibilityKind kind,
951                          bool IsMostRecent) {
952   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
953 
954   // Check the declaration itself first.
955   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
956     return V;
957 
958   // If this is a member class of a specialization of a class template
959   // and the corresponding decl has explicit visibility, use that.
960   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
961     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
962     if (InstantiatedFrom)
963       return getVisibilityOf(InstantiatedFrom, kind);
964   }
965 
966   // If there wasn't explicit visibility there, and this is a
967   // specialization of a class template, check for visibility
968   // on the pattern.
969   if (const ClassTemplateSpecializationDecl *spec
970         = dyn_cast<ClassTemplateSpecializationDecl>(ND))
971     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
972                            kind);
973 
974   // Use the most recent declaration.
975   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
976     const NamedDecl *MostRecent = ND->getMostRecentDecl();
977     if (MostRecent != ND)
978       return getExplicitVisibilityAux(MostRecent, kind, true);
979   }
980 
981   if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
982     if (Var->isStaticDataMember()) {
983       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
984       if (InstantiatedFrom)
985         return getVisibilityOf(InstantiatedFrom, kind);
986     }
987 
988     return None;
989   }
990   // Also handle function template specializations.
991   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
992     // If the function is a specialization of a template with an
993     // explicit visibility attribute, use that.
994     if (FunctionTemplateSpecializationInfo *templateInfo
995           = fn->getTemplateSpecializationInfo())
996       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
997                              kind);
998 
999     // If the function is a member of a specialization of a class template
1000     // and the corresponding decl has explicit visibility, use that.
1001     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1002     if (InstantiatedFrom)
1003       return getVisibilityOf(InstantiatedFrom, kind);
1004 
1005     return None;
1006   }
1007 
1008   // The visibility of a template is stored in the templated decl.
1009   if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
1010     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1011 
1012   return None;
1013 }
1014 
1015 Optional<Visibility>
1016 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1017   return getExplicitVisibilityAux(this, kind, false);
1018 }
1019 
1020 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1021                                    LVComputationKind computation) {
1022   // This lambda has its linkage/visibility determined by its owner.
1023   if (ContextDecl) {
1024     if (isa<ParmVarDecl>(ContextDecl))
1025       DC = ContextDecl->getDeclContext()->getRedeclContext();
1026     else
1027       return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1028   }
1029 
1030   if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1031     return getLVForDecl(ND, computation);
1032 
1033   return LinkageInfo::external();
1034 }
1035 
1036 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1037                                      LVComputationKind computation) {
1038   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1039     if (Function->isInAnonymousNamespace() &&
1040         !Function->isInExternCContext())
1041       return LinkageInfo::uniqueExternal();
1042 
1043     // This is a "void f();" which got merged with a file static.
1044     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1045       return LinkageInfo::internal();
1046 
1047     LinkageInfo LV;
1048     if (!hasExplicitVisibilityAlready(computation)) {
1049       if (Optional<Visibility> Vis =
1050               getExplicitVisibility(Function, computation))
1051         LV.mergeVisibility(*Vis, true);
1052     }
1053 
1054     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1055     // merging storage classes and visibility attributes, so we don't have to
1056     // look at previous decls in here.
1057 
1058     return LV;
1059   }
1060 
1061   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1062     if (Var->hasExternalStorage()) {
1063       if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1064         return LinkageInfo::uniqueExternal();
1065 
1066       LinkageInfo LV;
1067       if (Var->getStorageClass() == SC_PrivateExtern)
1068         LV.mergeVisibility(HiddenVisibility, true);
1069       else if (!hasExplicitVisibilityAlready(computation)) {
1070         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1071           LV.mergeVisibility(*Vis, true);
1072       }
1073 
1074       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1075         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1076         if (PrevLV.getLinkage())
1077           LV.setLinkage(PrevLV.getLinkage());
1078         LV.mergeVisibility(PrevLV);
1079       }
1080 
1081       return LV;
1082     }
1083 
1084     if (!Var->isStaticLocal())
1085       return LinkageInfo::none();
1086   }
1087 
1088   ASTContext &Context = D->getASTContext();
1089   if (!Context.getLangOpts().CPlusPlus)
1090     return LinkageInfo::none();
1091 
1092   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1093   if (!OuterD)
1094     return LinkageInfo::none();
1095 
1096   LinkageInfo LV;
1097   if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1098     if (!BD->getBlockManglingNumber())
1099       return LinkageInfo::none();
1100 
1101     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1102                          BD->getBlockManglingContextDecl(), computation);
1103   } else {
1104     const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1105     if (!FD->isInlined() &&
1106         FD->getTemplateSpecializationKind() == TSK_Undeclared)
1107       return LinkageInfo::none();
1108 
1109     LV = getLVForDecl(FD, computation);
1110   }
1111   if (!isExternallyVisible(LV.getLinkage()))
1112     return LinkageInfo::none();
1113   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1114                      LV.isVisibilityExplicit());
1115 }
1116 
1117 static inline const CXXRecordDecl*
1118 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1119   const CXXRecordDecl *Ret = Record;
1120   while (Record && Record->isLambda()) {
1121     Ret = Record;
1122     if (!Record->getParent()) break;
1123     // Get the Containing Class of this Lambda Class
1124     Record = dyn_cast_or_null<CXXRecordDecl>(
1125       Record->getParent()->getParent());
1126   }
1127   return Ret;
1128 }
1129 
1130 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1131                                     LVComputationKind computation) {
1132   // Objective-C: treat all Objective-C declarations as having external
1133   // linkage.
1134   switch (D->getKind()) {
1135     default:
1136       break;
1137     case Decl::ParmVar:
1138       return LinkageInfo::none();
1139     case Decl::TemplateTemplateParm: // count these as external
1140     case Decl::NonTypeTemplateParm:
1141     case Decl::ObjCAtDefsField:
1142     case Decl::ObjCCategory:
1143     case Decl::ObjCCategoryImpl:
1144     case Decl::ObjCCompatibleAlias:
1145     case Decl::ObjCImplementation:
1146     case Decl::ObjCMethod:
1147     case Decl::ObjCProperty:
1148     case Decl::ObjCPropertyImpl:
1149     case Decl::ObjCProtocol:
1150       return LinkageInfo::external();
1151 
1152     case Decl::CXXRecord: {
1153       const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1154       if (Record->isLambda()) {
1155         if (!Record->getLambdaManglingNumber()) {
1156           // This lambda has no mangling number, so it's internal.
1157           return LinkageInfo::internal();
1158         }
1159 
1160         // This lambda has its linkage/visibility determined:
1161         //  - either by the outermost lambda if that lambda has no mangling
1162         //    number.
1163         //  - or by the parent of the outer most lambda
1164         // This prevents infinite recursion in settings such as nested lambdas
1165         // used in NSDMI's, for e.g.
1166         //  struct L {
1167         //    int t{};
1168         //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1169         //  };
1170         const CXXRecordDecl *OuterMostLambda =
1171             getOutermostEnclosingLambda(Record);
1172         if (!OuterMostLambda->getLambdaManglingNumber())
1173           return LinkageInfo::internal();
1174 
1175         return getLVForClosure(
1176                   OuterMostLambda->getDeclContext()->getRedeclContext(),
1177                   OuterMostLambda->getLambdaContextDecl(), computation);
1178       }
1179 
1180       break;
1181     }
1182   }
1183 
1184   // Handle linkage for namespace-scope names.
1185   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1186     return getLVForNamespaceScopeDecl(D, computation);
1187 
1188   // C++ [basic.link]p5:
1189   //   In addition, a member function, static data member, a named
1190   //   class or enumeration of class scope, or an unnamed class or
1191   //   enumeration defined in a class-scope typedef declaration such
1192   //   that the class or enumeration has the typedef name for linkage
1193   //   purposes (7.1.3), has external linkage if the name of the class
1194   //   has external linkage.
1195   if (D->getDeclContext()->isRecord())
1196     return getLVForClassMember(D, computation);
1197 
1198   // C++ [basic.link]p6:
1199   //   The name of a function declared in block scope and the name of
1200   //   an object declared by a block scope extern declaration have
1201   //   linkage. If there is a visible declaration of an entity with
1202   //   linkage having the same name and type, ignoring entities
1203   //   declared outside the innermost enclosing namespace scope, the
1204   //   block scope declaration declares that same entity and receives
1205   //   the linkage of the previous declaration. If there is more than
1206   //   one such matching entity, the program is ill-formed. Otherwise,
1207   //   if no matching entity is found, the block scope entity receives
1208   //   external linkage.
1209   if (D->getDeclContext()->isFunctionOrMethod())
1210     return getLVForLocalDecl(D, computation);
1211 
1212   // C++ [basic.link]p6:
1213   //   Names not covered by these rules have no linkage.
1214   return LinkageInfo::none();
1215 }
1216 
1217 namespace clang {
1218 class LinkageComputer {
1219 public:
1220   static LinkageInfo getLVForDecl(const NamedDecl *D,
1221                                   LVComputationKind computation) {
1222     if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1223       return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1224 
1225     LinkageInfo LV = computeLVForDecl(D, computation);
1226     if (D->hasCachedLinkage())
1227       assert(D->getCachedLinkage() == LV.getLinkage());
1228 
1229     D->setCachedLinkage(LV.getLinkage());
1230 
1231 #ifndef NDEBUG
1232     // In C (because of gnu inline) and in c++ with microsoft extensions an
1233     // static can follow an extern, so we can have two decls with different
1234     // linkages.
1235     const LangOptions &Opts = D->getASTContext().getLangOpts();
1236     if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1237       return LV;
1238 
1239     // We have just computed the linkage for this decl. By induction we know
1240     // that all other computed linkages match, check that the one we just
1241     // computed also does.
1242     NamedDecl *Old = NULL;
1243     for (auto I : D->redecls()) {
1244       NamedDecl *T = cast<NamedDecl>(I);
1245       if (T == D)
1246         continue;
1247       if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1248         Old = T;
1249         break;
1250       }
1251     }
1252     assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1253 #endif
1254 
1255     return LV;
1256   }
1257 };
1258 }
1259 
1260 static LinkageInfo getLVForDecl(const NamedDecl *D,
1261                                 LVComputationKind computation) {
1262   return clang::LinkageComputer::getLVForDecl(D, computation);
1263 }
1264 
1265 std::string NamedDecl::getQualifiedNameAsString() const {
1266   std::string QualName;
1267   llvm::raw_string_ostream OS(QualName);
1268   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1269   return OS.str();
1270 }
1271 
1272 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1273   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1274 }
1275 
1276 void NamedDecl::printQualifiedName(raw_ostream &OS,
1277                                    const PrintingPolicy &P) const {
1278   const DeclContext *Ctx = getDeclContext();
1279 
1280   if (Ctx->isFunctionOrMethod()) {
1281     printName(OS);
1282     return;
1283   }
1284 
1285   typedef SmallVector<const DeclContext *, 8> ContextsTy;
1286   ContextsTy Contexts;
1287 
1288   // Collect contexts.
1289   while (Ctx && isa<NamedDecl>(Ctx)) {
1290     Contexts.push_back(Ctx);
1291     Ctx = Ctx->getParent();
1292   }
1293 
1294   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1295        I != E; ++I) {
1296     if (const ClassTemplateSpecializationDecl *Spec
1297           = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1298       OS << Spec->getName();
1299       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1300       TemplateSpecializationType::PrintTemplateArgumentList(OS,
1301                                                             TemplateArgs.data(),
1302                                                             TemplateArgs.size(),
1303                                                             P);
1304     } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1305       if (ND->isAnonymousNamespace())
1306         OS << "<anonymous namespace>";
1307       else
1308         OS << *ND;
1309     } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1310       if (!RD->getIdentifier())
1311         OS << "<anonymous " << RD->getKindName() << '>';
1312       else
1313         OS << *RD;
1314     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1315       const FunctionProtoType *FT = 0;
1316       if (FD->hasWrittenPrototype())
1317         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1318 
1319       OS << *FD << '(';
1320       if (FT) {
1321         unsigned NumParams = FD->getNumParams();
1322         for (unsigned i = 0; i < NumParams; ++i) {
1323           if (i)
1324             OS << ", ";
1325           OS << FD->getParamDecl(i)->getType().stream(P);
1326         }
1327 
1328         if (FT->isVariadic()) {
1329           if (NumParams > 0)
1330             OS << ", ";
1331           OS << "...";
1332         }
1333       }
1334       OS << ')';
1335     } else {
1336       OS << *cast<NamedDecl>(*I);
1337     }
1338     OS << "::";
1339   }
1340 
1341   if (getDeclName())
1342     OS << *this;
1343   else
1344     OS << "<anonymous>";
1345 }
1346 
1347 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1348                                      const PrintingPolicy &Policy,
1349                                      bool Qualified) const {
1350   if (Qualified)
1351     printQualifiedName(OS, Policy);
1352   else
1353     printName(OS);
1354 }
1355 
1356 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1357   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1358 
1359   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1360   // We want to keep it, unless it nominates same namespace.
1361   if (getKind() == Decl::UsingDirective) {
1362     return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1363              ->getOriginalNamespace() ==
1364            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1365              ->getOriginalNamespace();
1366   }
1367 
1368   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1369     // For function declarations, we keep track of redeclarations.
1370     return FD->getPreviousDecl() == OldD;
1371 
1372   // For function templates, the underlying function declarations are linked.
1373   if (const FunctionTemplateDecl *FunctionTemplate
1374         = dyn_cast<FunctionTemplateDecl>(this))
1375     if (const FunctionTemplateDecl *OldFunctionTemplate
1376           = dyn_cast<FunctionTemplateDecl>(OldD))
1377       return FunctionTemplate->getTemplatedDecl()
1378                ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1379 
1380   // For method declarations, we keep track of redeclarations.
1381   if (isa<ObjCMethodDecl>(this))
1382     return false;
1383 
1384   // FIXME: Is this correct if one of the decls comes from an inline namespace?
1385   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1386     return true;
1387 
1388   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1389     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1390            cast<UsingShadowDecl>(OldD)->getTargetDecl();
1391 
1392   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1393     ASTContext &Context = getASTContext();
1394     return Context.getCanonicalNestedNameSpecifier(
1395                                      cast<UsingDecl>(this)->getQualifier()) ==
1396            Context.getCanonicalNestedNameSpecifier(
1397                                         cast<UsingDecl>(OldD)->getQualifier());
1398   }
1399 
1400   if (isa<UnresolvedUsingValueDecl>(this) &&
1401       isa<UnresolvedUsingValueDecl>(OldD)) {
1402     ASTContext &Context = getASTContext();
1403     return Context.getCanonicalNestedNameSpecifier(
1404                       cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1405            Context.getCanonicalNestedNameSpecifier(
1406                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1407   }
1408 
1409   // A typedef of an Objective-C class type can replace an Objective-C class
1410   // declaration or definition, and vice versa.
1411   // FIXME: Is this correct if one of the decls comes from an inline namespace?
1412   if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1413       (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1414     return true;
1415 
1416   // For non-function declarations, if the declarations are of the
1417   // same kind and have the same parent then this must be a redeclaration,
1418   // or semantic analysis would not have given us the new declaration.
1419   // Note that inline namespaces can give us two declarations with the same
1420   // name and kind in the same scope but different contexts.
1421   return this->getKind() == OldD->getKind() &&
1422          this->getDeclContext()->getRedeclContext()->Equals(
1423              OldD->getDeclContext()->getRedeclContext());
1424 }
1425 
1426 bool NamedDecl::hasLinkage() const {
1427   return getFormalLinkage() != NoLinkage;
1428 }
1429 
1430 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1431   NamedDecl *ND = this;
1432   while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1433     ND = UD->getTargetDecl();
1434 
1435   if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1436     return AD->getClassInterface();
1437 
1438   return ND;
1439 }
1440 
1441 bool NamedDecl::isCXXInstanceMember() const {
1442   if (!isCXXClassMember())
1443     return false;
1444 
1445   const NamedDecl *D = this;
1446   if (isa<UsingShadowDecl>(D))
1447     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1448 
1449   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1450     return true;
1451   if (const CXXMethodDecl *MD =
1452           dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1453     return MD->isInstance();
1454   return false;
1455 }
1456 
1457 //===----------------------------------------------------------------------===//
1458 // DeclaratorDecl Implementation
1459 //===----------------------------------------------------------------------===//
1460 
1461 template <typename DeclT>
1462 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1463   if (decl->getNumTemplateParameterLists() > 0)
1464     return decl->getTemplateParameterList(0)->getTemplateLoc();
1465   else
1466     return decl->getInnerLocStart();
1467 }
1468 
1469 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1470   TypeSourceInfo *TSI = getTypeSourceInfo();
1471   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1472   return SourceLocation();
1473 }
1474 
1475 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1476   if (QualifierLoc) {
1477     // Make sure the extended decl info is allocated.
1478     if (!hasExtInfo()) {
1479       // Save (non-extended) type source info pointer.
1480       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1481       // Allocate external info struct.
1482       DeclInfo = new (getASTContext()) ExtInfo;
1483       // Restore savedTInfo into (extended) decl info.
1484       getExtInfo()->TInfo = savedTInfo;
1485     }
1486     // Set qualifier info.
1487     getExtInfo()->QualifierLoc = QualifierLoc;
1488   } else {
1489     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1490     if (hasExtInfo()) {
1491       if (getExtInfo()->NumTemplParamLists == 0) {
1492         // Save type source info pointer.
1493         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1494         // Deallocate the extended decl info.
1495         getASTContext().Deallocate(getExtInfo());
1496         // Restore savedTInfo into (non-extended) decl info.
1497         DeclInfo = savedTInfo;
1498       }
1499       else
1500         getExtInfo()->QualifierLoc = QualifierLoc;
1501     }
1502   }
1503 }
1504 
1505 void
1506 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1507                                               unsigned NumTPLists,
1508                                               TemplateParameterList **TPLists) {
1509   assert(NumTPLists > 0);
1510   // Make sure the extended decl info is allocated.
1511   if (!hasExtInfo()) {
1512     // Save (non-extended) type source info pointer.
1513     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1514     // Allocate external info struct.
1515     DeclInfo = new (getASTContext()) ExtInfo;
1516     // Restore savedTInfo into (extended) decl info.
1517     getExtInfo()->TInfo = savedTInfo;
1518   }
1519   // Set the template parameter lists info.
1520   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1521 }
1522 
1523 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1524   return getTemplateOrInnerLocStart(this);
1525 }
1526 
1527 namespace {
1528 
1529 // Helper function: returns true if QT is or contains a type
1530 // having a postfix component.
1531 bool typeIsPostfix(clang::QualType QT) {
1532   while (true) {
1533     const Type* T = QT.getTypePtr();
1534     switch (T->getTypeClass()) {
1535     default:
1536       return false;
1537     case Type::Pointer:
1538       QT = cast<PointerType>(T)->getPointeeType();
1539       break;
1540     case Type::BlockPointer:
1541       QT = cast<BlockPointerType>(T)->getPointeeType();
1542       break;
1543     case Type::MemberPointer:
1544       QT = cast<MemberPointerType>(T)->getPointeeType();
1545       break;
1546     case Type::LValueReference:
1547     case Type::RValueReference:
1548       QT = cast<ReferenceType>(T)->getPointeeType();
1549       break;
1550     case Type::PackExpansion:
1551       QT = cast<PackExpansionType>(T)->getPattern();
1552       break;
1553     case Type::Paren:
1554     case Type::ConstantArray:
1555     case Type::DependentSizedArray:
1556     case Type::IncompleteArray:
1557     case Type::VariableArray:
1558     case Type::FunctionProto:
1559     case Type::FunctionNoProto:
1560       return true;
1561     }
1562   }
1563 }
1564 
1565 } // namespace
1566 
1567 SourceRange DeclaratorDecl::getSourceRange() const {
1568   SourceLocation RangeEnd = getLocation();
1569   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1570     // If the declaration has no name or the type extends past the name take the
1571     // end location of the type.
1572     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1573       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1574   }
1575   return SourceRange(getOuterLocStart(), RangeEnd);
1576 }
1577 
1578 void
1579 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1580                                              unsigned NumTPLists,
1581                                              TemplateParameterList **TPLists) {
1582   assert((NumTPLists == 0 || TPLists != 0) &&
1583          "Empty array of template parameters with positive size!");
1584 
1585   // Free previous template parameters (if any).
1586   if (NumTemplParamLists > 0) {
1587     Context.Deallocate(TemplParamLists);
1588     TemplParamLists = 0;
1589     NumTemplParamLists = 0;
1590   }
1591   // Set info on matched template parameter lists (if any).
1592   if (NumTPLists > 0) {
1593     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1594     NumTemplParamLists = NumTPLists;
1595     for (unsigned i = NumTPLists; i-- > 0; )
1596       TemplParamLists[i] = TPLists[i];
1597   }
1598 }
1599 
1600 //===----------------------------------------------------------------------===//
1601 // VarDecl Implementation
1602 //===----------------------------------------------------------------------===//
1603 
1604 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1605   switch (SC) {
1606   case SC_None:                 break;
1607   case SC_Auto:                 return "auto";
1608   case SC_Extern:               return "extern";
1609   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1610   case SC_PrivateExtern:        return "__private_extern__";
1611   case SC_Register:             return "register";
1612   case SC_Static:               return "static";
1613   }
1614 
1615   llvm_unreachable("Invalid storage class");
1616 }
1617 
1618 VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1619                  SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1620                  TypeSourceInfo *TInfo, StorageClass SC)
1621     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
1622   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1623                 "VarDeclBitfields too large!");
1624   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1625                 "ParmVarDeclBitfields too large!");
1626   AllBits = 0;
1627   VarDeclBits.SClass = SC;
1628   // Everything else is implicitly initialized to false.
1629 }
1630 
1631 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1632                          SourceLocation StartL, SourceLocation IdL,
1633                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1634                          StorageClass S) {
1635   return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
1636 }
1637 
1638 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1639   return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1640                              QualType(), 0, SC_None);
1641 }
1642 
1643 void VarDecl::setStorageClass(StorageClass SC) {
1644   assert(isLegalForVariable(SC));
1645   VarDeclBits.SClass = SC;
1646 }
1647 
1648 SourceRange VarDecl::getSourceRange() const {
1649   if (const Expr *Init = getInit()) {
1650     SourceLocation InitEnd = Init->getLocEnd();
1651     // If Init is implicit, ignore its source range and fallback on
1652     // DeclaratorDecl::getSourceRange() to handle postfix elements.
1653     if (InitEnd.isValid() && InitEnd != getLocation())
1654       return SourceRange(getOuterLocStart(), InitEnd);
1655   }
1656   return DeclaratorDecl::getSourceRange();
1657 }
1658 
1659 template<typename T>
1660 static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
1661   // C++ [dcl.link]p1: All function types, function names with external linkage,
1662   // and variable names with external linkage have a language linkage.
1663   if (!D.hasExternalFormalLinkage())
1664     return NoLanguageLinkage;
1665 
1666   // Language linkage is a C++ concept, but saying that everything else in C has
1667   // C language linkage fits the implementation nicely.
1668   ASTContext &Context = D.getASTContext();
1669   if (!Context.getLangOpts().CPlusPlus)
1670     return CLanguageLinkage;
1671 
1672   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1673   // language linkage of the names of class members and the function type of
1674   // class member functions.
1675   const DeclContext *DC = D.getDeclContext();
1676   if (DC->isRecord())
1677     return CXXLanguageLinkage;
1678 
1679   // If the first decl is in an extern "C" context, any other redeclaration
1680   // will have C language linkage. If the first one is not in an extern "C"
1681   // context, we would have reported an error for any other decl being in one.
1682   if (isFirstInExternCContext(&D))
1683     return CLanguageLinkage;
1684   return CXXLanguageLinkage;
1685 }
1686 
1687 template<typename T>
1688 static bool isExternCTemplate(const T &D) {
1689   // Since the context is ignored for class members, they can only have C++
1690   // language linkage or no language linkage.
1691   const DeclContext *DC = D.getDeclContext();
1692   if (DC->isRecord()) {
1693     assert(D.getASTContext().getLangOpts().CPlusPlus);
1694     return false;
1695   }
1696 
1697   return D.getLanguageLinkage() == CLanguageLinkage;
1698 }
1699 
1700 LanguageLinkage VarDecl::getLanguageLinkage() const {
1701   return getLanguageLinkageTemplate(*this);
1702 }
1703 
1704 bool VarDecl::isExternC() const {
1705   return isExternCTemplate(*this);
1706 }
1707 
1708 bool VarDecl::isInExternCContext() const {
1709   return getLexicalDeclContext()->isExternCContext();
1710 }
1711 
1712 bool VarDecl::isInExternCXXContext() const {
1713   return getLexicalDeclContext()->isExternCXXContext();
1714 }
1715 
1716 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1717 
1718 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1719   ASTContext &C) const
1720 {
1721   // C++ [basic.def]p2:
1722   //   A declaration is a definition unless [...] it contains the 'extern'
1723   //   specifier or a linkage-specification and neither an initializer [...],
1724   //   it declares a static data member in a class declaration [...].
1725   // C++1y [temp.expl.spec]p15:
1726   //   An explicit specialization of a static data member or an explicit
1727   //   specialization of a static data member template is a definition if the
1728   //   declaration includes an initializer; otherwise, it is a declaration.
1729   //
1730   // FIXME: How do you declare (but not define) a partial specialization of
1731   // a static data member template outside the containing class?
1732   if (isStaticDataMember()) {
1733     if (isOutOfLine() &&
1734         (hasInit() ||
1735          // If the first declaration is out-of-line, this may be an
1736          // instantiation of an out-of-line partial specialization of a variable
1737          // template for which we have not yet instantiated the initializer.
1738          (getFirstDecl()->isOutOfLine()
1739               ? getTemplateSpecializationKind() == TSK_Undeclared
1740               : getTemplateSpecializationKind() !=
1741                     TSK_ExplicitSpecialization) ||
1742          isa<VarTemplatePartialSpecializationDecl>(this)))
1743       return Definition;
1744     else
1745       return DeclarationOnly;
1746   }
1747   // C99 6.7p5:
1748   //   A definition of an identifier is a declaration for that identifier that
1749   //   [...] causes storage to be reserved for that object.
1750   // Note: that applies for all non-file-scope objects.
1751   // C99 6.9.2p1:
1752   //   If the declaration of an identifier for an object has file scope and an
1753   //   initializer, the declaration is an external definition for the identifier
1754   if (hasInit())
1755     return Definition;
1756 
1757   if (hasAttr<AliasAttr>())
1758     return Definition;
1759 
1760   // A variable template specialization (other than a static data member
1761   // template or an explicit specialization) is a declaration until we
1762   // instantiate its initializer.
1763   if (isa<VarTemplateSpecializationDecl>(this) &&
1764       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1765     return DeclarationOnly;
1766 
1767   if (hasExternalStorage())
1768     return DeclarationOnly;
1769 
1770   // [dcl.link] p7:
1771   //   A declaration directly contained in a linkage-specification is treated
1772   //   as if it contains the extern specifier for the purpose of determining
1773   //   the linkage of the declared name and whether it is a definition.
1774   if (isSingleLineLanguageLinkage(*this))
1775     return DeclarationOnly;
1776 
1777   // C99 6.9.2p2:
1778   //   A declaration of an object that has file scope without an initializer,
1779   //   and without a storage class specifier or the scs 'static', constitutes
1780   //   a tentative definition.
1781   // No such thing in C++.
1782   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1783     return TentativeDefinition;
1784 
1785   // What's left is (in C, block-scope) declarations without initializers or
1786   // external storage. These are definitions.
1787   return Definition;
1788 }
1789 
1790 VarDecl *VarDecl::getActingDefinition() {
1791   DefinitionKind Kind = isThisDeclarationADefinition();
1792   if (Kind != TentativeDefinition)
1793     return 0;
1794 
1795   VarDecl *LastTentative = 0;
1796   VarDecl *First = getFirstDecl();
1797   for (auto I : First->redecls()) {
1798     Kind = I->isThisDeclarationADefinition();
1799     if (Kind == Definition)
1800       return 0;
1801     else if (Kind == TentativeDefinition)
1802       LastTentative = I;
1803   }
1804   return LastTentative;
1805 }
1806 
1807 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1808   VarDecl *First = getFirstDecl();
1809   for (auto I : First->redecls()) {
1810     if (I->isThisDeclarationADefinition(C) == Definition)
1811       return I;
1812   }
1813   return 0;
1814 }
1815 
1816 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1817   DefinitionKind Kind = DeclarationOnly;
1818 
1819   const VarDecl *First = getFirstDecl();
1820   for (auto I : First->redecls()) {
1821     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
1822     if (Kind == Definition)
1823       break;
1824   }
1825 
1826   return Kind;
1827 }
1828 
1829 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1830   for (auto I : redecls()) {
1831     if (auto Expr = I->getInit()) {
1832       D = I;
1833       return Expr;
1834     }
1835   }
1836   return 0;
1837 }
1838 
1839 bool VarDecl::isOutOfLine() const {
1840   if (Decl::isOutOfLine())
1841     return true;
1842 
1843   if (!isStaticDataMember())
1844     return false;
1845 
1846   // If this static data member was instantiated from a static data member of
1847   // a class template, check whether that static data member was defined
1848   // out-of-line.
1849   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1850     return VD->isOutOfLine();
1851 
1852   return false;
1853 }
1854 
1855 VarDecl *VarDecl::getOutOfLineDefinition() {
1856   if (!isStaticDataMember())
1857     return 0;
1858 
1859   for (auto RD : redecls()) {
1860     if (RD->getLexicalDeclContext()->isFileContext())
1861       return RD;
1862   }
1863 
1864   return 0;
1865 }
1866 
1867 void VarDecl::setInit(Expr *I) {
1868   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1869     Eval->~EvaluatedStmt();
1870     getASTContext().Deallocate(Eval);
1871   }
1872 
1873   Init = I;
1874 }
1875 
1876 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1877   const LangOptions &Lang = C.getLangOpts();
1878 
1879   if (!Lang.CPlusPlus)
1880     return false;
1881 
1882   // In C++11, any variable of reference type can be used in a constant
1883   // expression if it is initialized by a constant expression.
1884   if (Lang.CPlusPlus11 && getType()->isReferenceType())
1885     return true;
1886 
1887   // Only const objects can be used in constant expressions in C++. C++98 does
1888   // not require the variable to be non-volatile, but we consider this to be a
1889   // defect.
1890   if (!getType().isConstQualified() || getType().isVolatileQualified())
1891     return false;
1892 
1893   // In C++, const, non-volatile variables of integral or enumeration types
1894   // can be used in constant expressions.
1895   if (getType()->isIntegralOrEnumerationType())
1896     return true;
1897 
1898   // Additionally, in C++11, non-volatile constexpr variables can be used in
1899   // constant expressions.
1900   return Lang.CPlusPlus11 && isConstexpr();
1901 }
1902 
1903 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1904 /// form, which contains extra information on the evaluated value of the
1905 /// initializer.
1906 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1907   EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1908   if (!Eval) {
1909     Stmt *S = Init.get<Stmt *>();
1910     // Note: EvaluatedStmt contains an APValue, which usually holds
1911     // resources not allocated from the ASTContext.  We need to do some
1912     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1913     // where we can detect whether there's anything to clean up or not.
1914     Eval = new (getASTContext()) EvaluatedStmt;
1915     Eval->Value = S;
1916     Init = Eval;
1917   }
1918   return Eval;
1919 }
1920 
1921 APValue *VarDecl::evaluateValue() const {
1922   SmallVector<PartialDiagnosticAt, 8> Notes;
1923   return evaluateValue(Notes);
1924 }
1925 
1926 namespace {
1927 // Destroy an APValue that was allocated in an ASTContext.
1928 void DestroyAPValue(void* UntypedValue) {
1929   static_cast<APValue*>(UntypedValue)->~APValue();
1930 }
1931 } // namespace
1932 
1933 APValue *VarDecl::evaluateValue(
1934     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1935   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1936 
1937   // We only produce notes indicating why an initializer is non-constant the
1938   // first time it is evaluated. FIXME: The notes won't always be emitted the
1939   // first time we try evaluation, so might not be produced at all.
1940   if (Eval->WasEvaluated)
1941     return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1942 
1943   const Expr *Init = cast<Expr>(Eval->Value);
1944   assert(!Init->isValueDependent());
1945 
1946   if (Eval->IsEvaluating) {
1947     // FIXME: Produce a diagnostic for self-initialization.
1948     Eval->CheckedICE = true;
1949     Eval->IsICE = false;
1950     return 0;
1951   }
1952 
1953   Eval->IsEvaluating = true;
1954 
1955   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1956                                             this, Notes);
1957 
1958   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1959   // or that it's empty (so that there's nothing to clean up) if evaluation
1960   // failed.
1961   if (!Result)
1962     Eval->Evaluated = APValue();
1963   else if (Eval->Evaluated.needsCleanup())
1964     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
1965 
1966   Eval->IsEvaluating = false;
1967   Eval->WasEvaluated = true;
1968 
1969   // In C++11, we have determined whether the initializer was a constant
1970   // expression as a side-effect.
1971   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
1972     Eval->CheckedICE = true;
1973     Eval->IsICE = Result && Notes.empty();
1974   }
1975 
1976   return Result ? &Eval->Evaluated : 0;
1977 }
1978 
1979 bool VarDecl::checkInitIsICE() const {
1980   // Initializers of weak variables are never ICEs.
1981   if (isWeak())
1982     return false;
1983 
1984   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1985   if (Eval->CheckedICE)
1986     // We have already checked whether this subexpression is an
1987     // integral constant expression.
1988     return Eval->IsICE;
1989 
1990   const Expr *Init = cast<Expr>(Eval->Value);
1991   assert(!Init->isValueDependent());
1992 
1993   // In C++11, evaluate the initializer to check whether it's a constant
1994   // expression.
1995   if (getASTContext().getLangOpts().CPlusPlus11) {
1996     SmallVector<PartialDiagnosticAt, 8> Notes;
1997     evaluateValue(Notes);
1998     return Eval->IsICE;
1999   }
2000 
2001   // It's an ICE whether or not the definition we found is
2002   // out-of-line.  See DR 721 and the discussion in Clang PR
2003   // 6206 for details.
2004 
2005   if (Eval->CheckingICE)
2006     return false;
2007   Eval->CheckingICE = true;
2008 
2009   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2010   Eval->CheckingICE = false;
2011   Eval->CheckedICE = true;
2012   return Eval->IsICE;
2013 }
2014 
2015 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2016   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2017     return cast<VarDecl>(MSI->getInstantiatedFrom());
2018 
2019   return 0;
2020 }
2021 
2022 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2023   if (const VarTemplateSpecializationDecl *Spec =
2024           dyn_cast<VarTemplateSpecializationDecl>(this))
2025     return Spec->getSpecializationKind();
2026 
2027   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2028     return MSI->getTemplateSpecializationKind();
2029 
2030   return TSK_Undeclared;
2031 }
2032 
2033 SourceLocation VarDecl::getPointOfInstantiation() const {
2034   if (const VarTemplateSpecializationDecl *Spec =
2035           dyn_cast<VarTemplateSpecializationDecl>(this))
2036     return Spec->getPointOfInstantiation();
2037 
2038   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2039     return MSI->getPointOfInstantiation();
2040 
2041   return SourceLocation();
2042 }
2043 
2044 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2045   return getASTContext().getTemplateOrSpecializationInfo(this)
2046       .dyn_cast<VarTemplateDecl *>();
2047 }
2048 
2049 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2050   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2051 }
2052 
2053 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2054   if (isStaticDataMember())
2055     // FIXME: Remove ?
2056     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2057     return getASTContext().getTemplateOrSpecializationInfo(this)
2058         .dyn_cast<MemberSpecializationInfo *>();
2059   return 0;
2060 }
2061 
2062 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2063                                          SourceLocation PointOfInstantiation) {
2064   assert((isa<VarTemplateSpecializationDecl>(this) ||
2065           getMemberSpecializationInfo()) &&
2066          "not a variable or static data member template specialization");
2067 
2068   if (VarTemplateSpecializationDecl *Spec =
2069           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2070     Spec->setSpecializationKind(TSK);
2071     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2072         Spec->getPointOfInstantiation().isInvalid())
2073       Spec->setPointOfInstantiation(PointOfInstantiation);
2074   }
2075 
2076   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2077     MSI->setTemplateSpecializationKind(TSK);
2078     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2079         MSI->getPointOfInstantiation().isInvalid())
2080       MSI->setPointOfInstantiation(PointOfInstantiation);
2081   }
2082 }
2083 
2084 void
2085 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2086                                             TemplateSpecializationKind TSK) {
2087   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2088          "Previous template or instantiation?");
2089   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2090 }
2091 
2092 //===----------------------------------------------------------------------===//
2093 // ParmVarDecl Implementation
2094 //===----------------------------------------------------------------------===//
2095 
2096 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2097                                  SourceLocation StartLoc,
2098                                  SourceLocation IdLoc, IdentifierInfo *Id,
2099                                  QualType T, TypeSourceInfo *TInfo,
2100                                  StorageClass S, Expr *DefArg) {
2101   return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2102                                  S, DefArg);
2103 }
2104 
2105 QualType ParmVarDecl::getOriginalType() const {
2106   TypeSourceInfo *TSI = getTypeSourceInfo();
2107   QualType T = TSI ? TSI->getType() : getType();
2108   if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2109     return DT->getOriginalType();
2110   return T;
2111 }
2112 
2113 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2114   return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2115                                  0, QualType(), 0, SC_None, 0);
2116 }
2117 
2118 SourceRange ParmVarDecl::getSourceRange() const {
2119   if (!hasInheritedDefaultArg()) {
2120     SourceRange ArgRange = getDefaultArgRange();
2121     if (ArgRange.isValid())
2122       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2123   }
2124 
2125   // DeclaratorDecl considers the range of postfix types as overlapping with the
2126   // declaration name, but this is not the case with parameters in ObjC methods.
2127   if (isa<ObjCMethodDecl>(getDeclContext()))
2128     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2129 
2130   return DeclaratorDecl::getSourceRange();
2131 }
2132 
2133 Expr *ParmVarDecl::getDefaultArg() {
2134   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2135   assert(!hasUninstantiatedDefaultArg() &&
2136          "Default argument is not yet instantiated!");
2137 
2138   Expr *Arg = getInit();
2139   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2140     return E->getSubExpr();
2141 
2142   return Arg;
2143 }
2144 
2145 SourceRange ParmVarDecl::getDefaultArgRange() const {
2146   if (const Expr *E = getInit())
2147     return E->getSourceRange();
2148 
2149   if (hasUninstantiatedDefaultArg())
2150     return getUninstantiatedDefaultArg()->getSourceRange();
2151 
2152   return SourceRange();
2153 }
2154 
2155 bool ParmVarDecl::isParameterPack() const {
2156   return isa<PackExpansionType>(getType());
2157 }
2158 
2159 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2160   getASTContext().setParameterIndex(this, parameterIndex);
2161   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2162 }
2163 
2164 unsigned ParmVarDecl::getParameterIndexLarge() const {
2165   return getASTContext().getParameterIndex(this);
2166 }
2167 
2168 //===----------------------------------------------------------------------===//
2169 // FunctionDecl Implementation
2170 //===----------------------------------------------------------------------===//
2171 
2172 void FunctionDecl::getNameForDiagnostic(
2173     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2174   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2175   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2176   if (TemplateArgs)
2177     TemplateSpecializationType::PrintTemplateArgumentList(
2178         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2179 }
2180 
2181 bool FunctionDecl::isVariadic() const {
2182   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2183     return FT->isVariadic();
2184   return false;
2185 }
2186 
2187 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2188   for (auto I : redecls()) {
2189     if (I->Body || I->IsLateTemplateParsed) {
2190       Definition = I;
2191       return true;
2192     }
2193   }
2194 
2195   return false;
2196 }
2197 
2198 bool FunctionDecl::hasTrivialBody() const
2199 {
2200   Stmt *S = getBody();
2201   if (!S) {
2202     // Since we don't have a body for this function, we don't know if it's
2203     // trivial or not.
2204     return false;
2205   }
2206 
2207   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2208     return true;
2209   return false;
2210 }
2211 
2212 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2213   for (auto I : redecls()) {
2214     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2215         I->hasAttr<AliasAttr>()) {
2216       Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2217       return true;
2218     }
2219   }
2220 
2221   return false;
2222 }
2223 
2224 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2225   if (!hasBody(Definition))
2226     return 0;
2227 
2228   if (Definition->Body)
2229     return Definition->Body.get(getASTContext().getExternalSource());
2230 
2231   return 0;
2232 }
2233 
2234 void FunctionDecl::setBody(Stmt *B) {
2235   Body = B;
2236   if (B)
2237     EndRangeLoc = B->getLocEnd();
2238 }
2239 
2240 void FunctionDecl::setPure(bool P) {
2241   IsPure = P;
2242   if (P)
2243     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2244       Parent->markedVirtualFunctionPure();
2245 }
2246 
2247 template<std::size_t Len>
2248 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2249   IdentifierInfo *II = ND->getIdentifier();
2250   return II && II->isStr(Str);
2251 }
2252 
2253 bool FunctionDecl::isMain() const {
2254   const TranslationUnitDecl *tunit =
2255     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2256   return tunit &&
2257          !tunit->getASTContext().getLangOpts().Freestanding &&
2258          isNamed(this, "main");
2259 }
2260 
2261 bool FunctionDecl::isMSVCRTEntryPoint() const {
2262   const TranslationUnitDecl *TUnit =
2263       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2264   if (!TUnit)
2265     return false;
2266 
2267   // Even though we aren't really targeting MSVCRT if we are freestanding,
2268   // semantic analysis for these functions remains the same.
2269 
2270   // MSVCRT entry points only exist on MSVCRT targets.
2271   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2272     return false;
2273 
2274   // Nameless functions like constructors cannot be entry points.
2275   if (!getIdentifier())
2276     return false;
2277 
2278   return llvm::StringSwitch<bool>(getName())
2279       .Cases("main",     // an ANSI console app
2280              "wmain",    // a Unicode console App
2281              "WinMain",  // an ANSI GUI app
2282              "wWinMain", // a Unicode GUI app
2283              "DllMain",  // a DLL
2284              true)
2285       .Default(false);
2286 }
2287 
2288 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2289   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2290   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2291          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2292          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2293          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2294 
2295   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2296     return false;
2297 
2298   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2299   if (proto->getNumParams() != 2 || proto->isVariadic())
2300     return false;
2301 
2302   ASTContext &Context =
2303     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2304       ->getASTContext();
2305 
2306   // The result type and first argument type are constant across all
2307   // these operators.  The second argument must be exactly void*.
2308   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2309 }
2310 
2311 static bool isNamespaceStd(const DeclContext *DC) {
2312   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2313   return ND && isNamed(ND, "std") &&
2314          ND->getParent()->getRedeclContext()->isTranslationUnit();
2315 }
2316 
2317 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2318   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2319     return false;
2320   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2321       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2322       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2323       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2324     return false;
2325 
2326   if (isa<CXXRecordDecl>(getDeclContext()))
2327     return false;
2328 
2329   // This can only fail for an invalid 'operator new' declaration.
2330   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2331     return false;
2332 
2333   const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2334   if (FPT->getNumParams() > 2 || FPT->isVariadic())
2335     return false;
2336 
2337   // If this is a single-parameter function, it must be a replaceable global
2338   // allocation or deallocation function.
2339   if (FPT->getNumParams() == 1)
2340     return true;
2341 
2342   // Otherwise, we're looking for a second parameter whose type is
2343   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2344   QualType Ty = FPT->getParamType(1);
2345   ASTContext &Ctx = getASTContext();
2346   if (Ctx.getLangOpts().SizedDeallocation &&
2347       Ctx.hasSameType(Ty, Ctx.getSizeType()))
2348     return true;
2349   if (!Ty->isReferenceType())
2350     return false;
2351   Ty = Ty->getPointeeType();
2352   if (Ty.getCVRQualifiers() != Qualifiers::Const)
2353     return false;
2354   // FIXME: Recognise nothrow_t in an inline namespace inside std?
2355   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2356   return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2357 }
2358 
2359 FunctionDecl *
2360 FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2361   ASTContext &Ctx = getASTContext();
2362   if (!Ctx.getLangOpts().SizedDeallocation)
2363     return 0;
2364 
2365   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2366     return 0;
2367   if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2368       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2369     return 0;
2370   if (isa<CXXRecordDecl>(getDeclContext()))
2371     return 0;
2372 
2373   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2374     return 0;
2375 
2376   if (getNumParams() != 2 || isVariadic() ||
2377       !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
2378                        Ctx.getSizeType()))
2379     return 0;
2380 
2381   // This is a sized deallocation function. Find the corresponding unsized
2382   // deallocation function.
2383   lookup_const_result R = getDeclContext()->lookup(getDeclName());
2384   for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2385        ++RI)
2386     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2387       if (FD->getNumParams() == 1 && !FD->isVariadic())
2388         return FD;
2389   return 0;
2390 }
2391 
2392 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2393   return getLanguageLinkageTemplate(*this);
2394 }
2395 
2396 bool FunctionDecl::isExternC() const {
2397   return isExternCTemplate(*this);
2398 }
2399 
2400 bool FunctionDecl::isInExternCContext() const {
2401   return getLexicalDeclContext()->isExternCContext();
2402 }
2403 
2404 bool FunctionDecl::isInExternCXXContext() const {
2405   return getLexicalDeclContext()->isExternCXXContext();
2406 }
2407 
2408 bool FunctionDecl::isGlobal() const {
2409   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2410     return Method->isStatic();
2411 
2412   if (getCanonicalDecl()->getStorageClass() == SC_Static)
2413     return false;
2414 
2415   for (const DeclContext *DC = getDeclContext();
2416        DC->isNamespace();
2417        DC = DC->getParent()) {
2418     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2419       if (!Namespace->getDeclName())
2420         return false;
2421       break;
2422     }
2423   }
2424 
2425   return true;
2426 }
2427 
2428 bool FunctionDecl::isNoReturn() const {
2429   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2430          hasAttr<C11NoReturnAttr>() ||
2431          getType()->getAs<FunctionType>()->getNoReturnAttr();
2432 }
2433 
2434 void
2435 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2436   redeclarable_base::setPreviousDecl(PrevDecl);
2437 
2438   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2439     FunctionTemplateDecl *PrevFunTmpl
2440       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2441     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2442     FunTmpl->setPreviousDecl(PrevFunTmpl);
2443   }
2444 
2445   if (PrevDecl && PrevDecl->IsInline)
2446     IsInline = true;
2447 }
2448 
2449 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2450   return getFirstDecl();
2451 }
2452 
2453 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2454 
2455 /// \brief Returns a value indicating whether this function
2456 /// corresponds to a builtin function.
2457 ///
2458 /// The function corresponds to a built-in function if it is
2459 /// declared at translation scope or within an extern "C" block and
2460 /// its name matches with the name of a builtin. The returned value
2461 /// will be 0 for functions that do not correspond to a builtin, a
2462 /// value of type \c Builtin::ID if in the target-independent range
2463 /// \c [1,Builtin::First), or a target-specific builtin value.
2464 unsigned FunctionDecl::getBuiltinID() const {
2465   if (!getIdentifier())
2466     return 0;
2467 
2468   unsigned BuiltinID = getIdentifier()->getBuiltinID();
2469   if (!BuiltinID)
2470     return 0;
2471 
2472   ASTContext &Context = getASTContext();
2473   if (Context.getLangOpts().CPlusPlus) {
2474     const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2475         getFirstDecl()->getDeclContext());
2476     // In C++, the first declaration of a builtin is always inside an implicit
2477     // extern "C".
2478     // FIXME: A recognised library function may not be directly in an extern "C"
2479     // declaration, for instance "extern "C" { namespace std { decl } }".
2480     if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2481       return 0;
2482   }
2483 
2484   // If the function is marked "overloadable", it has a different mangled name
2485   // and is not the C library function.
2486   if (hasAttr<OverloadableAttr>())
2487     return 0;
2488 
2489   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2490     return BuiltinID;
2491 
2492   // This function has the name of a known C library
2493   // function. Determine whether it actually refers to the C library
2494   // function or whether it just has the same name.
2495 
2496   // If this is a static function, it's not a builtin.
2497   if (getStorageClass() == SC_Static)
2498     return 0;
2499 
2500   return BuiltinID;
2501 }
2502 
2503 
2504 /// getNumParams - Return the number of parameters this function must have
2505 /// based on its FunctionType.  This is the length of the ParamInfo array
2506 /// after it has been created.
2507 unsigned FunctionDecl::getNumParams() const {
2508   const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2509   return FPT ? FPT->getNumParams() : 0;
2510 }
2511 
2512 void FunctionDecl::setParams(ASTContext &C,
2513                              ArrayRef<ParmVarDecl *> NewParamInfo) {
2514   assert(ParamInfo == 0 && "Already has param info!");
2515   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2516 
2517   // Zero params -> null pointer.
2518   if (!NewParamInfo.empty()) {
2519     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2520     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2521   }
2522 }
2523 
2524 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2525   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2526 
2527   if (!NewDecls.empty()) {
2528     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2529     std::copy(NewDecls.begin(), NewDecls.end(), A);
2530     DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
2531   }
2532 }
2533 
2534 /// getMinRequiredArguments - Returns the minimum number of arguments
2535 /// needed to call this function. This may be fewer than the number of
2536 /// function parameters, if some of the parameters have default
2537 /// arguments (in C++) or the last parameter is a parameter pack.
2538 unsigned FunctionDecl::getMinRequiredArguments() const {
2539   if (!getASTContext().getLangOpts().CPlusPlus)
2540     return getNumParams();
2541 
2542   unsigned NumRequiredArgs = getNumParams();
2543 
2544   // If the last parameter is a parameter pack, we don't need an argument for
2545   // it.
2546   if (NumRequiredArgs > 0 &&
2547       getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2548     --NumRequiredArgs;
2549 
2550   // If this parameter has a default argument, we don't need an argument for
2551   // it.
2552   while (NumRequiredArgs > 0 &&
2553          getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
2554     --NumRequiredArgs;
2555 
2556   // We might have parameter packs before the end. These can't be deduced,
2557   // but they can still handle multiple arguments.
2558   unsigned ArgIdx = NumRequiredArgs;
2559   while (ArgIdx > 0) {
2560     if (getParamDecl(ArgIdx - 1)->isParameterPack())
2561       NumRequiredArgs = ArgIdx;
2562 
2563     --ArgIdx;
2564   }
2565 
2566   return NumRequiredArgs;
2567 }
2568 
2569 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2570   // Only consider file-scope declarations in this test.
2571   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2572     return false;
2573 
2574   // Only consider explicit declarations; the presence of a builtin for a
2575   // libcall shouldn't affect whether a definition is externally visible.
2576   if (Redecl->isImplicit())
2577     return false;
2578 
2579   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2580     return true; // Not an inline definition
2581 
2582   return false;
2583 }
2584 
2585 /// \brief For a function declaration in C or C++, determine whether this
2586 /// declaration causes the definition to be externally visible.
2587 ///
2588 /// Specifically, this determines if adding the current declaration to the set
2589 /// of redeclarations of the given functions causes
2590 /// isInlineDefinitionExternallyVisible to change from false to true.
2591 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2592   assert(!doesThisDeclarationHaveABody() &&
2593          "Must have a declaration without a body.");
2594 
2595   ASTContext &Context = getASTContext();
2596 
2597   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2598     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2599     // an externally visible definition.
2600     //
2601     // FIXME: What happens if gnu_inline gets added on after the first
2602     // declaration?
2603     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2604       return false;
2605 
2606     const FunctionDecl *Prev = this;
2607     bool FoundBody = false;
2608     while ((Prev = Prev->getPreviousDecl())) {
2609       FoundBody |= Prev->Body.isValid();
2610 
2611       if (Prev->Body) {
2612         // If it's not the case that both 'inline' and 'extern' are
2613         // specified on the definition, then it is always externally visible.
2614         if (!Prev->isInlineSpecified() ||
2615             Prev->getStorageClass() != SC_Extern)
2616           return false;
2617       } else if (Prev->isInlineSpecified() &&
2618                  Prev->getStorageClass() != SC_Extern) {
2619         return false;
2620       }
2621     }
2622     return FoundBody;
2623   }
2624 
2625   if (Context.getLangOpts().CPlusPlus)
2626     return false;
2627 
2628   // C99 6.7.4p6:
2629   //   [...] If all of the file scope declarations for a function in a
2630   //   translation unit include the inline function specifier without extern,
2631   //   then the definition in that translation unit is an inline definition.
2632   if (isInlineSpecified() && getStorageClass() != SC_Extern)
2633     return false;
2634   const FunctionDecl *Prev = this;
2635   bool FoundBody = false;
2636   while ((Prev = Prev->getPreviousDecl())) {
2637     FoundBody |= Prev->Body.isValid();
2638     if (RedeclForcesDefC99(Prev))
2639       return false;
2640   }
2641   return FoundBody;
2642 }
2643 
2644 /// \brief For an inline function definition in C, or for a gnu_inline function
2645 /// in C++, determine whether the definition will be externally visible.
2646 ///
2647 /// Inline function definitions are always available for inlining optimizations.
2648 /// However, depending on the language dialect, declaration specifiers, and
2649 /// attributes, the definition of an inline function may or may not be
2650 /// "externally" visible to other translation units in the program.
2651 ///
2652 /// In C99, inline definitions are not externally visible by default. However,
2653 /// if even one of the global-scope declarations is marked "extern inline", the
2654 /// inline definition becomes externally visible (C99 6.7.4p6).
2655 ///
2656 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2657 /// definition, we use the GNU semantics for inline, which are nearly the
2658 /// opposite of C99 semantics. In particular, "inline" by itself will create
2659 /// an externally visible symbol, but "extern inline" will not create an
2660 /// externally visible symbol.
2661 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2662   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2663   assert(isInlined() && "Function must be inline");
2664   ASTContext &Context = getASTContext();
2665 
2666   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2667     // Note: If you change the logic here, please change
2668     // doesDeclarationForceExternallyVisibleDefinition as well.
2669     //
2670     // If it's not the case that both 'inline' and 'extern' are
2671     // specified on the definition, then this inline definition is
2672     // externally visible.
2673     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2674       return true;
2675 
2676     // If any declaration is 'inline' but not 'extern', then this definition
2677     // is externally visible.
2678     for (auto Redecl : redecls()) {
2679       if (Redecl->isInlineSpecified() &&
2680           Redecl->getStorageClass() != SC_Extern)
2681         return true;
2682     }
2683 
2684     return false;
2685   }
2686 
2687   // The rest of this function is C-only.
2688   assert(!Context.getLangOpts().CPlusPlus &&
2689          "should not use C inline rules in C++");
2690 
2691   // C99 6.7.4p6:
2692   //   [...] If all of the file scope declarations for a function in a
2693   //   translation unit include the inline function specifier without extern,
2694   //   then the definition in that translation unit is an inline definition.
2695   for (auto Redecl : redecls()) {
2696     if (RedeclForcesDefC99(Redecl))
2697       return true;
2698   }
2699 
2700   // C99 6.7.4p6:
2701   //   An inline definition does not provide an external definition for the
2702   //   function, and does not forbid an external definition in another
2703   //   translation unit.
2704   return false;
2705 }
2706 
2707 /// getOverloadedOperator - Which C++ overloaded operator this
2708 /// function represents, if any.
2709 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2710   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2711     return getDeclName().getCXXOverloadedOperator();
2712   else
2713     return OO_None;
2714 }
2715 
2716 /// getLiteralIdentifier - The literal suffix identifier this function
2717 /// represents, if any.
2718 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2719   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2720     return getDeclName().getCXXLiteralIdentifier();
2721   else
2722     return 0;
2723 }
2724 
2725 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2726   if (TemplateOrSpecialization.isNull())
2727     return TK_NonTemplate;
2728   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2729     return TK_FunctionTemplate;
2730   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2731     return TK_MemberSpecialization;
2732   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2733     return TK_FunctionTemplateSpecialization;
2734   if (TemplateOrSpecialization.is
2735                                <DependentFunctionTemplateSpecializationInfo*>())
2736     return TK_DependentFunctionTemplateSpecialization;
2737 
2738   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2739 }
2740 
2741 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2742   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2743     return cast<FunctionDecl>(Info->getInstantiatedFrom());
2744 
2745   return 0;
2746 }
2747 
2748 void
2749 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2750                                                FunctionDecl *FD,
2751                                                TemplateSpecializationKind TSK) {
2752   assert(TemplateOrSpecialization.isNull() &&
2753          "Member function is already a specialization");
2754   MemberSpecializationInfo *Info
2755     = new (C) MemberSpecializationInfo(FD, TSK);
2756   TemplateOrSpecialization = Info;
2757 }
2758 
2759 bool FunctionDecl::isImplicitlyInstantiable() const {
2760   // If the function is invalid, it can't be implicitly instantiated.
2761   if (isInvalidDecl())
2762     return false;
2763 
2764   switch (getTemplateSpecializationKind()) {
2765   case TSK_Undeclared:
2766   case TSK_ExplicitInstantiationDefinition:
2767     return false;
2768 
2769   case TSK_ImplicitInstantiation:
2770     return true;
2771 
2772   // It is possible to instantiate TSK_ExplicitSpecialization kind
2773   // if the FunctionDecl has a class scope specialization pattern.
2774   case TSK_ExplicitSpecialization:
2775     return getClassScopeSpecializationPattern() != 0;
2776 
2777   case TSK_ExplicitInstantiationDeclaration:
2778     // Handled below.
2779     break;
2780   }
2781 
2782   // Find the actual template from which we will instantiate.
2783   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2784   bool HasPattern = false;
2785   if (PatternDecl)
2786     HasPattern = PatternDecl->hasBody(PatternDecl);
2787 
2788   // C++0x [temp.explicit]p9:
2789   //   Except for inline functions, other explicit instantiation declarations
2790   //   have the effect of suppressing the implicit instantiation of the entity
2791   //   to which they refer.
2792   if (!HasPattern || !PatternDecl)
2793     return true;
2794 
2795   return PatternDecl->isInlined();
2796 }
2797 
2798 bool FunctionDecl::isTemplateInstantiation() const {
2799   switch (getTemplateSpecializationKind()) {
2800     case TSK_Undeclared:
2801     case TSK_ExplicitSpecialization:
2802       return false;
2803     case TSK_ImplicitInstantiation:
2804     case TSK_ExplicitInstantiationDeclaration:
2805     case TSK_ExplicitInstantiationDefinition:
2806       return true;
2807   }
2808   llvm_unreachable("All TSK values handled.");
2809 }
2810 
2811 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2812   // Handle class scope explicit specialization special case.
2813   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2814     return getClassScopeSpecializationPattern();
2815 
2816   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2817     while (Primary->getInstantiatedFromMemberTemplate()) {
2818       // If we have hit a point where the user provided a specialization of
2819       // this template, we're done looking.
2820       if (Primary->isMemberSpecialization())
2821         break;
2822 
2823       Primary = Primary->getInstantiatedFromMemberTemplate();
2824     }
2825 
2826     return Primary->getTemplatedDecl();
2827   }
2828 
2829   return getInstantiatedFromMemberFunction();
2830 }
2831 
2832 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2833   if (FunctionTemplateSpecializationInfo *Info
2834         = TemplateOrSpecialization
2835             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2836     return Info->Template.getPointer();
2837   }
2838   return 0;
2839 }
2840 
2841 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2842     return getASTContext().getClassScopeSpecializationPattern(this);
2843 }
2844 
2845 const TemplateArgumentList *
2846 FunctionDecl::getTemplateSpecializationArgs() const {
2847   if (FunctionTemplateSpecializationInfo *Info
2848         = TemplateOrSpecialization
2849             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2850     return Info->TemplateArguments;
2851   }
2852   return 0;
2853 }
2854 
2855 const ASTTemplateArgumentListInfo *
2856 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2857   if (FunctionTemplateSpecializationInfo *Info
2858         = TemplateOrSpecialization
2859             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2860     return Info->TemplateArgumentsAsWritten;
2861   }
2862   return 0;
2863 }
2864 
2865 void
2866 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2867                                                 FunctionTemplateDecl *Template,
2868                                      const TemplateArgumentList *TemplateArgs,
2869                                                 void *InsertPos,
2870                                                 TemplateSpecializationKind TSK,
2871                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
2872                                           SourceLocation PointOfInstantiation) {
2873   assert(TSK != TSK_Undeclared &&
2874          "Must specify the type of function template specialization");
2875   FunctionTemplateSpecializationInfo *Info
2876     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2877   if (!Info)
2878     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2879                                                       TemplateArgs,
2880                                                       TemplateArgsAsWritten,
2881                                                       PointOfInstantiation);
2882   TemplateOrSpecialization = Info;
2883   Template->addSpecialization(Info, InsertPos);
2884 }
2885 
2886 void
2887 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2888                                     const UnresolvedSetImpl &Templates,
2889                              const TemplateArgumentListInfo &TemplateArgs) {
2890   assert(TemplateOrSpecialization.isNull());
2891   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2892   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2893   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2894   void *Buffer = Context.Allocate(Size);
2895   DependentFunctionTemplateSpecializationInfo *Info =
2896     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2897                                                              TemplateArgs);
2898   TemplateOrSpecialization = Info;
2899 }
2900 
2901 DependentFunctionTemplateSpecializationInfo::
2902 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2903                                       const TemplateArgumentListInfo &TArgs)
2904   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2905 
2906   d.NumTemplates = Ts.size();
2907   d.NumArgs = TArgs.size();
2908 
2909   FunctionTemplateDecl **TsArray =
2910     const_cast<FunctionTemplateDecl**>(getTemplates());
2911   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2912     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2913 
2914   TemplateArgumentLoc *ArgsArray =
2915     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2916   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2917     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2918 }
2919 
2920 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2921   // For a function template specialization, query the specialization
2922   // information object.
2923   FunctionTemplateSpecializationInfo *FTSInfo
2924     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2925   if (FTSInfo)
2926     return FTSInfo->getTemplateSpecializationKind();
2927 
2928   MemberSpecializationInfo *MSInfo
2929     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2930   if (MSInfo)
2931     return MSInfo->getTemplateSpecializationKind();
2932 
2933   return TSK_Undeclared;
2934 }
2935 
2936 void
2937 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2938                                           SourceLocation PointOfInstantiation) {
2939   if (FunctionTemplateSpecializationInfo *FTSInfo
2940         = TemplateOrSpecialization.dyn_cast<
2941                                     FunctionTemplateSpecializationInfo*>()) {
2942     FTSInfo->setTemplateSpecializationKind(TSK);
2943     if (TSK != TSK_ExplicitSpecialization &&
2944         PointOfInstantiation.isValid() &&
2945         FTSInfo->getPointOfInstantiation().isInvalid())
2946       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2947   } else if (MemberSpecializationInfo *MSInfo
2948              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2949     MSInfo->setTemplateSpecializationKind(TSK);
2950     if (TSK != TSK_ExplicitSpecialization &&
2951         PointOfInstantiation.isValid() &&
2952         MSInfo->getPointOfInstantiation().isInvalid())
2953       MSInfo->setPointOfInstantiation(PointOfInstantiation);
2954   } else
2955     llvm_unreachable("Function cannot have a template specialization kind");
2956 }
2957 
2958 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2959   if (FunctionTemplateSpecializationInfo *FTSInfo
2960         = TemplateOrSpecialization.dyn_cast<
2961                                         FunctionTemplateSpecializationInfo*>())
2962     return FTSInfo->getPointOfInstantiation();
2963   else if (MemberSpecializationInfo *MSInfo
2964              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2965     return MSInfo->getPointOfInstantiation();
2966 
2967   return SourceLocation();
2968 }
2969 
2970 bool FunctionDecl::isOutOfLine() const {
2971   if (Decl::isOutOfLine())
2972     return true;
2973 
2974   // If this function was instantiated from a member function of a
2975   // class template, check whether that member function was defined out-of-line.
2976   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2977     const FunctionDecl *Definition;
2978     if (FD->hasBody(Definition))
2979       return Definition->isOutOfLine();
2980   }
2981 
2982   // If this function was instantiated from a function template,
2983   // check whether that function template was defined out-of-line.
2984   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2985     const FunctionDecl *Definition;
2986     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2987       return Definition->isOutOfLine();
2988   }
2989 
2990   return false;
2991 }
2992 
2993 SourceRange FunctionDecl::getSourceRange() const {
2994   return SourceRange(getOuterLocStart(), EndRangeLoc);
2995 }
2996 
2997 unsigned FunctionDecl::getMemoryFunctionKind() const {
2998   IdentifierInfo *FnInfo = getIdentifier();
2999 
3000   if (!FnInfo)
3001     return 0;
3002 
3003   // Builtin handling.
3004   switch (getBuiltinID()) {
3005   case Builtin::BI__builtin_memset:
3006   case Builtin::BI__builtin___memset_chk:
3007   case Builtin::BImemset:
3008     return Builtin::BImemset;
3009 
3010   case Builtin::BI__builtin_memcpy:
3011   case Builtin::BI__builtin___memcpy_chk:
3012   case Builtin::BImemcpy:
3013     return Builtin::BImemcpy;
3014 
3015   case Builtin::BI__builtin_memmove:
3016   case Builtin::BI__builtin___memmove_chk:
3017   case Builtin::BImemmove:
3018     return Builtin::BImemmove;
3019 
3020   case Builtin::BIstrlcpy:
3021     return Builtin::BIstrlcpy;
3022   case Builtin::BIstrlcat:
3023     return Builtin::BIstrlcat;
3024 
3025   case Builtin::BI__builtin_memcmp:
3026   case Builtin::BImemcmp:
3027     return Builtin::BImemcmp;
3028 
3029   case Builtin::BI__builtin_strncpy:
3030   case Builtin::BI__builtin___strncpy_chk:
3031   case Builtin::BIstrncpy:
3032     return Builtin::BIstrncpy;
3033 
3034   case Builtin::BI__builtin_strncmp:
3035   case Builtin::BIstrncmp:
3036     return Builtin::BIstrncmp;
3037 
3038   case Builtin::BI__builtin_strncasecmp:
3039   case Builtin::BIstrncasecmp:
3040     return Builtin::BIstrncasecmp;
3041 
3042   case Builtin::BI__builtin_strncat:
3043   case Builtin::BI__builtin___strncat_chk:
3044   case Builtin::BIstrncat:
3045     return Builtin::BIstrncat;
3046 
3047   case Builtin::BI__builtin_strndup:
3048   case Builtin::BIstrndup:
3049     return Builtin::BIstrndup;
3050 
3051   case Builtin::BI__builtin_strlen:
3052   case Builtin::BIstrlen:
3053     return Builtin::BIstrlen;
3054 
3055   default:
3056     if (isExternC()) {
3057       if (FnInfo->isStr("memset"))
3058         return Builtin::BImemset;
3059       else if (FnInfo->isStr("memcpy"))
3060         return Builtin::BImemcpy;
3061       else if (FnInfo->isStr("memmove"))
3062         return Builtin::BImemmove;
3063       else if (FnInfo->isStr("memcmp"))
3064         return Builtin::BImemcmp;
3065       else if (FnInfo->isStr("strncpy"))
3066         return Builtin::BIstrncpy;
3067       else if (FnInfo->isStr("strncmp"))
3068         return Builtin::BIstrncmp;
3069       else if (FnInfo->isStr("strncasecmp"))
3070         return Builtin::BIstrncasecmp;
3071       else if (FnInfo->isStr("strncat"))
3072         return Builtin::BIstrncat;
3073       else if (FnInfo->isStr("strndup"))
3074         return Builtin::BIstrndup;
3075       else if (FnInfo->isStr("strlen"))
3076         return Builtin::BIstrlen;
3077     }
3078     break;
3079   }
3080   return 0;
3081 }
3082 
3083 //===----------------------------------------------------------------------===//
3084 // FieldDecl Implementation
3085 //===----------------------------------------------------------------------===//
3086 
3087 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3088                              SourceLocation StartLoc, SourceLocation IdLoc,
3089                              IdentifierInfo *Id, QualType T,
3090                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3091                              InClassInitStyle InitStyle) {
3092   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3093                                BW, Mutable, InitStyle);
3094 }
3095 
3096 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3097   return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3098                                0, QualType(), 0, 0, false, ICIS_NoInit);
3099 }
3100 
3101 bool FieldDecl::isAnonymousStructOrUnion() const {
3102   if (!isImplicit() || getDeclName())
3103     return false;
3104 
3105   if (const RecordType *Record = getType()->getAs<RecordType>())
3106     return Record->getDecl()->isAnonymousStructOrUnion();
3107 
3108   return false;
3109 }
3110 
3111 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3112   assert(isBitField() && "not a bitfield");
3113   Expr *BitWidth = InitializerOrBitWidth.getPointer();
3114   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3115 }
3116 
3117 unsigned FieldDecl::getFieldIndex() const {
3118   const FieldDecl *Canonical = getCanonicalDecl();
3119   if (Canonical != this)
3120     return Canonical->getFieldIndex();
3121 
3122   if (CachedFieldIndex) return CachedFieldIndex - 1;
3123 
3124   unsigned Index = 0;
3125   const RecordDecl *RD = getParent();
3126 
3127   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
3128        I != E; ++I, ++Index)
3129     I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3130 
3131   assert(CachedFieldIndex && "failed to find field in parent");
3132   return CachedFieldIndex - 1;
3133 }
3134 
3135 SourceRange FieldDecl::getSourceRange() const {
3136   if (const Expr *E = InitializerOrBitWidth.getPointer())
3137     return SourceRange(getInnerLocStart(), E->getLocEnd());
3138   return DeclaratorDecl::getSourceRange();
3139 }
3140 
3141 void FieldDecl::setBitWidth(Expr *Width) {
3142   assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3143          "bit width or initializer already set");
3144   InitializerOrBitWidth.setPointer(Width);
3145 }
3146 
3147 void FieldDecl::setInClassInitializer(Expr *Init) {
3148   assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
3149          "bit width or initializer already set");
3150   InitializerOrBitWidth.setPointer(Init);
3151 }
3152 
3153 //===----------------------------------------------------------------------===//
3154 // TagDecl Implementation
3155 //===----------------------------------------------------------------------===//
3156 
3157 SourceLocation TagDecl::getOuterLocStart() const {
3158   return getTemplateOrInnerLocStart(this);
3159 }
3160 
3161 SourceRange TagDecl::getSourceRange() const {
3162   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3163   return SourceRange(getOuterLocStart(), E);
3164 }
3165 
3166 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3167 
3168 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3169   NamedDeclOrQualifier = TDD;
3170   if (TypeForDecl)
3171     assert(TypeForDecl->isLinkageValid());
3172   assert(isLinkageValid());
3173 }
3174 
3175 void TagDecl::startDefinition() {
3176   IsBeingDefined = true;
3177 
3178   if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3179     struct CXXRecordDecl::DefinitionData *Data =
3180       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3181     for (auto I : redecls())
3182       cast<CXXRecordDecl>(I)->DefinitionData = Data;
3183   }
3184 }
3185 
3186 void TagDecl::completeDefinition() {
3187   assert((!isa<CXXRecordDecl>(this) ||
3188           cast<CXXRecordDecl>(this)->hasDefinition()) &&
3189          "definition completed but not started");
3190 
3191   IsCompleteDefinition = true;
3192   IsBeingDefined = false;
3193 
3194   if (ASTMutationListener *L = getASTMutationListener())
3195     L->CompletedTagDefinition(this);
3196 }
3197 
3198 TagDecl *TagDecl::getDefinition() const {
3199   if (isCompleteDefinition())
3200     return const_cast<TagDecl *>(this);
3201 
3202   // If it's possible for us to have an out-of-date definition, check now.
3203   if (MayHaveOutOfDateDef) {
3204     if (IdentifierInfo *II = getIdentifier()) {
3205       if (II->isOutOfDate()) {
3206         updateOutOfDate(*II);
3207       }
3208     }
3209   }
3210 
3211   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3212     return CXXRD->getDefinition();
3213 
3214   for (auto R : redecls())
3215     if (R->isCompleteDefinition())
3216       return R;
3217 
3218   return 0;
3219 }
3220 
3221 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3222   if (QualifierLoc) {
3223     // Make sure the extended qualifier info is allocated.
3224     if (!hasExtInfo())
3225       NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3226     // Set qualifier info.
3227     getExtInfo()->QualifierLoc = QualifierLoc;
3228   } else {
3229     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3230     if (hasExtInfo()) {
3231       if (getExtInfo()->NumTemplParamLists == 0) {
3232         getASTContext().Deallocate(getExtInfo());
3233         NamedDeclOrQualifier = (TypedefNameDecl*) 0;
3234       }
3235       else
3236         getExtInfo()->QualifierLoc = QualifierLoc;
3237     }
3238   }
3239 }
3240 
3241 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3242                                             unsigned NumTPLists,
3243                                             TemplateParameterList **TPLists) {
3244   assert(NumTPLists > 0);
3245   // Make sure the extended decl info is allocated.
3246   if (!hasExtInfo())
3247     // Allocate external info struct.
3248     NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3249   // Set the template parameter lists info.
3250   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3251 }
3252 
3253 //===----------------------------------------------------------------------===//
3254 // EnumDecl Implementation
3255 //===----------------------------------------------------------------------===//
3256 
3257 void EnumDecl::anchor() { }
3258 
3259 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3260                            SourceLocation StartLoc, SourceLocation IdLoc,
3261                            IdentifierInfo *Id,
3262                            EnumDecl *PrevDecl, bool IsScoped,
3263                            bool IsScopedUsingClassTag, bool IsFixed) {
3264   EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3265                                         IsScoped, IsScopedUsingClassTag,
3266                                         IsFixed);
3267   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3268   C.getTypeDeclType(Enum, PrevDecl);
3269   return Enum;
3270 }
3271 
3272 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3273   EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3274                                         0, 0, false, false, false);
3275   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3276   return Enum;
3277 }
3278 
3279 SourceRange EnumDecl::getIntegerTypeRange() const {
3280   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3281     return TI->getTypeLoc().getSourceRange();
3282   return SourceRange();
3283 }
3284 
3285 void EnumDecl::completeDefinition(QualType NewType,
3286                                   QualType NewPromotionType,
3287                                   unsigned NumPositiveBits,
3288                                   unsigned NumNegativeBits) {
3289   assert(!isCompleteDefinition() && "Cannot redefine enums!");
3290   if (!IntegerType)
3291     IntegerType = NewType.getTypePtr();
3292   PromotionType = NewPromotionType;
3293   setNumPositiveBits(NumPositiveBits);
3294   setNumNegativeBits(NumNegativeBits);
3295   TagDecl::completeDefinition();
3296 }
3297 
3298 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3299   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3300     return MSI->getTemplateSpecializationKind();
3301 
3302   return TSK_Undeclared;
3303 }
3304 
3305 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3306                                          SourceLocation PointOfInstantiation) {
3307   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3308   assert(MSI && "Not an instantiated member enumeration?");
3309   MSI->setTemplateSpecializationKind(TSK);
3310   if (TSK != TSK_ExplicitSpecialization &&
3311       PointOfInstantiation.isValid() &&
3312       MSI->getPointOfInstantiation().isInvalid())
3313     MSI->setPointOfInstantiation(PointOfInstantiation);
3314 }
3315 
3316 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3317   if (SpecializationInfo)
3318     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3319 
3320   return 0;
3321 }
3322 
3323 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3324                                             TemplateSpecializationKind TSK) {
3325   assert(!SpecializationInfo && "Member enum is already a specialization");
3326   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3327 }
3328 
3329 //===----------------------------------------------------------------------===//
3330 // RecordDecl Implementation
3331 //===----------------------------------------------------------------------===//
3332 
3333 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3334                        SourceLocation StartLoc, SourceLocation IdLoc,
3335                        IdentifierInfo *Id, RecordDecl *PrevDecl)
3336   : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
3337   HasFlexibleArrayMember = false;
3338   AnonymousStructOrUnion = false;
3339   HasObjectMember = false;
3340   HasVolatileMember = false;
3341   LoadedFieldsFromExternalStorage = false;
3342   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3343 }
3344 
3345 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3346                                SourceLocation StartLoc, SourceLocation IdLoc,
3347                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
3348   RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3349                                          PrevDecl);
3350   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3351 
3352   C.getTypeDeclType(R, PrevDecl);
3353   return R;
3354 }
3355 
3356 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3357   RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3358                                          SourceLocation(), 0, 0);
3359   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3360   return R;
3361 }
3362 
3363 bool RecordDecl::isInjectedClassName() const {
3364   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3365     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3366 }
3367 
3368 RecordDecl::field_iterator RecordDecl::field_begin() const {
3369   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3370     LoadFieldsFromExternalStorage();
3371 
3372   return field_iterator(decl_iterator(FirstDecl));
3373 }
3374 
3375 /// completeDefinition - Notes that the definition of this type is now
3376 /// complete.
3377 void RecordDecl::completeDefinition() {
3378   assert(!isCompleteDefinition() && "Cannot redefine record!");
3379   TagDecl::completeDefinition();
3380 }
3381 
3382 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3383 /// This which can be turned on with an attribute, pragma, or the
3384 /// -mms-bitfields command-line option.
3385 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3386   return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3387 }
3388 
3389 static bool isFieldOrIndirectField(Decl::Kind K) {
3390   return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3391 }
3392 
3393 void RecordDecl::LoadFieldsFromExternalStorage() const {
3394   ExternalASTSource *Source = getASTContext().getExternalSource();
3395   assert(hasExternalLexicalStorage() && Source && "No external storage?");
3396 
3397   // Notify that we have a RecordDecl doing some initialization.
3398   ExternalASTSource::Deserializing TheFields(Source);
3399 
3400   SmallVector<Decl*, 64> Decls;
3401   LoadedFieldsFromExternalStorage = true;
3402   switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3403                                            Decls)) {
3404   case ELR_Success:
3405     break;
3406 
3407   case ELR_AlreadyLoaded:
3408   case ELR_Failure:
3409     return;
3410   }
3411 
3412 #ifndef NDEBUG
3413   // Check that all decls we got were FieldDecls.
3414   for (unsigned i=0, e=Decls.size(); i != e; ++i)
3415     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3416 #endif
3417 
3418   if (Decls.empty())
3419     return;
3420 
3421   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3422                                                  /*FieldsAlreadyLoaded=*/false);
3423 }
3424 
3425 //===----------------------------------------------------------------------===//
3426 // BlockDecl Implementation
3427 //===----------------------------------------------------------------------===//
3428 
3429 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3430   assert(ParamInfo == 0 && "Already has param info!");
3431 
3432   // Zero params -> null pointer.
3433   if (!NewParamInfo.empty()) {
3434     NumParams = NewParamInfo.size();
3435     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3436     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3437   }
3438 }
3439 
3440 void BlockDecl::setCaptures(ASTContext &Context,
3441                             const Capture *begin,
3442                             const Capture *end,
3443                             bool capturesCXXThis) {
3444   CapturesCXXThis = capturesCXXThis;
3445 
3446   if (begin == end) {
3447     NumCaptures = 0;
3448     Captures = 0;
3449     return;
3450   }
3451 
3452   NumCaptures = end - begin;
3453 
3454   // Avoid new Capture[] because we don't want to provide a default
3455   // constructor.
3456   size_t allocationSize = NumCaptures * sizeof(Capture);
3457   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3458   memcpy(buffer, begin, allocationSize);
3459   Captures = static_cast<Capture*>(buffer);
3460 }
3461 
3462 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3463   for (const auto &I : captures())
3464     // Only auto vars can be captured, so no redeclaration worries.
3465     if (I.getVariable() == variable)
3466       return true;
3467 
3468   return false;
3469 }
3470 
3471 SourceRange BlockDecl::getSourceRange() const {
3472   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3473 }
3474 
3475 //===----------------------------------------------------------------------===//
3476 // Other Decl Allocation/Deallocation Method Implementations
3477 //===----------------------------------------------------------------------===//
3478 
3479 void TranslationUnitDecl::anchor() { }
3480 
3481 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3482   return new (C, (DeclContext*)0) TranslationUnitDecl(C);
3483 }
3484 
3485 void LabelDecl::anchor() { }
3486 
3487 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3488                              SourceLocation IdentL, IdentifierInfo *II) {
3489   return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
3490 }
3491 
3492 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3493                              SourceLocation IdentL, IdentifierInfo *II,
3494                              SourceLocation GnuLabelL) {
3495   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3496   return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
3497 }
3498 
3499 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3500   return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
3501 }
3502 
3503 void ValueDecl::anchor() { }
3504 
3505 bool ValueDecl::isWeak() const {
3506   for (const auto *I : attrs())
3507     if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
3508       return true;
3509 
3510   return isWeakImported();
3511 }
3512 
3513 void ImplicitParamDecl::anchor() { }
3514 
3515 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3516                                              SourceLocation IdLoc,
3517                                              IdentifierInfo *Id,
3518                                              QualType Type) {
3519   return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
3520 }
3521 
3522 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3523                                                          unsigned ID) {
3524   return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3525 }
3526 
3527 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3528                                    SourceLocation StartLoc,
3529                                    const DeclarationNameInfo &NameInfo,
3530                                    QualType T, TypeSourceInfo *TInfo,
3531                                    StorageClass SC,
3532                                    bool isInlineSpecified,
3533                                    bool hasWrittenPrototype,
3534                                    bool isConstexprSpecified) {
3535   FunctionDecl *New =
3536       new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3537                                isInlineSpecified, isConstexprSpecified);
3538   New->HasWrittenPrototype = hasWrittenPrototype;
3539   return New;
3540 }
3541 
3542 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3543   return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3544                                   DeclarationNameInfo(), QualType(), 0,
3545                                   SC_None, false, false);
3546 }
3547 
3548 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3549   return new (C, DC) BlockDecl(DC, L);
3550 }
3551 
3552 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3553   return new (C, ID) BlockDecl(0, SourceLocation());
3554 }
3555 
3556 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3557                                    unsigned NumParams) {
3558   return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3559       CapturedDecl(DC, NumParams);
3560 }
3561 
3562 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3563                                                unsigned NumParams) {
3564   return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3565       CapturedDecl(0, NumParams);
3566 }
3567 
3568 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3569                                            SourceLocation L,
3570                                            IdentifierInfo *Id, QualType T,
3571                                            Expr *E, const llvm::APSInt &V) {
3572   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3573 }
3574 
3575 EnumConstantDecl *
3576 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3577   return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3578                                       llvm::APSInt());
3579 }
3580 
3581 void IndirectFieldDecl::anchor() { }
3582 
3583 IndirectFieldDecl *
3584 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3585                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
3586                           unsigned CHS) {
3587   return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3588 }
3589 
3590 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3591                                                          unsigned ID) {
3592   return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3593                                        QualType(), 0, 0);
3594 }
3595 
3596 SourceRange EnumConstantDecl::getSourceRange() const {
3597   SourceLocation End = getLocation();
3598   if (Init)
3599     End = Init->getLocEnd();
3600   return SourceRange(getLocation(), End);
3601 }
3602 
3603 void TypeDecl::anchor() { }
3604 
3605 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3606                                  SourceLocation StartLoc, SourceLocation IdLoc,
3607                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3608   return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
3609 }
3610 
3611 void TypedefNameDecl::anchor() { }
3612 
3613 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3614   return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3615 }
3616 
3617 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3618                                      SourceLocation StartLoc,
3619                                      SourceLocation IdLoc, IdentifierInfo *Id,
3620                                      TypeSourceInfo *TInfo) {
3621   return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3622 }
3623 
3624 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3625   return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3626 }
3627 
3628 SourceRange TypedefDecl::getSourceRange() const {
3629   SourceLocation RangeEnd = getLocation();
3630   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3631     if (typeIsPostfix(TInfo->getType()))
3632       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3633   }
3634   return SourceRange(getLocStart(), RangeEnd);
3635 }
3636 
3637 SourceRange TypeAliasDecl::getSourceRange() const {
3638   SourceLocation RangeEnd = getLocStart();
3639   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3640     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3641   return SourceRange(getLocStart(), RangeEnd);
3642 }
3643 
3644 void FileScopeAsmDecl::anchor() { }
3645 
3646 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3647                                            StringLiteral *Str,
3648                                            SourceLocation AsmLoc,
3649                                            SourceLocation RParenLoc) {
3650   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3651 }
3652 
3653 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3654                                                        unsigned ID) {
3655   return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3656 }
3657 
3658 void EmptyDecl::anchor() {}
3659 
3660 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3661   return new (C, DC) EmptyDecl(DC, L);
3662 }
3663 
3664 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3665   return new (C, ID) EmptyDecl(0, SourceLocation());
3666 }
3667 
3668 //===----------------------------------------------------------------------===//
3669 // ImportDecl Implementation
3670 //===----------------------------------------------------------------------===//
3671 
3672 /// \brief Retrieve the number of module identifiers needed to name the given
3673 /// module.
3674 static unsigned getNumModuleIdentifiers(Module *Mod) {
3675   unsigned Result = 1;
3676   while (Mod->Parent) {
3677     Mod = Mod->Parent;
3678     ++Result;
3679   }
3680   return Result;
3681 }
3682 
3683 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3684                        Module *Imported,
3685                        ArrayRef<SourceLocation> IdentifierLocs)
3686   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3687     NextLocalImport()
3688 {
3689   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3690   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3691   memcpy(StoredLocs, IdentifierLocs.data(),
3692          IdentifierLocs.size() * sizeof(SourceLocation));
3693 }
3694 
3695 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3696                        Module *Imported, SourceLocation EndLoc)
3697   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3698     NextLocalImport()
3699 {
3700   *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3701 }
3702 
3703 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3704                                SourceLocation StartLoc, Module *Imported,
3705                                ArrayRef<SourceLocation> IdentifierLocs) {
3706   return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3707       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3708 }
3709 
3710 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3711                                        SourceLocation StartLoc,
3712                                        Module *Imported,
3713                                        SourceLocation EndLoc) {
3714   ImportDecl *Import =
3715       new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3716                                                      Imported, EndLoc);
3717   Import->setImplicit();
3718   return Import;
3719 }
3720 
3721 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3722                                            unsigned NumLocations) {
3723   return new (C, ID, NumLocations * sizeof(SourceLocation))
3724       ImportDecl(EmptyShell());
3725 }
3726 
3727 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3728   if (!ImportedAndComplete.getInt())
3729     return None;
3730 
3731   const SourceLocation *StoredLocs
3732     = reinterpret_cast<const SourceLocation *>(this + 1);
3733   return ArrayRef<SourceLocation>(StoredLocs,
3734                                   getNumModuleIdentifiers(getImportedModule()));
3735 }
3736 
3737 SourceRange ImportDecl::getSourceRange() const {
3738   if (!ImportedAndComplete.getInt())
3739     return SourceRange(getLocation(),
3740                        *reinterpret_cast<const SourceLocation *>(this + 1));
3741 
3742   return SourceRange(getLocation(), getIdentifierLocs().back());
3743 }
3744