xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision 723928c7)
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   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1385     return true;
1386 
1387   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1388     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1389            cast<UsingShadowDecl>(OldD)->getTargetDecl();
1390 
1391   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1392     ASTContext &Context = getASTContext();
1393     return Context.getCanonicalNestedNameSpecifier(
1394                                      cast<UsingDecl>(this)->getQualifier()) ==
1395            Context.getCanonicalNestedNameSpecifier(
1396                                         cast<UsingDecl>(OldD)->getQualifier());
1397   }
1398 
1399   if (isa<UnresolvedUsingValueDecl>(this) &&
1400       isa<UnresolvedUsingValueDecl>(OldD)) {
1401     ASTContext &Context = getASTContext();
1402     return Context.getCanonicalNestedNameSpecifier(
1403                       cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1404            Context.getCanonicalNestedNameSpecifier(
1405                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1406   }
1407 
1408   // A typedef of an Objective-C class type can replace an Objective-C class
1409   // declaration or definition, and vice versa.
1410   if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1411       (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1412     return true;
1413 
1414   // For non-function declarations, if the declarations are of the
1415   // same kind then this must be a redeclaration, or semantic analysis
1416   // would not have given us the new declaration.
1417   return this->getKind() == OldD->getKind();
1418 }
1419 
1420 bool NamedDecl::hasLinkage() const {
1421   return getFormalLinkage() != NoLinkage;
1422 }
1423 
1424 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1425   NamedDecl *ND = this;
1426   while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1427     ND = UD->getTargetDecl();
1428 
1429   if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1430     return AD->getClassInterface();
1431 
1432   return ND;
1433 }
1434 
1435 bool NamedDecl::isCXXInstanceMember() const {
1436   if (!isCXXClassMember())
1437     return false;
1438 
1439   const NamedDecl *D = this;
1440   if (isa<UsingShadowDecl>(D))
1441     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1442 
1443   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1444     return true;
1445   if (const CXXMethodDecl *MD =
1446           dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1447     return MD->isInstance();
1448   return false;
1449 }
1450 
1451 //===----------------------------------------------------------------------===//
1452 // DeclaratorDecl Implementation
1453 //===----------------------------------------------------------------------===//
1454 
1455 template <typename DeclT>
1456 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1457   if (decl->getNumTemplateParameterLists() > 0)
1458     return decl->getTemplateParameterList(0)->getTemplateLoc();
1459   else
1460     return decl->getInnerLocStart();
1461 }
1462 
1463 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1464   TypeSourceInfo *TSI = getTypeSourceInfo();
1465   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1466   return SourceLocation();
1467 }
1468 
1469 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1470   if (QualifierLoc) {
1471     // Make sure the extended decl info is allocated.
1472     if (!hasExtInfo()) {
1473       // Save (non-extended) type source info pointer.
1474       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1475       // Allocate external info struct.
1476       DeclInfo = new (getASTContext()) ExtInfo;
1477       // Restore savedTInfo into (extended) decl info.
1478       getExtInfo()->TInfo = savedTInfo;
1479     }
1480     // Set qualifier info.
1481     getExtInfo()->QualifierLoc = QualifierLoc;
1482   } else {
1483     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1484     if (hasExtInfo()) {
1485       if (getExtInfo()->NumTemplParamLists == 0) {
1486         // Save type source info pointer.
1487         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1488         // Deallocate the extended decl info.
1489         getASTContext().Deallocate(getExtInfo());
1490         // Restore savedTInfo into (non-extended) decl info.
1491         DeclInfo = savedTInfo;
1492       }
1493       else
1494         getExtInfo()->QualifierLoc = QualifierLoc;
1495     }
1496   }
1497 }
1498 
1499 void
1500 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1501                                               unsigned NumTPLists,
1502                                               TemplateParameterList **TPLists) {
1503   assert(NumTPLists > 0);
1504   // Make sure the extended decl info is allocated.
1505   if (!hasExtInfo()) {
1506     // Save (non-extended) type source info pointer.
1507     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1508     // Allocate external info struct.
1509     DeclInfo = new (getASTContext()) ExtInfo;
1510     // Restore savedTInfo into (extended) decl info.
1511     getExtInfo()->TInfo = savedTInfo;
1512   }
1513   // Set the template parameter lists info.
1514   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1515 }
1516 
1517 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1518   return getTemplateOrInnerLocStart(this);
1519 }
1520 
1521 namespace {
1522 
1523 // Helper function: returns true if QT is or contains a type
1524 // having a postfix component.
1525 bool typeIsPostfix(clang::QualType QT) {
1526   while (true) {
1527     const Type* T = QT.getTypePtr();
1528     switch (T->getTypeClass()) {
1529     default:
1530       return false;
1531     case Type::Pointer:
1532       QT = cast<PointerType>(T)->getPointeeType();
1533       break;
1534     case Type::BlockPointer:
1535       QT = cast<BlockPointerType>(T)->getPointeeType();
1536       break;
1537     case Type::MemberPointer:
1538       QT = cast<MemberPointerType>(T)->getPointeeType();
1539       break;
1540     case Type::LValueReference:
1541     case Type::RValueReference:
1542       QT = cast<ReferenceType>(T)->getPointeeType();
1543       break;
1544     case Type::PackExpansion:
1545       QT = cast<PackExpansionType>(T)->getPattern();
1546       break;
1547     case Type::Paren:
1548     case Type::ConstantArray:
1549     case Type::DependentSizedArray:
1550     case Type::IncompleteArray:
1551     case Type::VariableArray:
1552     case Type::FunctionProto:
1553     case Type::FunctionNoProto:
1554       return true;
1555     }
1556   }
1557 }
1558 
1559 } // namespace
1560 
1561 SourceRange DeclaratorDecl::getSourceRange() const {
1562   SourceLocation RangeEnd = getLocation();
1563   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1564     // If the declaration has no name or the type extends past the name take the
1565     // end location of the type.
1566     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1567       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1568   }
1569   return SourceRange(getOuterLocStart(), RangeEnd);
1570 }
1571 
1572 void
1573 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1574                                              unsigned NumTPLists,
1575                                              TemplateParameterList **TPLists) {
1576   assert((NumTPLists == 0 || TPLists != 0) &&
1577          "Empty array of template parameters with positive size!");
1578 
1579   // Free previous template parameters (if any).
1580   if (NumTemplParamLists > 0) {
1581     Context.Deallocate(TemplParamLists);
1582     TemplParamLists = 0;
1583     NumTemplParamLists = 0;
1584   }
1585   // Set info on matched template parameter lists (if any).
1586   if (NumTPLists > 0) {
1587     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1588     NumTemplParamLists = NumTPLists;
1589     for (unsigned i = NumTPLists; i-- > 0; )
1590       TemplParamLists[i] = TPLists[i];
1591   }
1592 }
1593 
1594 //===----------------------------------------------------------------------===//
1595 // VarDecl Implementation
1596 //===----------------------------------------------------------------------===//
1597 
1598 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1599   switch (SC) {
1600   case SC_None:                 break;
1601   case SC_Auto:                 return "auto";
1602   case SC_Extern:               return "extern";
1603   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1604   case SC_PrivateExtern:        return "__private_extern__";
1605   case SC_Register:             return "register";
1606   case SC_Static:               return "static";
1607   }
1608 
1609   llvm_unreachable("Invalid storage class");
1610 }
1611 
1612 VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1613                  SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1614                  TypeSourceInfo *TInfo, StorageClass SC)
1615     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
1616   assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
1617   assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
1618   AllBits = 0;
1619   VarDeclBits.SClass = SC;
1620   // Everything else is implicitly initialized to false.
1621 }
1622 
1623 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1624                          SourceLocation StartL, SourceLocation IdL,
1625                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1626                          StorageClass S) {
1627   return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
1628 }
1629 
1630 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1631   return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1632                              QualType(), 0, SC_None);
1633 }
1634 
1635 void VarDecl::setStorageClass(StorageClass SC) {
1636   assert(isLegalForVariable(SC));
1637   VarDeclBits.SClass = SC;
1638 }
1639 
1640 SourceRange VarDecl::getSourceRange() const {
1641   if (const Expr *Init = getInit()) {
1642     SourceLocation InitEnd = Init->getLocEnd();
1643     // If Init is implicit, ignore its source range and fallback on
1644     // DeclaratorDecl::getSourceRange() to handle postfix elements.
1645     if (InitEnd.isValid() && InitEnd != getLocation())
1646       return SourceRange(getOuterLocStart(), InitEnd);
1647   }
1648   return DeclaratorDecl::getSourceRange();
1649 }
1650 
1651 template<typename T>
1652 static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
1653   // C++ [dcl.link]p1: All function types, function names with external linkage,
1654   // and variable names with external linkage have a language linkage.
1655   if (!D.hasExternalFormalLinkage())
1656     return NoLanguageLinkage;
1657 
1658   // Language linkage is a C++ concept, but saying that everything else in C has
1659   // C language linkage fits the implementation nicely.
1660   ASTContext &Context = D.getASTContext();
1661   if (!Context.getLangOpts().CPlusPlus)
1662     return CLanguageLinkage;
1663 
1664   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1665   // language linkage of the names of class members and the function type of
1666   // class member functions.
1667   const DeclContext *DC = D.getDeclContext();
1668   if (DC->isRecord())
1669     return CXXLanguageLinkage;
1670 
1671   // If the first decl is in an extern "C" context, any other redeclaration
1672   // will have C language linkage. If the first one is not in an extern "C"
1673   // context, we would have reported an error for any other decl being in one.
1674   if (isFirstInExternCContext(&D))
1675     return CLanguageLinkage;
1676   return CXXLanguageLinkage;
1677 }
1678 
1679 template<typename T>
1680 static bool isExternCTemplate(const T &D) {
1681   // Since the context is ignored for class members, they can only have C++
1682   // language linkage or no language linkage.
1683   const DeclContext *DC = D.getDeclContext();
1684   if (DC->isRecord()) {
1685     assert(D.getASTContext().getLangOpts().CPlusPlus);
1686     return false;
1687   }
1688 
1689   return D.getLanguageLinkage() == CLanguageLinkage;
1690 }
1691 
1692 LanguageLinkage VarDecl::getLanguageLinkage() const {
1693   return getLanguageLinkageTemplate(*this);
1694 }
1695 
1696 bool VarDecl::isExternC() const {
1697   return isExternCTemplate(*this);
1698 }
1699 
1700 bool VarDecl::isInExternCContext() const {
1701   return getLexicalDeclContext()->isExternCContext();
1702 }
1703 
1704 bool VarDecl::isInExternCXXContext() const {
1705   return getLexicalDeclContext()->isExternCXXContext();
1706 }
1707 
1708 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1709 
1710 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1711   ASTContext &C) const
1712 {
1713   // C++ [basic.def]p2:
1714   //   A declaration is a definition unless [...] it contains the 'extern'
1715   //   specifier or a linkage-specification and neither an initializer [...],
1716   //   it declares a static data member in a class declaration [...].
1717   // C++1y [temp.expl.spec]p15:
1718   //   An explicit specialization of a static data member or an explicit
1719   //   specialization of a static data member template is a definition if the
1720   //   declaration includes an initializer; otherwise, it is a declaration.
1721   //
1722   // FIXME: How do you declare (but not define) a partial specialization of
1723   // a static data member template outside the containing class?
1724   if (isStaticDataMember()) {
1725     if (isOutOfLine() &&
1726         (hasInit() ||
1727          // If the first declaration is out-of-line, this may be an
1728          // instantiation of an out-of-line partial specialization of a variable
1729          // template for which we have not yet instantiated the initializer.
1730          (getFirstDecl()->isOutOfLine()
1731               ? getTemplateSpecializationKind() == TSK_Undeclared
1732               : getTemplateSpecializationKind() !=
1733                     TSK_ExplicitSpecialization) ||
1734          isa<VarTemplatePartialSpecializationDecl>(this)))
1735       return Definition;
1736     else
1737       return DeclarationOnly;
1738   }
1739   // C99 6.7p5:
1740   //   A definition of an identifier is a declaration for that identifier that
1741   //   [...] causes storage to be reserved for that object.
1742   // Note: that applies for all non-file-scope objects.
1743   // C99 6.9.2p1:
1744   //   If the declaration of an identifier for an object has file scope and an
1745   //   initializer, the declaration is an external definition for the identifier
1746   if (hasInit())
1747     return Definition;
1748 
1749   if (hasAttr<AliasAttr>())
1750     return Definition;
1751 
1752   // A variable template specialization (other than a static data member
1753   // template or an explicit specialization) is a declaration until we
1754   // instantiate its initializer.
1755   if (isa<VarTemplateSpecializationDecl>(this) &&
1756       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1757     return DeclarationOnly;
1758 
1759   if (hasExternalStorage())
1760     return DeclarationOnly;
1761 
1762   // [dcl.link] p7:
1763   //   A declaration directly contained in a linkage-specification is treated
1764   //   as if it contains the extern specifier for the purpose of determining
1765   //   the linkage of the declared name and whether it is a definition.
1766   if (isSingleLineLanguageLinkage(*this))
1767     return DeclarationOnly;
1768 
1769   // C99 6.9.2p2:
1770   //   A declaration of an object that has file scope without an initializer,
1771   //   and without a storage class specifier or the scs 'static', constitutes
1772   //   a tentative definition.
1773   // No such thing in C++.
1774   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1775     return TentativeDefinition;
1776 
1777   // What's left is (in C, block-scope) declarations without initializers or
1778   // external storage. These are definitions.
1779   return Definition;
1780 }
1781 
1782 VarDecl *VarDecl::getActingDefinition() {
1783   DefinitionKind Kind = isThisDeclarationADefinition();
1784   if (Kind != TentativeDefinition)
1785     return 0;
1786 
1787   VarDecl *LastTentative = 0;
1788   VarDecl *First = getFirstDecl();
1789   for (auto I : First->redecls()) {
1790     Kind = I->isThisDeclarationADefinition();
1791     if (Kind == Definition)
1792       return 0;
1793     else if (Kind == TentativeDefinition)
1794       LastTentative = I;
1795   }
1796   return LastTentative;
1797 }
1798 
1799 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1800   VarDecl *First = getFirstDecl();
1801   for (auto I : First->redecls()) {
1802     if (I->isThisDeclarationADefinition(C) == Definition)
1803       return I;
1804   }
1805   return 0;
1806 }
1807 
1808 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1809   DefinitionKind Kind = DeclarationOnly;
1810 
1811   const VarDecl *First = getFirstDecl();
1812   for (auto I : First->redecls()) {
1813     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
1814     if (Kind == Definition)
1815       break;
1816   }
1817 
1818   return Kind;
1819 }
1820 
1821 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1822   for (auto I : redecls()) {
1823     if (auto Expr = I->getInit()) {
1824       D = I;
1825       return Expr;
1826     }
1827   }
1828   return 0;
1829 }
1830 
1831 bool VarDecl::isOutOfLine() const {
1832   if (Decl::isOutOfLine())
1833     return true;
1834 
1835   if (!isStaticDataMember())
1836     return false;
1837 
1838   // If this static data member was instantiated from a static data member of
1839   // a class template, check whether that static data member was defined
1840   // out-of-line.
1841   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1842     return VD->isOutOfLine();
1843 
1844   return false;
1845 }
1846 
1847 VarDecl *VarDecl::getOutOfLineDefinition() {
1848   if (!isStaticDataMember())
1849     return 0;
1850 
1851   for (auto RD : redecls()) {
1852     if (RD->getLexicalDeclContext()->isFileContext())
1853       return RD;
1854   }
1855 
1856   return 0;
1857 }
1858 
1859 void VarDecl::setInit(Expr *I) {
1860   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1861     Eval->~EvaluatedStmt();
1862     getASTContext().Deallocate(Eval);
1863   }
1864 
1865   Init = I;
1866 }
1867 
1868 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1869   const LangOptions &Lang = C.getLangOpts();
1870 
1871   if (!Lang.CPlusPlus)
1872     return false;
1873 
1874   // In C++11, any variable of reference type can be used in a constant
1875   // expression if it is initialized by a constant expression.
1876   if (Lang.CPlusPlus11 && getType()->isReferenceType())
1877     return true;
1878 
1879   // Only const objects can be used in constant expressions in C++. C++98 does
1880   // not require the variable to be non-volatile, but we consider this to be a
1881   // defect.
1882   if (!getType().isConstQualified() || getType().isVolatileQualified())
1883     return false;
1884 
1885   // In C++, const, non-volatile variables of integral or enumeration types
1886   // can be used in constant expressions.
1887   if (getType()->isIntegralOrEnumerationType())
1888     return true;
1889 
1890   // Additionally, in C++11, non-volatile constexpr variables can be used in
1891   // constant expressions.
1892   return Lang.CPlusPlus11 && isConstexpr();
1893 }
1894 
1895 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1896 /// form, which contains extra information on the evaluated value of the
1897 /// initializer.
1898 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1899   EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1900   if (!Eval) {
1901     Stmt *S = Init.get<Stmt *>();
1902     // Note: EvaluatedStmt contains an APValue, which usually holds
1903     // resources not allocated from the ASTContext.  We need to do some
1904     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1905     // where we can detect whether there's anything to clean up or not.
1906     Eval = new (getASTContext()) EvaluatedStmt;
1907     Eval->Value = S;
1908     Init = Eval;
1909   }
1910   return Eval;
1911 }
1912 
1913 APValue *VarDecl::evaluateValue() const {
1914   SmallVector<PartialDiagnosticAt, 8> Notes;
1915   return evaluateValue(Notes);
1916 }
1917 
1918 namespace {
1919 // Destroy an APValue that was allocated in an ASTContext.
1920 void DestroyAPValue(void* UntypedValue) {
1921   static_cast<APValue*>(UntypedValue)->~APValue();
1922 }
1923 } // namespace
1924 
1925 APValue *VarDecl::evaluateValue(
1926     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1927   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1928 
1929   // We only produce notes indicating why an initializer is non-constant the
1930   // first time it is evaluated. FIXME: The notes won't always be emitted the
1931   // first time we try evaluation, so might not be produced at all.
1932   if (Eval->WasEvaluated)
1933     return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1934 
1935   const Expr *Init = cast<Expr>(Eval->Value);
1936   assert(!Init->isValueDependent());
1937 
1938   if (Eval->IsEvaluating) {
1939     // FIXME: Produce a diagnostic for self-initialization.
1940     Eval->CheckedICE = true;
1941     Eval->IsICE = false;
1942     return 0;
1943   }
1944 
1945   Eval->IsEvaluating = true;
1946 
1947   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1948                                             this, Notes);
1949 
1950   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1951   // or that it's empty (so that there's nothing to clean up) if evaluation
1952   // failed.
1953   if (!Result)
1954     Eval->Evaluated = APValue();
1955   else if (Eval->Evaluated.needsCleanup())
1956     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
1957 
1958   Eval->IsEvaluating = false;
1959   Eval->WasEvaluated = true;
1960 
1961   // In C++11, we have determined whether the initializer was a constant
1962   // expression as a side-effect.
1963   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
1964     Eval->CheckedICE = true;
1965     Eval->IsICE = Result && Notes.empty();
1966   }
1967 
1968   return Result ? &Eval->Evaluated : 0;
1969 }
1970 
1971 bool VarDecl::checkInitIsICE() const {
1972   // Initializers of weak variables are never ICEs.
1973   if (isWeak())
1974     return false;
1975 
1976   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1977   if (Eval->CheckedICE)
1978     // We have already checked whether this subexpression is an
1979     // integral constant expression.
1980     return Eval->IsICE;
1981 
1982   const Expr *Init = cast<Expr>(Eval->Value);
1983   assert(!Init->isValueDependent());
1984 
1985   // In C++11, evaluate the initializer to check whether it's a constant
1986   // expression.
1987   if (getASTContext().getLangOpts().CPlusPlus11) {
1988     SmallVector<PartialDiagnosticAt, 8> Notes;
1989     evaluateValue(Notes);
1990     return Eval->IsICE;
1991   }
1992 
1993   // It's an ICE whether or not the definition we found is
1994   // out-of-line.  See DR 721 and the discussion in Clang PR
1995   // 6206 for details.
1996 
1997   if (Eval->CheckingICE)
1998     return false;
1999   Eval->CheckingICE = true;
2000 
2001   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2002   Eval->CheckingICE = false;
2003   Eval->CheckedICE = true;
2004   return Eval->IsICE;
2005 }
2006 
2007 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2008   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2009     return cast<VarDecl>(MSI->getInstantiatedFrom());
2010 
2011   return 0;
2012 }
2013 
2014 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2015   if (const VarTemplateSpecializationDecl *Spec =
2016           dyn_cast<VarTemplateSpecializationDecl>(this))
2017     return Spec->getSpecializationKind();
2018 
2019   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2020     return MSI->getTemplateSpecializationKind();
2021 
2022   return TSK_Undeclared;
2023 }
2024 
2025 SourceLocation VarDecl::getPointOfInstantiation() const {
2026   if (const VarTemplateSpecializationDecl *Spec =
2027           dyn_cast<VarTemplateSpecializationDecl>(this))
2028     return Spec->getPointOfInstantiation();
2029 
2030   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2031     return MSI->getPointOfInstantiation();
2032 
2033   return SourceLocation();
2034 }
2035 
2036 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2037   return getASTContext().getTemplateOrSpecializationInfo(this)
2038       .dyn_cast<VarTemplateDecl *>();
2039 }
2040 
2041 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2042   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2043 }
2044 
2045 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2046   if (isStaticDataMember())
2047     // FIXME: Remove ?
2048     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2049     return getASTContext().getTemplateOrSpecializationInfo(this)
2050         .dyn_cast<MemberSpecializationInfo *>();
2051   return 0;
2052 }
2053 
2054 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2055                                          SourceLocation PointOfInstantiation) {
2056   assert((isa<VarTemplateSpecializationDecl>(this) ||
2057           getMemberSpecializationInfo()) &&
2058          "not a variable or static data member template specialization");
2059 
2060   if (VarTemplateSpecializationDecl *Spec =
2061           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2062     Spec->setSpecializationKind(TSK);
2063     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2064         Spec->getPointOfInstantiation().isInvalid())
2065       Spec->setPointOfInstantiation(PointOfInstantiation);
2066   }
2067 
2068   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2069     MSI->setTemplateSpecializationKind(TSK);
2070     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2071         MSI->getPointOfInstantiation().isInvalid())
2072       MSI->setPointOfInstantiation(PointOfInstantiation);
2073   }
2074 }
2075 
2076 void
2077 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2078                                             TemplateSpecializationKind TSK) {
2079   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2080          "Previous template or instantiation?");
2081   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2082 }
2083 
2084 //===----------------------------------------------------------------------===//
2085 // ParmVarDecl Implementation
2086 //===----------------------------------------------------------------------===//
2087 
2088 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2089                                  SourceLocation StartLoc,
2090                                  SourceLocation IdLoc, IdentifierInfo *Id,
2091                                  QualType T, TypeSourceInfo *TInfo,
2092                                  StorageClass S, Expr *DefArg) {
2093   return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2094                                  S, DefArg);
2095 }
2096 
2097 QualType ParmVarDecl::getOriginalType() const {
2098   TypeSourceInfo *TSI = getTypeSourceInfo();
2099   QualType T = TSI ? TSI->getType() : getType();
2100   if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2101     return DT->getOriginalType();
2102   return T;
2103 }
2104 
2105 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2106   return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2107                                  0, QualType(), 0, SC_None, 0);
2108 }
2109 
2110 SourceRange ParmVarDecl::getSourceRange() const {
2111   if (!hasInheritedDefaultArg()) {
2112     SourceRange ArgRange = getDefaultArgRange();
2113     if (ArgRange.isValid())
2114       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2115   }
2116 
2117   // DeclaratorDecl considers the range of postfix types as overlapping with the
2118   // declaration name, but this is not the case with parameters in ObjC methods.
2119   if (isa<ObjCMethodDecl>(getDeclContext()))
2120     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2121 
2122   return DeclaratorDecl::getSourceRange();
2123 }
2124 
2125 Expr *ParmVarDecl::getDefaultArg() {
2126   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2127   assert(!hasUninstantiatedDefaultArg() &&
2128          "Default argument is not yet instantiated!");
2129 
2130   Expr *Arg = getInit();
2131   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2132     return E->getSubExpr();
2133 
2134   return Arg;
2135 }
2136 
2137 SourceRange ParmVarDecl::getDefaultArgRange() const {
2138   if (const Expr *E = getInit())
2139     return E->getSourceRange();
2140 
2141   if (hasUninstantiatedDefaultArg())
2142     return getUninstantiatedDefaultArg()->getSourceRange();
2143 
2144   return SourceRange();
2145 }
2146 
2147 bool ParmVarDecl::isParameterPack() const {
2148   return isa<PackExpansionType>(getType());
2149 }
2150 
2151 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2152   getASTContext().setParameterIndex(this, parameterIndex);
2153   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2154 }
2155 
2156 unsigned ParmVarDecl::getParameterIndexLarge() const {
2157   return getASTContext().getParameterIndex(this);
2158 }
2159 
2160 //===----------------------------------------------------------------------===//
2161 // FunctionDecl Implementation
2162 //===----------------------------------------------------------------------===//
2163 
2164 void FunctionDecl::getNameForDiagnostic(
2165     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2166   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2167   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2168   if (TemplateArgs)
2169     TemplateSpecializationType::PrintTemplateArgumentList(
2170         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2171 }
2172 
2173 bool FunctionDecl::isVariadic() const {
2174   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2175     return FT->isVariadic();
2176   return false;
2177 }
2178 
2179 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2180   for (auto I : redecls()) {
2181     if (I->Body || I->IsLateTemplateParsed) {
2182       Definition = I;
2183       return true;
2184     }
2185   }
2186 
2187   return false;
2188 }
2189 
2190 bool FunctionDecl::hasTrivialBody() const
2191 {
2192   Stmt *S = getBody();
2193   if (!S) {
2194     // Since we don't have a body for this function, we don't know if it's
2195     // trivial or not.
2196     return false;
2197   }
2198 
2199   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2200     return true;
2201   return false;
2202 }
2203 
2204 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2205   for (auto I : redecls()) {
2206     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2207         I->hasAttr<AliasAttr>()) {
2208       Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2209       return true;
2210     }
2211   }
2212 
2213   return false;
2214 }
2215 
2216 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2217   if (!hasBody(Definition))
2218     return 0;
2219 
2220   if (Definition->Body)
2221     return Definition->Body.get(getASTContext().getExternalSource());
2222 
2223   return 0;
2224 }
2225 
2226 void FunctionDecl::setBody(Stmt *B) {
2227   Body = B;
2228   if (B)
2229     EndRangeLoc = B->getLocEnd();
2230 }
2231 
2232 void FunctionDecl::setPure(bool P) {
2233   IsPure = P;
2234   if (P)
2235     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2236       Parent->markedVirtualFunctionPure();
2237 }
2238 
2239 template<std::size_t Len>
2240 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2241   IdentifierInfo *II = ND->getIdentifier();
2242   return II && II->isStr(Str);
2243 }
2244 
2245 bool FunctionDecl::isMain() const {
2246   const TranslationUnitDecl *tunit =
2247     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2248   return tunit &&
2249          !tunit->getASTContext().getLangOpts().Freestanding &&
2250          isNamed(this, "main");
2251 }
2252 
2253 bool FunctionDecl::isMSVCRTEntryPoint() const {
2254   const TranslationUnitDecl *TUnit =
2255       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2256   if (!TUnit)
2257     return false;
2258 
2259   // Even though we aren't really targeting MSVCRT if we are freestanding,
2260   // semantic analysis for these functions remains the same.
2261 
2262   // MSVCRT entry points only exist on MSVCRT targets.
2263   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2264     return false;
2265 
2266   // Nameless functions like constructors cannot be entry points.
2267   if (!getIdentifier())
2268     return false;
2269 
2270   return llvm::StringSwitch<bool>(getName())
2271       .Cases("main",     // an ANSI console app
2272              "wmain",    // a Unicode console App
2273              "WinMain",  // an ANSI GUI app
2274              "wWinMain", // a Unicode GUI app
2275              "DllMain",  // a DLL
2276              true)
2277       .Default(false);
2278 }
2279 
2280 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2281   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2282   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2283          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2284          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2285          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2286 
2287   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2288     return false;
2289 
2290   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2291   if (proto->getNumParams() != 2 || proto->isVariadic())
2292     return false;
2293 
2294   ASTContext &Context =
2295     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2296       ->getASTContext();
2297 
2298   // The result type and first argument type are constant across all
2299   // these operators.  The second argument must be exactly void*.
2300   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2301 }
2302 
2303 static bool isNamespaceStd(const DeclContext *DC) {
2304   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2305   return ND && isNamed(ND, "std") &&
2306          ND->getParent()->getRedeclContext()->isTranslationUnit();
2307 }
2308 
2309 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2310   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2311     return false;
2312   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2313       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2314       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2315       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2316     return false;
2317 
2318   if (isa<CXXRecordDecl>(getDeclContext()))
2319     return false;
2320 
2321   // This can only fail for an invalid 'operator new' declaration.
2322   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2323     return false;
2324 
2325   const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2326   if (FPT->getNumParams() > 2 || FPT->isVariadic())
2327     return false;
2328 
2329   // If this is a single-parameter function, it must be a replaceable global
2330   // allocation or deallocation function.
2331   if (FPT->getNumParams() == 1)
2332     return true;
2333 
2334   // Otherwise, we're looking for a second parameter whose type is
2335   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2336   QualType Ty = FPT->getParamType(1);
2337   ASTContext &Ctx = getASTContext();
2338   if (Ctx.getLangOpts().SizedDeallocation &&
2339       Ctx.hasSameType(Ty, Ctx.getSizeType()))
2340     return true;
2341   if (!Ty->isReferenceType())
2342     return false;
2343   Ty = Ty->getPointeeType();
2344   if (Ty.getCVRQualifiers() != Qualifiers::Const)
2345     return false;
2346   // FIXME: Recognise nothrow_t in an inline namespace inside std?
2347   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2348   return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2349 }
2350 
2351 FunctionDecl *
2352 FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2353   ASTContext &Ctx = getASTContext();
2354   if (!Ctx.getLangOpts().SizedDeallocation)
2355     return 0;
2356 
2357   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2358     return 0;
2359   if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2360       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2361     return 0;
2362   if (isa<CXXRecordDecl>(getDeclContext()))
2363     return 0;
2364 
2365   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2366     return 0;
2367 
2368   if (getNumParams() != 2 || isVariadic() ||
2369       !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
2370                        Ctx.getSizeType()))
2371     return 0;
2372 
2373   // This is a sized deallocation function. Find the corresponding unsized
2374   // deallocation function.
2375   lookup_const_result R = getDeclContext()->lookup(getDeclName());
2376   for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2377        ++RI)
2378     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2379       if (FD->getNumParams() == 1 && !FD->isVariadic())
2380         return FD;
2381   return 0;
2382 }
2383 
2384 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2385   return getLanguageLinkageTemplate(*this);
2386 }
2387 
2388 bool FunctionDecl::isExternC() const {
2389   return isExternCTemplate(*this);
2390 }
2391 
2392 bool FunctionDecl::isInExternCContext() const {
2393   return getLexicalDeclContext()->isExternCContext();
2394 }
2395 
2396 bool FunctionDecl::isInExternCXXContext() const {
2397   return getLexicalDeclContext()->isExternCXXContext();
2398 }
2399 
2400 bool FunctionDecl::isGlobal() const {
2401   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2402     return Method->isStatic();
2403 
2404   if (getCanonicalDecl()->getStorageClass() == SC_Static)
2405     return false;
2406 
2407   for (const DeclContext *DC = getDeclContext();
2408        DC->isNamespace();
2409        DC = DC->getParent()) {
2410     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2411       if (!Namespace->getDeclName())
2412         return false;
2413       break;
2414     }
2415   }
2416 
2417   return true;
2418 }
2419 
2420 bool FunctionDecl::isNoReturn() const {
2421   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2422          hasAttr<C11NoReturnAttr>() ||
2423          getType()->getAs<FunctionType>()->getNoReturnAttr();
2424 }
2425 
2426 void
2427 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2428   redeclarable_base::setPreviousDecl(PrevDecl);
2429 
2430   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2431     FunctionTemplateDecl *PrevFunTmpl
2432       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2433     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2434     FunTmpl->setPreviousDecl(PrevFunTmpl);
2435   }
2436 
2437   if (PrevDecl && PrevDecl->IsInline)
2438     IsInline = true;
2439 }
2440 
2441 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2442   return getFirstDecl();
2443 }
2444 
2445 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2446 
2447 /// \brief Returns a value indicating whether this function
2448 /// corresponds to a builtin function.
2449 ///
2450 /// The function corresponds to a built-in function if it is
2451 /// declared at translation scope or within an extern "C" block and
2452 /// its name matches with the name of a builtin. The returned value
2453 /// will be 0 for functions that do not correspond to a builtin, a
2454 /// value of type \c Builtin::ID if in the target-independent range
2455 /// \c [1,Builtin::First), or a target-specific builtin value.
2456 unsigned FunctionDecl::getBuiltinID() const {
2457   if (!getIdentifier())
2458     return 0;
2459 
2460   unsigned BuiltinID = getIdentifier()->getBuiltinID();
2461   if (!BuiltinID)
2462     return 0;
2463 
2464   ASTContext &Context = getASTContext();
2465   if (Context.getLangOpts().CPlusPlus) {
2466     const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2467         getFirstDecl()->getDeclContext());
2468     // In C++, the first declaration of a builtin is always inside an implicit
2469     // extern "C".
2470     // FIXME: A recognised library function may not be directly in an extern "C"
2471     // declaration, for instance "extern "C" { namespace std { decl } }".
2472     if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2473       return 0;
2474   }
2475 
2476   // If the function is marked "overloadable", it has a different mangled name
2477   // and is not the C library function.
2478   if (hasAttr<OverloadableAttr>())
2479     return 0;
2480 
2481   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2482     return BuiltinID;
2483 
2484   // This function has the name of a known C library
2485   // function. Determine whether it actually refers to the C library
2486   // function or whether it just has the same name.
2487 
2488   // If this is a static function, it's not a builtin.
2489   if (getStorageClass() == SC_Static)
2490     return 0;
2491 
2492   return BuiltinID;
2493 }
2494 
2495 
2496 /// getNumParams - Return the number of parameters this function must have
2497 /// based on its FunctionType.  This is the length of the ParamInfo array
2498 /// after it has been created.
2499 unsigned FunctionDecl::getNumParams() const {
2500   const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2501   return FPT ? FPT->getNumParams() : 0;
2502 }
2503 
2504 void FunctionDecl::setParams(ASTContext &C,
2505                              ArrayRef<ParmVarDecl *> NewParamInfo) {
2506   assert(ParamInfo == 0 && "Already has param info!");
2507   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2508 
2509   // Zero params -> null pointer.
2510   if (!NewParamInfo.empty()) {
2511     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2512     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2513   }
2514 }
2515 
2516 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2517   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2518 
2519   if (!NewDecls.empty()) {
2520     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2521     std::copy(NewDecls.begin(), NewDecls.end(), A);
2522     DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
2523   }
2524 }
2525 
2526 /// getMinRequiredArguments - Returns the minimum number of arguments
2527 /// needed to call this function. This may be fewer than the number of
2528 /// function parameters, if some of the parameters have default
2529 /// arguments (in C++) or the last parameter is a parameter pack.
2530 unsigned FunctionDecl::getMinRequiredArguments() const {
2531   if (!getASTContext().getLangOpts().CPlusPlus)
2532     return getNumParams();
2533 
2534   unsigned NumRequiredArgs = getNumParams();
2535 
2536   // If the last parameter is a parameter pack, we don't need an argument for
2537   // it.
2538   if (NumRequiredArgs > 0 &&
2539       getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2540     --NumRequiredArgs;
2541 
2542   // If this parameter has a default argument, we don't need an argument for
2543   // it.
2544   while (NumRequiredArgs > 0 &&
2545          getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
2546     --NumRequiredArgs;
2547 
2548   // We might have parameter packs before the end. These can't be deduced,
2549   // but they can still handle multiple arguments.
2550   unsigned ArgIdx = NumRequiredArgs;
2551   while (ArgIdx > 0) {
2552     if (getParamDecl(ArgIdx - 1)->isParameterPack())
2553       NumRequiredArgs = ArgIdx;
2554 
2555     --ArgIdx;
2556   }
2557 
2558   return NumRequiredArgs;
2559 }
2560 
2561 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2562   // Only consider file-scope declarations in this test.
2563   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2564     return false;
2565 
2566   // Only consider explicit declarations; the presence of a builtin for a
2567   // libcall shouldn't affect whether a definition is externally visible.
2568   if (Redecl->isImplicit())
2569     return false;
2570 
2571   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2572     return true; // Not an inline definition
2573 
2574   return false;
2575 }
2576 
2577 /// \brief For a function declaration in C or C++, determine whether this
2578 /// declaration causes the definition to be externally visible.
2579 ///
2580 /// Specifically, this determines if adding the current declaration to the set
2581 /// of redeclarations of the given functions causes
2582 /// isInlineDefinitionExternallyVisible to change from false to true.
2583 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2584   assert(!doesThisDeclarationHaveABody() &&
2585          "Must have a declaration without a body.");
2586 
2587   ASTContext &Context = getASTContext();
2588 
2589   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2590     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2591     // an externally visible definition.
2592     //
2593     // FIXME: What happens if gnu_inline gets added on after the first
2594     // declaration?
2595     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2596       return false;
2597 
2598     const FunctionDecl *Prev = this;
2599     bool FoundBody = false;
2600     while ((Prev = Prev->getPreviousDecl())) {
2601       FoundBody |= Prev->Body.isValid();
2602 
2603       if (Prev->Body) {
2604         // If it's not the case that both 'inline' and 'extern' are
2605         // specified on the definition, then it is always externally visible.
2606         if (!Prev->isInlineSpecified() ||
2607             Prev->getStorageClass() != SC_Extern)
2608           return false;
2609       } else if (Prev->isInlineSpecified() &&
2610                  Prev->getStorageClass() != SC_Extern) {
2611         return false;
2612       }
2613     }
2614     return FoundBody;
2615   }
2616 
2617   if (Context.getLangOpts().CPlusPlus)
2618     return false;
2619 
2620   // C99 6.7.4p6:
2621   //   [...] If all of the file scope declarations for a function in a
2622   //   translation unit include the inline function specifier without extern,
2623   //   then the definition in that translation unit is an inline definition.
2624   if (isInlineSpecified() && getStorageClass() != SC_Extern)
2625     return false;
2626   const FunctionDecl *Prev = this;
2627   bool FoundBody = false;
2628   while ((Prev = Prev->getPreviousDecl())) {
2629     FoundBody |= Prev->Body.isValid();
2630     if (RedeclForcesDefC99(Prev))
2631       return false;
2632   }
2633   return FoundBody;
2634 }
2635 
2636 /// \brief For an inline function definition in C, or for a gnu_inline function
2637 /// in C++, determine whether the definition will be externally visible.
2638 ///
2639 /// Inline function definitions are always available for inlining optimizations.
2640 /// However, depending on the language dialect, declaration specifiers, and
2641 /// attributes, the definition of an inline function may or may not be
2642 /// "externally" visible to other translation units in the program.
2643 ///
2644 /// In C99, inline definitions are not externally visible by default. However,
2645 /// if even one of the global-scope declarations is marked "extern inline", the
2646 /// inline definition becomes externally visible (C99 6.7.4p6).
2647 ///
2648 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2649 /// definition, we use the GNU semantics for inline, which are nearly the
2650 /// opposite of C99 semantics. In particular, "inline" by itself will create
2651 /// an externally visible symbol, but "extern inline" will not create an
2652 /// externally visible symbol.
2653 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2654   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2655   assert(isInlined() && "Function must be inline");
2656   ASTContext &Context = getASTContext();
2657 
2658   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2659     // Note: If you change the logic here, please change
2660     // doesDeclarationForceExternallyVisibleDefinition as well.
2661     //
2662     // If it's not the case that both 'inline' and 'extern' are
2663     // specified on the definition, then this inline definition is
2664     // externally visible.
2665     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2666       return true;
2667 
2668     // If any declaration is 'inline' but not 'extern', then this definition
2669     // is externally visible.
2670     for (auto Redecl : redecls()) {
2671       if (Redecl->isInlineSpecified() &&
2672           Redecl->getStorageClass() != SC_Extern)
2673         return true;
2674     }
2675 
2676     return false;
2677   }
2678 
2679   // The rest of this function is C-only.
2680   assert(!Context.getLangOpts().CPlusPlus &&
2681          "should not use C inline rules in C++");
2682 
2683   // C99 6.7.4p6:
2684   //   [...] If all of the file scope declarations for a function in a
2685   //   translation unit include the inline function specifier without extern,
2686   //   then the definition in that translation unit is an inline definition.
2687   for (auto Redecl : redecls()) {
2688     if (RedeclForcesDefC99(Redecl))
2689       return true;
2690   }
2691 
2692   // C99 6.7.4p6:
2693   //   An inline definition does not provide an external definition for the
2694   //   function, and does not forbid an external definition in another
2695   //   translation unit.
2696   return false;
2697 }
2698 
2699 /// getOverloadedOperator - Which C++ overloaded operator this
2700 /// function represents, if any.
2701 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2702   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2703     return getDeclName().getCXXOverloadedOperator();
2704   else
2705     return OO_None;
2706 }
2707 
2708 /// getLiteralIdentifier - The literal suffix identifier this function
2709 /// represents, if any.
2710 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2711   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2712     return getDeclName().getCXXLiteralIdentifier();
2713   else
2714     return 0;
2715 }
2716 
2717 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2718   if (TemplateOrSpecialization.isNull())
2719     return TK_NonTemplate;
2720   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2721     return TK_FunctionTemplate;
2722   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2723     return TK_MemberSpecialization;
2724   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2725     return TK_FunctionTemplateSpecialization;
2726   if (TemplateOrSpecialization.is
2727                                <DependentFunctionTemplateSpecializationInfo*>())
2728     return TK_DependentFunctionTemplateSpecialization;
2729 
2730   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2731 }
2732 
2733 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2734   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2735     return cast<FunctionDecl>(Info->getInstantiatedFrom());
2736 
2737   return 0;
2738 }
2739 
2740 void
2741 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2742                                                FunctionDecl *FD,
2743                                                TemplateSpecializationKind TSK) {
2744   assert(TemplateOrSpecialization.isNull() &&
2745          "Member function is already a specialization");
2746   MemberSpecializationInfo *Info
2747     = new (C) MemberSpecializationInfo(FD, TSK);
2748   TemplateOrSpecialization = Info;
2749 }
2750 
2751 bool FunctionDecl::isImplicitlyInstantiable() const {
2752   // If the function is invalid, it can't be implicitly instantiated.
2753   if (isInvalidDecl())
2754     return false;
2755 
2756   switch (getTemplateSpecializationKind()) {
2757   case TSK_Undeclared:
2758   case TSK_ExplicitInstantiationDefinition:
2759     return false;
2760 
2761   case TSK_ImplicitInstantiation:
2762     return true;
2763 
2764   // It is possible to instantiate TSK_ExplicitSpecialization kind
2765   // if the FunctionDecl has a class scope specialization pattern.
2766   case TSK_ExplicitSpecialization:
2767     return getClassScopeSpecializationPattern() != 0;
2768 
2769   case TSK_ExplicitInstantiationDeclaration:
2770     // Handled below.
2771     break;
2772   }
2773 
2774   // Find the actual template from which we will instantiate.
2775   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2776   bool HasPattern = false;
2777   if (PatternDecl)
2778     HasPattern = PatternDecl->hasBody(PatternDecl);
2779 
2780   // C++0x [temp.explicit]p9:
2781   //   Except for inline functions, other explicit instantiation declarations
2782   //   have the effect of suppressing the implicit instantiation of the entity
2783   //   to which they refer.
2784   if (!HasPattern || !PatternDecl)
2785     return true;
2786 
2787   return PatternDecl->isInlined();
2788 }
2789 
2790 bool FunctionDecl::isTemplateInstantiation() const {
2791   switch (getTemplateSpecializationKind()) {
2792     case TSK_Undeclared:
2793     case TSK_ExplicitSpecialization:
2794       return false;
2795     case TSK_ImplicitInstantiation:
2796     case TSK_ExplicitInstantiationDeclaration:
2797     case TSK_ExplicitInstantiationDefinition:
2798       return true;
2799   }
2800   llvm_unreachable("All TSK values handled.");
2801 }
2802 
2803 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2804   // Handle class scope explicit specialization special case.
2805   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2806     return getClassScopeSpecializationPattern();
2807 
2808   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2809     while (Primary->getInstantiatedFromMemberTemplate()) {
2810       // If we have hit a point where the user provided a specialization of
2811       // this template, we're done looking.
2812       if (Primary->isMemberSpecialization())
2813         break;
2814 
2815       Primary = Primary->getInstantiatedFromMemberTemplate();
2816     }
2817 
2818     return Primary->getTemplatedDecl();
2819   }
2820 
2821   return getInstantiatedFromMemberFunction();
2822 }
2823 
2824 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2825   if (FunctionTemplateSpecializationInfo *Info
2826         = TemplateOrSpecialization
2827             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2828     return Info->Template.getPointer();
2829   }
2830   return 0;
2831 }
2832 
2833 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2834     return getASTContext().getClassScopeSpecializationPattern(this);
2835 }
2836 
2837 const TemplateArgumentList *
2838 FunctionDecl::getTemplateSpecializationArgs() const {
2839   if (FunctionTemplateSpecializationInfo *Info
2840         = TemplateOrSpecialization
2841             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2842     return Info->TemplateArguments;
2843   }
2844   return 0;
2845 }
2846 
2847 const ASTTemplateArgumentListInfo *
2848 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2849   if (FunctionTemplateSpecializationInfo *Info
2850         = TemplateOrSpecialization
2851             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2852     return Info->TemplateArgumentsAsWritten;
2853   }
2854   return 0;
2855 }
2856 
2857 void
2858 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2859                                                 FunctionTemplateDecl *Template,
2860                                      const TemplateArgumentList *TemplateArgs,
2861                                                 void *InsertPos,
2862                                                 TemplateSpecializationKind TSK,
2863                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
2864                                           SourceLocation PointOfInstantiation) {
2865   assert(TSK != TSK_Undeclared &&
2866          "Must specify the type of function template specialization");
2867   FunctionTemplateSpecializationInfo *Info
2868     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2869   if (!Info)
2870     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2871                                                       TemplateArgs,
2872                                                       TemplateArgsAsWritten,
2873                                                       PointOfInstantiation);
2874   TemplateOrSpecialization = Info;
2875   Template->addSpecialization(Info, InsertPos);
2876 }
2877 
2878 void
2879 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2880                                     const UnresolvedSetImpl &Templates,
2881                              const TemplateArgumentListInfo &TemplateArgs) {
2882   assert(TemplateOrSpecialization.isNull());
2883   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2884   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2885   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2886   void *Buffer = Context.Allocate(Size);
2887   DependentFunctionTemplateSpecializationInfo *Info =
2888     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2889                                                              TemplateArgs);
2890   TemplateOrSpecialization = Info;
2891 }
2892 
2893 DependentFunctionTemplateSpecializationInfo::
2894 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2895                                       const TemplateArgumentListInfo &TArgs)
2896   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2897 
2898   d.NumTemplates = Ts.size();
2899   d.NumArgs = TArgs.size();
2900 
2901   FunctionTemplateDecl **TsArray =
2902     const_cast<FunctionTemplateDecl**>(getTemplates());
2903   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2904     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2905 
2906   TemplateArgumentLoc *ArgsArray =
2907     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2908   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2909     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2910 }
2911 
2912 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2913   // For a function template specialization, query the specialization
2914   // information object.
2915   FunctionTemplateSpecializationInfo *FTSInfo
2916     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2917   if (FTSInfo)
2918     return FTSInfo->getTemplateSpecializationKind();
2919 
2920   MemberSpecializationInfo *MSInfo
2921     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2922   if (MSInfo)
2923     return MSInfo->getTemplateSpecializationKind();
2924 
2925   return TSK_Undeclared;
2926 }
2927 
2928 void
2929 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2930                                           SourceLocation PointOfInstantiation) {
2931   if (FunctionTemplateSpecializationInfo *FTSInfo
2932         = TemplateOrSpecialization.dyn_cast<
2933                                     FunctionTemplateSpecializationInfo*>()) {
2934     FTSInfo->setTemplateSpecializationKind(TSK);
2935     if (TSK != TSK_ExplicitSpecialization &&
2936         PointOfInstantiation.isValid() &&
2937         FTSInfo->getPointOfInstantiation().isInvalid())
2938       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2939   } else if (MemberSpecializationInfo *MSInfo
2940              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2941     MSInfo->setTemplateSpecializationKind(TSK);
2942     if (TSK != TSK_ExplicitSpecialization &&
2943         PointOfInstantiation.isValid() &&
2944         MSInfo->getPointOfInstantiation().isInvalid())
2945       MSInfo->setPointOfInstantiation(PointOfInstantiation);
2946   } else
2947     llvm_unreachable("Function cannot have a template specialization kind");
2948 }
2949 
2950 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2951   if (FunctionTemplateSpecializationInfo *FTSInfo
2952         = TemplateOrSpecialization.dyn_cast<
2953                                         FunctionTemplateSpecializationInfo*>())
2954     return FTSInfo->getPointOfInstantiation();
2955   else if (MemberSpecializationInfo *MSInfo
2956              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2957     return MSInfo->getPointOfInstantiation();
2958 
2959   return SourceLocation();
2960 }
2961 
2962 bool FunctionDecl::isOutOfLine() const {
2963   if (Decl::isOutOfLine())
2964     return true;
2965 
2966   // If this function was instantiated from a member function of a
2967   // class template, check whether that member function was defined out-of-line.
2968   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2969     const FunctionDecl *Definition;
2970     if (FD->hasBody(Definition))
2971       return Definition->isOutOfLine();
2972   }
2973 
2974   // If this function was instantiated from a function template,
2975   // check whether that function template was defined out-of-line.
2976   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2977     const FunctionDecl *Definition;
2978     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2979       return Definition->isOutOfLine();
2980   }
2981 
2982   return false;
2983 }
2984 
2985 SourceRange FunctionDecl::getSourceRange() const {
2986   return SourceRange(getOuterLocStart(), EndRangeLoc);
2987 }
2988 
2989 unsigned FunctionDecl::getMemoryFunctionKind() const {
2990   IdentifierInfo *FnInfo = getIdentifier();
2991 
2992   if (!FnInfo)
2993     return 0;
2994 
2995   // Builtin handling.
2996   switch (getBuiltinID()) {
2997   case Builtin::BI__builtin_memset:
2998   case Builtin::BI__builtin___memset_chk:
2999   case Builtin::BImemset:
3000     return Builtin::BImemset;
3001 
3002   case Builtin::BI__builtin_memcpy:
3003   case Builtin::BI__builtin___memcpy_chk:
3004   case Builtin::BImemcpy:
3005     return Builtin::BImemcpy;
3006 
3007   case Builtin::BI__builtin_memmove:
3008   case Builtin::BI__builtin___memmove_chk:
3009   case Builtin::BImemmove:
3010     return Builtin::BImemmove;
3011 
3012   case Builtin::BIstrlcpy:
3013     return Builtin::BIstrlcpy;
3014   case Builtin::BIstrlcat:
3015     return Builtin::BIstrlcat;
3016 
3017   case Builtin::BI__builtin_memcmp:
3018   case Builtin::BImemcmp:
3019     return Builtin::BImemcmp;
3020 
3021   case Builtin::BI__builtin_strncpy:
3022   case Builtin::BI__builtin___strncpy_chk:
3023   case Builtin::BIstrncpy:
3024     return Builtin::BIstrncpy;
3025 
3026   case Builtin::BI__builtin_strncmp:
3027   case Builtin::BIstrncmp:
3028     return Builtin::BIstrncmp;
3029 
3030   case Builtin::BI__builtin_strncasecmp:
3031   case Builtin::BIstrncasecmp:
3032     return Builtin::BIstrncasecmp;
3033 
3034   case Builtin::BI__builtin_strncat:
3035   case Builtin::BI__builtin___strncat_chk:
3036   case Builtin::BIstrncat:
3037     return Builtin::BIstrncat;
3038 
3039   case Builtin::BI__builtin_strndup:
3040   case Builtin::BIstrndup:
3041     return Builtin::BIstrndup;
3042 
3043   case Builtin::BI__builtin_strlen:
3044   case Builtin::BIstrlen:
3045     return Builtin::BIstrlen;
3046 
3047   default:
3048     if (isExternC()) {
3049       if (FnInfo->isStr("memset"))
3050         return Builtin::BImemset;
3051       else if (FnInfo->isStr("memcpy"))
3052         return Builtin::BImemcpy;
3053       else if (FnInfo->isStr("memmove"))
3054         return Builtin::BImemmove;
3055       else if (FnInfo->isStr("memcmp"))
3056         return Builtin::BImemcmp;
3057       else if (FnInfo->isStr("strncpy"))
3058         return Builtin::BIstrncpy;
3059       else if (FnInfo->isStr("strncmp"))
3060         return Builtin::BIstrncmp;
3061       else if (FnInfo->isStr("strncasecmp"))
3062         return Builtin::BIstrncasecmp;
3063       else if (FnInfo->isStr("strncat"))
3064         return Builtin::BIstrncat;
3065       else if (FnInfo->isStr("strndup"))
3066         return Builtin::BIstrndup;
3067       else if (FnInfo->isStr("strlen"))
3068         return Builtin::BIstrlen;
3069     }
3070     break;
3071   }
3072   return 0;
3073 }
3074 
3075 //===----------------------------------------------------------------------===//
3076 // FieldDecl Implementation
3077 //===----------------------------------------------------------------------===//
3078 
3079 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3080                              SourceLocation StartLoc, SourceLocation IdLoc,
3081                              IdentifierInfo *Id, QualType T,
3082                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3083                              InClassInitStyle InitStyle) {
3084   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3085                                BW, Mutable, InitStyle);
3086 }
3087 
3088 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3089   return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3090                                0, QualType(), 0, 0, false, ICIS_NoInit);
3091 }
3092 
3093 bool FieldDecl::isAnonymousStructOrUnion() const {
3094   if (!isImplicit() || getDeclName())
3095     return false;
3096 
3097   if (const RecordType *Record = getType()->getAs<RecordType>())
3098     return Record->getDecl()->isAnonymousStructOrUnion();
3099 
3100   return false;
3101 }
3102 
3103 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3104   assert(isBitField() && "not a bitfield");
3105   Expr *BitWidth = InitializerOrBitWidth.getPointer();
3106   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3107 }
3108 
3109 unsigned FieldDecl::getFieldIndex() const {
3110   const FieldDecl *Canonical = getCanonicalDecl();
3111   if (Canonical != this)
3112     return Canonical->getFieldIndex();
3113 
3114   if (CachedFieldIndex) return CachedFieldIndex - 1;
3115 
3116   unsigned Index = 0;
3117   const RecordDecl *RD = getParent();
3118 
3119   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
3120        I != E; ++I, ++Index)
3121     I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3122 
3123   assert(CachedFieldIndex && "failed to find field in parent");
3124   return CachedFieldIndex - 1;
3125 }
3126 
3127 SourceRange FieldDecl::getSourceRange() const {
3128   if (const Expr *E = InitializerOrBitWidth.getPointer())
3129     return SourceRange(getInnerLocStart(), E->getLocEnd());
3130   return DeclaratorDecl::getSourceRange();
3131 }
3132 
3133 void FieldDecl::setBitWidth(Expr *Width) {
3134   assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3135          "bit width or initializer already set");
3136   InitializerOrBitWidth.setPointer(Width);
3137 }
3138 
3139 void FieldDecl::setInClassInitializer(Expr *Init) {
3140   assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
3141          "bit width or initializer already set");
3142   InitializerOrBitWidth.setPointer(Init);
3143 }
3144 
3145 //===----------------------------------------------------------------------===//
3146 // TagDecl Implementation
3147 //===----------------------------------------------------------------------===//
3148 
3149 SourceLocation TagDecl::getOuterLocStart() const {
3150   return getTemplateOrInnerLocStart(this);
3151 }
3152 
3153 SourceRange TagDecl::getSourceRange() const {
3154   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3155   return SourceRange(getOuterLocStart(), E);
3156 }
3157 
3158 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3159 
3160 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3161   NamedDeclOrQualifier = TDD;
3162   if (TypeForDecl)
3163     assert(TypeForDecl->isLinkageValid());
3164   assert(isLinkageValid());
3165 }
3166 
3167 void TagDecl::startDefinition() {
3168   IsBeingDefined = true;
3169 
3170   if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3171     struct CXXRecordDecl::DefinitionData *Data =
3172       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3173     for (auto I : redecls())
3174       cast<CXXRecordDecl>(I)->DefinitionData = Data;
3175   }
3176 }
3177 
3178 void TagDecl::completeDefinition() {
3179   assert((!isa<CXXRecordDecl>(this) ||
3180           cast<CXXRecordDecl>(this)->hasDefinition()) &&
3181          "definition completed but not started");
3182 
3183   IsCompleteDefinition = true;
3184   IsBeingDefined = false;
3185 
3186   if (ASTMutationListener *L = getASTMutationListener())
3187     L->CompletedTagDefinition(this);
3188 }
3189 
3190 TagDecl *TagDecl::getDefinition() const {
3191   if (isCompleteDefinition())
3192     return const_cast<TagDecl *>(this);
3193 
3194   // If it's possible for us to have an out-of-date definition, check now.
3195   if (MayHaveOutOfDateDef) {
3196     if (IdentifierInfo *II = getIdentifier()) {
3197       if (II->isOutOfDate()) {
3198         updateOutOfDate(*II);
3199       }
3200     }
3201   }
3202 
3203   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3204     return CXXRD->getDefinition();
3205 
3206   for (auto R : redecls())
3207     if (R->isCompleteDefinition())
3208       return R;
3209 
3210   return 0;
3211 }
3212 
3213 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3214   if (QualifierLoc) {
3215     // Make sure the extended qualifier info is allocated.
3216     if (!hasExtInfo())
3217       NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3218     // Set qualifier info.
3219     getExtInfo()->QualifierLoc = QualifierLoc;
3220   } else {
3221     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3222     if (hasExtInfo()) {
3223       if (getExtInfo()->NumTemplParamLists == 0) {
3224         getASTContext().Deallocate(getExtInfo());
3225         NamedDeclOrQualifier = (TypedefNameDecl*) 0;
3226       }
3227       else
3228         getExtInfo()->QualifierLoc = QualifierLoc;
3229     }
3230   }
3231 }
3232 
3233 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3234                                             unsigned NumTPLists,
3235                                             TemplateParameterList **TPLists) {
3236   assert(NumTPLists > 0);
3237   // Make sure the extended decl info is allocated.
3238   if (!hasExtInfo())
3239     // Allocate external info struct.
3240     NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3241   // Set the template parameter lists info.
3242   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3243 }
3244 
3245 //===----------------------------------------------------------------------===//
3246 // EnumDecl Implementation
3247 //===----------------------------------------------------------------------===//
3248 
3249 void EnumDecl::anchor() { }
3250 
3251 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3252                            SourceLocation StartLoc, SourceLocation IdLoc,
3253                            IdentifierInfo *Id,
3254                            EnumDecl *PrevDecl, bool IsScoped,
3255                            bool IsScopedUsingClassTag, bool IsFixed) {
3256   EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3257                                         IsScoped, IsScopedUsingClassTag,
3258                                         IsFixed);
3259   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3260   C.getTypeDeclType(Enum, PrevDecl);
3261   return Enum;
3262 }
3263 
3264 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3265   EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3266                                         0, 0, false, false, false);
3267   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3268   return Enum;
3269 }
3270 
3271 SourceRange EnumDecl::getIntegerTypeRange() const {
3272   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3273     return TI->getTypeLoc().getSourceRange();
3274   return SourceRange();
3275 }
3276 
3277 void EnumDecl::completeDefinition(QualType NewType,
3278                                   QualType NewPromotionType,
3279                                   unsigned NumPositiveBits,
3280                                   unsigned NumNegativeBits) {
3281   assert(!isCompleteDefinition() && "Cannot redefine enums!");
3282   if (!IntegerType)
3283     IntegerType = NewType.getTypePtr();
3284   PromotionType = NewPromotionType;
3285   setNumPositiveBits(NumPositiveBits);
3286   setNumNegativeBits(NumNegativeBits);
3287   TagDecl::completeDefinition();
3288 }
3289 
3290 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3291   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3292     return MSI->getTemplateSpecializationKind();
3293 
3294   return TSK_Undeclared;
3295 }
3296 
3297 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3298                                          SourceLocation PointOfInstantiation) {
3299   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3300   assert(MSI && "Not an instantiated member enumeration?");
3301   MSI->setTemplateSpecializationKind(TSK);
3302   if (TSK != TSK_ExplicitSpecialization &&
3303       PointOfInstantiation.isValid() &&
3304       MSI->getPointOfInstantiation().isInvalid())
3305     MSI->setPointOfInstantiation(PointOfInstantiation);
3306 }
3307 
3308 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3309   if (SpecializationInfo)
3310     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3311 
3312   return 0;
3313 }
3314 
3315 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3316                                             TemplateSpecializationKind TSK) {
3317   assert(!SpecializationInfo && "Member enum is already a specialization");
3318   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3319 }
3320 
3321 //===----------------------------------------------------------------------===//
3322 // RecordDecl Implementation
3323 //===----------------------------------------------------------------------===//
3324 
3325 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3326                        SourceLocation StartLoc, SourceLocation IdLoc,
3327                        IdentifierInfo *Id, RecordDecl *PrevDecl)
3328   : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
3329   HasFlexibleArrayMember = false;
3330   AnonymousStructOrUnion = false;
3331   HasObjectMember = false;
3332   HasVolatileMember = false;
3333   LoadedFieldsFromExternalStorage = false;
3334   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3335 }
3336 
3337 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3338                                SourceLocation StartLoc, SourceLocation IdLoc,
3339                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
3340   RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3341                                          PrevDecl);
3342   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3343 
3344   C.getTypeDeclType(R, PrevDecl);
3345   return R;
3346 }
3347 
3348 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3349   RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3350                                          SourceLocation(), 0, 0);
3351   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3352   return R;
3353 }
3354 
3355 bool RecordDecl::isInjectedClassName() const {
3356   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3357     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3358 }
3359 
3360 RecordDecl::field_iterator RecordDecl::field_begin() const {
3361   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3362     LoadFieldsFromExternalStorage();
3363 
3364   return field_iterator(decl_iterator(FirstDecl));
3365 }
3366 
3367 /// completeDefinition - Notes that the definition of this type is now
3368 /// complete.
3369 void RecordDecl::completeDefinition() {
3370   assert(!isCompleteDefinition() && "Cannot redefine record!");
3371   TagDecl::completeDefinition();
3372 }
3373 
3374 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3375 /// This which can be turned on with an attribute, pragma, or the
3376 /// -mms-bitfields command-line option.
3377 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3378   return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3379 }
3380 
3381 static bool isFieldOrIndirectField(Decl::Kind K) {
3382   return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3383 }
3384 
3385 void RecordDecl::LoadFieldsFromExternalStorage() const {
3386   ExternalASTSource *Source = getASTContext().getExternalSource();
3387   assert(hasExternalLexicalStorage() && Source && "No external storage?");
3388 
3389   // Notify that we have a RecordDecl doing some initialization.
3390   ExternalASTSource::Deserializing TheFields(Source);
3391 
3392   SmallVector<Decl*, 64> Decls;
3393   LoadedFieldsFromExternalStorage = true;
3394   switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3395                                            Decls)) {
3396   case ELR_Success:
3397     break;
3398 
3399   case ELR_AlreadyLoaded:
3400   case ELR_Failure:
3401     return;
3402   }
3403 
3404 #ifndef NDEBUG
3405   // Check that all decls we got were FieldDecls.
3406   for (unsigned i=0, e=Decls.size(); i != e; ++i)
3407     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3408 #endif
3409 
3410   if (Decls.empty())
3411     return;
3412 
3413   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3414                                                  /*FieldsAlreadyLoaded=*/false);
3415 }
3416 
3417 //===----------------------------------------------------------------------===//
3418 // BlockDecl Implementation
3419 //===----------------------------------------------------------------------===//
3420 
3421 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3422   assert(ParamInfo == 0 && "Already has param info!");
3423 
3424   // Zero params -> null pointer.
3425   if (!NewParamInfo.empty()) {
3426     NumParams = NewParamInfo.size();
3427     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3428     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3429   }
3430 }
3431 
3432 void BlockDecl::setCaptures(ASTContext &Context,
3433                             const Capture *begin,
3434                             const Capture *end,
3435                             bool capturesCXXThis) {
3436   CapturesCXXThis = capturesCXXThis;
3437 
3438   if (begin == end) {
3439     NumCaptures = 0;
3440     Captures = 0;
3441     return;
3442   }
3443 
3444   NumCaptures = end - begin;
3445 
3446   // Avoid new Capture[] because we don't want to provide a default
3447   // constructor.
3448   size_t allocationSize = NumCaptures * sizeof(Capture);
3449   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3450   memcpy(buffer, begin, allocationSize);
3451   Captures = static_cast<Capture*>(buffer);
3452 }
3453 
3454 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3455   for (capture_const_iterator
3456          i = capture_begin(), e = capture_end(); i != e; ++i)
3457     // Only auto vars can be captured, so no redeclaration worries.
3458     if (i->getVariable() == variable)
3459       return true;
3460 
3461   return false;
3462 }
3463 
3464 SourceRange BlockDecl::getSourceRange() const {
3465   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3466 }
3467 
3468 //===----------------------------------------------------------------------===//
3469 // Other Decl Allocation/Deallocation Method Implementations
3470 //===----------------------------------------------------------------------===//
3471 
3472 void TranslationUnitDecl::anchor() { }
3473 
3474 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3475   return new (C, (DeclContext*)0) TranslationUnitDecl(C);
3476 }
3477 
3478 void LabelDecl::anchor() { }
3479 
3480 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3481                              SourceLocation IdentL, IdentifierInfo *II) {
3482   return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
3483 }
3484 
3485 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3486                              SourceLocation IdentL, IdentifierInfo *II,
3487                              SourceLocation GnuLabelL) {
3488   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3489   return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
3490 }
3491 
3492 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3493   return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
3494 }
3495 
3496 void ValueDecl::anchor() { }
3497 
3498 bool ValueDecl::isWeak() const {
3499   for (const auto *I : attrs())
3500     if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
3501       return true;
3502 
3503   return isWeakImported();
3504 }
3505 
3506 void ImplicitParamDecl::anchor() { }
3507 
3508 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3509                                              SourceLocation IdLoc,
3510                                              IdentifierInfo *Id,
3511                                              QualType Type) {
3512   return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
3513 }
3514 
3515 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3516                                                          unsigned ID) {
3517   return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3518 }
3519 
3520 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3521                                    SourceLocation StartLoc,
3522                                    const DeclarationNameInfo &NameInfo,
3523                                    QualType T, TypeSourceInfo *TInfo,
3524                                    StorageClass SC,
3525                                    bool isInlineSpecified,
3526                                    bool hasWrittenPrototype,
3527                                    bool isConstexprSpecified) {
3528   FunctionDecl *New =
3529       new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3530                                isInlineSpecified, isConstexprSpecified);
3531   New->HasWrittenPrototype = hasWrittenPrototype;
3532   return New;
3533 }
3534 
3535 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3536   return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3537                                   DeclarationNameInfo(), QualType(), 0,
3538                                   SC_None, false, false);
3539 }
3540 
3541 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3542   return new (C, DC) BlockDecl(DC, L);
3543 }
3544 
3545 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3546   return new (C, ID) BlockDecl(0, SourceLocation());
3547 }
3548 
3549 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3550                                    unsigned NumParams) {
3551   return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3552       CapturedDecl(DC, NumParams);
3553 }
3554 
3555 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3556                                                unsigned NumParams) {
3557   return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3558       CapturedDecl(0, NumParams);
3559 }
3560 
3561 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3562                                            SourceLocation L,
3563                                            IdentifierInfo *Id, QualType T,
3564                                            Expr *E, const llvm::APSInt &V) {
3565   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3566 }
3567 
3568 EnumConstantDecl *
3569 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3570   return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3571                                       llvm::APSInt());
3572 }
3573 
3574 void IndirectFieldDecl::anchor() { }
3575 
3576 IndirectFieldDecl *
3577 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3578                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
3579                           unsigned CHS) {
3580   return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3581 }
3582 
3583 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3584                                                          unsigned ID) {
3585   return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3586                                        QualType(), 0, 0);
3587 }
3588 
3589 SourceRange EnumConstantDecl::getSourceRange() const {
3590   SourceLocation End = getLocation();
3591   if (Init)
3592     End = Init->getLocEnd();
3593   return SourceRange(getLocation(), End);
3594 }
3595 
3596 void TypeDecl::anchor() { }
3597 
3598 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3599                                  SourceLocation StartLoc, SourceLocation IdLoc,
3600                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3601   return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
3602 }
3603 
3604 void TypedefNameDecl::anchor() { }
3605 
3606 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3607   return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3608 }
3609 
3610 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3611                                      SourceLocation StartLoc,
3612                                      SourceLocation IdLoc, IdentifierInfo *Id,
3613                                      TypeSourceInfo *TInfo) {
3614   return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3615 }
3616 
3617 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3618   return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3619 }
3620 
3621 SourceRange TypedefDecl::getSourceRange() const {
3622   SourceLocation RangeEnd = getLocation();
3623   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3624     if (typeIsPostfix(TInfo->getType()))
3625       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3626   }
3627   return SourceRange(getLocStart(), RangeEnd);
3628 }
3629 
3630 SourceRange TypeAliasDecl::getSourceRange() const {
3631   SourceLocation RangeEnd = getLocStart();
3632   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3633     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3634   return SourceRange(getLocStart(), RangeEnd);
3635 }
3636 
3637 void FileScopeAsmDecl::anchor() { }
3638 
3639 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3640                                            StringLiteral *Str,
3641                                            SourceLocation AsmLoc,
3642                                            SourceLocation RParenLoc) {
3643   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3644 }
3645 
3646 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3647                                                        unsigned ID) {
3648   return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3649 }
3650 
3651 void EmptyDecl::anchor() {}
3652 
3653 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3654   return new (C, DC) EmptyDecl(DC, L);
3655 }
3656 
3657 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3658   return new (C, ID) EmptyDecl(0, SourceLocation());
3659 }
3660 
3661 //===----------------------------------------------------------------------===//
3662 // ImportDecl Implementation
3663 //===----------------------------------------------------------------------===//
3664 
3665 /// \brief Retrieve the number of module identifiers needed to name the given
3666 /// module.
3667 static unsigned getNumModuleIdentifiers(Module *Mod) {
3668   unsigned Result = 1;
3669   while (Mod->Parent) {
3670     Mod = Mod->Parent;
3671     ++Result;
3672   }
3673   return Result;
3674 }
3675 
3676 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3677                        Module *Imported,
3678                        ArrayRef<SourceLocation> IdentifierLocs)
3679   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3680     NextLocalImport()
3681 {
3682   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3683   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3684   memcpy(StoredLocs, IdentifierLocs.data(),
3685          IdentifierLocs.size() * sizeof(SourceLocation));
3686 }
3687 
3688 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3689                        Module *Imported, SourceLocation EndLoc)
3690   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3691     NextLocalImport()
3692 {
3693   *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3694 }
3695 
3696 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3697                                SourceLocation StartLoc, Module *Imported,
3698                                ArrayRef<SourceLocation> IdentifierLocs) {
3699   return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3700       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3701 }
3702 
3703 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3704                                        SourceLocation StartLoc,
3705                                        Module *Imported,
3706                                        SourceLocation EndLoc) {
3707   ImportDecl *Import =
3708       new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3709                                                      Imported, EndLoc);
3710   Import->setImplicit();
3711   return Import;
3712 }
3713 
3714 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3715                                            unsigned NumLocations) {
3716   return new (C, ID, NumLocations * sizeof(SourceLocation))
3717       ImportDecl(EmptyShell());
3718 }
3719 
3720 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3721   if (!ImportedAndComplete.getInt())
3722     return None;
3723 
3724   const SourceLocation *StoredLocs
3725     = reinterpret_cast<const SourceLocation *>(this + 1);
3726   return ArrayRef<SourceLocation>(StoredLocs,
3727                                   getNumModuleIdentifiers(getImportedModule()));
3728 }
3729 
3730 SourceRange ImportDecl::getSourceRange() const {
3731   if (!ImportedAndComplete.getInt())
3732     return SourceRange(getLocation(),
3733                        *reinterpret_cast<const SourceLocation *>(this + 1));
3734 
3735   return SourceRange(getLocation(), getIdentifierLocs().back());
3736 }
3737