Clang Project

clang_source_code/lib/AST/Decl.cpp
1//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Decl.h"
14#include "Linkage.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTDiagnostic.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CanonicalType.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclOpenMP.h"
24#include "clang/AST/DeclTemplate.h"
25#include "clang/AST/DeclarationName.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExternalASTSource.h"
29#include "clang/AST/ODRHash.h"
30#include "clang/AST/PrettyDeclStackTrace.h"
31#include "clang/AST/PrettyPrinter.h"
32#include "clang/AST/Redeclarable.h"
33#include "clang/AST/Stmt.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/Basic/Builtins.h"
38#include "clang/Basic/IdentifierTable.h"
39#include "clang/Basic/LLVM.h"
40#include "clang/Basic/LangOptions.h"
41#include "clang/Basic/Linkage.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/PartialDiagnostic.h"
44#include "clang/Basic/SanitizerBlacklist.h"
45#include "clang/Basic/Sanitizers.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/Specifiers.h"
49#include "clang/Basic/TargetCXXABI.h"
50#include "clang/Basic/TargetInfo.h"
51#include "clang/Basic/Visibility.h"
52#include "llvm/ADT/APSInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/None.h"
55#include "llvm/ADT/Optional.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringSwitch.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/Triple.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/raw_ostream.h"
64#include <algorithm>
65#include <cassert>
66#include <cstddef>
67#include <cstring>
68#include <memory>
69#include <string>
70#include <tuple>
71#include <type_traits>
72
73using namespace clang;
74
75Decl *clang::getPrimaryMergedDecl(Decl *D) {
76  return D->getASTContext().getPrimaryMergedDecl(D);
77}
78
79void PrettyDeclStackTraceEntry::print(raw_ostream &OSconst {
80  SourceLocation Loc = this->Loc;
81  if (!Loc.isValid() && TheDeclLoc = TheDecl->getLocation();
82  if (Loc.isValid()) {
83    Loc.print(OSContext.getSourceManager());
84    OS << ": ";
85  }
86  OS << Message;
87
88  if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
89    OS << " '";
90    ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
91    OS << "'";
92  }
93
94  OS << '\n';
95}
96
97// Defined here so that it can be inlined into its direct callers.
98bool Decl::isOutOfLine() const {
99  return !getLexicalDeclContext()->Equals(getDeclContext());
100}
101
102TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
103    : Decl(TranslationUnit, nullptr, SourceLocation()),
104      DeclContext(TranslationUnit), Ctx(ctx) {}
105
106//===----------------------------------------------------------------------===//
107// NamedDecl Implementation
108//===----------------------------------------------------------------------===//
109
110// Visibility rules aren't rigorously externally specified, but here
111// are the basic principles behind what we implement:
112//
113// 1. An explicit visibility attribute is generally a direct expression
114// of the user's intent and should be honored.  Only the innermost
115// visibility attribute applies.  If no visibility attribute applies,
116// global visibility settings are considered.
117//
118// 2. There is one caveat to the above: on or in a template pattern,
119// an explicit visibility attribute is just a default rule, and
120// visibility can be decreased by the visibility of template
121// arguments.  But this, too, has an exception: an attribute on an
122// explicit specialization or instantiation causes all the visibility
123// restrictions of the template arguments to be ignored.
124//
125// 3. A variable that does not otherwise have explicit visibility can
126// be restricted by the visibility of its type.
127//
128// 4. A visibility restriction is explicit if it comes from an
129// attribute (or something like it), not a global visibility setting.
130// When emitting a reference to an external symbol, visibility
131// restrictions are ignored unless they are explicit.
132//
133// 5. When computing the visibility of a non-type, including a
134// non-type member of a class, only non-type visibility restrictions
135// are considered: the 'visibility' attribute, global value-visibility
136// settings, and a few special cases like __private_extern.
137//
138// 6. When computing the visibility of a type, including a type member
139// of a class, only type visibility restrictions are considered:
140// the 'type_visibility' attribute and global type-visibility settings.
141// However, a 'visibility' attribute counts as a 'type_visibility'
142// attribute on any declaration that only has the former.
143//
144// The visibility of a "secondary" entity, like a template argument,
145// is computed using the kind of that entity, not the kind of the
146// primary entity for which we are computing visibility.  For example,
147// the visibility of a specialization of either of these templates:
148//   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
149//   template <class T, bool (&compare)(T, X)> class matcher;
150// is restricted according to the type visibility of the argument 'T',
151// the type visibility of 'bool(&)(T,X)', and the value visibility of
152// the argument function 'compare'.  That 'has_match' is a value
153// and 'matcher' is a type only matters when looking for attributes
154// and settings from the immediate context.
155
156/// Does this computation kind permit us to consider additional
157/// visibility settings from attributes and the like?
158static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
159  return computation.IgnoreExplicitVisibility;
160}
161
162/// Given an LVComputationKind, return one of the same type/value sort
163/// that records that it already has explicit visibility.
164static LVComputationKind
165withExplicitVisibilityAlready(LVComputationKind Kind) {
166  Kind.IgnoreExplicitVisibility = true;
167  return Kind;
168}
169
170static Optional<VisibilitygetExplicitVisibility(const NamedDecl *D,
171                                                  LVComputationKind kind) {
172   (0) . __assert_fail ("!kind.IgnoreExplicitVisibility && \"asking for explicit visibility when we shouldn't be\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 173, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!kind.IgnoreExplicitVisibility &&
173 (0) . __assert_fail ("!kind.IgnoreExplicitVisibility && \"asking for explicit visibility when we shouldn't be\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 173, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "asking for explicit visibility when we shouldn't be");
174  return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
175}
176
177/// Is the given declaration a "type" or a "value" for the purposes of
178/// visibility computation?
179static bool usesTypeVisibility(const NamedDecl *D) {
180  return isa<TypeDecl>(D) ||
181         isa<ClassTemplateDecl>(D) ||
182         isa<ObjCInterfaceDecl>(D);
183}
184
185/// Does the given declaration have member specialization information,
186/// and if so, is it an explicit specialization?
187template <class T> static typename
188std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
189isExplicitMemberSpecialization(const T *D) {
190  if (const MemberSpecializationInfo *member =
191        D->getMemberSpecializationInfo()) {
192    return member->isExplicitSpecialization();
193  }
194  return false;
195}
196
197/// For templates, this question is easier: a member template can't be
198/// explicitly instantiated, so there's a single bit indicating whether
199/// or not this is an explicit member specialization.
200static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
201  return D->isMemberSpecialization();
202}
203
204/// Given a visibility attribute, return the explicit visibility
205/// associated with it.
206template <class T>
207static Visibility getVisibilityFromAttr(const T *attr) {
208  switch (attr->getVisibility()) {
209  case T::Default:
210    return DefaultVisibility;
211  case T::Hidden:
212    return HiddenVisibility;
213  case T::Protected:
214    return ProtectedVisibility;
215  }
216  llvm_unreachable("bad visibility kind");
217}
218
219/// Return the explicit visibility of the given declaration.
220static Optional<VisibilitygetVisibilityOf(const NamedDecl *D,
221                                    NamedDecl::ExplicitVisibilityKind kind) {
222  // If we're ultimately computing the visibility of a type, look for
223  // a 'type_visibility' attribute before looking for 'visibility'.
224  if (kind == NamedDecl::VisibilityForType) {
225    if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
226      return getVisibilityFromAttr(A);
227    }
228  }
229
230  // If this declaration has an explicit visibility attribute, use it.
231  if (const auto *A = D->getAttr<VisibilityAttr>()) {
232    return getVisibilityFromAttr(A);
233  }
234
235  return None;
236}
237
238LinkageInfo LinkageComputer::getLVForType(const Type &T,
239                                          LVComputationKind computation) {
240  if (computation.IgnoreAllVisibility)
241    return LinkageInfo(T.getLinkage(), DefaultVisibilitytrue);
242  return getTypeLinkageAndVisibility(&T);
243}
244
245/// Get the most restrictive linkage for the types in the given
246/// template parameter list.  For visibility purposes, template
247/// parameters are part of the signature of a template.
248LinkageInfo LinkageComputer::getLVForTemplateParameterList(
249    const TemplateParameterList *ParamsLVComputationKind computation) {
250  LinkageInfo LV;
251  for (const NamedDecl *P : *Params) {
252    // Template type parameters are the most common and never
253    // contribute to visibility, pack or not.
254    if (isa<TemplateTypeParmDecl>(P))
255      continue;
256
257    // Non-type template parameters can be restricted by the value type, e.g.
258    //   template <enum X> class A { ... };
259    // We have to be careful here, though, because we can be dealing with
260    // dependent types.
261    if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
262      // Handle the non-pack case first.
263      if (!NTTP->isExpandedParameterPack()) {
264        if (!NTTP->getType()->isDependentType()) {
265          LV.merge(getLVForType(*NTTP->getType(), computation));
266        }
267        continue;
268      }
269
270      // Look at all the types in an expanded pack.
271      for (unsigned i = 0n = NTTP->getNumExpansionTypes(); i != n; ++i) {
272        QualType type = NTTP->getExpansionType(i);
273        if (!type->isDependentType())
274          LV.merge(getTypeLinkageAndVisibility(type));
275      }
276      continue;
277    }
278
279    // Template template parameters can be restricted by their
280    // template parameters, recursively.
281    const auto *TTP = cast<TemplateTemplateParmDecl>(P);
282
283    // Handle the non-pack case first.
284    if (!TTP->isExpandedParameterPack()) {
285      LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
286                                             computation));
287      continue;
288    }
289
290    // Look at all expansions in an expanded pack.
291    for (unsigned i = 0n = TTP->getNumExpansionTemplateParameters();
292           i != n; ++i) {
293      LV.merge(getLVForTemplateParameterList(
294          TTP->getExpansionTemplateParameters(i), computation));
295    }
296  }
297
298  return LV;
299}
300
301static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
302  const Decl *Ret = nullptr;
303  const DeclContext *DC = D->getDeclContext();
304  while (DC->getDeclKind() != Decl::TranslationUnit) {
305    if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
306      Ret = cast<Decl>(DC);
307    DC = DC->getParent();
308  }
309  return Ret;
310}
311
312/// Get the most restrictive linkage for the types and
313/// declarations in the given template argument list.
314///
315/// Note that we don't take an LVComputationKind because we always
316/// want to honor the visibility of template arguments in the same way.
317LinkageInfo
318LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgumentArgs,
319                                              LVComputationKind computation) {
320  LinkageInfo LV;
321
322  for (const TemplateArgument &Arg : Args) {
323    switch (Arg.getKind()) {
324    case TemplateArgument::Null:
325    case TemplateArgument::Integral:
326    case TemplateArgument::Expression:
327      continue;
328
329    case TemplateArgument::Type:
330      LV.merge(getLVForType(*Arg.getAsType(), computation));
331      continue;
332
333    case TemplateArgument::Declaration: {
334      const NamedDecl *ND = Arg.getAsDecl();
335      assert(!usesTypeVisibility(ND));
336      LV.merge(getLVForDecl(ND, computation));
337      continue;
338    }
339
340    case TemplateArgument::NullPtr:
341      LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
342      continue;
343
344    case TemplateArgument::Template:
345    case TemplateArgument::TemplateExpansion:
346      if (TemplateDecl *Template =
347              Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
348        LV.merge(getLVForDecl(Template, computation));
349      continue;
350
351    case TemplateArgument::Pack:
352      LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
353      continue;
354    }
355    llvm_unreachable("bad template argument kind");
356  }
357
358  return LV;
359}
360
361LinkageInfo
362LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
363                                              LVComputationKind computation) {
364  return getLVForTemplateArgumentList(TArgs.asArray(), computation);
365}
366
367static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
368                        const FunctionTemplateSpecializationInfo *specInfo) {
369  // Include visibility from the template parameters and arguments
370  // only if this is not an explicit instantiation or specialization
371  // with direct explicit visibility.  (Implicit instantiations won't
372  // have a direct attribute.)
373  if (!specInfo->isExplicitInstantiationOrSpecialization())
374    return true;
375
376  return !fn->hasAttr<VisibilityAttr>();
377}
378
379/// Merge in template-related linkage and visibility for the given
380/// function template specialization.
381///
382/// We don't need a computation kind here because we can assume
383/// LVForValue.
384///
385/// \param[out] LV the computation to use for the parent
386void LinkageComputer::mergeTemplateLV(
387    LinkageInfo &LVconst FunctionDecl *fn,
388    const FunctionTemplateSpecializationInfo *specInfo,
389    LVComputationKind computation) {
390  bool considerVisibility =
391    shouldConsiderTemplateVisibility(fnspecInfo);
392
393  // Merge information from the template parameters.
394  FunctionTemplateDecl *temp = specInfo->getTemplate();
395  LinkageInfo tempLV =
396    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
397  LV.mergeMaybeWithVisibility(tempLVconsiderVisibility);
398
399  // Merge information from the template arguments.
400  const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
401  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgscomputation);
402  LV.mergeMaybeWithVisibility(argsLVconsiderVisibility);
403}
404
405/// Does the given declaration have a direct visibility attribute
406/// that would match the given rules?
407static bool hasDirectVisibilityAttribute(const NamedDecl *D,
408                                         LVComputationKind computation) {
409  if (computation.IgnoreAllVisibility)
410    return false;
411
412  return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
413         D->hasAttr<VisibilityAttr>();
414}
415
416/// Should we consider visibility associated with the template
417/// arguments and parameters of the given class template specialization?
418static bool shouldConsiderTemplateVisibility(
419                                 const ClassTemplateSpecializationDecl *spec,
420                                 LVComputationKind computation) {
421  // Include visibility from the template parameters and arguments
422  // only if this is not an explicit instantiation or specialization
423  // with direct explicit visibility (and note that implicit
424  // instantiations won't have a direct attribute).
425  //
426  // Furthermore, we want to ignore template parameters and arguments
427  // for an explicit specialization when computing the visibility of a
428  // member thereof with explicit visibility.
429  //
430  // This is a bit complex; let's unpack it.
431  //
432  // An explicit class specialization is an independent, top-level
433  // declaration.  As such, if it or any of its members has an
434  // explicit visibility attribute, that must directly express the
435  // user's intent, and we should honor it.  The same logic applies to
436  // an explicit instantiation of a member of such a thing.
437
438  // Fast path: if this is not an explicit instantiation or
439  // specialization, we always want to consider template-related
440  // visibility restrictions.
441  if (!spec->isExplicitInstantiationOrSpecialization())
442    return true;
443
444  // This is the 'member thereof' check.
445  if (spec->isExplicitSpecialization() &&
446      hasExplicitVisibilityAlready(computation))
447    return false;
448
449  return !hasDirectVisibilityAttribute(speccomputation);
450}
451
452/// Merge in template-related linkage and visibility for the given
453/// class template specialization.
454void LinkageComputer::mergeTemplateLV(
455    LinkageInfo &LVconst ClassTemplateSpecializationDecl *spec,
456    LVComputationKind computation) {
457  bool considerVisibility = shouldConsiderTemplateVisibility(speccomputation);
458
459  // Merge information from the template parameters, but ignore
460  // visibility if we're only considering template arguments.
461
462  ClassTemplateDecl *temp = spec->getSpecializedTemplate();
463  LinkageInfo tempLV =
464    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
465  LV.mergeMaybeWithVisibility(tempLV,
466           considerVisibility && !hasExplicitVisibilityAlready(computation));
467
468  // Merge information from the template arguments.  We ignore
469  // template-argument visibility if we've got an explicit
470  // instantiation with a visibility attribute.
471  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
472  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgscomputation);
473  if (considerVisibility)
474    LV.mergeVisibility(argsLV);
475  LV.mergeExternalVisibility(argsLV);
476}
477
478/// Should we consider visibility associated with the template
479/// arguments and parameters of the given variable template
480/// specialization? As usual, follow class template specialization
481/// logic up to initialization.
482static bool shouldConsiderTemplateVisibility(
483                                 const VarTemplateSpecializationDecl *spec,
484                                 LVComputationKind computation) {
485  // Include visibility from the template parameters and arguments
486  // only if this is not an explicit instantiation or specialization
487  // with direct explicit visibility (and note that implicit
488  // instantiations won't have a direct attribute).
489  if (!spec->isExplicitInstantiationOrSpecialization())
490    return true;
491
492  // An explicit variable specialization is an independent, top-level
493  // declaration.  As such, if it has an explicit visibility attribute,
494  // that must directly express the user's intent, and we should honor
495  // it.
496  if (spec->isExplicitSpecialization() &&
497      hasExplicitVisibilityAlready(computation))
498    return false;
499
500  return !hasDirectVisibilityAttribute(speccomputation);
501}
502
503/// Merge in template-related linkage and visibility for the given
504/// variable template specialization. As usual, follow class template
505/// specialization logic up to initialization.
506void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
507                                      const VarTemplateSpecializationDecl *spec,
508                                      LVComputationKind computation) {
509  bool considerVisibility = shouldConsiderTemplateVisibility(speccomputation);
510
511  // Merge information from the template parameters, but ignore
512  // visibility if we're only considering template arguments.
513
514  VarTemplateDecl *temp = spec->getSpecializedTemplate();
515  LinkageInfo tempLV =
516    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
517  LV.mergeMaybeWithVisibility(tempLV,
518           considerVisibility && !hasExplicitVisibilityAlready(computation));
519
520  // Merge information from the template arguments.  We ignore
521  // template-argument visibility if we've got an explicit
522  // instantiation with a visibility attribute.
523  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
524  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgscomputation);
525  if (considerVisibility)
526    LV.mergeVisibility(argsLV);
527  LV.mergeExternalVisibility(argsLV);
528}
529
530static bool useInlineVisibilityHidden(const NamedDecl *D) {
531  // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
532  const LangOptions &Opts = D->getASTContext().getLangOpts();
533  if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
534    return false;
535
536  const auto *FD = dyn_cast<FunctionDecl>(D);
537  if (!FD)
538    return false;
539
540  TemplateSpecializationKind TSK = TSK_Undeclared;
541  if (FunctionTemplateSpecializationInfo *spec
542      = FD->getTemplateSpecializationInfo()) {
543    TSK = spec->getTemplateSpecializationKind();
544  } else if (MemberSpecializationInfo *MSI =
545             FD->getMemberSpecializationInfo()) {
546    TSK = MSI->getTemplateSpecializationKind();
547  }
548
549  const FunctionDecl *Def = nullptr;
550  // InlineVisibilityHidden only applies to definitions, and
551  // isInlined() only gives meaningful answers on definitions
552  // anyway.
553  return TSK != TSK_ExplicitInstantiationDeclaration &&
554    TSK != TSK_ExplicitInstantiationDefinition &&
555    FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
556}
557
558template <typename T> static bool isFirstInExternCContext(T *D) {
559  const T *First = D->getFirstDecl();
560  return First->isInExternCContext();
561}
562
563static bool isSingleLineLanguageLinkage(const Decl &D) {
564  if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
565    if (!SD->hasBraces())
566      return true;
567  return false;
568}
569
570static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
571  // FIXME: Handle isModulePrivate.
572  switch (D->getModuleOwnershipKind()) {
573  case Decl::ModuleOwnershipKind::Unowned:
574  case Decl::ModuleOwnershipKind::ModulePrivate:
575    return false;
576  case Decl::ModuleOwnershipKind::Visible:
577  case Decl::ModuleOwnershipKind::VisibleWhenImported:
578    if (auto *M = D->getOwningModule())
579      return M->Kind == Module::ModuleInterfaceUnit;
580  }
581  llvm_unreachable("unexpected module ownership kind");
582}
583
584static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
585  // Internal linkage declarations within a module interface unit are modeled
586  // as "module-internal linkage", which means that they have internal linkage
587  // formally but can be indirectly accessed from outside the module via inline
588  // functions and templates defined within the module.
589  if (auto *M = D->getOwningModule())
590    if (M->Kind == Module::ModuleInterfaceUnit)
591      return LinkageInfo(ModuleInternalLinkageDefaultVisibilityfalse);
592
593  return LinkageInfo::internal();
594}
595
596static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
597  // C++ Modules TS [basic.link]/6.8:
598  //   - A name declared at namespace scope that does not have internal linkage
599  //     by the previous rules and that is introduced by a non-exported
600  //     declaration has module linkage.
601  if (auto *M = D->getOwningModule())
602    if (M->Kind == Module::ModuleInterfaceUnit)
603      if (!isExportedFromModuleIntefaceUnit(
604              cast<NamedDecl>(D->getCanonicalDecl())))
605        return LinkageInfo(ModuleLinkageDefaultVisibilityfalse);
606
607  return LinkageInfo::external();
608}
609
610LinkageInfo
611LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
612                                            LVComputationKind computation,
613                                            bool IgnoreVarTypeLinkage) {
614   (0) . __assert_fail ("D->getDeclContext()->getRedeclContext()->isFileContext() && \"Not a name having namespace scope\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 615, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
615 (0) . __assert_fail ("D->getDeclContext()->getRedeclContext()->isFileContext() && \"Not a name having namespace scope\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 615, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Not a name having namespace scope");
616  ASTContext &Context = D->getASTContext();
617
618  // C++ [basic.link]p3:
619  //   A name having namespace scope (3.3.6) has internal linkage if it
620  //   is the name of
621  //     - an object, reference, function or function template that is
622  //       explicitly declared static; or,
623  // (This bullet corresponds to C99 6.2.2p3.)
624  if (const auto *Var = dyn_cast<VarDecl>(D)) {
625    // Explicitly declared static.
626    if (Var->getStorageClass() == SC_Static)
627      return getInternalLinkageFor(Var);
628
629    // - a non-inline, non-volatile object or reference that is explicitly
630    //   declared const or constexpr and neither explicitly declared extern
631    //   nor previously declared to have external linkage; or (there is no
632    //   equivalent in C99)
633    // The C++ modules TS adds "non-exported" to this list.
634    if (Context.getLangOpts().CPlusPlus &&
635        Var->getType().isConstQualified() &&
636        !Var->getType().isVolatileQualified() &&
637        !Var->isInline() &&
638        !isExportedFromModuleIntefaceUnit(Var)) {
639      const VarDecl *PrevVar = Var->getPreviousDecl();
640      if (PrevVar)
641        return getLVForDecl(PrevVarcomputation);
642
643      if (Var->getStorageClass() != SC_Extern &&
644          Var->getStorageClass() != SC_PrivateExtern &&
645          !isSingleLineLanguageLinkage(*Var))
646        return getInternalLinkageFor(Var);
647    }
648
649    for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
650         PrevVar = PrevVar->getPreviousDecl()) {
651      if (PrevVar->getStorageClass() == SC_PrivateExtern &&
652          Var->getStorageClass() == SC_None)
653        return getDeclLinkageAndVisibility(PrevVar);
654      // Explicitly declared static.
655      if (PrevVar->getStorageClass() == SC_Static)
656        return getInternalLinkageFor(Var);
657    }
658  } else if (const FunctionDecl *Function = D->getAsFunction()) {
659    // C++ [temp]p4:
660    //   A non-member function template can have internal linkage; any
661    //   other template name shall have external linkage.
662
663    // Explicitly declared static.
664    if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
665      return getInternalLinkageFor(Function);
666  } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
667    //   - a data member of an anonymous union.
668    const VarDecl *VD = IFD->getVarDecl();
669     (0) . __assert_fail ("VD && \"Expected a VarDecl in this IndirectFieldDecl!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 669, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
670    return getLVForNamespaceScopeDecl(VDcomputationIgnoreVarTypeLinkage);
671  }
672   (0) . __assert_fail ("!isa(D) && \"Didn't expect a FieldDecl!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 672, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
673
674  if (D->isInAnonymousNamespace()) {
675    const auto *Var = dyn_cast<VarDecl>(D);
676    const auto *Func = dyn_cast<FunctionDecl>(D);
677    // FIXME: The check for extern "C" here is not justified by the standard
678    // wording, but we retain it from the pre-DR1113 model to avoid breaking
679    // code.
680    //
681    // C++11 [basic.link]p4:
682    //   An unnamed namespace or a namespace declared directly or indirectly
683    //   within an unnamed namespace has internal linkage.
684    if ((!Var || !isFirstInExternCContext(Var)) &&
685        (!Func || !isFirstInExternCContext(Func)))
686      return getInternalLinkageFor(D);
687  }
688
689  // Set up the defaults.
690
691  // C99 6.2.2p5:
692  //   If the declaration of an identifier for an object has file
693  //   scope and no storage-class specifier, its linkage is
694  //   external.
695  LinkageInfo LV = getExternalLinkageFor(D);
696
697  if (!hasExplicitVisibilityAlready(computation)) {
698    if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
699      LV.mergeVisibility(*Vis, true);
700    } else {
701      // If we're declared in a namespace with a visibility attribute,
702      // use that namespace's visibility, and it still counts as explicit.
703      for (const DeclContext *DC = D->getDeclContext();
704           !isa<TranslationUnitDecl>(DC);
705           DC = DC->getParent()) {
706        const auto *ND = dyn_cast<NamespaceDecl>(DC);
707        if (!ND) continue;
708        if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
709          LV.mergeVisibility(*Vis, true);
710          break;
711        }
712      }
713    }
714
715    // Add in global settings if the above didn't give us direct visibility.
716    if (!LV.isVisibilityExplicit()) {
717      // Use global type/value visibility as appropriate.
718      Visibility globalVisibility =
719          computation.isValueVisibility()
720              ? Context.getLangOpts().getValueVisibilityMode()
721              : Context.getLangOpts().getTypeVisibilityMode();
722      LV.mergeVisibility(globalVisibility/*explicit*/ false);
723
724      // If we're paying attention to global visibility, apply
725      // -finline-visibility-hidden if this is an inline method.
726      if (useInlineVisibilityHidden(D))
727        LV.mergeVisibility(HiddenVisibility/*visibilityExplicit=*/false);
728    }
729  }
730
731  // C++ [basic.link]p4:
732
733  //   A name having namespace scope has external linkage if it is the
734  //   name of
735  //
736  //     - an object or reference, unless it has internal linkage; or
737  if (const auto *Var = dyn_cast<VarDecl>(D)) {
738    // GCC applies the following optimization to variables and static
739    // data members, but not to functions:
740    //
741    // Modify the variable's LV by the LV of its type unless this is
742    // C or extern "C".  This follows from [basic.link]p9:
743    //   A type without linkage shall not be used as the type of a
744    //   variable or function with external linkage unless
745    //    - the entity has C language linkage, or
746    //    - the entity is declared within an unnamed namespace, or
747    //    - the entity is not used or is defined in the same
748    //      translation unit.
749    // and [basic.link]p10:
750    //   ...the types specified by all declarations referring to a
751    //   given variable or function shall be identical...
752    // C does not have an equivalent rule.
753    //
754    // Ignore this if we've got an explicit attribute;  the user
755    // probably knows what they're doing.
756    //
757    // Note that we don't want to make the variable non-external
758    // because of this, but unique-external linkage suits us.
759    if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
760        !IgnoreVarTypeLinkage) {
761      LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
762      if (!isExternallyVisible(TypeLV.getLinkage()))
763        return LinkageInfo::uniqueExternal();
764      if (!LV.isVisibilityExplicit())
765        LV.mergeVisibility(TypeLV);
766    }
767
768    if (Var->getStorageClass() == SC_PrivateExtern)
769      LV.mergeVisibility(HiddenVisibilitytrue);
770
771    // Note that Sema::MergeVarDecl already takes care of implementing
772    // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
773    // to do it here.
774
775    // As per function and class template specializations (below),
776    // consider LV for the template and template arguments.  We're at file
777    // scope, so we do not need to worry about nested specializations.
778    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
779      mergeTemplateLV(LV, spec, computation);
780    }
781
782  //     - a function, unless it has internal linkage; or
783  } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
784    // In theory, we can modify the function's LV by the LV of its
785    // type unless it has C linkage (see comment above about variables
786    // for justification).  In practice, GCC doesn't do this, so it's
787    // just too painful to make work.
788
789    if (Function->getStorageClass() == SC_PrivateExtern)
790      LV.mergeVisibility(HiddenVisibilitytrue);
791
792    // Note that Sema::MergeCompatibleFunctionDecls already takes care of
793    // merging storage classes and visibility attributes, so we don't have to
794    // look at previous decls in here.
795
796    // In C++, then if the type of the function uses a type with
797    // unique-external linkage, it's not legally usable from outside
798    // this translation unit.  However, we should use the C linkage
799    // rules instead for extern "C" declarations.
800    if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
801      // Only look at the type-as-written. Otherwise, deducing the return type
802      // of a function could change its linkage.
803      QualType TypeAsWritten = Function->getType();
804      if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
805        TypeAsWritten = TSI->getType();
806      if (!isExternallyVisible(TypeAsWritten->getLinkage()))
807        return LinkageInfo::uniqueExternal();
808    }
809
810    // Consider LV from the template and the template arguments.
811    // We're at file scope, so we do not need to worry about nested
812    // specializations.
813    if (FunctionTemplateSpecializationInfo *specInfo
814                               = Function->getTemplateSpecializationInfo()) {
815      mergeTemplateLV(LV, Function, specInfo, computation);
816    }
817
818  //     - a named class (Clause 9), or an unnamed class defined in a
819  //       typedef declaration in which the class has the typedef name
820  //       for linkage purposes (7.1.3); or
821  //     - a named enumeration (7.2), or an unnamed enumeration
822  //       defined in a typedef declaration in which the enumeration
823  //       has the typedef name for linkage purposes (7.1.3); or
824  } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
825    // Unnamed tags have no linkage.
826    if (!Tag->hasNameForLinkage())
827      return LinkageInfo::none();
828
829    // If this is a class template specialization, consider the
830    // linkage of the template and template arguments.  We're at file
831    // scope, so we do not need to worry about nested specializations.
832    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
833      mergeTemplateLV(LV, spec, computation);
834    }
835
836  //     - an enumerator belonging to an enumeration with external linkage;
837  } else if (isa<EnumConstantDecl>(D)) {
838    LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
839                                      computation);
840    if (!isExternalFormalLinkage(EnumLV.getLinkage()))
841      return LinkageInfo::none();
842    LV.merge(EnumLV);
843
844  //     - a template, unless it is a function template that has
845  //       internal linkage (Clause 14);
846  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
847    bool considerVisibility = !hasExplicitVisibilityAlready(computation);
848    LinkageInfo tempLV =
849      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
850    LV.mergeMaybeWithVisibility(tempLVconsiderVisibility);
851
852  //     - a namespace (7.3), unless it is declared within an unnamed
853  //       namespace.
854  //
855  // We handled names in anonymous namespaces above.
856  } else if (isa<NamespaceDecl>(D)) {
857    return LV;
858
859  // By extension, we assign external linkage to Objective-C
860  // interfaces.
861  } else if (isa<ObjCInterfaceDecl>(D)) {
862    // fallout
863
864  } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
865    // A typedef declaration has linkage if it gives a type a name for
866    // linkage purposes.
867    if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
868      return LinkageInfo::none();
869
870  // Everything not covered here has no linkage.
871  } else {
872    return LinkageInfo::none();
873  }
874
875  // If we ended up with non-externally-visible linkage, visibility should
876  // always be default.
877  if (!isExternallyVisible(LV.getLinkage()))
878    return LinkageInfo(LV.getLinkage(), DefaultVisibilityfalse);
879
880  return LV;
881}
882
883LinkageInfo
884LinkageComputer::getLVForClassMember(const NamedDecl *D,
885                                     LVComputationKind computation,
886                                     bool IgnoreVarTypeLinkage) {
887  // Only certain class members have linkage.  Note that fields don't
888  // really have linkage, but it's convenient to say they do for the
889  // purposes of calculating linkage of pointer-to-data-member
890  // template arguments.
891  //
892  // Templates also don't officially have linkage, but since we ignore
893  // the C++ standard and look at template arguments when determining
894  // linkage and visibility of a template specialization, we might hit
895  // a template template argument that way. If we do, we need to
896  // consider its linkage.
897  if (!(isa<CXXMethodDecl>(D) ||
898        isa<VarDecl>(D) ||
899        isa<FieldDecl>(D) ||
900        isa<IndirectFieldDecl>(D) ||
901        isa<TagDecl>(D) ||
902        isa<TemplateDecl>(D)))
903    return LinkageInfo::none();
904
905  LinkageInfo LV;
906
907  // If we have an explicit visibility attribute, merge that in.
908  if (!hasExplicitVisibilityAlready(computation)) {
909    if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
910      LV.mergeVisibility(*Vis, true);
911    // If we're paying attention to global visibility, apply
912    // -finline-visibility-hidden if this is an inline method.
913    //
914    // Note that we do this before merging information about
915    // the class visibility.
916    if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
917      LV.mergeVisibility(HiddenVisibility/*visibilityExplicit=*/false);
918  }
919
920  // If this class member has an explicit visibility attribute, the only
921  // thing that can change its visibility is the template arguments, so
922  // only look for them when processing the class.
923  LVComputationKind classComputation = computation;
924  if (LV.isVisibilityExplicit())
925    classComputation = withExplicitVisibilityAlready(computation);
926
927  LinkageInfo classLV =
928    getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
929  // The member has the same linkage as the class. If that's not externally
930  // visible, we don't need to compute anything about the linkage.
931  // FIXME: If we're only computing linkage, can we bail out here?
932  if (!isExternallyVisible(classLV.getLinkage()))
933    return classLV;
934
935
936  // Otherwise, don't merge in classLV yet, because in certain cases
937  // we need to completely ignore the visibility from it.
938
939  // Specifically, if this decl exists and has an explicit attribute.
940  const NamedDecl *explicitSpecSuppressor = nullptr;
941
942  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
943    // Only look at the type-as-written. Otherwise, deducing the return type
944    // of a function could change its linkage.
945    QualType TypeAsWritten = MD->getType();
946    if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
947      TypeAsWritten = TSI->getType();
948    if (!isExternallyVisible(TypeAsWritten->getLinkage()))
949      return LinkageInfo::uniqueExternal();
950
951    // If this is a method template specialization, use the linkage for
952    // the template parameters and arguments.
953    if (FunctionTemplateSpecializationInfo *spec
954           = MD->getTemplateSpecializationInfo()) {
955      mergeTemplateLV(LV, MD, spec, computation);
956      if (spec->isExplicitSpecialization()) {
957        explicitSpecSuppressor = MD;
958      } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
959        explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
960      }
961    } else if (isExplicitMemberSpecialization(MD)) {
962      explicitSpecSuppressor = MD;
963    }
964
965  } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
966    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
967      mergeTemplateLV(LV, spec, computation);
968      if (spec->isExplicitSpecialization()) {
969        explicitSpecSuppressor = spec;
970      } else {
971        const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
972        if (isExplicitMemberSpecialization(temp)) {
973          explicitSpecSuppressor = temp->getTemplatedDecl();
974        }
975      }
976    } else if (isExplicitMemberSpecialization(RD)) {
977      explicitSpecSuppressor = RD;
978    }
979
980  // Static data members.
981  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
982    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
983      mergeTemplateLV(LV, spec, computation);
984
985    // Modify the variable's linkage by its type, but ignore the
986    // type's visibility unless it's a definition.
987    if (!IgnoreVarTypeLinkage) {
988      LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
989      // FIXME: If the type's linkage is not externally visible, we can
990      // give this static data member UniqueExternalLinkage.
991      if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
992        LV.mergeVisibility(typeLV);
993      LV.mergeExternalVisibility(typeLV);
994    }
995
996    if (isExplicitMemberSpecialization(VD)) {
997      explicitSpecSuppressor = VD;
998    }
999
1000  // Template members.
1001  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1002    bool considerVisibility =
1003      (!LV.isVisibilityExplicit() &&
1004       !classLV.isVisibilityExplicit() &&
1005       !hasExplicitVisibilityAlready(computation));
1006    LinkageInfo tempLV =
1007      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1008    LV.mergeMaybeWithVisibility(tempLVconsiderVisibility);
1009
1010    if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1011      if (isExplicitMemberSpecialization(redeclTemp)) {
1012        explicitSpecSuppressor = temp->getTemplatedDecl();
1013      }
1014    }
1015  }
1016
1017  // We should never be looking for an attribute directly on a template.
1018  (explicitSpecSuppressor)", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 1018, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1019
1020  // If this member is an explicit member specialization, and it has
1021  // an explicit attribute, ignore visibility from the parent.
1022  bool considerClassVisibility = true;
1023  if (explicitSpecSuppressor &&
1024      // optimization: hasDVA() is true only with explicit visibility.
1025      LV.isVisibilityExplicit() &&
1026      classLV.getVisibility() != DefaultVisibility &&
1027      hasDirectVisibilityAttribute(explicitSpecSuppressorcomputation)) {
1028    considerClassVisibility = false;
1029  }
1030
1031  // Finally, merge in information from the class.
1032  LV.mergeMaybeWithVisibility(classLVconsiderClassVisibility);
1033  return LV;
1034}
1035
1036void NamedDecl::anchor() {}
1037
1038bool NamedDecl::isLinkageValid() const {
1039  if (!hasCachedLinkage())
1040    return true;
1041
1042  Linkage L = LinkageComputer{}
1043                  .computeLVForDecl(thisLVComputationKind::forLinkageOnly())
1044                  .getLinkage();
1045  return L == getCachedLinkage();
1046}
1047
1048ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1049  StringRef name = getName();
1050  if (name.empty()) return SFF_None;
1051
1052  if (name.front() == 'C')
1053    if (name == "CFStringCreateWithFormat" ||
1054        name == "CFStringCreateWithFormatAndArguments" ||
1055        name == "CFStringAppendFormat" ||
1056        name == "CFStringAppendFormatAndArguments")
1057      return SFF_CFString;
1058  return SFF_None;
1059}
1060
1061Linkage NamedDecl::getLinkageInternal() const {
1062  // We don't care about visibility here, so ask for the cheapest
1063  // possible visibility analysis.
1064  return LinkageComputer{}
1065      .getLVForDecl(thisLVComputationKind::forLinkageOnly())
1066      .getLinkage();
1067}
1068
1069LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1070  return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1071}
1072
1073static Optional<Visibility>
1074getExplicitVisibilityAux(const NamedDecl *ND,
1075                         NamedDecl::ExplicitVisibilityKind kind,
1076                         bool IsMostRecent) {
1077  getMostRecentDecl()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 1077, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1078
1079  // Check the declaration itself first.
1080  if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1081    return V;
1082
1083  // If this is a member class of a specialization of a class template
1084  // and the corresponding decl has explicit visibility, use that.
1085  if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1086    CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1087    if (InstantiatedFrom)
1088      return getVisibilityOf(InstantiatedFrom, kind);
1089  }
1090
1091  // If there wasn't explicit visibility there, and this is a
1092  // specialization of a class template, check for visibility
1093  // on the pattern.
1094  if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1095    // Walk all the template decl till this point to see if there are
1096    // explicit visibility attributes.
1097    const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1098    while (TD != nullptr) {
1099      auto Vis = getVisibilityOf(TD, kind);
1100      if (Vis != None)
1101        return Vis;
1102      TD = TD->getPreviousDecl();
1103    }
1104    return None;
1105  }
1106
1107  // Use the most recent declaration.
1108  if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1109    const NamedDecl *MostRecent = ND->getMostRecentDecl();
1110    if (MostRecent != ND)
1111      return getExplicitVisibilityAux(MostRecent, kind, true);
1112  }
1113
1114  if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1115    if (Var->isStaticDataMember()) {
1116      VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1117      if (InstantiatedFrom)
1118        return getVisibilityOf(InstantiatedFrom, kind);
1119    }
1120
1121    if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1122      return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1123                             kind);
1124
1125    return None;
1126  }
1127  // Also handle function template specializations.
1128  if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1129    // If the function is a specialization of a template with an
1130    // explicit visibility attribute, use that.
1131    if (FunctionTemplateSpecializationInfo *templateInfo
1132          = fn->getTemplateSpecializationInfo())
1133      return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1134                             kind);
1135
1136    // If the function is a member of a specialization of a class template
1137    // and the corresponding decl has explicit visibility, use that.
1138    FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1139    if (InstantiatedFrom)
1140      return getVisibilityOf(InstantiatedFrom, kind);
1141
1142    return None;
1143  }
1144
1145  // The visibility of a template is stored in the templated decl.
1146  if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1147    return getVisibilityOf(TD->getTemplatedDecl(), kind);
1148
1149  return None;
1150}
1151
1152Optional<Visibility>
1153NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kindconst {
1154  return getExplicitVisibilityAux(this, kind, false);
1155}
1156
1157LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1158                                             Decl *ContextDecl,
1159                                             LVComputationKind computation) {
1160  // This lambda has its linkage/visibility determined by its owner.
1161  const NamedDecl *Owner;
1162  if (!ContextDecl)
1163    Owner = dyn_cast<NamedDecl>(DC);
1164  else if (isa<ParmVarDecl>(ContextDecl))
1165    Owner =
1166        dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1167  else
1168    Owner = cast<NamedDecl>(ContextDecl);
1169
1170  if (!Owner)
1171    return LinkageInfo::none();
1172
1173  // If the owner has a deduced type, we need to skip querying the linkage and
1174  // visibility of that type, because it might involve this closure type.  The
1175  // only effect of this is that we might give a lambda VisibleNoLinkage rather
1176  // than NoLinkage when we don't strictly need to, which is benign.
1177  auto *VD = dyn_cast<VarDecl>(Owner);
1178  LinkageInfo OwnerLV =
1179      VD && VD->getType()->getContainedDeducedType()
1180          ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1181          : getLVForDecl(Owner, computation);
1182
1183  // A lambda never formally has linkage. But if the owner is externally
1184  // visible, then the lambda is too. We apply the same rules to blocks.
1185  if (!isExternallyVisible(OwnerLV.getLinkage()))
1186    return LinkageInfo::none();
1187  return LinkageInfo(VisibleNoLinkageOwnerLV.getVisibility(),
1188                     OwnerLV.isVisibilityExplicit());
1189}
1190
1191LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1192                                               LVComputationKind computation) {
1193  if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1194    if (Function->isInAnonymousNamespace() &&
1195        !isFirstInExternCContext(Function))
1196      return getInternalLinkageFor(Function);
1197
1198    // This is a "void f();" which got merged with a file static.
1199    if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1200      return getInternalLinkageFor(Function);
1201
1202    LinkageInfo LV;
1203    if (!hasExplicitVisibilityAlready(computation)) {
1204      if (Optional<Visibility> Vis =
1205              getExplicitVisibility(Function, computation))
1206        LV.mergeVisibility(*Vis, true);
1207    }
1208
1209    // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1210    // merging storage classes and visibility attributes, so we don't have to
1211    // look at previous decls in here.
1212
1213    return LV;
1214  }
1215
1216  if (const auto *Var = dyn_cast<VarDecl>(D)) {
1217    if (Var->hasExternalStorage()) {
1218      if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1219        return getInternalLinkageFor(Var);
1220
1221      LinkageInfo LV;
1222      if (Var->getStorageClass() == SC_PrivateExtern)
1223        LV.mergeVisibility(HiddenVisibilitytrue);
1224      else if (!hasExplicitVisibilityAlready(computation)) {
1225        if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1226          LV.mergeVisibility(*Vis, true);
1227      }
1228
1229      if (const VarDecl *Prev = Var->getPreviousDecl()) {
1230        LinkageInfo PrevLV = getLVForDecl(Prevcomputation);
1231        if (PrevLV.getLinkage())
1232          LV.setLinkage(PrevLV.getLinkage());
1233        LV.mergeVisibility(PrevLV);
1234      }
1235
1236      return LV;
1237    }
1238
1239    if (!Var->isStaticLocal())
1240      return LinkageInfo::none();
1241  }
1242
1243  ASTContext &Context = D->getASTContext();
1244  if (!Context.getLangOpts().CPlusPlus)
1245    return LinkageInfo::none();
1246
1247  const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1248  if (!OuterD || OuterD->isInvalidDecl())
1249    return LinkageInfo::none();
1250
1251  LinkageInfo LV;
1252  if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1253    if (!BD->getBlockManglingNumber())
1254      return LinkageInfo::none();
1255
1256    LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1257                         BD->getBlockManglingContextDecl(), computation);
1258  } else {
1259    const auto *FD = cast<FunctionDecl>(OuterD);
1260    if (!FD->isInlined() &&
1261        !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1262      return LinkageInfo::none();
1263
1264    // If a function is hidden by -fvisibility-inlines-hidden option and
1265    // is not explicitly attributed as a hidden function,
1266    // we should not make static local variables in the function hidden.
1267    LV = getLVForDecl(FD, computation);
1268    if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1269        !LV.isVisibilityExplicit()) {
1270      (D)->isStaticLocal()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 1270, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(cast<VarDecl>(D)->isStaticLocal());
1271      // If this was an implicitly hidden inline method, check again for
1272      // explicit visibility on the parent class, and use that for static locals
1273      // if present.
1274      if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1275        LV = getLVForDecl(MD->getParent(), computation);
1276      if (!LV.isVisibilityExplicit()) {
1277        Visibility globalVisibility =
1278            computation.isValueVisibility()
1279                ? Context.getLangOpts().getValueVisibilityMode()
1280                : Context.getLangOpts().getTypeVisibilityMode();
1281        return LinkageInfo(VisibleNoLinkageglobalVisibility,
1282                           /*visibilityExplicit=*/false);
1283      }
1284    }
1285  }
1286  if (!isExternallyVisible(LV.getLinkage()))
1287    return LinkageInfo::none();
1288  return LinkageInfo(VisibleNoLinkageLV.getVisibility(),
1289                     LV.isVisibilityExplicit());
1290}
1291
1292static inline const CXXRecordDecl*
1293getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1294  const CXXRecordDecl *Ret = Record;
1295  while (Record && Record->isLambda()) {
1296    Ret = Record;
1297    if (!Record->getParent()) break;
1298    // Get the Containing Class of this Lambda Class
1299    Record = dyn_cast_or_null<CXXRecordDecl>(
1300      Record->getParent()->getParent());
1301  }
1302  return Ret;
1303}
1304
1305LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1306                                              LVComputationKind computation,
1307                                              bool IgnoreVarTypeLinkage) {
1308  // Internal_linkage attribute overrides other considerations.
1309  if (D->hasAttr<InternalLinkageAttr>())
1310    return getInternalLinkageFor(D);
1311
1312  // Objective-C: treat all Objective-C declarations as having external
1313  // linkage.
1314  switch (D->getKind()) {
1315    default:
1316      break;
1317
1318    // Per C++ [basic.link]p2, only the names of objects, references,
1319    // functions, types, templates, namespaces, and values ever have linkage.
1320    //
1321    // Note that the name of a typedef, namespace alias, using declaration,
1322    // and so on are not the name of the corresponding type, namespace, or
1323    // declaration, so they do *not* have linkage.
1324    case Decl::ImplicitParam:
1325    case Decl::Label:
1326    case Decl::NamespaceAlias:
1327    case Decl::ParmVar:
1328    case Decl::Using:
1329    case Decl::UsingShadow:
1330    case Decl::UsingDirective:
1331      return LinkageInfo::none();
1332
1333    case Decl::EnumConstant:
1334      // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1335      if (D->getASTContext().getLangOpts().CPlusPlus)
1336        return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1337      return LinkageInfo::visible_none();
1338
1339    case Decl::Typedef:
1340    case Decl::TypeAlias:
1341      // A typedef declaration has linkage if it gives a type a name for
1342      // linkage purposes.
1343      if (!cast<TypedefNameDecl>(D)
1344               ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1345        return LinkageInfo::none();
1346      break;
1347
1348    case Decl::TemplateTemplateParm: // count these as external
1349    case Decl::NonTypeTemplateParm:
1350    case Decl::ObjCAtDefsField:
1351    case Decl::ObjCCategory:
1352    case Decl::ObjCCategoryImpl:
1353    case Decl::ObjCCompatibleAlias:
1354    case Decl::ObjCImplementation:
1355    case Decl::ObjCMethod:
1356    case Decl::ObjCProperty:
1357    case Decl::ObjCPropertyImpl:
1358    case Decl::ObjCProtocol:
1359      return getExternalLinkageFor(D);
1360
1361    case Decl::CXXRecord: {
1362      const auto *Record = cast<CXXRecordDecl>(D);
1363      if (Record->isLambda()) {
1364        if (!Record->getLambdaManglingNumber()) {
1365          // This lambda has no mangling number, so it's internal.
1366          return getInternalLinkageFor(D);
1367        }
1368
1369        // This lambda has its linkage/visibility determined:
1370        //  - either by the outermost lambda if that lambda has no mangling
1371        //    number.
1372        //  - or by the parent of the outer most lambda
1373        // This prevents infinite recursion in settings such as nested lambdas
1374        // used in NSDMI's, for e.g.
1375        //  struct L {
1376        //    int t{};
1377        //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1378        //  };
1379        const CXXRecordDecl *OuterMostLambda =
1380            getOutermostEnclosingLambda(Record);
1381        if (!OuterMostLambda->getLambdaManglingNumber())
1382          return getInternalLinkageFor(D);
1383
1384        return getLVForClosure(
1385                  OuterMostLambda->getDeclContext()->getRedeclContext(),
1386                  OuterMostLambda->getLambdaContextDecl(), computation);
1387      }
1388
1389      break;
1390    }
1391  }
1392
1393  // Handle linkage for namespace-scope names.
1394  if (D->getDeclContext()->getRedeclContext()->isFileContext())
1395    return getLVForNamespaceScopeDecl(DcomputationIgnoreVarTypeLinkage);
1396
1397  // C++ [basic.link]p5:
1398  //   In addition, a member function, static data member, a named
1399  //   class or enumeration of class scope, or an unnamed class or
1400  //   enumeration defined in a class-scope typedef declaration such
1401  //   that the class or enumeration has the typedef name for linkage
1402  //   purposes (7.1.3), has external linkage if the name of the class
1403  //   has external linkage.
1404  if (D->getDeclContext()->isRecord())
1405    return getLVForClassMember(DcomputationIgnoreVarTypeLinkage);
1406
1407  // C++ [basic.link]p6:
1408  //   The name of a function declared in block scope and the name of
1409  //   an object declared by a block scope extern declaration have
1410  //   linkage. If there is a visible declaration of an entity with
1411  //   linkage having the same name and type, ignoring entities
1412  //   declared outside the innermost enclosing namespace scope, the
1413  //   block scope declaration declares that same entity and receives
1414  //   the linkage of the previous declaration. If there is more than
1415  //   one such matching entity, the program is ill-formed. Otherwise,
1416  //   if no matching entity is found, the block scope entity receives
1417  //   external linkage.
1418  if (D->getDeclContext()->isFunctionOrMethod())
1419    return getLVForLocalDecl(Dcomputation);
1420
1421  // C++ [basic.link]p6:
1422  //   Names not covered by these rules have no linkage.
1423  return LinkageInfo::none();
1424}
1425
1426/// getLVForDecl - Get the linkage and visibility for the given declaration.
1427LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1428                                          LVComputationKind computation) {
1429  // Internal_linkage attribute overrides other considerations.
1430  if (D->hasAttr<InternalLinkageAttr>())
1431    return getInternalLinkageFor(D);
1432
1433  if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1434    return LinkageInfo(D->getCachedLinkage(), DefaultVisibilityfalse);
1435
1436  if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1437    return *LI;
1438
1439  LinkageInfo LV = computeLVForDecl(Dcomputation);
1440  if (D->hasCachedLinkage())
1441    getCachedLinkage() == LV.getLinkage()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 1441, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(D->getCachedLinkage() == LV.getLinkage());
1442
1443  D->setCachedLinkage(LV.getLinkage());
1444  cache(DcomputationLV);
1445
1446#ifndef NDEBUG
1447  // In C (because of gnu inline) and in c++ with microsoft extensions an
1448  // static can follow an extern, so we can have two decls with different
1449  // linkages.
1450  const LangOptions &Opts = D->getASTContext().getLangOpts();
1451  if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1452    return LV;
1453
1454  // We have just computed the linkage for this decl. By induction we know
1455  // that all other computed linkages match, check that the one we just
1456  // computed also does.
1457  NamedDecl *Old = nullptr;
1458  for (auto I : D->redecls()) {
1459    auto *T = cast<NamedDecl>(I);
1460    if (T == D)
1461      continue;
1462    if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1463      Old = T;
1464      break;
1465    }
1466  }
1467  getCachedLinkage() == D->getCachedLinkage()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 1467, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1468#endif
1469
1470  return LV;
1471}
1472
1473LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1474  return getLVForDecl(D,
1475                      LVComputationKind(usesTypeVisibility(D)
1476                                            ? NamedDecl::VisibilityForType
1477                                            : NamedDecl::VisibilityForValue));
1478}
1479
1480Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkageconst {
1481  Module *M = getOwningModule();
1482  if (!M)
1483    return nullptr;
1484
1485  switch (M->Kind) {
1486  case Module::ModuleMapModule:
1487    // Module map modules have no special linkage semantics.
1488    return nullptr;
1489
1490  case Module::ModuleInterfaceUnit:
1491    return M;
1492
1493  case Module::GlobalModuleFragment: {
1494    // External linkage declarations in the global module have no owning module
1495    // for linkage purposes. But internal linkage declarations in the global
1496    // module fragment of a particular module are owned by that module for
1497    // linkage purposes.
1498    if (IgnoreLinkage)
1499      return nullptr;
1500    bool InternalLinkage;
1501    if (auto *ND = dyn_cast<NamedDecl>(this))
1502      InternalLinkage = !ND->hasExternalFormalLinkage();
1503    else {
1504      auto *NSD = dyn_cast<NamespaceDecl>(this);
1505      InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1506                        isInAnonymousNamespace();
1507    }
1508    return InternalLinkage ? M->Parent : nullptr;
1509  }
1510  }
1511
1512  llvm_unreachable("unknown module kind");
1513}
1514
1515void NamedDecl::printName(raw_ostream &osconst {
1516  os << Name;
1517}
1518
1519std::string NamedDecl::getQualifiedNameAsString() const {
1520  std::string QualName;
1521  llvm::raw_string_ostream OS(QualName);
1522  printQualifiedName(OS, getASTContext().getPrintingPolicy());
1523  return OS.str();
1524}
1525
1526void NamedDecl::printQualifiedName(raw_ostream &OSconst {
1527  printQualifiedName(OSgetASTContext().getPrintingPolicy());
1528}
1529
1530void NamedDecl::printQualifiedName(raw_ostream &OS,
1531                                   const PrintingPolicy &Pconst {
1532  const DeclContext *Ctx = getDeclContext();
1533
1534  // For ObjC methods, look through categories and use the interface as context.
1535  if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1536    if (auto *ID = MD->getClassInterface())
1537      Ctx = ID;
1538
1539  if (Ctx->isFunctionOrMethod()) {
1540    printName(OS);
1541    return;
1542  }
1543
1544  using ContextsTy = SmallVector<const DeclContext *, 8>;
1545  ContextsTy Contexts;
1546
1547  // Collect named contexts.
1548  while (Ctx) {
1549    if (isa<NamedDecl>(Ctx))
1550      Contexts.push_back(Ctx);
1551    Ctx = Ctx->getParent();
1552  }
1553
1554  for (const DeclContext *DC : llvm::reverse(Contexts)) {
1555    if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1556      OS << Spec->getName();
1557      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1558      printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
1559    } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1560      if (P.SuppressUnwrittenScope &&
1561          (ND->isAnonymousNamespace() || ND->isInline()))
1562        continue;
1563      if (ND->isAnonymousNamespace()) {
1564        OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1565                                : "(anonymous namespace)");
1566      }
1567      else
1568        OS << *ND;
1569    } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1570      if (!RD->getIdentifier())
1571        OS << "(anonymous " << RD->getKindName() << ')';
1572      else
1573        OS << *RD;
1574    } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1575      const FunctionProtoType *FT = nullptr;
1576      if (FD->hasWrittenPrototype())
1577        FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1578
1579      OS << *FD << '(';
1580      if (FT) {
1581        unsigned NumParams = FD->getNumParams();
1582        for (unsigned i = 0; i < NumParams; ++i) {
1583          if (i)
1584            OS << ", ";
1585          OS << FD->getParamDecl(i)->getType().stream(P);
1586        }
1587
1588        if (FT->isVariadic()) {
1589          if (NumParams > 0)
1590            OS << ", ";
1591          OS << "...";
1592        }
1593      }
1594      OS << ')';
1595    } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1596      // C++ [dcl.enum]p10: Each enum-name and each unscoped
1597      // enumerator is declared in the scope that immediately contains
1598      // the enum-specifier. Each scoped enumerator is declared in the
1599      // scope of the enumeration.
1600      // For the case of unscoped enumerator, do not include in the qualified
1601      // name any information about its enum enclosing scope, as its visibility
1602      // is global.
1603      if (ED->isScoped())
1604        OS << *ED;
1605      else
1606        continue;
1607    } else {
1608      OS << *cast<NamedDecl>(DC);
1609    }
1610    OS << "::";
1611  }
1612
1613  if (getDeclName() || isa<DecompositionDecl>(this))
1614    OS << *this;
1615  else
1616    OS << "(anonymous)";
1617}
1618
1619void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1620                                     const PrintingPolicy &Policy,
1621                                     bool Qualifiedconst {
1622  if (Qualified)
1623    printQualifiedName(OSPolicy);
1624  else
1625    printName(OS);
1626}
1627
1628template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1629  return true;
1630}
1631static bool isRedeclarableImpl(...) { return false; }
1632static bool isRedeclarable(Decl::Kind K) {
1633  switch (K) {
1634#define DECL(Type, Base) \
1635  case Decl::Type: \
1636    return isRedeclarableImpl((Type##Decl *)nullptr);
1637#define ABSTRACT_DECL(DECL)
1638#include "clang/AST/DeclNodes.inc"
1639  }
1640  llvm_unreachable("unknown decl kind");
1641}
1642
1643bool NamedDecl::declarationReplaces(NamedDecl *OldDbool IsKnownNewerconst {
1644   (0) . __assert_fail ("getDeclName() == OldD->getDeclName() && \"Declaration name mismatch\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 1644, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1645
1646  // Never replace one imported declaration with another; we need both results
1647  // when re-exporting.
1648  if (OldD->isFromASTFile() && isFromASTFile())
1649    return false;
1650
1651  // A kind mismatch implies that the declaration is not replaced.
1652  if (OldD->getKind() != getKind())
1653    return false;
1654
1655  // For method declarations, we never replace. (Why?)
1656  if (isa<ObjCMethodDecl>(this))
1657    return false;
1658
1659  // For parameters, pick the newer one. This is either an error or (in
1660  // Objective-C) permitted as an extension.
1661  if (isa<ParmVarDecl>(this))
1662    return true;
1663
1664  // Inline namespaces can give us two declarations with the same
1665  // name and kind in the same scope but different contexts; we should
1666  // keep both declarations in this case.
1667  if (!this->getDeclContext()->getRedeclContext()->Equals(
1668          OldD->getDeclContext()->getRedeclContext()))
1669    return false;
1670
1671  // Using declarations can be replaced if they import the same name from the
1672  // same context.
1673  if (auto *UD = dyn_cast<UsingDecl>(this)) {
1674    ASTContext &Context = getASTContext();
1675    return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1676           Context.getCanonicalNestedNameSpecifier(
1677               cast<UsingDecl>(OldD)->getQualifier());
1678  }
1679  if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1680    ASTContext &Context = getASTContext();
1681    return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1682           Context.getCanonicalNestedNameSpecifier(
1683                        cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1684  }
1685
1686  if (isRedeclarable(getKind())) {
1687    if (getCanonicalDecl() != OldD->getCanonicalDecl())
1688      return false;
1689
1690    if (IsKnownNewer)
1691      return true;
1692
1693    // Check whether this is actually newer than OldD. We want to keep the
1694    // newer declaration. This loop will usually only iterate once, because
1695    // OldD is usually the previous declaration.
1696    for (auto D : redecls()) {
1697      if (D == OldD)
1698        break;
1699
1700      // If we reach the canonical declaration, then OldD is not actually older
1701      // than this one.
1702      //
1703      // FIXME: In this case, we should not add this decl to the lookup table.
1704      if (D->isCanonicalDecl())
1705        return false;
1706    }
1707
1708    // It's a newer declaration of the same kind of declaration in the same
1709    // scope: we want this decl instead of the existing one.
1710    return true;
1711  }
1712
1713  // In all other cases, we need to keep both declarations in case they have
1714  // different visibility. Any attempt to use the name will result in an
1715  // ambiguity if more than one is visible.
1716  return false;
1717}
1718
1719bool NamedDecl::hasLinkage() const {
1720  return getFormalLinkage() != NoLinkage;
1721}
1722
1723NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1724  NamedDecl *ND = this;
1725  while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1726    ND = UD->getTargetDecl();
1727
1728  if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1729    return AD->getClassInterface();
1730
1731  if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1732    return AD->getNamespace();
1733
1734  return ND;
1735}
1736
1737bool NamedDecl::isCXXInstanceMember() const {
1738  if (!isCXXClassMember())
1739    return false;
1740
1741  const NamedDecl *D = this;
1742  if (isa<UsingShadowDecl>(D))
1743    D = cast<UsingShadowDecl>(D)->getTargetDecl();
1744
1745  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1746    return true;
1747  if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1748    return MD->isInstance();
1749  return false;
1750}
1751
1752//===----------------------------------------------------------------------===//
1753// DeclaratorDecl Implementation
1754//===----------------------------------------------------------------------===//
1755
1756template <typename DeclT>
1757static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1758  if (decl->getNumTemplateParameterLists() > 0)
1759    return decl->getTemplateParameterList(0)->getTemplateLoc();
1760  else
1761    return decl->getInnerLocStart();
1762}
1763
1764SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1765  TypeSourceInfo *TSI = getTypeSourceInfo();
1766  if (TSIreturn TSI->getTypeLoc().getBeginLoc();
1767  return SourceLocation();
1768}
1769
1770void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1771  if (QualifierLoc) {
1772    // Make sure the extended decl info is allocated.
1773    if (!hasExtInfo()) {
1774      // Save (non-extended) type source info pointer.
1775      auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1776      // Allocate external info struct.
1777      DeclInfo = new (getASTContext()) ExtInfo;
1778      // Restore savedTInfo into (extended) decl info.
1779      getExtInfo()->TInfo = savedTInfo;
1780    }
1781    // Set qualifier info.
1782    getExtInfo()->QualifierLoc = QualifierLoc;
1783  } else {
1784    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1785    if (hasExtInfo()) {
1786      if (getExtInfo()->NumTemplParamLists == 0) {
1787        // Save type source info pointer.
1788        TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1789        // Deallocate the extended decl info.
1790        getASTContext().Deallocate(getExtInfo());
1791        // Restore savedTInfo into (non-extended) decl info.
1792        DeclInfo = savedTInfo;
1793      }
1794      else
1795        getExtInfo()->QualifierLoc = QualifierLoc;
1796    }
1797  }
1798}
1799
1800void DeclaratorDecl::setTemplateParameterListsInfo(
1801    ASTContext &ContextArrayRef<TemplateParameterList *> TPLists) {
1802  assert(!TPLists.empty());
1803  // Make sure the extended decl info is allocated.
1804  if (!hasExtInfo()) {
1805    // Save (non-extended) type source info pointer.
1806    auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1807    // Allocate external info struct.
1808    DeclInfo = new (getASTContext()) ExtInfo;
1809    // Restore savedTInfo into (extended) decl info.
1810    getExtInfo()->TInfo = savedTInfo;
1811  }
1812  // Set the template parameter lists info.
1813  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1814}
1815
1816SourceLocation DeclaratorDecl::getOuterLocStart() const {
1817  return getTemplateOrInnerLocStart(this);
1818}
1819
1820// Helper function: returns true if QT is or contains a type
1821// having a postfix component.
1822static bool typeIsPostfix(QualType QT) {
1823  while (true) {
1824    const TypeT = QT.getTypePtr();
1825    switch (T->getTypeClass()) {
1826    default:
1827      return false;
1828    case Type::Pointer:
1829      QT = cast<PointerType>(T)->getPointeeType();
1830      break;
1831    case Type::BlockPointer:
1832      QT = cast<BlockPointerType>(T)->getPointeeType();
1833      break;
1834    case Type::MemberPointer:
1835      QT = cast<MemberPointerType>(T)->getPointeeType();
1836      break;
1837    case Type::LValueReference:
1838    case Type::RValueReference:
1839      QT = cast<ReferenceType>(T)->getPointeeType();
1840      break;
1841    case Type::PackExpansion:
1842      QT = cast<PackExpansionType>(T)->getPattern();
1843      break;
1844    case Type::Paren:
1845    case Type::ConstantArray:
1846    case Type::DependentSizedArray:
1847    case Type::IncompleteArray:
1848    case Type::VariableArray:
1849    case Type::FunctionProto:
1850    case Type::FunctionNoProto:
1851      return true;
1852    }
1853  }
1854}
1855
1856SourceRange DeclaratorDecl::getSourceRange() const {
1857  SourceLocation RangeEnd = getLocation();
1858  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1859    // If the declaration has no name or the type extends past the name take the
1860    // end location of the type.
1861    if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1862      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1863  }
1864  return SourceRange(getOuterLocStart(), RangeEnd);
1865}
1866
1867void QualifierInfo::setTemplateParameterListsInfo(
1868    ASTContext &ContextArrayRef<TemplateParameterList *> TPLists) {
1869  // Free previous template parameters (if any).
1870  if (NumTemplParamLists > 0) {
1871    Context.Deallocate(TemplParamLists);
1872    TemplParamLists = nullptr;
1873    NumTemplParamLists = 0;
1874  }
1875  // Set info on matched template parameter lists (if any).
1876  if (!TPLists.empty()) {
1877    TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1878    NumTemplParamLists = TPLists.size();
1879    std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1880  }
1881}
1882
1883//===----------------------------------------------------------------------===//
1884// VarDecl Implementation
1885//===----------------------------------------------------------------------===//
1886
1887const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1888  switch (SC) {
1889  case SC_None:                 break;
1890  case SC_Auto:                 return "auto";
1891  case SC_Extern:               return "extern";
1892  case SC_PrivateExtern:        return "__private_extern__";
1893  case SC_Register:             return "register";
1894  case SC_Static:               return "static";
1895  }
1896
1897  llvm_unreachable("Invalid storage class");
1898}
1899
1900VarDecl::VarDecl(Kind DKASTContext &CDeclContext *DC,
1901                 SourceLocation StartLocSourceLocation IdLoc,
1902                 IdentifierInfo *IdQualType TTypeSourceInfo *TInfo,
1903                 StorageClass SC)
1904    : DeclaratorDecl(DKDCIdLocIdTTInfoStartLoc),
1905      redeclarable_base(C) {
1906  static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1907                "VarDeclBitfields too large!");
1908  static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1909                "ParmVarDeclBitfields too large!");
1910  static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1911                "NonParmVarDeclBitfields too large!");
1912  AllBits = 0;
1913  VarDeclBits.SClass = SC;
1914  // Everything else is implicitly initialized to false.
1915}
1916
1917VarDecl *VarDecl::Create(ASTContext &CDeclContext *DC,
1918                         SourceLocation StartLSourceLocation IdL,
1919                         IdentifierInfo *IdQualType TTypeSourceInfo *TInfo,
1920                         StorageClass S) {
1921  return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1922}
1923
1924VarDecl *VarDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
1925  return new (C, ID)
1926      VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1927              QualType(), nullptr, SC_None);
1928}
1929
1930void VarDecl::setStorageClass(StorageClass SC) {
1931  assert(isLegalForVariable(SC));
1932  VarDeclBits.SClass = SC;
1933}
1934
1935VarDecl::TLSKind VarDecl::getTLSKind() const {
1936  switch (VarDeclBits.TSCSpec) {
1937  case TSCS_unspecified:
1938    if (!hasAttr<ThreadAttr>() &&
1939        !(getASTContext().getLangOpts().OpenMPUseTLS &&
1940          getASTContext().getTargetInfo().isTLSSupported() &&
1941          hasAttr<OMPThreadPrivateDeclAttr>()))
1942      return TLS_None;
1943    return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1944                LangOptions::MSVC2015)) ||
1945            hasAttr<OMPThreadPrivateDeclAttr>())
1946               ? TLS_Dynamic
1947               : TLS_Static;
1948  case TSCS___thread// Fall through.
1949  case TSCS__Thread_local:
1950    return TLS_Static;
1951  case TSCS_thread_local:
1952    return TLS_Dynamic;
1953  }
1954  llvm_unreachable("Unknown thread storage class specifier!");
1955}
1956
1957SourceRange VarDecl::getSourceRange() const {
1958  if (const Expr *Init = getInit()) {
1959    SourceLocation InitEnd = Init->getEndLoc();
1960    // If Init is implicit, ignore its source range and fallback on
1961    // DeclaratorDecl::getSourceRange() to handle postfix elements.
1962    if (InitEnd.isValid() && InitEnd != getLocation())
1963      return SourceRange(getOuterLocStart(), InitEnd);
1964  }
1965  return DeclaratorDecl::getSourceRange();
1966}
1967
1968template<typename T>
1969static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1970  // C++ [dcl.link]p1: All function types, function names with external linkage,
1971  // and variable names with external linkage have a language linkage.
1972  if (!D.hasExternalFormalLinkage())
1973    return NoLanguageLinkage;
1974
1975  // Language linkage is a C++ concept, but saying that everything else in C has
1976  // C language linkage fits the implementation nicely.
1977  ASTContext &Context = D.getASTContext();
1978  if (!Context.getLangOpts().CPlusPlus)
1979    return CLanguageLinkage;
1980
1981  // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1982  // language linkage of the names of class members and the function type of
1983  // class member functions.
1984  const DeclContext *DC = D.getDeclContext();
1985  if (DC->isRecord())
1986    return CXXLanguageLinkage;
1987
1988  // If the first decl is in an extern "C" context, any other redeclaration
1989  // will have C language linkage. If the first one is not in an extern "C"
1990  // context, we would have reported an error for any other decl being in one.
1991  if (isFirstInExternCContext(&D))
1992    return CLanguageLinkage;
1993  return CXXLanguageLinkage;
1994}
1995
1996template<typename T>
1997static bool isDeclExternC(const T &D) {
1998  // Since the context is ignored for class members, they can only have C++
1999  // language linkage or no language linkage.
2000  const DeclContext *DC = D.getDeclContext();
2001  if (DC->isRecord()) {
2002    assert(D.getASTContext().getLangOpts().CPlusPlus);
2003    return false;
2004  }
2005
2006  return D.getLanguageLinkage() == CLanguageLinkage;
2007}
2008
2009LanguageLinkage VarDecl::getLanguageLinkage() const {
2010  return getDeclLanguageLinkage(*this);
2011}
2012
2013bool VarDecl::isExternC() const {
2014  return isDeclExternC(*this);
2015}
2016
2017bool VarDecl::isInExternCContext() const {
2018  return getLexicalDeclContext()->isExternCContext();
2019}
2020
2021bool VarDecl::isInExternCXXContext() const {
2022  return getLexicalDeclContext()->isExternCXXContext();
2023}
2024
2025VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2026
2027VarDecl::DefinitionKind
2028VarDecl::isThisDeclarationADefinition(ASTContext &Cconst {
2029  if (isThisDeclarationADemotedDefinition())
2030    return DeclarationOnly;
2031
2032  // C++ [basic.def]p2:
2033  //   A declaration is a definition unless [...] it contains the 'extern'
2034  //   specifier or a linkage-specification and neither an initializer [...],
2035  //   it declares a non-inline static data member in a class declaration [...],
2036  //   it declares a static data member outside a class definition and the variable
2037  //   was defined within the class with the constexpr specifier [...],
2038  // C++1y [temp.expl.spec]p15:
2039  //   An explicit specialization of a static data member or an explicit
2040  //   specialization of a static data member template is a definition if the
2041  //   declaration includes an initializer; otherwise, it is a declaration.
2042  //
2043  // FIXME: How do you declare (but not define) a partial specialization of
2044  // a static data member template outside the containing class?
2045  if (isStaticDataMember()) {
2046    if (isOutOfLine() &&
2047        !(getCanonicalDecl()->isInline() &&
2048          getCanonicalDecl()->isConstexpr()) &&
2049        (hasInit() ||
2050         // If the first declaration is out-of-line, this may be an
2051         // instantiation of an out-of-line partial specialization of a variable
2052         // template for which we have not yet instantiated the initializer.
2053         (getFirstDecl()->isOutOfLine()
2054              ? getTemplateSpecializationKind() == TSK_Undeclared
2055              : getTemplateSpecializationKind() !=
2056                    TSK_ExplicitSpecialization) ||
2057         isa<VarTemplatePartialSpecializationDecl>(this)))
2058      return Definition;
2059    else if (!isOutOfLine() && isInline())
2060      return Definition;
2061    else
2062      return DeclarationOnly;
2063  }
2064  // C99 6.7p5:
2065  //   A definition of an identifier is a declaration for that identifier that
2066  //   [...] causes storage to be reserved for that object.
2067  // Note: that applies for all non-file-scope objects.
2068  // C99 6.9.2p1:
2069  //   If the declaration of an identifier for an object has file scope and an
2070  //   initializer, the declaration is an external definition for the identifier
2071  if (hasInit())
2072    return Definition;
2073
2074  if (hasDefiningAttr())
2075    return Definition;
2076
2077  if (const auto *SAA = getAttr<SelectAnyAttr>())
2078    if (!SAA->isInherited())
2079      return Definition;
2080
2081  // A variable template specialization (other than a static data member
2082  // template or an explicit specialization) is a declaration until we
2083  // instantiate its initializer.
2084  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2085    if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2086        !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2087        !VTSD->IsCompleteDefinition)
2088      return DeclarationOnly;
2089  }
2090
2091  if (hasExternalStorage())
2092    return DeclarationOnly;
2093
2094  // [dcl.link] p7:
2095  //   A declaration directly contained in a linkage-specification is treated
2096  //   as if it contains the extern specifier for the purpose of determining
2097  //   the linkage of the declared name and whether it is a definition.
2098  if (isSingleLineLanguageLinkage(*this))
2099    return DeclarationOnly;
2100
2101  // C99 6.9.2p2:
2102  //   A declaration of an object that has file scope without an initializer,
2103  //   and without a storage class specifier or the scs 'static', constitutes
2104  //   a tentative definition.
2105  // No such thing in C++.
2106  if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2107    return TentativeDefinition;
2108
2109  // What's left is (in C, block-scope) declarations without initializers or
2110  // external storage. These are definitions.
2111  return Definition;
2112}
2113
2114VarDecl *VarDecl::getActingDefinition() {
2115  DefinitionKind Kind = isThisDeclarationADefinition();
2116  if (Kind != TentativeDefinition)
2117    return nullptr;
2118
2119  VarDecl *LastTentative = nullptr;
2120  VarDecl *First = getFirstDecl();
2121  for (auto I : First->redecls()) {
2122    Kind = I->isThisDeclarationADefinition();
2123    if (Kind == Definition)
2124      return nullptr;
2125    else if (Kind == TentativeDefinition)
2126      LastTentative = I;
2127  }
2128  return LastTentative;
2129}
2130
2131VarDecl *VarDecl::getDefinition(ASTContext &C) {
2132  VarDecl *First = getFirstDecl();
2133  for (auto I : First->redecls()) {
2134    if (I->isThisDeclarationADefinition(C) == Definition)
2135      return I;
2136  }
2137  return nullptr;
2138}
2139
2140VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &Cconst {
2141  DefinitionKind Kind = DeclarationOnly;
2142
2143  const VarDecl *First = getFirstDecl();
2144  for (auto I : First->redecls()) {
2145    Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2146    if (Kind == Definition)
2147      break;
2148  }
2149
2150  return Kind;
2151}
2152
2153const Expr *VarDecl::getAnyInitializer(const VarDecl *&Dconst {
2154  for (auto I : redecls()) {
2155    if (auto Expr = I->getInit()) {
2156      D = I;
2157      return Expr;
2158    }
2159  }
2160  return nullptr;
2161}
2162
2163bool VarDecl::hasInit() const {
2164  if (auto *P = dyn_cast<ParmVarDecl>(this))
2165    if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2166      return false;
2167
2168  return !Init.isNull();
2169}
2170
2171Expr *VarDecl::getInit() {
2172  if (!hasInit())
2173    return nullptr;
2174
2175  if (auto *S = Init.dyn_cast<Stmt *>())
2176    return cast<Expr>(S);
2177
2178  return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2179}
2180
2181Stmt **VarDecl::getInitAddress() {
2182  if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2183    return &ES->Value;
2184
2185  return Init.getAddrOfPtr1();
2186}
2187
2188bool VarDecl::isOutOfLine() const {
2189  if (Decl::isOutOfLine())
2190    return true;
2191
2192  if (!isStaticDataMember())
2193    return false;
2194
2195  // If this static data member was instantiated from a static data member of
2196  // a class template, check whether that static data member was defined
2197  // out-of-line.
2198  if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2199    return VD->isOutOfLine();
2200
2201  return false;
2202}
2203
2204void VarDecl::setInit(Expr *I) {
2205  if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2206    Eval->~EvaluatedStmt();
2207    getASTContext().Deallocate(Eval);
2208  }
2209
2210  Init = I;
2211}
2212
2213bool VarDecl::isUsableInConstantExpressions(ASTContext &Cconst {
2214  const LangOptions &Lang = C.getLangOpts();
2215
2216  if (!Lang.CPlusPlus)
2217    return false;
2218
2219  // In C++11, any variable of reference type can be used in a constant
2220  // expression if it is initialized by a constant expression.
2221  if (Lang.CPlusPlus11 && getType()->isReferenceType())
2222    return true;
2223
2224  // Only const objects can be used in constant expressions in C++. C++98 does
2225  // not require the variable to be non-volatile, but we consider this to be a
2226  // defect.
2227  if (!getType().isConstQualified() || getType().isVolatileQualified())
2228    return false;
2229
2230  // In C++, const, non-volatile variables of integral or enumeration types
2231  // can be used in constant expressions.
2232  if (getType()->isIntegralOrEnumerationType())
2233    return true;
2234
2235  // Additionally, in C++11, non-volatile constexpr variables can be used in
2236  // constant expressions.
2237  return Lang.CPlusPlus11 && isConstexpr();
2238}
2239
2240/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2241/// form, which contains extra information on the evaluated value of the
2242/// initializer.
2243EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2244  auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2245  if (!Eval) {
2246    // Note: EvaluatedStmt contains an APValue, which usually holds
2247    // resources not allocated from the ASTContext.  We need to do some
2248    // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2249    // where we can detect whether there's anything to clean up or not.
2250    Eval = new (getASTContext()) EvaluatedStmt;
2251    Eval->Value = Init.get<Stmt *>();
2252    Init = Eval;
2253  }
2254  return Eval;
2255}
2256
2257APValue *VarDecl::evaluateValue() const {
2258  SmallVector<PartialDiagnosticAt8Notes;
2259  return evaluateValue(Notes);
2260}
2261
2262APValue *VarDecl::evaluateValue(
2263    SmallVectorImpl<PartialDiagnosticAt> &Notesconst {
2264  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2265
2266  // We only produce notes indicating why an initializer is non-constant the
2267  // first time it is evaluated. FIXME: The notes won't always be emitted the
2268  // first time we try evaluation, so might not be produced at all.
2269  if (Eval->WasEvaluated)
2270    return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2271
2272  const auto *Init = cast<Expr>(Eval->Value);
2273  isValueDependent()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2273, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Init->isValueDependent());
2274
2275  if (Eval->IsEvaluating) {
2276    // FIXME: Produce a diagnostic for self-initialization.
2277    Eval->CheckedICE = true;
2278    Eval->IsICE = false;
2279    return nullptr;
2280  }
2281
2282  Eval->IsEvaluating = true;
2283
2284  bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2285                                            this, Notes);
2286
2287  // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2288  // or that it's empty (so that there's nothing to clean up) if evaluation
2289  // failed.
2290  if (!Result)
2291    Eval->Evaluated = APValue();
2292  else if (Eval->Evaluated.needsCleanup())
2293    getASTContext().addDestruction(&Eval->Evaluated);
2294
2295  Eval->IsEvaluating = false;
2296  Eval->WasEvaluated = true;
2297
2298  // In C++11, we have determined whether the initializer was a constant
2299  // expression as a side-effect.
2300  if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2301    Eval->CheckedICE = true;
2302    Eval->IsICE = Result && Notes.empty();
2303  }
2304
2305  return Result ? &Eval->Evaluated : nullptr;
2306}
2307
2308APValue *VarDecl::getEvaluatedValue() const {
2309  if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2310    if (Eval->WasEvaluated)
2311      return &Eval->Evaluated;
2312
2313  return nullptr;
2314}
2315
2316bool VarDecl::isInitKnownICE() const {
2317  if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2318    return Eval->CheckedICE;
2319
2320  return false;
2321}
2322
2323bool VarDecl::isInitICE() const {
2324   (0) . __assert_fail ("isInitKnownICE() && \"Check whether we already know that the initializer is an ICE\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2325, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isInitKnownICE() &&
2325 (0) . __assert_fail ("isInitKnownICE() && \"Check whether we already know that the initializer is an ICE\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2325, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Check whether we already know that the initializer is an ICE");
2326  return Init.get<EvaluatedStmt *>()->IsICE;
2327}
2328
2329bool VarDecl::checkInitIsICE() const {
2330  // Initializers of weak variables are never ICEs.
2331  if (isWeak())
2332    return false;
2333
2334  EvaluatedStmt *Eval = ensureEvaluatedStmt();
2335  if (Eval->CheckedICE)
2336    // We have already checked whether this subexpression is an
2337    // integral constant expression.
2338    return Eval->IsICE;
2339
2340  const auto *Init = cast<Expr>(Eval->Value);
2341  isValueDependent()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2341, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Init->isValueDependent());
2342
2343  // In C++11, evaluate the initializer to check whether it's a constant
2344  // expression.
2345  if (getASTContext().getLangOpts().CPlusPlus11) {
2346    SmallVector<PartialDiagnosticAt8Notes;
2347    evaluateValue(Notes);
2348    return Eval->IsICE;
2349  }
2350
2351  // It's an ICE whether or not the definition we found is
2352  // out-of-line.  See DR 721 and the discussion in Clang PR
2353  // 6206 for details.
2354
2355  if (Eval->CheckingICE)
2356    return false;
2357  Eval->CheckingICE = true;
2358
2359  Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2360  Eval->CheckingICE = false;
2361  Eval->CheckedICE = true;
2362  return Eval->IsICE;
2363}
2364
2365template<typename DeclT>
2366static DeclT *getDefinitionOrSelf(DeclT *D) {
2367  assert(D);
2368  if (auto *Def = D->getDefinition())
2369    return Def;
2370  return D;
2371}
2372
2373bool VarDecl::isEscapingByref() const {
2374  return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2375}
2376
2377bool VarDecl::isNonEscapingByref() const {
2378  return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2379}
2380
2381VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2382  // If it's a variable template specialization, find the template or partial
2383  // specialization from which it was instantiated.
2384  if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2385    auto From = VDTemplSpec->getInstantiatedFrom();
2386    if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2387      while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2388        if (NewVTD->isMemberSpecialization())
2389          break;
2390        VTD = NewVTD;
2391      }
2392      return getDefinitionOrSelf(VTD->getTemplatedDecl());
2393    }
2394    if (auto *VTPSD =
2395            From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2396      while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2397        if (NewVTPSD->isMemberSpecialization())
2398          break;
2399        VTPSD = NewVTPSD;
2400      }
2401      return getDefinitionOrSelf<VarDecl>(VTPSD);
2402    }
2403  }
2404
2405  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2406    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2407      VarDecl *VD = getInstantiatedFromStaticDataMember();
2408      while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2409        VD = NewVD;
2410      return getDefinitionOrSelf(VD);
2411    }
2412  }
2413
2414  if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
2415    while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2416      if (VarTemplate->isMemberSpecialization())
2417        break;
2418      VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2419    }
2420
2421    return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2422  }
2423  return nullptr;
2424}
2425
2426VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2427  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2428    return cast<VarDecl>(MSI->getInstantiatedFrom());
2429
2430  return nullptr;
2431}
2432
2433TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2434  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2435    return Spec->getSpecializationKind();
2436
2437  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2438    return MSI->getTemplateSpecializationKind();
2439
2440  return TSK_Undeclared;
2441}
2442
2443SourceLocation VarDecl::getPointOfInstantiation() const {
2444  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2445    return Spec->getPointOfInstantiation();
2446
2447  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2448    return MSI->getPointOfInstantiation();
2449
2450  return SourceLocation();
2451}
2452
2453VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2454  return getASTContext().getTemplateOrSpecializationInfo(this)
2455      .dyn_cast<VarTemplateDecl *>();
2456}
2457
2458void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2459  getASTContext().setTemplateOrSpecializationInfo(thisTemplate);
2460}
2461
2462bool VarDecl::isKnownToBeDefined() const {
2463  const auto &LangOpts = getASTContext().getLangOpts();
2464  // In CUDA mode without relocatable device code, variables of form 'extern
2465  // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2466  // memory pool.  These are never undefined variables, even if they appear
2467  // inside of an anon namespace or static function.
2468  //
2469  // With CUDA relocatable device code enabled, these variables don't get
2470  // special handling; they're treated like regular extern variables.
2471  if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2472      hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2473      isa<IncompleteArrayType>(getType()))
2474    return true;
2475
2476  return hasDefinition();
2477}
2478
2479bool VarDecl::isNoDestroy(const ASTContext &Ctxconst {
2480  return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2481                                (!Ctx.getLangOpts().RegisterStaticDestructors &&
2482                                 !hasAttr<AlwaysDestroyAttr>()));
2483}
2484
2485MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2486  if (isStaticDataMember())
2487    // FIXME: Remove ?
2488    // return getASTContext().getInstantiatedFromStaticDataMember(this);
2489    return getASTContext().getTemplateOrSpecializationInfo(this)
2490        .dyn_cast<MemberSpecializationInfo *>();
2491  return nullptr;
2492}
2493
2494void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2495                                         SourceLocation PointOfInstantiation) {
2496   (0) . __assert_fail ("(isa(this) || getMemberSpecializationInfo()) && \"not a variable or static data member template specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2498, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((isa<VarTemplateSpecializationDecl>(this) ||
2497 (0) . __assert_fail ("(isa(this) || getMemberSpecializationInfo()) && \"not a variable or static data member template specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2498, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">          getMemberSpecializationInfo()) &&
2498 (0) . __assert_fail ("(isa(this) || getMemberSpecializationInfo()) && \"not a variable or static data member template specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2498, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "not a variable or static data member template specialization");
2499
2500  if (VarTemplateSpecializationDecl *Spec =
2501          dyn_cast<VarTemplateSpecializationDecl>(this)) {
2502    Spec->setSpecializationKind(TSK);
2503    if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2504        Spec->getPointOfInstantiation().isInvalid()) {
2505      Spec->setPointOfInstantiation(PointOfInstantiation);
2506      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2507        L->InstantiationRequested(this);
2508    }
2509  }
2510
2511  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2512    MSI->setTemplateSpecializationKind(TSK);
2513    if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2514        MSI->getPointOfInstantiation().isInvalid()) {
2515      MSI->setPointOfInstantiation(PointOfInstantiation);
2516      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2517        L->InstantiationRequested(this);
2518    }
2519  }
2520}
2521
2522void
2523VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2524                                            TemplateSpecializationKind TSK) {
2525   (0) . __assert_fail ("getASTContext().getTemplateOrSpecializationInfo(this).isNull() && \"Previous template or instantiation?\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2526, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2526 (0) . __assert_fail ("getASTContext().getTemplateOrSpecializationInfo(this).isNull() && \"Previous template or instantiation?\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2526, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Previous template or instantiation?");
2527  getASTContext().setInstantiatedFromStaticDataMember(thisVDTSK);
2528}
2529
2530//===----------------------------------------------------------------------===//
2531// ParmVarDecl Implementation
2532//===----------------------------------------------------------------------===//
2533
2534ParmVarDecl *ParmVarDecl::Create(ASTContext &CDeclContext *DC,
2535                                 SourceLocation StartLoc,
2536                                 SourceLocation IdLocIdentifierInfo *Id,
2537                                 QualType TTypeSourceInfo *TInfo,
2538                                 StorageClass SExpr *DefArg) {
2539  return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2540                                 S, DefArg);
2541}
2542
2543QualType ParmVarDecl::getOriginalType() const {
2544  TypeSourceInfo *TSI = getTypeSourceInfo();
2545  QualType T = TSI ? TSI->getType() : getType();
2546  if (const auto *DT = dyn_cast<DecayedType>(T))
2547    return DT->getOriginalType();
2548  return T;
2549}
2550
2551ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
2552  return new (C, ID)
2553      ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2554                  nullptr, QualType(), nullptr, SC_None, nullptr);
2555}
2556
2557SourceRange ParmVarDecl::getSourceRange() const {
2558  if (!hasInheritedDefaultArg()) {
2559    SourceRange ArgRange = getDefaultArgRange();
2560    if (ArgRange.isValid())
2561      return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2562  }
2563
2564  // DeclaratorDecl considers the range of postfix types as overlapping with the
2565  // declaration name, but this is not the case with parameters in ObjC methods.
2566  if (isa<ObjCMethodDecl>(getDeclContext()))
2567    return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2568
2569  return DeclaratorDecl::getSourceRange();
2570}
2571
2572Expr *ParmVarDecl::getDefaultArg() {
2573   (0) . __assert_fail ("!hasUnparsedDefaultArg() && \"Default argument is not yet parsed!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2573, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2574   (0) . __assert_fail ("!hasUninstantiatedDefaultArg() && \"Default argument is not yet instantiated!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2575, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!hasUninstantiatedDefaultArg() &&
2575 (0) . __assert_fail ("!hasUninstantiatedDefaultArg() && \"Default argument is not yet instantiated!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2575, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Default argument is not yet instantiated!");
2576
2577  Expr *Arg = getInit();
2578  if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2579    return E->getSubExpr();
2580
2581  return Arg;
2582}
2583
2584void ParmVarDecl::setDefaultArg(Expr *defarg) {
2585  ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2586  Init = defarg;
2587}
2588
2589SourceRange ParmVarDecl::getDefaultArgRange() const {
2590  switch (ParmVarDeclBits.DefaultArgKind) {
2591  case DAK_None:
2592  case DAK_Unparsed:
2593    // Nothing we can do here.
2594    return SourceRange();
2595
2596  case DAK_Uninstantiated:
2597    return getUninstantiatedDefaultArg()->getSourceRange();
2598
2599  case DAK_Normal:
2600    if (const Expr *E = getInit())
2601      return E->getSourceRange();
2602
2603    // Missing an actual expression, may be invalid.
2604    return SourceRange();
2605  }
2606  llvm_unreachable("Invalid default argument kind.");
2607}
2608
2609void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2610  ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2611  Init = arg;
2612}
2613
2614Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2615   (0) . __assert_fail ("hasUninstantiatedDefaultArg() && \"Wrong kind of initialization expression!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2616, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(hasUninstantiatedDefaultArg() &&
2616 (0) . __assert_fail ("hasUninstantiatedDefaultArg() && \"Wrong kind of initialization expression!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2616, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Wrong kind of initialization expression!");
2617  return cast_or_null<Expr>(Init.get<Stmt *>());
2618}
2619
2620bool ParmVarDecl::hasDefaultArg() const {
2621  // FIXME: We should just return false for DAK_None here once callers are
2622  // prepared for the case that we encountered an invalid default argument and
2623  // were unable to even build an invalid expression.
2624  return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2625         !Init.isNull();
2626}
2627
2628bool ParmVarDecl::isParameterPack() const {
2629  return isa<PackExpansionType>(getType());
2630}
2631
2632void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2633  getASTContext().setParameterIndex(thisparameterIndex);
2634  ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2635}
2636
2637unsigned ParmVarDecl::getParameterIndexLarge() const {
2638  return getASTContext().getParameterIndex(this);
2639}
2640
2641//===----------------------------------------------------------------------===//
2642// FunctionDecl Implementation
2643//===----------------------------------------------------------------------===//
2644
2645FunctionDecl::FunctionDecl(Kind DKASTContext &CDeclContext *DC,
2646                           SourceLocation StartLoc,
2647                           const DeclarationNameInfo &NameInfoQualType T,
2648                           TypeSourceInfo *TInfoStorageClass S,
2649                           bool isInlineSpecifiedbool isConstexprSpecified)
2650    : DeclaratorDecl(DKDCNameInfo.getLoc(), NameInfo.getName(), TTInfo,
2651                     StartLoc),
2652      DeclContext(DK), redeclarable_base(C), ODRHash(0),
2653      EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2654  isFunctionType()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2654, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(T.isNull() || T->isFunctionType());
2655  FunctionDeclBits.SClass = S;
2656  FunctionDeclBits.IsInline = isInlineSpecified;
2657  FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2658  FunctionDeclBits.IsExplicitSpecified = false;
2659  FunctionDeclBits.IsVirtualAsWritten = false;
2660  FunctionDeclBits.IsPure = false;
2661  FunctionDeclBits.HasInheritedPrototype = false;
2662  FunctionDeclBits.HasWrittenPrototype = true;
2663  FunctionDeclBits.IsDeleted = false;
2664  FunctionDeclBits.IsTrivial = false;
2665  FunctionDeclBits.IsTrivialForCall = false;
2666  FunctionDeclBits.IsDefaulted = false;
2667  FunctionDeclBits.IsExplicitlyDefaulted = false;
2668  FunctionDeclBits.HasImplicitReturnZero = false;
2669  FunctionDeclBits.IsLateTemplateParsed = false;
2670  FunctionDeclBits.IsConstexpr = isConstexprSpecified;
2671  FunctionDeclBits.InstantiationIsPending = false;
2672  FunctionDeclBits.UsesSEHTry = false;
2673  FunctionDeclBits.HasSkippedBody = false;
2674  FunctionDeclBits.WillHaveBody = false;
2675  FunctionDeclBits.IsMultiVersion = false;
2676  FunctionDeclBits.IsCopyDeductionCandidate = false;
2677  FunctionDeclBits.HasODRHash = false;
2678}
2679
2680void FunctionDecl::getNameForDiagnostic(
2681    raw_ostream &OSconst PrintingPolicy &Policybool Qualifiedconst {
2682  NamedDecl::getNameForDiagnostic(OSPolicyQualified);
2683  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2684  if (TemplateArgs)
2685    printTemplateArgumentList(OSTemplateArgs->asArray(), Policy);
2686}
2687
2688bool FunctionDecl::isVariadic() const {
2689  if (const auto *FT = getType()->getAs<FunctionProtoType>())
2690    return FT->isVariadic();
2691  return false;
2692}
2693
2694bool FunctionDecl::hasBody(const FunctionDecl *&Definitionconst {
2695  for (auto I : redecls()) {
2696    if (I->doesThisDeclarationHaveABody()) {
2697      Definition = I;
2698      return true;
2699    }
2700  }
2701
2702  return false;
2703}
2704
2705bool FunctionDecl::hasTrivialBody() const
2706{
2707  Stmt *S = getBody();
2708  if (!S) {
2709    // Since we don't have a body for this function, we don't know if it's
2710    // trivial or not.
2711    return false;
2712  }
2713
2714  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2715    return true;
2716  return false;
2717}
2718
2719bool FunctionDecl::isDefined(const FunctionDecl *&Definitionconst {
2720  for (auto I : redecls()) {
2721    if (I->isThisDeclarationADefinition()) {
2722      Definition = I;
2723      return true;
2724    }
2725  }
2726
2727  return false;
2728}
2729
2730Stmt *FunctionDecl::getBody(const FunctionDecl *&Definitionconst {
2731  if (!hasBody(Definition))
2732    return nullptr;
2733
2734  if (Definition->Body)
2735    return Definition->Body.get(getASTContext().getExternalSource());
2736
2737  return nullptr;
2738}
2739
2740void FunctionDecl::setBody(Stmt *B) {
2741  Body = B;
2742  if (B)
2743    EndRangeLoc = B->getEndLoc();
2744}
2745
2746void FunctionDecl::setPure(bool P) {
2747  FunctionDeclBits.IsPure = P;
2748  if (P)
2749    if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2750      Parent->markedVirtualFunctionPure();
2751}
2752
2753template<std::size_t Len>
2754static bool isNamed(const NamedDecl *NDconst char (&Str)[Len]) {
2755  IdentifierInfo *II = ND->getIdentifier();
2756  return II && II->isStr(Str);
2757}
2758
2759bool FunctionDecl::isMain() const {
2760  const TranslationUnitDecl *tunit =
2761    dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2762  return tunit &&
2763         !tunit->getASTContext().getLangOpts().Freestanding &&
2764         isNamed(this"main");
2765}
2766
2767bool FunctionDecl::isMSVCRTEntryPoint() const {
2768  const TranslationUnitDecl *TUnit =
2769      dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2770  if (!TUnit)
2771    return false;
2772
2773  // Even though we aren't really targeting MSVCRT if we are freestanding,
2774  // semantic analysis for these functions remains the same.
2775
2776  // MSVCRT entry points only exist on MSVCRT targets.
2777  if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2778    return false;
2779
2780  // Nameless functions like constructors cannot be entry points.
2781  if (!getIdentifier())
2782    return false;
2783
2784  return llvm::StringSwitch<bool>(getName())
2785      .Cases("main",     // an ANSI console app
2786             "wmain",    // a Unicode console App
2787             "WinMain",  // an ANSI GUI app
2788             "wWinMain"// a Unicode GUI app
2789             "DllMain",  // a DLL
2790             true)
2791      .Default(false);
2792}
2793
2794bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2795  assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2796  assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2797         getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2798         getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2799         getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2800
2801  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2802    return false;
2803
2804  const auto *proto = getType()->castAs<FunctionProtoType>();
2805  if (proto->getNumParams() != 2 || proto->isVariadic())
2806    return false;
2807
2808  ASTContext &Context =
2809    cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2810      ->getASTContext();
2811
2812  // The result type and first argument type are constant across all
2813  // these operators.  The second argument must be exactly void*.
2814  return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2815}
2816
2817bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAlignedconst {
2818  if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2819    return false;
2820  if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2821      getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2822      getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2823      getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2824    return false;
2825
2826  if (isa<CXXRecordDecl>(getDeclContext()))
2827    return false;
2828
2829  // This can only fail for an invalid 'operator new' declaration.
2830  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2831    return false;
2832
2833  const auto *FPT = getType()->castAs<FunctionProtoType>();
2834  if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
2835    return false;
2836
2837  // If this is a single-parameter function, it must be a replaceable global
2838  // allocation or deallocation function.
2839  if (FPT->getNumParams() == 1)
2840    return true;
2841
2842  unsigned Params = 1;
2843  QualType Ty = FPT->getParamType(Params);
2844  ASTContext &Ctx = getASTContext();
2845
2846  auto Consume = [&] {
2847    ++Params;
2848    Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2849  };
2850
2851  // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2852  bool IsSizedDelete = false;
2853  if (Ctx.getLangOpts().SizedDeallocation &&
2854      (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2855       getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2856      Ctx.hasSameType(TyCtx.getSizeType())) {
2857    IsSizedDelete = true;
2858    Consume();
2859  }
2860
2861  // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2862  // new/delete.
2863  if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2864    if (IsAligned)
2865      *IsAligned = true;
2866    Consume();
2867  }
2868
2869  // Finally, if this is not a sized delete, the final parameter can
2870  // be a 'const std::nothrow_t&'.
2871  if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2872    Ty = Ty->getPointeeType();
2873    if (Ty.getCVRQualifiers() != Qualifiers::Const)
2874      return false;
2875    const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2876    if (RD && isNamed(RD"nothrow_t") && RD->isInStdNamespace())
2877      Consume();
2878  }
2879
2880  return Params == FPT->getNumParams();
2881}
2882
2883bool FunctionDecl::isDestroyingOperatorDelete() const {
2884  // C++ P0722:
2885  //   Within a class C, a single object deallocation function with signature
2886  //     (T, std::destroying_delete_t, <more params>)
2887  //   is a destroying operator delete.
2888  if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2889      getNumParams() < 2)
2890    return false;
2891
2892  auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2893  return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2894         RD->getIdentifier()->isStr("destroying_delete_t");
2895}
2896
2897LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2898  return getDeclLanguageLinkage(*this);
2899}
2900
2901bool FunctionDecl::isExternC() const {
2902  return isDeclExternC(*this);
2903}
2904
2905bool FunctionDecl::isInExternCContext() const {
2906  return getLexicalDeclContext()->isExternCContext();
2907}
2908
2909bool FunctionDecl::isInExternCXXContext() const {
2910  return getLexicalDeclContext()->isExternCXXContext();
2911}
2912
2913bool FunctionDecl::isGlobal() const {
2914  if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
2915    return Method->isStatic();
2916
2917  if (getCanonicalDecl()->getStorageClass() == SC_Static)
2918    return false;
2919
2920  for (const DeclContext *DC = getDeclContext();
2921       DC->isNamespace();
2922       DC = DC->getParent()) {
2923    if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
2924      if (!Namespace->getDeclName())
2925        return false;
2926      break;
2927    }
2928  }
2929
2930  return true;
2931}
2932
2933bool FunctionDecl::isNoReturn() const {
2934  if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2935      hasAttr<C11NoReturnAttr>())
2936    return true;
2937
2938  if (auto *FnTy = getType()->getAs<FunctionType>())
2939    return FnTy->getNoReturnAttr();
2940
2941  return false;
2942}
2943
2944
2945MultiVersionKind FunctionDecl::getMultiVersionKind() const {
2946  if (hasAttr<TargetAttr>())
2947    return MultiVersionKind::Target;
2948  if (hasAttr<CPUDispatchAttr>())
2949    return MultiVersionKind::CPUDispatch;
2950  if (hasAttr<CPUSpecificAttr>())
2951    return MultiVersionKind::CPUSpecific;
2952  return MultiVersionKind::None;
2953}
2954
2955bool FunctionDecl::isCPUDispatchMultiVersion() const {
2956  return isMultiVersion() && hasAttr<CPUDispatchAttr>();
2957}
2958
2959bool FunctionDecl::isCPUSpecificMultiVersion() const {
2960  return isMultiVersion() && hasAttr<CPUSpecificAttr>();
2961}
2962
2963bool FunctionDecl::isTargetMultiVersion() const {
2964  return isMultiVersion() && hasAttr<TargetAttr>();
2965}
2966
2967void
2968FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2969  redeclarable_base::setPreviousDecl(PrevDecl);
2970
2971  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2972    FunctionTemplateDecl *PrevFunTmpl
2973      = PrevDeclPrevDecl->getDescribedFunctionTemplate() : nullptr;
2974     (0) . __assert_fail ("(!PrevDecl || PrevFunTmpl) && \"Function/function template mismatch\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 2974, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2975    FunTmpl->setPreviousDecl(PrevFunTmpl);
2976  }
2977
2978  if (PrevDecl && PrevDecl->isInlined())
2979    setImplicitlyInline(true);
2980}
2981
2982FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2983
2984/// Returns a value indicating whether this function corresponds to a builtin
2985/// function.
2986///
2987/// The function corresponds to a built-in function if it is declared at
2988/// translation scope or within an extern "C" block and its name matches with
2989/// the name of a builtin. The returned value will be 0 for functions that do
2990/// not correspond to a builtin, a value of type \c Builtin::ID if in the
2991/// target-independent range \c [1,Builtin::First), or a target-specific builtin
2992/// value.
2993///
2994/// \param ConsiderWrapperFunctions If true, we should consider wrapper
2995/// functions as their wrapped builtins. This shouldn't be done in general, but
2996/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
2997unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctionsconst {
2998  if (!getIdentifier())
2999    return 0;
3000
3001  unsigned BuiltinID = getIdentifier()->getBuiltinID();
3002  if (!BuiltinID)
3003    return 0;
3004
3005  ASTContext &Context = getASTContext();
3006  if (Context.getLangOpts().CPlusPlus) {
3007    const auto *LinkageDecl =
3008        dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
3009    // In C++, the first declaration of a builtin is always inside an implicit
3010    // extern "C".
3011    // FIXME: A recognised library function may not be directly in an extern "C"
3012    // declaration, for instance "extern "C" { namespace std { decl } }".
3013    if (!LinkageDecl) {
3014      if (BuiltinID == Builtin::BI__GetExceptionInfo &&
3015          Context.getTargetInfo().getCXXABI().isMicrosoft())
3016        return Builtin::BI__GetExceptionInfo;
3017      return 0;
3018    }
3019    if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
3020      return 0;
3021  }
3022
3023  // If the function is marked "overloadable", it has a different mangled name
3024  // and is not the C library function.
3025  if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>())
3026    return 0;
3027
3028  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3029    return BuiltinID;
3030
3031  // This function has the name of a known C library
3032  // function. Determine whether it actually refers to the C library
3033  // function or whether it just has the same name.
3034
3035  // If this is a static function, it's not a builtin.
3036  if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3037    return 0;
3038
3039  // OpenCL v1.2 s6.9.f - The library functions defined in
3040  // the C99 standard headers are not available.
3041  if (Context.getLangOpts().OpenCL &&
3042      Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3043    return 0;
3044
3045  // CUDA does not have device-side standard library. printf and malloc are the
3046  // only special cases that are supported by device-side runtime.
3047  if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3048      !hasAttr<CUDAHostAttr>() &&
3049      !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3050    return 0;
3051
3052  return BuiltinID;
3053}
3054
3055/// getNumParams - Return the number of parameters this function must have
3056/// based on its FunctionType.  This is the length of the ParamInfo array
3057/// after it has been created.
3058unsigned FunctionDecl::getNumParams() const {
3059  const auto *FPT = getType()->getAs<FunctionProtoType>();
3060  return FPT ? FPT->getNumParams() : 0;
3061}
3062
3063void FunctionDecl::setParams(ASTContext &C,
3064                             ArrayRef<ParmVarDecl *> NewParamInfo) {
3065   (0) . __assert_fail ("!ParamInfo && \"Already has param info!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3065, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!ParamInfo && "Already has param info!");
3066   (0) . __assert_fail ("NewParamInfo.size() == getNumParams() && \"Parameter count mismatch!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3066, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3067
3068  // Zero params -> null pointer.
3069  if (!NewParamInfo.empty()) {
3070    ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3071    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3072  }
3073}
3074
3075/// getMinRequiredArguments - Returns the minimum number of arguments
3076/// needed to call this function. This may be fewer than the number of
3077/// function parameters, if some of the parameters have default
3078/// arguments (in C++) or are parameter packs (C++11).
3079unsigned FunctionDecl::getMinRequiredArguments() const {
3080  if (!getASTContext().getLangOpts().CPlusPlus)
3081    return getNumParams();
3082
3083  unsigned NumRequiredArgs = 0;
3084  for (auto *Param : parameters())
3085    if (!Param->isParameterPack() && !Param->hasDefaultArg())
3086      ++NumRequiredArgs;
3087  return NumRequiredArgs;
3088}
3089
3090/// The combination of the extern and inline keywords under MSVC forces
3091/// the function to be required.
3092///
3093/// Note: This function assumes that we will only get called when isInlined()
3094/// would return true for this FunctionDecl.
3095bool FunctionDecl::isMSExternInline() const {
3096   (0) . __assert_fail ("isInlined() && \"expected to get called on an inlined function!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3096, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isInlined() && "expected to get called on an inlined function!");
3097
3098  const ASTContext &Context = getASTContext();
3099  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3100      !hasAttr<DLLExportAttr>())
3101    return false;
3102
3103  for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3104       FD = FD->getPreviousDecl())
3105    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3106      return true;
3107
3108  return false;
3109}
3110
3111static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3112  if (Redecl->getStorageClass() != SC_Extern)
3113    return false;
3114
3115  for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3116       FD = FD->getPreviousDecl())
3117    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3118      return false;
3119
3120  return true;
3121}
3122
3123static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3124  // Only consider file-scope declarations in this test.
3125  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3126    return false;
3127
3128  // Only consider explicit declarations; the presence of a builtin for a
3129  // libcall shouldn't affect whether a definition is externally visible.
3130  if (Redecl->isImplicit())
3131    return false;
3132
3133  if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3134    return true// Not an inline definition
3135
3136  return false;
3137}
3138
3139/// For a function declaration in C or C++, determine whether this
3140/// declaration causes the definition to be externally visible.
3141///
3142/// For instance, this determines if adding the current declaration to the set
3143/// of redeclarations of the given functions causes
3144/// isInlineDefinitionExternallyVisible to change from false to true.
3145bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3146   (0) . __assert_fail ("!doesThisDeclarationHaveABody() && \"Must have a declaration without a body.\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3147, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!doesThisDeclarationHaveABody() &&
3147 (0) . __assert_fail ("!doesThisDeclarationHaveABody() && \"Must have a declaration without a body.\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3147, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Must have a declaration without a body.");
3148
3149  ASTContext &Context = getASTContext();
3150
3151  if (Context.getLangOpts().MSVCCompat) {
3152    const FunctionDecl *Definition;
3153    if (hasBody(Definition) && Definition->isInlined() &&
3154        redeclForcesDefMSVC(this))
3155      return true;
3156  }
3157
3158  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3159    // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3160    // an externally visible definition.
3161    //
3162    // FIXME: What happens if gnu_inline gets added on after the first
3163    // declaration?
3164    if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3165      return false;
3166
3167    const FunctionDecl *Prev = this;
3168    bool FoundBody = false;
3169    while ((Prev = Prev->getPreviousDecl())) {
3170      FoundBody |= Prev->Body.isValid();
3171
3172      if (Prev->Body) {
3173        // If it's not the case that both 'inline' and 'extern' are
3174        // specified on the definition, then it is always externally visible.
3175        if (!Prev->isInlineSpecified() ||
3176            Prev->getStorageClass() != SC_Extern)
3177          return false;
3178      } else if (Prev->isInlineSpecified() &&
3179                 Prev->getStorageClass() != SC_Extern) {
3180        return false;
3181      }
3182    }
3183    return FoundBody;
3184  }
3185
3186  if (Context.getLangOpts().CPlusPlus)
3187    return false;
3188
3189  // C99 6.7.4p6:
3190  //   [...] If all of the file scope declarations for a function in a
3191  //   translation unit include the inline function specifier without extern,
3192  //   then the definition in that translation unit is an inline definition.
3193  if (isInlineSpecified() && getStorageClass() != SC_Extern)
3194    return false;
3195  const FunctionDecl *Prev = this;
3196  bool FoundBody = false;
3197  while ((Prev = Prev->getPreviousDecl())) {
3198    FoundBody |= Prev->Body.isValid();
3199    if (RedeclForcesDefC99(Prev))
3200      return false;
3201  }
3202  return FoundBody;
3203}
3204
3205SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3206  const TypeSourceInfo *TSI = getTypeSourceInfo();
3207  if (!TSI)
3208    return SourceRange();
3209  FunctionTypeLoc FTL =
3210      TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3211  if (!FTL)
3212    return SourceRange();
3213
3214  // Skip self-referential return types.
3215  const SourceManager &SM = getASTContext().getSourceManager();
3216  SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3217  SourceLocation Boundary = getNameInfo().getBeginLoc();
3218  if (RTRange.isInvalid() || Boundary.isInvalid() ||
3219      !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3220    return SourceRange();
3221
3222  return RTRange;
3223}
3224
3225SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3226  const TypeSourceInfo *TSI = getTypeSourceInfo();
3227  if (!TSI)
3228    return SourceRange();
3229  FunctionTypeLoc FTL =
3230    TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3231  if (!FTL)
3232    return SourceRange();
3233
3234  return FTL.getExceptionSpecRange();
3235}
3236
3237/// For an inline function definition in C, or for a gnu_inline function
3238/// in C++, determine whether the definition will be externally visible.
3239///
3240/// Inline function definitions are always available for inlining optimizations.
3241/// However, depending on the language dialect, declaration specifiers, and
3242/// attributes, the definition of an inline function may or may not be
3243/// "externally" visible to other translation units in the program.
3244///
3245/// In C99, inline definitions are not externally visible by default. However,
3246/// if even one of the global-scope declarations is marked "extern inline", the
3247/// inline definition becomes externally visible (C99 6.7.4p6).
3248///
3249/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3250/// definition, we use the GNU semantics for inline, which are nearly the
3251/// opposite of C99 semantics. In particular, "inline" by itself will create
3252/// an externally visible symbol, but "extern inline" will not create an
3253/// externally visible symbol.
3254bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3255   (0) . __assert_fail ("(doesThisDeclarationHaveABody() || willHaveBody()) && \"Must be a function definition\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3256, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3256 (0) . __assert_fail ("(doesThisDeclarationHaveABody() || willHaveBody()) && \"Must be a function definition\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3256, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Must be a function definition");
3257   (0) . __assert_fail ("isInlined() && \"Function must be inline\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3257, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isInlined() && "Function must be inline");
3258  ASTContext &Context = getASTContext();
3259
3260  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3261    // Note: If you change the logic here, please change
3262    // doesDeclarationForceExternallyVisibleDefinition as well.
3263    //
3264    // If it's not the case that both 'inline' and 'extern' are
3265    // specified on the definition, then this inline definition is
3266    // externally visible.
3267    if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3268      return true;
3269
3270    // If any declaration is 'inline' but not 'extern', then this definition
3271    // is externally visible.
3272    for (auto Redecl : redecls()) {
3273      if (Redecl->isInlineSpecified() &&
3274          Redecl->getStorageClass() != SC_Extern)
3275        return true;
3276    }
3277
3278    return false;
3279  }
3280
3281  // The rest of this function is C-only.
3282   (0) . __assert_fail ("!Context.getLangOpts().CPlusPlus && \"should not use C inline rules in C++\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3283, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Context.getLangOpts().CPlusPlus &&
3283 (0) . __assert_fail ("!Context.getLangOpts().CPlusPlus && \"should not use C inline rules in C++\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3283, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "should not use C inline rules in C++");
3284
3285  // C99 6.7.4p6:
3286  //   [...] If all of the file scope declarations for a function in a
3287  //   translation unit include the inline function specifier without extern,
3288  //   then the definition in that translation unit is an inline definition.
3289  for (auto Redecl : redecls()) {
3290    if (RedeclForcesDefC99(Redecl))
3291      return true;
3292  }
3293
3294  // C99 6.7.4p6:
3295  //   An inline definition does not provide an external definition for the
3296  //   function, and does not forbid an external definition in another
3297  //   translation unit.
3298  return false;
3299}
3300
3301/// getOverloadedOperator - Which C++ overloaded operator this
3302/// function represents, if any.
3303OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3304  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3305    return getDeclName().getCXXOverloadedOperator();
3306  else
3307    return OO_None;
3308}
3309
3310/// getLiteralIdentifier - The literal suffix identifier this function
3311/// represents, if any.
3312const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3313  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3314    return getDeclName().getCXXLiteralIdentifier();
3315  else
3316    return nullptr;
3317}
3318
3319FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3320  if (TemplateOrSpecialization.isNull())
3321    return TK_NonTemplate;
3322  if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3323    return TK_FunctionTemplate;
3324  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3325    return TK_MemberSpecialization;
3326  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3327    return TK_FunctionTemplateSpecialization;
3328  if (TemplateOrSpecialization.is
3329                               <DependentFunctionTemplateSpecializationInfo*>())
3330    return TK_DependentFunctionTemplateSpecialization;
3331
3332  llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3333}
3334
3335FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3336  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3337    return cast<FunctionDecl>(Info->getInstantiatedFrom());
3338
3339  return nullptr;
3340}
3341
3342MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3343  return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3344}
3345
3346void
3347FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3348                                               FunctionDecl *FD,
3349                                               TemplateSpecializationKind TSK) {
3350   (0) . __assert_fail ("TemplateOrSpecialization.isNull() && \"Member function is already a specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3351, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TemplateOrSpecialization.isNull() &&
3351 (0) . __assert_fail ("TemplateOrSpecialization.isNull() && \"Member function is already a specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3351, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Member function is already a specialization");
3352  MemberSpecializationInfo *Info
3353    = new (C) MemberSpecializationInfo(FD, TSK);
3354  TemplateOrSpecialization = Info;
3355}
3356
3357FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3358  return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3359}
3360
3361void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3362  TemplateOrSpecialization = Template;
3363}
3364
3365bool FunctionDecl::isImplicitlyInstantiable() const {
3366  // If the function is invalid, it can't be implicitly instantiated.
3367  if (isInvalidDecl())
3368    return false;
3369
3370  switch (getTemplateSpecializationKind()) {
3371  case TSK_Undeclared:
3372  case TSK_ExplicitInstantiationDefinition:
3373    return false;
3374
3375  case TSK_ImplicitInstantiation:
3376    return true;
3377
3378  // It is possible to instantiate TSK_ExplicitSpecialization kind
3379  // if the FunctionDecl has a class scope specialization pattern.
3380  case TSK_ExplicitSpecialization:
3381    return getClassScopeSpecializationPattern() != nullptr;
3382
3383  case TSK_ExplicitInstantiationDeclaration:
3384    // Handled below.
3385    break;
3386  }
3387
3388  // Find the actual template from which we will instantiate.
3389  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3390  bool HasPattern = false;
3391  if (PatternDecl)
3392    HasPattern = PatternDecl->hasBody(PatternDecl);
3393
3394  // C++0x [temp.explicit]p9:
3395  //   Except for inline functions, other explicit instantiation declarations
3396  //   have the effect of suppressing the implicit instantiation of the entity
3397  //   to which they refer.
3398  if (!HasPattern || !PatternDecl)
3399    return true;
3400
3401  return PatternDecl->isInlined();
3402}
3403
3404bool FunctionDecl::isTemplateInstantiation() const {
3405  switch (getTemplateSpecializationKind()) {
3406    case TSK_Undeclared:
3407    case TSK_ExplicitSpecialization:
3408      return false;
3409    case TSK_ImplicitInstantiation:
3410    case TSK_ExplicitInstantiationDeclaration:
3411    case TSK_ExplicitInstantiationDefinition:
3412      return true;
3413  }
3414  llvm_unreachable("All TSK values handled.");
3415}
3416
3417FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
3418  // Handle class scope explicit specialization special case.
3419  if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3420    if (auto *Spec = getClassScopeSpecializationPattern())
3421      return getDefinitionOrSelf(Spec);
3422    return nullptr;
3423  }
3424
3425  // If this is a generic lambda call operator specialization, its
3426  // instantiation pattern is always its primary template's pattern
3427  // even if its primary template was instantiated from another
3428  // member template (which happens with nested generic lambdas).
3429  // Since a lambda's call operator's body is transformed eagerly,
3430  // we don't have to go hunting for a prototype definition template
3431  // (i.e. instantiated-from-member-template) to use as an instantiation
3432  // pattern.
3433
3434  if (isGenericLambdaCallOperatorSpecialization(
3435          dyn_cast<CXXMethodDecl>(this))) {
3436     (0) . __assert_fail ("getPrimaryTemplate() && \"not a generic lambda call operator?\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3436, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3437    return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3438  }
3439
3440  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3441    while (Primary->getInstantiatedFromMemberTemplate()) {
3442      // If we have hit a point where the user provided a specialization of
3443      // this template, we're done looking.
3444      if (Primary->isMemberSpecialization())
3445        break;
3446      Primary = Primary->getInstantiatedFromMemberTemplate();
3447    }
3448
3449    return getDefinitionOrSelf(Primary->getTemplatedDecl());
3450  }
3451
3452  if (auto *MFD = getInstantiatedFromMemberFunction())
3453    return getDefinitionOrSelf(MFD);
3454
3455  return nullptr;
3456}
3457
3458FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3459  if (FunctionTemplateSpecializationInfo *Info
3460        = TemplateOrSpecialization
3461            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3462    return Info->Template.getPointer();
3463  }
3464  return nullptr;
3465}
3466
3467FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3468    return getASTContext().getClassScopeSpecializationPattern(this);
3469}
3470
3471FunctionTemplateSpecializationInfo *
3472FunctionDecl::getTemplateSpecializationInfo() const {
3473  return TemplateOrSpecialization
3474      .dyn_cast<FunctionTemplateSpecializationInfo *>();
3475}
3476
3477const TemplateArgumentList *
3478FunctionDecl::getTemplateSpecializationArgs() const {
3479  if (FunctionTemplateSpecializationInfo *Info
3480        = TemplateOrSpecialization
3481            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3482    return Info->TemplateArguments;
3483  }
3484  return nullptr;
3485}
3486
3487const ASTTemplateArgumentListInfo *
3488FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3489  if (FunctionTemplateSpecializationInfo *Info
3490        = TemplateOrSpecialization
3491            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3492    return Info->TemplateArgumentsAsWritten;
3493  }
3494  return nullptr;
3495}
3496
3497void
3498FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3499                                                FunctionTemplateDecl *Template,
3500                                     const TemplateArgumentList *TemplateArgs,
3501                                                void *InsertPos,
3502                                                TemplateSpecializationKind TSK,
3503                        const TemplateArgumentListInfo *TemplateArgsAsWritten,
3504                                          SourceLocation PointOfInstantiation) {
3505   (0) . __assert_fail ("TSK != TSK_Undeclared && \"Must specify the type of function template specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3506, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TSK != TSK_Undeclared &&
3506 (0) . __assert_fail ("TSK != TSK_Undeclared && \"Must specify the type of function template specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3506, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Must specify the type of function template specialization");
3507  FunctionTemplateSpecializationInfo *Info
3508    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3509  if (!Info)
3510    Info = FunctionTemplateSpecializationInfo::Create(CthisTemplateTSK,
3511                                                      TemplateArgs,
3512                                                      TemplateArgsAsWritten,
3513                                                      PointOfInstantiation);
3514  TemplateOrSpecialization = Info;
3515  Template->addSpecialization(InfoInsertPos);
3516}
3517
3518void
3519FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3520                                    const UnresolvedSetImpl &Templates,
3521                             const TemplateArgumentListInfo &TemplateArgs) {
3522  assert(TemplateOrSpecialization.isNull());
3523  DependentFunctionTemplateSpecializationInfo *Info =
3524      DependentFunctionTemplateSpecializationInfo::Create(ContextTemplates,
3525                                                          TemplateArgs);
3526  TemplateOrSpecialization = Info;
3527}
3528
3529DependentFunctionTemplateSpecializationInfo *
3530FunctionDecl::getDependentSpecializationInfo() const {
3531  return TemplateOrSpecialization
3532      .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3533}
3534
3535DependentFunctionTemplateSpecializationInfo *
3536DependentFunctionTemplateSpecializationInfo::Create(
3537    ASTContext &Contextconst UnresolvedSetImpl &Ts,
3538    const TemplateArgumentListInfo &TArgs) {
3539  void *Buffer = Context.Allocate(
3540      totalSizeToAlloc<TemplateArgumentLocFunctionTemplateDecl *>(
3541          TArgs.size(), Ts.size()));
3542  return new (BufferDependentFunctionTemplateSpecializationInfo(TsTArgs);
3543}
3544
3545DependentFunctionTemplateSpecializationInfo::
3546DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3547                                      const TemplateArgumentListInfo &TArgs)
3548  : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3549  NumTemplates = Ts.size();
3550  NumArgs = TArgs.size();
3551
3552  FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3553  for (unsigned I = 0E = Ts.size(); I != E; ++I)
3554    TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3555
3556  TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3557  for (unsigned I = 0E = TArgs.size(); I != E; ++I)
3558    new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3559}
3560
3561TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3562  // For a function template specialization, query the specialization
3563  // information object.
3564  FunctionTemplateSpecializationInfo *FTSInfo
3565    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3566  if (FTSInfo)
3567    return FTSInfo->getTemplateSpecializationKind();
3568
3569  MemberSpecializationInfo *MSInfo
3570    = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3571  if (MSInfo)
3572    return MSInfo->getTemplateSpecializationKind();
3573
3574  return TSK_Undeclared;
3575}
3576
3577void
3578FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3579                                          SourceLocation PointOfInstantiation) {
3580  if (FunctionTemplateSpecializationInfo *FTSInfo
3581        = TemplateOrSpecialization.dyn_cast<
3582                                    FunctionTemplateSpecializationInfo*>()) {
3583    FTSInfo->setTemplateSpecializationKind(TSK);
3584    if (TSK != TSK_ExplicitSpecialization &&
3585        PointOfInstantiation.isValid() &&
3586        FTSInfo->getPointOfInstantiation().isInvalid()) {
3587      FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3588      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3589        L->InstantiationRequested(this);
3590    }
3591  } else if (MemberSpecializationInfo *MSInfo
3592             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3593    MSInfo->setTemplateSpecializationKind(TSK);
3594    if (TSK != TSK_ExplicitSpecialization &&
3595        PointOfInstantiation.isValid() &&
3596        MSInfo->getPointOfInstantiation().isInvalid()) {
3597      MSInfo->setPointOfInstantiation(PointOfInstantiation);
3598      if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3599        L->InstantiationRequested(this);
3600    }
3601  } else
3602    llvm_unreachable("Function cannot have a template specialization kind");
3603}
3604
3605SourceLocation FunctionDecl::getPointOfInstantiation() const {
3606  if (FunctionTemplateSpecializationInfo *FTSInfo
3607        = TemplateOrSpecialization.dyn_cast<
3608                                        FunctionTemplateSpecializationInfo*>())
3609    return FTSInfo->getPointOfInstantiation();
3610  else if (MemberSpecializationInfo *MSInfo
3611             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3612    return MSInfo->getPointOfInstantiation();
3613
3614  return SourceLocation();
3615}
3616
3617bool FunctionDecl::isOutOfLine() const {
3618  if (Decl::isOutOfLine())
3619    return true;
3620
3621  // If this function was instantiated from a member function of a
3622  // class template, check whether that member function was defined out-of-line.
3623  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3624    const FunctionDecl *Definition;
3625    if (FD->hasBody(Definition))
3626      return Definition->isOutOfLine();
3627  }
3628
3629  // If this function was instantiated from a function template,
3630  // check whether that function template was defined out-of-line.
3631  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3632    const FunctionDecl *Definition;
3633    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3634      return Definition->isOutOfLine();
3635  }
3636
3637  return false;
3638}
3639
3640SourceRange FunctionDecl::getSourceRange() const {
3641  return SourceRange(getOuterLocStart(), EndRangeLoc);
3642}
3643
3644unsigned FunctionDecl::getMemoryFunctionKind() const {
3645  IdentifierInfo *FnInfo = getIdentifier();
3646
3647  if (!FnInfo)
3648    return 0;
3649
3650  // Builtin handling.
3651  switch (getBuiltinID()) {
3652  case Builtin::BI__builtin_memset:
3653  case Builtin::BI__builtin___memset_chk:
3654  case Builtin::BImemset:
3655    return Builtin::BImemset;
3656
3657  case Builtin::BI__builtin_memcpy:
3658  case Builtin::BI__builtin___memcpy_chk:
3659  case Builtin::BImemcpy:
3660    return Builtin::BImemcpy;
3661
3662  case Builtin::BI__builtin_memmove:
3663  case Builtin::BI__builtin___memmove_chk:
3664  case Builtin::BImemmove:
3665    return Builtin::BImemmove;
3666
3667  case Builtin::BIstrlcpy:
3668  case Builtin::BI__builtin___strlcpy_chk:
3669    return Builtin::BIstrlcpy;
3670
3671  case Builtin::BIstrlcat:
3672  case Builtin::BI__builtin___strlcat_chk:
3673    return Builtin::BIstrlcat;
3674
3675  case Builtin::BI__builtin_memcmp:
3676  case Builtin::BImemcmp:
3677    return Builtin::BImemcmp;
3678
3679  case Builtin::BI__builtin_bcmp:
3680  case Builtin::BIbcmp:
3681    return Builtin::BIbcmp;
3682
3683  case Builtin::BI__builtin_strncpy:
3684  case Builtin::BI__builtin___strncpy_chk:
3685  case Builtin::BIstrncpy:
3686    return Builtin::BIstrncpy;
3687
3688  case Builtin::BI__builtin_strncmp:
3689  case Builtin::BIstrncmp:
3690    return Builtin::BIstrncmp;
3691
3692  case Builtin::BI__builtin_strncasecmp:
3693  case Builtin::BIstrncasecmp:
3694    return Builtin::BIstrncasecmp;
3695
3696  case Builtin::BI__builtin_strncat:
3697  case Builtin::BI__builtin___strncat_chk:
3698  case Builtin::BIstrncat:
3699    return Builtin::BIstrncat;
3700
3701  case Builtin::BI__builtin_strndup:
3702  case Builtin::BIstrndup:
3703    return Builtin::BIstrndup;
3704
3705  case Builtin::BI__builtin_strlen:
3706  case Builtin::BIstrlen:
3707    return Builtin::BIstrlen;
3708
3709  case Builtin::BI__builtin_bzero:
3710  case Builtin::BIbzero:
3711    return Builtin::BIbzero;
3712
3713  default:
3714    if (isExternC()) {
3715      if (FnInfo->isStr("memset"))
3716        return Builtin::BImemset;
3717      else if (FnInfo->isStr("memcpy"))
3718        return Builtin::BImemcpy;
3719      else if (FnInfo->isStr("memmove"))
3720        return Builtin::BImemmove;
3721      else if (FnInfo->isStr("memcmp"))
3722        return Builtin::BImemcmp;
3723      else if (FnInfo->isStr("bcmp"))
3724        return Builtin::BIbcmp;
3725      else if (FnInfo->isStr("strncpy"))
3726        return Builtin::BIstrncpy;
3727      else if (FnInfo->isStr("strncmp"))
3728        return Builtin::BIstrncmp;
3729      else if (FnInfo->isStr("strncasecmp"))
3730        return Builtin::BIstrncasecmp;
3731      else if (FnInfo->isStr("strncat"))
3732        return Builtin::BIstrncat;
3733      else if (FnInfo->isStr("strndup"))
3734        return Builtin::BIstrndup;
3735      else if (FnInfo->isStr("strlen"))
3736        return Builtin::BIstrlen;
3737      else if (FnInfo->isStr("bzero"))
3738        return Builtin::BIbzero;
3739    }
3740    break;
3741  }
3742  return 0;
3743}
3744
3745unsigned FunctionDecl::getODRHash() const {
3746  assert(hasODRHash());
3747  return ODRHash;
3748}
3749
3750unsigned FunctionDecl::getODRHash() {
3751  if (hasODRHash())
3752    return ODRHash;
3753
3754  if (auto *FT = getInstantiatedFromMemberFunction()) {
3755    setHasODRHash(true);
3756    ODRHash = FT->getODRHash();
3757    return ODRHash;
3758  }
3759
3760  class ODRHash Hash;
3761  Hash.AddFunctionDecl(this);
3762  setHasODRHash(true);
3763  ODRHash = Hash.CalculateHash();
3764  return ODRHash;
3765}
3766
3767//===----------------------------------------------------------------------===//
3768// FieldDecl Implementation
3769//===----------------------------------------------------------------------===//
3770
3771FieldDecl *FieldDecl::Create(const ASTContext &CDeclContext *DC,
3772                             SourceLocation StartLocSourceLocation IdLoc,
3773                             IdentifierInfo *IdQualType T,
3774                             TypeSourceInfo *TInfoExpr *BWbool Mutable,
3775                             InClassInitStyle InitStyle) {
3776  return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3777                               BW, Mutable, InitStyle);
3778}
3779
3780FieldDecl *FieldDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
3781  return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3782                               SourceLocation(), nullptr, QualType(), nullptr,
3783                               nullptrfalse, ICIS_NoInit);
3784}
3785
3786bool FieldDecl::isAnonymousStructOrUnion() const {
3787  if (!isImplicit() || getDeclName())
3788    return false;
3789
3790  if (const auto *Record = getType()->getAs<RecordType>())
3791    return Record->getDecl()->isAnonymousStructOrUnion();
3792
3793  return false;
3794}
3795
3796unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctxconst {
3797   (0) . __assert_fail ("isBitField() && \"not a bitfield\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3797, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isBitField() && "not a bitfield");
3798  return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
3799}
3800
3801bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctxconst {
3802  return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
3803         getBitWidthValue(Ctx) == 0;
3804}
3805
3806unsigned FieldDecl::getFieldIndex() const {
3807  const FieldDecl *Canonical = getCanonicalDecl();
3808  if (Canonical != this)
3809    return Canonical->getFieldIndex();
3810
3811  if (CachedFieldIndexreturn CachedFieldIndex - 1;
3812
3813  unsigned Index = 0;
3814  const RecordDecl *RD = getParent()->getDefinition();
3815   (0) . __assert_fail ("RD && \"requested index for field of struct with no definition\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3815, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(RD && "requested index for field of struct with no definition");
3816
3817  for (auto *Field : RD->fields()) {
3818    Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3819    ++Index;
3820  }
3821
3822   (0) . __assert_fail ("CachedFieldIndex && \"failed to find field in parent\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3822, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CachedFieldIndex && "failed to find field in parent");
3823  return CachedFieldIndex - 1;
3824}
3825
3826SourceRange FieldDecl::getSourceRange() const {
3827  const Expr *FinalExpr = getInClassInitializer();
3828  if (!FinalExpr)
3829    FinalExpr = getBitWidth();
3830  if (FinalExpr)
3831    return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
3832  return DeclaratorDecl::getSourceRange();
3833}
3834
3835void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3836   (0) . __assert_fail ("(getParent()->isLambda() || getParent()->isCapturedRecord()) && \"capturing type in non-lambda or captured record.\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3837, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3837 (0) . __assert_fail ("(getParent()->isLambda() || getParent()->isCapturedRecord()) && \"capturing type in non-lambda or captured record.\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3837, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "capturing type in non-lambda or captured record.");
3838   (0) . __assert_fail ("InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer() == nullptr && \"bit width, initializer or captured type already set\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3840, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(InitStorage.getInt() == ISK_NoInit &&
3839 (0) . __assert_fail ("InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer() == nullptr && \"bit width, initializer or captured type already set\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3840, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         InitStorage.getPointer() == nullptr &&
3840 (0) . __assert_fail ("InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer() == nullptr && \"bit width, initializer or captured type already set\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3840, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "bit width, initializer or captured type already set");
3841  InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3842                               ISK_CapturedVLAType);
3843}
3844
3845//===----------------------------------------------------------------------===//
3846// TagDecl Implementation
3847//===----------------------------------------------------------------------===//
3848
3849TagDecl::TagDecl(Kind DKTagKind TKconst ASTContext &CDeclContext *DC,
3850                 SourceLocation LIdentifierInfo *IdTagDecl *PrevDecl,
3851                 SourceLocation StartL)
3852    : TypeDecl(DKDCLIdStartL), DeclContext(DK), redeclarable_base(C),
3853      TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3854   (0) . __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3855, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((DK != Enum || TK == TTK_Enum) &&
3855 (0) . __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3855, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "EnumDecl not matched with TTK_Enum");
3856  setPreviousDecl(PrevDecl);
3857  setTagKind(TK);
3858  setCompleteDefinition(false);
3859  setBeingDefined(false);
3860  setEmbeddedInDeclarator(false);
3861  setFreeStanding(false);
3862  setCompleteDefinitionRequired(false);
3863}
3864
3865SourceLocation TagDecl::getOuterLocStart() const {
3866  return getTemplateOrInnerLocStart(this);
3867}
3868
3869SourceRange TagDecl::getSourceRange() const {
3870  SourceLocation RBraceLoc = BraceRange.getEnd();
3871  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3872  return SourceRange(getOuterLocStart(), E);
3873}
3874
3875TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3876
3877void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3878  TypedefNameDeclOrQualifier = TDD;
3879  if (const Type *T = getTypeForDecl()) {
3880    (void)T;
3881    isLinkageValid()", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3881, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(T->isLinkageValid());
3882  }
3883  assert(isLinkageValid());
3884}
3885
3886void TagDecl::startDefinition() {
3887  setBeingDefined(true);
3888
3889  if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
3890    struct CXXRecordDecl::DefinitionData *Data =
3891      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3892    for (auto I : redecls())
3893      cast<CXXRecordDecl>(I)->DefinitionData = Data;
3894  }
3895}
3896
3897void TagDecl::completeDefinition() {
3898   (0) . __assert_fail ("(!isa(this) || cast(this)->hasDefinition()) && \"definition completed but not started\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3900, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((!isa<CXXRecordDecl>(this) ||
3899 (0) . __assert_fail ("(!isa(this) || cast(this)->hasDefinition()) && \"definition completed but not started\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3900, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">          cast<CXXRecordDecl>(this)->hasDefinition()) &&
3900 (0) . __assert_fail ("(!isa(this) || cast(this)->hasDefinition()) && \"definition completed but not started\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 3900, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "definition completed but not started");
3901
3902  setCompleteDefinition(true);
3903  setBeingDefined(false);
3904
3905  if (ASTMutationListener *L = getASTMutationListener())
3906    L->CompletedTagDefinition(this);
3907}
3908
3909TagDecl *TagDecl::getDefinition() const {
3910  if (isCompleteDefinition())
3911    return const_cast<TagDecl *>(this);
3912
3913  // If it's possible for us to have an out-of-date definition, check now.
3914  if (mayHaveOutOfDateDef()) {
3915    if (IdentifierInfo *II = getIdentifier()) {
3916      if (II->isOutOfDate()) {
3917        updateOutOfDate(*II);
3918      }
3919    }
3920  }
3921
3922  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
3923    return CXXRD->getDefinition();
3924
3925  for (auto R : redecls())
3926    if (R->isCompleteDefinition())
3927      return R;
3928
3929  return nullptr;
3930}
3931
3932void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3933  if (QualifierLoc) {
3934    // Make sure the extended qualifier info is allocated.
3935    if (!hasExtInfo())
3936      TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3937    // Set qualifier info.
3938    getExtInfo()->QualifierLoc = QualifierLoc;
3939  } else {
3940    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3941    if (hasExtInfo()) {
3942      if (getExtInfo()->NumTemplParamLists == 0) {
3943        getASTContext().Deallocate(getExtInfo());
3944        TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
3945      }
3946      else
3947        getExtInfo()->QualifierLoc = QualifierLoc;
3948    }
3949  }
3950}
3951
3952void TagDecl::setTemplateParameterListsInfo(
3953    ASTContext &ContextArrayRef<TemplateParameterList *> TPLists) {
3954  assert(!TPLists.empty());
3955  // Make sure the extended decl info is allocated.
3956  if (!hasExtInfo())
3957    // Allocate external info struct.
3958    TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3959  // Set the template parameter lists info.
3960  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
3961}
3962
3963//===----------------------------------------------------------------------===//
3964// EnumDecl Implementation
3965//===----------------------------------------------------------------------===//
3966
3967EnumDecl::EnumDecl(ASTContext &CDeclContext *DCSourceLocation StartLoc,
3968                   SourceLocation IdLocIdentifierInfo *IdEnumDecl *PrevDecl,
3969                   bool Scopedbool ScopedUsingClassTagbool Fixed)
3970    : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3971  assert(Scoped || !ScopedUsingClassTag);
3972  IntegerType = nullptr;
3973  setNumPositiveBits(0);
3974  setNumNegativeBits(0);
3975  setScoped(Scoped);
3976  setScopedUsingClassTag(ScopedUsingClassTag);
3977  setFixed(Fixed);
3978  setHasODRHash(false);
3979  ODRHash = 0;
3980}
3981
3982void EnumDecl::anchor() {}
3983
3984EnumDecl *EnumDecl::Create(ASTContext &CDeclContext *DC,
3985                           SourceLocation StartLocSourceLocation IdLoc,
3986                           IdentifierInfo *Id,
3987                           EnumDecl *PrevDeclbool IsScoped,
3988                           bool IsScopedUsingClassTagbool IsFixed) {
3989  auto *Enum = new (CDCEnumDecl(CDCStartLocIdLocIdPrevDecl,
3990                                    IsScopedIsScopedUsingClassTagIsFixed);
3991  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
3992  C.getTypeDeclType(EnumPrevDecl);
3993  return Enum;
3994}
3995
3996EnumDecl *EnumDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
3997  EnumDecl *Enum =
3998      new (CIDEnumDecl(CnullptrSourceLocation(), SourceLocation(),
3999                           nullptrnullptrfalsefalsefalse);
4000  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4001  return Enum;
4002}
4003
4004SourceRange EnumDecl::getIntegerTypeRange() const {
4005  if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4006    return TI->getTypeLoc().getSourceRange();
4007  return SourceRange();
4008}
4009
4010void EnumDecl::completeDefinition(QualType NewType,
4011                                  QualType NewPromotionType,
4012                                  unsigned NumPositiveBits,
4013                                  unsigned NumNegativeBits) {
4014   (0) . __assert_fail ("!isCompleteDefinition() && \"Cannot redefine enums!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4014, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isCompleteDefinition() && "Cannot redefine enums!");
4015  if (!IntegerType)
4016    IntegerType = NewType.getTypePtr();
4017  PromotionType = NewPromotionType;
4018  setNumPositiveBits(NumPositiveBits);
4019  setNumNegativeBits(NumNegativeBits);
4020  TagDecl::completeDefinition();
4021}
4022
4023bool EnumDecl::isClosed() const {
4024  if (const auto *A = getAttr<EnumExtensibilityAttr>())
4025    return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4026  return true;
4027}
4028
4029bool EnumDecl::isClosedFlag() const {
4030  return isClosed() && hasAttr<FlagEnumAttr>();
4031}
4032
4033bool EnumDecl::isClosedNonFlag() const {
4034  return isClosed() && !hasAttr<FlagEnumAttr>();
4035}
4036
4037TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4038  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4039    return MSI->getTemplateSpecializationKind();
4040
4041  return TSK_Undeclared;
4042}
4043
4044void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4045                                         SourceLocation PointOfInstantiation) {
4046  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4047   (0) . __assert_fail ("MSI && \"Not an instantiated member enumeration?\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4047, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(MSI && "Not an instantiated member enumeration?");
4048  MSI->setTemplateSpecializationKind(TSK);
4049  if (TSK != TSK_ExplicitSpecialization &&
4050      PointOfInstantiation.isValid() &&
4051      MSI->getPointOfInstantiation().isInvalid())
4052    MSI->setPointOfInstantiation(PointOfInstantiation);
4053}
4054
4055EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4056  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4057    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4058      EnumDecl *ED = getInstantiatedFromMemberEnum();
4059      while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4060        ED = NewED;
4061      return getDefinitionOrSelf(ED);
4062    }
4063  }
4064
4065   (0) . __assert_fail ("!isTemplateInstantiation(getTemplateSpecializationKind()) && \"couldn't find pattern for enum instantiation\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4066, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4066 (0) . __assert_fail ("!isTemplateInstantiation(getTemplateSpecializationKind()) && \"couldn't find pattern for enum instantiation\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4066, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "couldn't find pattern for enum instantiation");
4067  return nullptr;
4068}
4069
4070EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4071  if (SpecializationInfo)
4072    return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4073
4074  return nullptr;
4075}
4076
4077void EnumDecl::setInstantiationOfMemberEnum(ASTContext &CEnumDecl *ED,
4078                                            TemplateSpecializationKind TSK) {
4079   (0) . __assert_fail ("!SpecializationInfo && \"Member enum is already a specialization\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4079, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!SpecializationInfo && "Member enum is already a specialization");
4080  SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4081}
4082
4083unsigned EnumDecl::getODRHash() {
4084  if (hasODRHash())
4085    return ODRHash;
4086
4087  class ODRHash Hash;
4088  Hash.AddEnumDecl(this);
4089  setHasODRHash(true);
4090  ODRHash = Hash.CalculateHash();
4091  return ODRHash;
4092}
4093
4094//===----------------------------------------------------------------------===//
4095// RecordDecl Implementation
4096//===----------------------------------------------------------------------===//
4097
4098RecordDecl::RecordDecl(Kind DKTagKind TKconst ASTContext &C,
4099                       DeclContext *DCSourceLocation StartLoc,
4100                       SourceLocation IdLocIdentifierInfo *Id,
4101                       RecordDecl *PrevDecl)
4102    : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4103   (0) . __assert_fail ("classof(static_cast(this)) && \"Invalid Kind!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4103, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4104  setHasFlexibleArrayMember(false);
4105  setAnonymousStructOrUnion(false);
4106  setHasObjectMember(false);
4107  setHasVolatileMember(false);
4108  setHasLoadedFieldsFromExternalStorage(false);
4109  setNonTrivialToPrimitiveDefaultInitialize(false);
4110  setNonTrivialToPrimitiveCopy(false);
4111  setNonTrivialToPrimitiveDestroy(false);
4112  setParamDestroyedInCallee(false);
4113  setArgPassingRestrictions(APK_CanPassInRegs);
4114}
4115
4116RecordDecl *RecordDecl::Create(const ASTContext &CTagKind TKDeclContext *DC,
4117                               SourceLocation StartLocSourceLocation IdLoc,
4118                               IdentifierInfo *IdRecordDeclPrevDecl) {
4119  RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4120                                         StartLoc, IdLoc, Id, PrevDecl);
4121  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4122
4123  C.getTypeDeclType(RPrevDecl);
4124  return R;
4125}
4126
4127RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &Cunsigned ID) {
4128  RecordDecl *R =
4129      new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4130                             SourceLocation(), nullptrnullptr);
4131  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4132  return R;
4133}
4134
4135bool RecordDecl::isInjectedClassName() const {
4136  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4137    cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4138}
4139
4140bool RecordDecl::isLambda() const {
4141  if (auto RD = dyn_cast<CXXRecordDecl>(this))
4142    return RD->isLambda();
4143  return false;
4144}
4145
4146bool RecordDecl::isCapturedRecord() const {
4147  return hasAttr<CapturedRecordAttr>();
4148}
4149
4150void RecordDecl::setCapturedRecord() {
4151  addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4152}
4153
4154RecordDecl::field_iterator RecordDecl::field_begin() const {
4155  if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4156    LoadFieldsFromExternalStorage();
4157
4158  return field_iterator(decl_iterator(FirstDecl));
4159}
4160
4161/// completeDefinition - Notes that the definition of this type is now
4162/// complete.
4163void RecordDecl::completeDefinition() {
4164   (0) . __assert_fail ("!isCompleteDefinition() && \"Cannot redefine record!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4164, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isCompleteDefinition() && "Cannot redefine record!");
4165  TagDecl::completeDefinition();
4166}
4167
4168/// isMsStruct - Get whether or not this record uses ms_struct layout.
4169/// This which can be turned on with an attribute, pragma, or the
4170/// -mms-bitfields command-line option.
4171bool RecordDecl::isMsStruct(const ASTContext &Cconst {
4172  return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4173}
4174
4175void RecordDecl::LoadFieldsFromExternalStorage() const {
4176  ExternalASTSource *Source = getASTContext().getExternalSource();
4177   (0) . __assert_fail ("hasExternalLexicalStorage() && Source && \"No external storage?\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4177, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(hasExternalLexicalStorage() && Source && "No external storage?");
4178
4179  // Notify that we have a RecordDecl doing some initialization.
4180  ExternalASTSource::Deserializing TheFields(Source);
4181
4182  SmallVector<Decl*, 64Decls;
4183  setHasLoadedFieldsFromExternalStorage(true);
4184  Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4185    return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4186  }, Decls);
4187
4188#ifndef NDEBUG
4189  // Check that all decls we got were FieldDecls.
4190  for (unsigned i=0, e=Decls.size(); i != e; ++i)
4191    (Decls[i]) || isa(Decls[i])", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4191, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4192#endif
4193
4194  if (Decls.empty())
4195    return;
4196
4197  std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4198                                                 /*FieldsAlreadyLoaded=*/false);
4199}
4200
4201bool RecordDecl::mayInsertExtraPadding(bool EmitRemarkconst {
4202  ASTContext &Context = getASTContext();
4203  const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4204      (SanitizerKind::Address | SanitizerKind::KernelAddress);
4205  if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4206    return false;
4207  const auto &Blacklist = Context.getSanitizerBlacklist();
4208  const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4209  // We may be able to relax some of these requirements.
4210  int ReasonToReject = -1;
4211  if (!CXXRD || CXXRD->isExternCContext())
4212    ReasonToReject = 0;  // is not C++.
4213  else if (CXXRD->hasAttr<PackedAttr>())
4214    ReasonToReject = 1;  // is packed.
4215  else if (CXXRD->isUnion())
4216    ReasonToReject = 2;  // is a union.
4217  else if (CXXRD->isTriviallyCopyable())
4218    ReasonToReject = 3;  // is trivially copyable.
4219  else if (CXXRD->hasTrivialDestructor())
4220    ReasonToReject = 4;  // has trivial destructor.
4221  else if (CXXRD->isStandardLayout())
4222    ReasonToReject = 5;  // is standard layout.
4223  else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4224                                           "field-padding"))
4225    ReasonToReject = 6;  // is in a blacklisted file.
4226  else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4227                                       getQualifiedNameAsString(),
4228                                       "field-padding"))
4229    ReasonToReject = 7;  // is blacklisted.
4230
4231  if (EmitRemark) {
4232    if (ReasonToReject >= 0)
4233      Context.getDiagnostics().Report(
4234          getLocation(),
4235          diag::remark_sanitize_address_insert_extra_padding_rejected)
4236          << getQualifiedNameAsString() << ReasonToReject;
4237    else
4238      Context.getDiagnostics().Report(
4239          getLocation(),
4240          diag::remark_sanitize_address_insert_extra_padding_accepted)
4241          << getQualifiedNameAsString();
4242  }
4243  return ReasonToReject < 0;
4244}
4245
4246const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4247  for (const auto *I : fields()) {
4248    if (I->getIdentifier())
4249      return I;
4250
4251    if (const auto *RT = I->getType()->getAs<RecordType>())
4252      if (const FieldDecl *NamedDataMember =
4253              RT->getDecl()->findFirstNamedDataMember())
4254        return NamedDataMember;
4255  }
4256
4257  // We didn't find a named data member.
4258  return nullptr;
4259}
4260
4261//===----------------------------------------------------------------------===//
4262// BlockDecl Implementation
4263//===----------------------------------------------------------------------===//
4264
4265BlockDecl::BlockDecl(DeclContext *DCSourceLocation CaretLoc)
4266    : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4267  setIsVariadic(false);
4268  setCapturesCXXThis(false);
4269  setBlockMissingReturnType(true);
4270  setIsConversionFromLambda(false);
4271  setDoesNotEscape(false);
4272  setCanAvoidCopyToHeap(false);
4273}
4274
4275void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4276   (0) . __assert_fail ("!ParamInfo && \"Already has param info!\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4276, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!ParamInfo && "Already has param info!");
4277
4278  // Zero params -> null pointer.
4279  if (!NewParamInfo.empty()) {
4280    NumParams = NewParamInfo.size();
4281    ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4282    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4283  }
4284}
4285
4286void BlockDecl::setCaptures(ASTContext &ContextArrayRef<CaptureCaptures,
4287                            bool CapturesCXXThis) {
4288  this->setCapturesCXXThis(CapturesCXXThis);
4289  this->NumCaptures = Captures.size();
4290
4291  if (Captures.empty()) {
4292    this->Captures = nullptr;
4293    return;
4294  }
4295
4296  this->Captures = Captures.copy(Context).data();
4297}
4298
4299bool BlockDecl::capturesVariable(const VarDecl *variableconst {
4300  for (const auto &I : captures())
4301    // Only auto vars can be captured, so no redeclaration worries.
4302    if (I.getVariable() == variable)
4303      return true;
4304
4305  return false;
4306}
4307
4308SourceRange BlockDecl::getSourceRange() const {
4309  return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4310}
4311
4312//===----------------------------------------------------------------------===//
4313// Other Decl Allocation/Deallocation Method Implementations
4314//===----------------------------------------------------------------------===//
4315
4316void TranslationUnitDecl::anchor() {}
4317
4318TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4319  return new (C, (DeclContext *)nullptrTranslationUnitDecl(C);
4320}
4321
4322void PragmaCommentDecl::anchor() {}
4323
4324PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4325                                             TranslationUnitDecl *DC,
4326                                             SourceLocation CommentLoc,
4327                                             PragmaMSCommentKind CommentKind,
4328                                             StringRef Arg) {
4329  PragmaCommentDecl *PCD =
4330      new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4331          PragmaCommentDecl(DC, CommentLoc, CommentKind);
4332  memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4333  PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4334  return PCD;
4335}
4336
4337PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4338                                                         unsigned ID,
4339                                                         unsigned ArgSize) {
4340  return new (CID, additionalSizeToAlloc<char>(ArgSize + 1))
4341      PragmaCommentDecl(nullptrSourceLocation(), PCK_Unknown);
4342}
4343
4344void PragmaDetectMismatchDecl::anchor() {}
4345
4346PragmaDetectMismatchDecl *
4347PragmaDetectMismatchDecl::Create(const ASTContext &CTranslationUnitDecl *DC,
4348                                 SourceLocation LocStringRef Name,
4349                                 StringRef Value) {
4350  size_t ValueStart = Name.size() + 1;
4351  PragmaDetectMismatchDecl *PDMD =
4352      new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4353          PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4354  memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4355  PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4356  memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4357         Value.size());
4358  PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4359  return PDMD;
4360}
4361
4362PragmaDetectMismatchDecl *
4363PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &Cunsigned ID,
4364                                             unsigned NameValueSize) {
4365  return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4366      PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4367}
4368
4369void ExternCContextDecl::anchor() {}
4370
4371ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4372                                               TranslationUnitDecl *DC) {
4373  return new (C, DC) ExternCContextDecl(DC);
4374}
4375
4376void LabelDecl::anchor() {}
4377
4378LabelDecl *LabelDecl::Create(ASTContext &CDeclContext *DC,
4379                             SourceLocation IdentLIdentifierInfo *II) {
4380  return new (CDCLabelDecl(DCIdentLIInullptrIdentL);
4381}
4382
4383LabelDecl *LabelDecl::Create(ASTContext &CDeclContext *DC,
4384                             SourceLocation IdentLIdentifierInfo *II,
4385                             SourceLocation GnuLabelL) {
4386   (0) . __assert_fail ("GnuLabelL != IdentL && \"Use this only for GNU local labels\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/Decl.cpp", 4386, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4387  return new (CDCLabelDecl(DCIdentLIInullptrGnuLabelL);
4388}
4389
4390LabelDecl *LabelDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4391  return new (CIDLabelDecl(nullptrSourceLocation(), nullptrnullptr,
4392                               SourceLocation());
4393}
4394
4395void LabelDecl::setMSAsmLabel(StringRef Name) {
4396  char *Buffer = new (getASTContext(), 1char[Name.size() + 1];
4397  memcpy(Buffer, Name.data(), Name.size());
4398  Buffer[Name.size()] = '\0';
4399  MSAsmName = Buffer;
4400}
4401
4402void ValueDecl::anchor() {}
4403
4404bool ValueDecl::isWeak() const {
4405  for (const auto *I : attrs())
4406    if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
4407      return true;
4408
4409  return isWeakImported();
4410}
4411
4412void ImplicitParamDecl::anchor() {}
4413
4414ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &CDeclContext *DC,
4415                                             SourceLocation IdLoc,
4416                                             IdentifierInfo *IdQualType Type,
4417                                             ImplicitParamKind ParamKind) {
4418  return new (CDCImplicitParamDecl(CDCIdLocIdTypeParamKind);
4419}
4420
4421ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &CQualType Type,
4422                                             ImplicitParamKind ParamKind) {
4423  return new (CnullptrImplicitParamDecl(CTypeParamKind);
4424}
4425
4426ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4427                                                         unsigned ID) {
4428  return new (CIDImplicitParamDecl(CQualType(), ImplicitParamKind::Other);
4429}
4430
4431FunctionDecl *FunctionDecl::Create(ASTContext &CDeclContext *DC,
4432                                   SourceLocation StartLoc,
4433                                   const DeclarationNameInfo &NameInfo,
4434                                   QualType TTypeSourceInfo *TInfo,
4435                                   StorageClass SC,
4436                                   bool isInlineSpecified,
4437                                   bool hasWrittenPrototype,
4438                                   bool isConstexprSpecified) {
4439  FunctionDecl *New =
4440      new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4441                               SC, isInlineSpecified, isConstexprSpecified);
4442  New->setHasWrittenPrototype(hasWrittenPrototype);
4443  return New;
4444}
4445
4446FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4447  return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
4448                                  DeclarationNameInfo(), QualType(), nullptr,
4449                                  SC_None, falsefalse);
4450}
4451
4452BlockDecl *BlockDecl::Create(ASTContext &CDeclContext *DCSourceLocation L) {
4453  return new (CDCBlockDecl(DCL);
4454}
4455
4456BlockDecl *BlockDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4457  return new (CIDBlockDecl(nullptrSourceLocation());
4458}
4459
4460CapturedDecl::CapturedDecl(DeclContext *DCunsigned NumParams)
4461    : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4462      NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptrfalse) {}
4463
4464CapturedDecl *CapturedDecl::Create(ASTContext &CDeclContext *DC,
4465                                   unsigned NumParams) {
4466  return new (CDC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4467      CapturedDecl(DCNumParams);
4468}
4469
4470CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &Cunsigned ID,
4471                                               unsigned NumParams) {
4472  return new (CID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4473      CapturedDecl(nullptrNumParams);
4474}
4475
4476Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4477void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4478
4479bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4480void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4481
4482EnumConstantDecl *EnumConstantDecl::Create(ASTContext &CEnumDecl *CD,
4483                                           SourceLocation L,
4484                                           IdentifierInfo *IdQualType T,
4485                                           Expr *Econst llvm::APSInt &V) {
4486  return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4487}
4488
4489EnumConstantDecl *
4490EnumConstantDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4491  return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4492                                      QualType(), nullptr, llvm::APSInt());
4493}
4494
4495void IndirectFieldDecl::anchor() {}
4496
4497IndirectFieldDecl::IndirectFieldDecl(ASTContext &CDeclContext *DC,
4498                                     SourceLocation LDeclarationName N,
4499                                     QualType T,
4500                                     MutableArrayRef<NamedDecl *> CH)
4501    : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4502      ChainingSize(CH.size()) {
4503  // In C++, indirect field declarations conflict with tag declarations in the
4504  // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4505  if (C.getLangOpts().CPlusPlus)
4506    IdentifierNamespace |= IDNS_Tag;
4507}
4508
4509IndirectFieldDecl *
4510IndirectFieldDecl::Create(ASTContext &CDeclContext *DCSourceLocation L,
4511                          IdentifierInfo *IdQualType T,
4512                          llvm::MutableArrayRef<NamedDecl *> CH) {
4513  return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4514}
4515
4516IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4517                                                         unsigned ID) {
4518  return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4519                                       DeclarationName(), QualType(), None);
4520}
4521
4522SourceRange EnumConstantDecl::getSourceRange() const {
4523  SourceLocation End = getLocation();
4524  if (Init)
4525    End = Init->getEndLoc();
4526  return SourceRange(getLocation(), End);
4527}
4528
4529void TypeDecl::anchor() {}
4530
4531TypedefDecl *TypedefDecl::Create(ASTContext &CDeclContext *DC,
4532                                 SourceLocation StartLocSourceLocation IdLoc,
4533                                 IdentifierInfo *IdTypeSourceInfo *TInfo) {
4534  return new (CDCTypedefDecl(CDCStartLocIdLocIdTInfo);
4535}
4536
4537void TypedefNameDecl::anchor() {}
4538
4539TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedeclconst {
4540  if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4541    auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4542    auto *ThisTypedef = this;
4543    if (AnyRedecl && OwningTypedef) {
4544      OwningTypedef = OwningTypedef->getCanonicalDecl();
4545      ThisTypedef = ThisTypedef->getCanonicalDecl();
4546    }
4547    if (OwningTypedef == ThisTypedef)
4548      return TT->getDecl();
4549  }
4550
4551  return nullptr;
4552}
4553
4554bool TypedefNameDecl::isTransparentTagSlow() const {
4555  auto determineIsTransparent = [&]() {
4556    if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4557      if (auto *TD = TT->getDecl()) {
4558        if (TD->getName() != getName())
4559          return false;
4560        SourceLocation TTLoc = getLocation();
4561        SourceLocation TDLoc = TD->getLocation();
4562        if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4563          return false;
4564        SourceManager &SM = getASTContext().getSourceManager();
4565        return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4566      }
4567    }
4568    return false;
4569  };
4570
4571  bool isTransparent = determineIsTransparent();
4572  MaybeModedTInfo.setInt((isTransparent << 1) | 1);
4573  return isTransparent;
4574}
4575
4576TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4577  return new (CIDTypedefDecl(CnullptrSourceLocation(), SourceLocation(),
4578                                 nullptrnullptr);
4579}
4580
4581TypeAliasDecl *TypeAliasDecl::Create(ASTContext &CDeclContext *DC,
4582                                     SourceLocation StartLoc,
4583                                     SourceLocation IdLocIdentifierInfo *Id,
4584                                     TypeSourceInfo *TInfo) {
4585  return new (CDCTypeAliasDecl(CDCStartLocIdLocIdTInfo);
4586}
4587
4588TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4589  return new (CIDTypeAliasDecl(CnullptrSourceLocation(),
4590                                   SourceLocation(), nullptrnullptr);
4591}
4592
4593SourceRange TypedefDecl::getSourceRange() const {
4594  SourceLocation RangeEnd = getLocation();
4595  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4596    if (typeIsPostfix(TInfo->getType()))
4597      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4598  }
4599  return SourceRange(getBeginLoc(), RangeEnd);
4600}
4601
4602SourceRange TypeAliasDecl::getSourceRange() const {
4603  SourceLocation RangeEnd = getBeginLoc();
4604  if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4605    RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4606  return SourceRange(getBeginLoc(), RangeEnd);
4607}
4608
4609void FileScopeAsmDecl::anchor() {}
4610
4611FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &CDeclContext *DC,
4612                                           StringLiteral *Str,
4613                                           SourceLocation AsmLoc,
4614                                           SourceLocation RParenLoc) {
4615  return new (CDCFileScopeAsmDecl(DCStrAsmLocRParenLoc);
4616}
4617
4618FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4619                                                       unsigned ID) {
4620  return new (CIDFileScopeAsmDecl(nullptrnullptrSourceLocation(),
4621                                      SourceLocation());
4622}
4623
4624void EmptyDecl::anchor() {}
4625
4626EmptyDecl *EmptyDecl::Create(ASTContext &CDeclContext *DCSourceLocation L) {
4627  return new (CDCEmptyDecl(DCL);
4628}
4629
4630EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4631  return new (CIDEmptyDecl(nullptrSourceLocation());
4632}
4633
4634//===----------------------------------------------------------------------===//
4635// ImportDecl Implementation
4636//===----------------------------------------------------------------------===//
4637
4638/// Retrieve the number of module identifiers needed to name the given
4639/// module.
4640static unsigned getNumModuleIdentifiers(Module *Mod) {
4641  unsigned Result = 1;
4642  while (Mod->Parent) {
4643    Mod = Mod->Parent;
4644    ++Result;
4645  }
4646  return Result;
4647}
4648
4649ImportDecl::ImportDecl(DeclContext *DCSourceLocation StartLoc,
4650                       Module *Imported,
4651                       ArrayRef<SourceLocationIdentifierLocs)
4652  : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
4653  assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4654  auto *StoredLocs = getTrailingObjects<SourceLocation>();
4655  std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4656                          StoredLocs);
4657}
4658
4659ImportDecl::ImportDecl(DeclContext *DCSourceLocation StartLoc,
4660                       Module *ImportedSourceLocation EndLoc)
4661  : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
4662  *getTrailingObjects<SourceLocation>() = EndLoc;
4663}
4664
4665ImportDecl *ImportDecl::Create(ASTContext &CDeclContext *DC,
4666                               SourceLocation StartLocModule *Imported,
4667                               ArrayRef<SourceLocationIdentifierLocs) {
4668  return new (C, DC,
4669              additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
4670      ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4671}
4672
4673ImportDecl *ImportDecl::CreateImplicit(ASTContext &CDeclContext *DC,
4674                                       SourceLocation StartLoc,
4675                                       Module *Imported,
4676                                       SourceLocation EndLoc) {
4677  ImportDecl *Import = new (CDC, additionalSizeToAlloc<SourceLocation>(1))
4678      ImportDecl(DCStartLocImportedEndLoc);
4679  Import->setImplicit();
4680  return Import;
4681}
4682
4683ImportDecl *ImportDecl::CreateDeserialized(ASTContext &Cunsigned ID,
4684                                           unsigned NumLocations) {
4685  return new (CID, additionalSizeToAlloc<SourceLocation>(NumLocations))
4686      ImportDecl(EmptyShell());
4687}
4688
4689ArrayRef<SourceLocationImportDecl::getIdentifierLocs() const {
4690  if (!ImportedAndComplete.getInt())
4691    return None;
4692
4693  const auto *StoredLocs = getTrailingObjects<SourceLocation>();
4694  return llvm::makeArrayRef(StoredLocs,
4695                            getNumModuleIdentifiers(getImportedModule()));
4696}
4697
4698SourceRange ImportDecl::getSourceRange() const {
4699  if (!ImportedAndComplete.getInt())
4700    return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4701
4702  return SourceRange(getLocation(), getIdentifierLocs().back());
4703}
4704
4705//===----------------------------------------------------------------------===//
4706// ExportDecl Implementation
4707//===----------------------------------------------------------------------===//
4708
4709void ExportDecl::anchor() {}
4710
4711ExportDecl *ExportDecl::Create(ASTContext &CDeclContext *DC,
4712                               SourceLocation ExportLoc) {
4713  return new (CDCExportDecl(DCExportLoc);
4714}
4715
4716ExportDecl *ExportDecl::CreateDeserialized(ASTContext &Cunsigned ID) {
4717  return new (CIDExportDecl(nullptrSourceLocation());
4718}
4719
clang::PrettyDeclStackTraceEntry::print
clang::Decl::isOutOfLine
clang::LinkageComputer::getLVForType
clang::LinkageComputer::getLVForTemplateParameterList
clang::LinkageComputer::getLVForTemplateArgumentList
clang::LinkageComputer::getLVForTemplateArgumentList
clang::LinkageComputer::mergeTemplateLV
clang::LinkageComputer::mergeTemplateLV
clang::LinkageComputer::mergeTemplateLV
clang::LinkageComputer::getLVForNamespaceScopeDecl
clang::LinkageComputer::getLVForClassMember
clang::NamedDecl::anchor
clang::NamedDecl::isLinkageValid
clang::NamedDecl::getObjCFStringFormattingFamily
clang::NamedDecl::getLinkageInternal
clang::NamedDecl::getLinkageAndVisibility
clang::NamedDecl::getExplicitVisibility
clang::LinkageComputer::getLVForClosure
clang::LinkageComputer::getLVForLocalDecl
clang::LinkageComputer::computeLVForDecl
clang::LinkageComputer::getLVForDecl
clang::LinkageComputer::getDeclLinkageAndVisibility
clang::Decl::getOwningModuleForLinkage
clang::NamedDecl::printName
clang::NamedDecl::getQualifiedNameAsString
clang::NamedDecl::printQualifiedName
clang::NamedDecl::printQualifiedName
clang::NamedDecl::getNameForDiagnostic
clang::NamedDecl::declarationReplaces
clang::NamedDecl::hasLinkage
clang::NamedDecl::getUnderlyingDeclImpl
clang::NamedDecl::isCXXInstanceMember
clang::DeclaratorDecl::getTypeSpecStartLoc
clang::DeclaratorDecl::setQualifierInfo
clang::DeclaratorDecl::setTemplateParameterListsInfo
clang::DeclaratorDecl::getOuterLocStart
clang::DeclaratorDecl::getSourceRange
clang::QualifierInfo::setTemplateParameterListsInfo
clang::VarDecl::getStorageClassSpecifierString
clang::VarDecl::Create
clang::VarDecl::CreateDeserialized
clang::VarDecl::setStorageClass
clang::VarDecl::getTLSKind
clang::VarDecl::getSourceRange
clang::VarDecl::getLanguageLinkage
clang::VarDecl::isExternC
clang::VarDecl::isInExternCContext
clang::VarDecl::isInExternCXXContext
clang::VarDecl::getCanonicalDecl
clang::VarDecl::isThisDeclarationADefinition
clang::VarDecl::getActingDefinition
clang::VarDecl::getDefinition
clang::VarDecl::hasDefinition
clang::VarDecl::getAnyInitializer
clang::VarDecl::hasInit
clang::VarDecl::getInit
clang::VarDecl::getInitAddress
clang::VarDecl::isOutOfLine
clang::VarDecl::setInit
clang::VarDecl::isUsableInConstantExpressions
clang::VarDecl::ensureEvaluatedStmt
clang::VarDecl::evaluateValue
clang::VarDecl::evaluateValue
clang::VarDecl::getEvaluatedValue
clang::VarDecl::isInitKnownICE
clang::VarDecl::isInitICE
clang::VarDecl::checkInitIsICE
clang::VarDecl::isEscapingByref
clang::VarDecl::isNonEscapingByref
clang::VarDecl::getTemplateInstantiationPattern
clang::VarDecl::getInstantiatedFromStaticDataMember
clang::VarDecl::getTemplateSpecializationKind
clang::VarDecl::getPointOfInstantiation
clang::VarDecl::getDescribedVarTemplate
clang::VarDecl::setDescribedVarTemplate
clang::VarDecl::isKnownToBeDefined
clang::VarDecl::isNoDestroy
clang::VarDecl::getMemberSpecializationInfo
clang::VarDecl::setTemplateSpecializationKind
clang::VarDecl::setInstantiationOfStaticDataMember
clang::ParmVarDecl::Create
clang::ParmVarDecl::getOriginalType
clang::ParmVarDecl::CreateDeserialized
clang::ParmVarDecl::getSourceRange
clang::ParmVarDecl::getDefaultArg
clang::ParmVarDecl::setDefaultArg
clang::ParmVarDecl::getDefaultArgRange
clang::ParmVarDecl::setUninstantiatedDefaultArg
clang::ParmVarDecl::getUninstantiatedDefaultArg
clang::ParmVarDecl::hasDefaultArg
clang::ParmVarDecl::isParameterPack
clang::ParmVarDecl::setParameterIndexLarge
clang::ParmVarDecl::getParameterIndexLarge
clang::FunctionDecl::getNameForDiagnostic
clang::FunctionDecl::isVariadic
clang::FunctionDecl::hasBody
clang::FunctionDecl::hasTrivialBody
clang::FunctionDecl::isDefined
clang::FunctionDecl::getBody
clang::FunctionDecl::setBody
clang::FunctionDecl::setPure
clang::FunctionDecl::isMain
clang::FunctionDecl::isMSVCRTEntryPoint
clang::FunctionDecl::isReservedGlobalPlacementOperator
clang::FunctionDecl::isReplaceableGlobalAllocationFunction
clang::FunctionDecl::isDestroyingOperatorDelete
clang::FunctionDecl::getLanguageLinkage
clang::FunctionDecl::isExternC
clang::FunctionDecl::isInExternCContext
clang::FunctionDecl::isInExternCXXContext
clang::FunctionDecl::isGlobal
clang::FunctionDecl::isNoReturn
clang::FunctionDecl::getMultiVersionKind
clang::FunctionDecl::isCPUDispatchMultiVersion
clang::FunctionDecl::isCPUSpecificMultiVersion
clang::FunctionDecl::isTargetMultiVersion
clang::FunctionDecl::setPreviousDeclaration
clang::FunctionDecl::getCanonicalDecl
clang::FunctionDecl::getBuiltinID
clang::FunctionDecl::getNumParams
clang::FunctionDecl::setParams
clang::FunctionDecl::getMinRequiredArguments
clang::FunctionDecl::isMSExternInline
clang::FunctionDecl::doesDeclarationForceExternallyVisibleDefinition
clang::FunctionDecl::getReturnTypeSourceRange
clang::FunctionDecl::getExceptionSpecSourceRange
clang::FunctionDecl::isInlineDefinitionExternallyVisible
clang::FunctionDecl::getOverloadedOperator
clang::FunctionDecl::getLiteralIdentifier
clang::FunctionDecl::getTemplatedKind
clang::FunctionDecl::getInstantiatedFromMemberFunction
clang::FunctionDecl::getMemberSpecializationInfo
clang::FunctionDecl::setInstantiationOfMemberFunction
clang::FunctionDecl::getDescribedFunctionTemplate
clang::FunctionDecl::setDescribedFunctionTemplate
clang::FunctionDecl::isImplicitlyInstantiable
clang::FunctionDecl::isTemplateInstantiation
clang::FunctionDecl::getTemplateInstantiationPattern
clang::FunctionDecl::getPrimaryTemplate
clang::FunctionDecl::getClassScopeSpecializationPattern
clang::FunctionDecl::getTemplateSpecializationInfo
clang::FunctionDecl::getTemplateSpecializationArgs
clang::FunctionDecl::getTemplateSpecializationArgsAsWritten
clang::FunctionDecl::setFunctionTemplateSpecialization
clang::FunctionDecl::setDependentTemplateSpecialization
clang::FunctionDecl::getDependentSpecializationInfo
clang::DependentFunctionTemplateSpecializationInfo::Create
clang::FunctionDecl::getTemplateSpecializationKind
clang::FunctionDecl::setTemplateSpecializationKind
clang::FunctionDecl::getPointOfInstantiation
clang::FunctionDecl::isOutOfLine
clang::FunctionDecl::getSourceRange
clang::FunctionDecl::getMemoryFunctionKind
clang::FunctionDecl::getODRHash
clang::FunctionDecl::getODRHash
clang::FieldDecl::Create
clang::FieldDecl::CreateDeserialized
clang::FieldDecl::isAnonymousStructOrUnion
clang::FieldDecl::getBitWidthValue
clang::FieldDecl::isZeroLengthBitField
clang::FieldDecl::getFieldIndex
clang::FieldDecl::getSourceRange
clang::FieldDecl::setCapturedVLAType
clang::TagDecl::getOuterLocStart
clang::TagDecl::getSourceRange
clang::TagDecl::getCanonicalDecl
clang::TagDecl::setTypedefNameForAnonDecl
clang::TagDecl::startDefinition
clang::TagDecl::completeDefinition
clang::TagDecl::getDefinition
clang::TagDecl::setQualifierInfo
clang::TagDecl::setTemplateParameterListsInfo
clang::EnumDecl::anchor
clang::EnumDecl::Create
clang::EnumDecl::CreateDeserialized
clang::EnumDecl::getIntegerTypeRange
clang::EnumDecl::completeDefinition
clang::EnumDecl::isClosed
clang::EnumDecl::isClosedFlag
clang::EnumDecl::isClosedNonFlag
clang::EnumDecl::getTemplateSpecializationKind
clang::EnumDecl::setTemplateSpecializationKind
clang::EnumDecl::getTemplateInstantiationPattern
clang::EnumDecl::getInstantiatedFromMemberEnum
clang::EnumDecl::setInstantiationOfMemberEnum
clang::EnumDecl::getODRHash
clang::RecordDecl::Create
clang::RecordDecl::CreateDeserialized
clang::RecordDecl::isInjectedClassName
clang::RecordDecl::isLambda
clang::RecordDecl::isCapturedRecord
clang::RecordDecl::setCapturedRecord
clang::RecordDecl::field_begin
clang::RecordDecl::completeDefinition
clang::RecordDecl::isMsStruct
clang::RecordDecl::LoadFieldsFromExternalStorage
clang::RecordDecl::mayInsertExtraPadding
clang::RecordDecl::findFirstNamedDataMember
clang::BlockDecl::setParams
clang::BlockDecl::setCaptures
clang::BlockDecl::capturesVariable
clang::BlockDecl::getSourceRange
clang::TranslationUnitDecl::anchor
clang::TranslationUnitDecl::Create
clang::PragmaCommentDecl::anchor
clang::PragmaCommentDecl::Create
clang::PragmaCommentDecl::CreateDeserialized
clang::PragmaDetectMismatchDecl::anchor
clang::PragmaDetectMismatchDecl::Create
clang::PragmaDetectMismatchDecl::CreateDeserialized
clang::ExternCContextDecl::anchor
clang::ExternCContextDecl::Create
clang::LabelDecl::anchor
clang::LabelDecl::Create
clang::LabelDecl::Create
clang::LabelDecl::CreateDeserialized
clang::LabelDecl::setMSAsmLabel
clang::ValueDecl::anchor
clang::ValueDecl::isWeak
clang::ImplicitParamDecl::anchor
clang::ImplicitParamDecl::Create
clang::ImplicitParamDecl::Create
clang::ImplicitParamDecl::CreateDeserialized
clang::FunctionDecl::Create
clang::FunctionDecl::CreateDeserialized
clang::BlockDecl::Create
clang::BlockDecl::CreateDeserialized
clang::CapturedDecl::Create
clang::CapturedDecl::CreateDeserialized
clang::CapturedDecl::getBody
clang::CapturedDecl::setBody
clang::CapturedDecl::isNothrow
clang::CapturedDecl::setNothrow
clang::EnumConstantDecl::Create
clang::EnumConstantDecl::CreateDeserialized
clang::IndirectFieldDecl::anchor
clang::IndirectFieldDecl::Create
clang::IndirectFieldDecl::CreateDeserialized
clang::EnumConstantDecl::getSourceRange
clang::TypeDecl::anchor
clang::TypedefDecl::Create
clang::TypedefNameDecl::anchor
clang::TypedefNameDecl::getAnonDeclWithTypedefName
clang::TypedefNameDecl::isTransparentTagSlow
clang::TypedefDecl::CreateDeserialized
clang::TypeAliasDecl::Create
clang::TypeAliasDecl::CreateDeserialized
clang::TypedefDecl::getSourceRange
clang::TypeAliasDecl::getSourceRange
clang::FileScopeAsmDecl::anchor
clang::FileScopeAsmDecl::Create
clang::FileScopeAsmDecl::CreateDeserialized
clang::EmptyDecl::anchor
clang::EmptyDecl::Create
clang::EmptyDecl::CreateDeserialized
clang::ImportDecl::Create
clang::ImportDecl::CreateImplicit
clang::ImportDecl::CreateDeserialized
clang::ImportDecl::getIdentifierLocs
clang::ImportDecl::getSourceRange
clang::ExportDecl::anchor
clang::ExportDecl::Create
clang::ExportDecl::CreateDeserialized