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