clang  3.9.0
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements C++ template instantiation for declarations.
10 //
11 //===----------------------------------------------------------------------===/
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Template.h"
25 
26 using namespace clang;
27 
28 static bool isDeclWithinFunction(const Decl *D) {
29  const DeclContext *DC = D->getDeclContext();
30  if (DC->isFunctionOrMethod())
31  return true;
32 
33  if (DC->isRecord())
34  return cast<CXXRecordDecl>(DC)->isLocalClass();
35 
36  return false;
37 }
38 
39 template<typename DeclT>
40 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41  const MultiLevelTemplateArgumentList &TemplateArgs) {
42  if (!OldDecl->getQualifierLoc())
43  return false;
44 
45  assert((NewDecl->getFriendObjectKind() ||
46  !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47  "non-friend with qualified name defined in dependent context");
48  Sema::ContextRAII SavedContext(
49  SemaRef,
50  const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51  ? NewDecl->getLexicalDeclContext()
52  : OldDecl->getLexicalDeclContext()));
53 
54  NestedNameSpecifierLoc NewQualifierLoc
55  = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56  TemplateArgs);
57 
58  if (!NewQualifierLoc)
59  return true;
60 
61  NewDecl->setQualifierInfo(NewQualifierLoc);
62  return false;
63 }
64 
66  DeclaratorDecl *NewDecl) {
67  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
68 }
69 
71  TagDecl *NewDecl) {
72  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
73 }
74 
75 // Include attribute instantiation code.
76 #include "clang/Sema/AttrTemplateInstantiate.inc"
77 
79  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80  const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81  if (Aligned->isAlignmentExpr()) {
82  // The alignment expression is a constant expression.
84  ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85  if (!Result.isInvalid())
86  S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
87  Aligned->getSpellingListIndex(), IsPackExpansion);
88  } else {
89  TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90  TemplateArgs, Aligned->getLocation(),
91  DeclarationName());
92  if (Result)
93  S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94  Aligned->getSpellingListIndex(), IsPackExpansion);
95  }
96 }
97 
99  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100  const AlignedAttr *Aligned, Decl *New) {
101  if (!Aligned->isPackExpansion()) {
102  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
103  return;
104  }
105 
107  if (Aligned->isAlignmentExpr())
108  S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
109  Unexpanded);
110  else
111  S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
112  Unexpanded);
113  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
114 
115  // Determine whether we can expand this attribute pack yet.
116  bool Expand = true, RetainExpansion = false;
117  Optional<unsigned> NumExpansions;
118  // FIXME: Use the actual location of the ellipsis.
119  SourceLocation EllipsisLoc = Aligned->getLocation();
120  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121  Unexpanded, TemplateArgs, Expand,
122  RetainExpansion, NumExpansions))
123  return;
124 
125  if (!Expand) {
126  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
128  } else {
129  for (unsigned I = 0; I != *NumExpansions; ++I) {
131  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
132  }
133  }
134 }
135 
137  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138  const AssumeAlignedAttr *Aligned, Decl *New) {
139  // The alignment expression is a constant expression.
141 
142  Expr *E, *OE = nullptr;
143  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144  if (Result.isInvalid())
145  return;
146  E = Result.getAs<Expr>();
147 
148  if (Aligned->getOffset()) {
149  Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150  if (Result.isInvalid())
151  return;
152  OE = Result.getAs<Expr>();
153  }
154 
155  S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156  Aligned->getSpellingListIndex());
157 }
158 
160  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161  const AlignValueAttr *Aligned, Decl *New) {
162  // The alignment expression is a constant expression.
164  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165  if (!Result.isInvalid())
166  S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167  Aligned->getSpellingListIndex());
168 }
169 
171  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172  const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
173  Expr *Cond = nullptr;
174  {
176  ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177  if (Result.isInvalid())
178  return;
179  Cond = Result.getAs<Expr>();
180  }
181  if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183  if (Converted.isInvalid())
184  return;
185  Cond = Converted.get();
186  }
187 
189  if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190  !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
191  Diags)) {
192  S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193  for (int I = 0, N = Diags.size(); I != N; ++I)
194  S.Diag(Diags[I].first, Diags[I].second);
195  return;
196  }
197 
198  EnableIfAttr *EIA = new (S.getASTContext())
199  EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
200  A->getMessage(),
201  A->getSpellingListIndex());
202  New->addAttr(EIA);
203 }
204 
205 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
206 // template A as the base and arguments from TemplateArgs.
208  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
209  const CUDALaunchBoundsAttr &Attr, Decl *New) {
210  // The alignment expression is a constant expression.
212 
213  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
214  if (Result.isInvalid())
215  return;
216  Expr *MaxThreads = Result.getAs<Expr>();
217 
218  Expr *MinBlocks = nullptr;
219  if (Attr.getMinBlocks()) {
220  Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
221  if (Result.isInvalid())
222  return;
223  MinBlocks = Result.getAs<Expr>();
224  }
225 
226  S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
227  Attr.getSpellingListIndex());
228 }
229 
230 static void
232  const MultiLevelTemplateArgumentList &TemplateArgs,
233  const ModeAttr &Attr, Decl *New) {
234  S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
235  Attr.getSpellingListIndex(), /*InInstantiation=*/true);
236 }
237 
238 /// Instantiation of 'declare simd' attribute and its arguments.
240  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
241  const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
242  // Allow 'this' in clauses with varlists.
243  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
244  New = FTD->getTemplatedDecl();
245  auto *FD = cast<FunctionDecl>(New);
246  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
247  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
248  SmallVector<unsigned, 4> LinModifiers;
249 
250  auto &&Subst = [&](Expr *E) -> ExprResult {
251  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
252  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
253  Sema::ContextRAII SavedContext(S, FD);
254  LocalInstantiationScope Local(S);
255  if (FD->getNumParams() > PVD->getFunctionScopeIndex())
256  Local.InstantiatedLocal(
257  PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
258  return S.SubstExpr(E, TemplateArgs);
259  }
260  Sema::CXXThisScopeRAII ThisScope(S, ThisContext, /*TypeQuals=*/0,
261  FD->isCXXInstanceMember());
262  return S.SubstExpr(E, TemplateArgs);
263  };
264 
265  ExprResult Simdlen;
266  if (auto *E = Attr.getSimdlen())
267  Simdlen = Subst(E);
268 
269  if (Attr.uniforms_size() > 0) {
270  for(auto *E : Attr.uniforms()) {
271  ExprResult Inst = Subst(E);
272  if (Inst.isInvalid())
273  continue;
274  Uniforms.push_back(Inst.get());
275  }
276  }
277 
278  auto AI = Attr.alignments_begin();
279  for (auto *E : Attr.aligneds()) {
280  ExprResult Inst = Subst(E);
281  if (Inst.isInvalid())
282  continue;
283  Aligneds.push_back(Inst.get());
284  Inst = ExprEmpty();
285  if (*AI)
286  Inst = S.SubstExpr(*AI, TemplateArgs);
287  Alignments.push_back(Inst.get());
288  ++AI;
289  }
290 
291  auto SI = Attr.steps_begin();
292  for (auto *E : Attr.linears()) {
293  ExprResult Inst = Subst(E);
294  if (Inst.isInvalid())
295  continue;
296  Linears.push_back(Inst.get());
297  Inst = ExprEmpty();
298  if (*SI)
299  Inst = S.SubstExpr(*SI, TemplateArgs);
300  Steps.push_back(Inst.get());
301  ++SI;
302  }
303  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
305  S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
306  Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
307  Attr.getRange());
308 }
309 
311  const Decl *Tmpl, Decl *New,
312  LateInstantiatedAttrVec *LateAttrs,
313  LocalInstantiationScope *OuterMostScope) {
314  for (const auto *TmplAttr : Tmpl->attrs()) {
315  // FIXME: This should be generalized to more than just the AlignedAttr.
316  const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
317  if (Aligned && Aligned->isAlignmentDependent()) {
318  instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
319  continue;
320  }
321 
322  const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
323  if (AssumeAligned) {
324  instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
325  continue;
326  }
327 
328  const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
329  if (AlignValue) {
330  instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
331  continue;
332  }
333 
334  const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
335  if (EnableIf && EnableIf->getCond()->isValueDependent()) {
336  instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
337  New);
338  continue;
339  }
340 
341  if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
342  dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
343  instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
344  *CUDALaunchBounds, New);
345  continue;
346  }
347 
348  if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
349  instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
350  continue;
351  }
352 
353  if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
354  instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
355  continue;
356  }
357 
358  // Existing DLL attribute on the instantiation takes precedence.
359  if (TmplAttr->getKind() == attr::DLLExport ||
360  TmplAttr->getKind() == attr::DLLImport) {
361  if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
362  continue;
363  }
364  }
365 
366  if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
367  AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
368  ABIAttr->getSpellingListIndex());
369  continue;
370  }
371 
372  if (isa<NSConsumedAttr>(TmplAttr) || isa<CFConsumedAttr>(TmplAttr)) {
373  AddNSConsumedAttr(TmplAttr->getRange(), New,
374  TmplAttr->getSpellingListIndex(),
375  isa<NSConsumedAttr>(TmplAttr),
376  /*template instantiation*/ true);
377  continue;
378  }
379 
380  assert(!TmplAttr->isPackExpansion());
381  if (TmplAttr->isLateParsed() && LateAttrs) {
382  // Late parsed attributes must be instantiated and attached after the
383  // enclosing class has been instantiated. See Sema::InstantiateClass.
384  LocalInstantiationScope *Saved = nullptr;
386  Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
387  LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
388  } else {
389  // Allow 'this' within late-parsed attributes.
390  NamedDecl *ND = dyn_cast<NamedDecl>(New);
391  CXXRecordDecl *ThisContext =
392  dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
393  CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
394  ND && ND->isCXXInstanceMember());
395 
396  Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
397  *this, TemplateArgs);
398  if (NewAttr)
399  New->addAttr(NewAttr);
400  }
401  }
402 }
403 
404 /// Get the previous declaration of a declaration for the purposes of template
405 /// instantiation. If this finds a previous declaration, then the previous
406 /// declaration of the instantiation of D should be an instantiation of the
407 /// result of this function.
408 template<typename DeclT>
409 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
410  DeclT *Result = D->getPreviousDecl();
411 
412  // If the declaration is within a class, and the previous declaration was
413  // merged from a different definition of that class, then we don't have a
414  // previous declaration for the purpose of template instantiation.
415  if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
416  D->getLexicalDeclContext() != Result->getLexicalDeclContext())
417  return nullptr;
418 
419  return Result;
420 }
421 
422 Decl *
423 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
424  llvm_unreachable("Translation units cannot be instantiated");
425 }
426 
427 Decl *
428 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
429  llvm_unreachable("pragma comment cannot be instantiated");
430 }
431 
432 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
434  llvm_unreachable("pragma comment cannot be instantiated");
435 }
436 
437 Decl *
438 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
439  llvm_unreachable("extern \"C\" context cannot be instantiated");
440 }
441 
442 Decl *
443 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
444  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
445  D->getIdentifier());
446  Owner->addDecl(Inst);
447  return Inst;
448 }
449 
450 Decl *
451 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
452  llvm_unreachable("Namespaces cannot be instantiated");
453 }
454 
455 Decl *
456 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
457  NamespaceAliasDecl *Inst
458  = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
459  D->getNamespaceLoc(),
460  D->getAliasLoc(),
461  D->getIdentifier(),
462  D->getQualifierLoc(),
463  D->getTargetNameLoc(),
464  D->getNamespace());
465  Owner->addDecl(Inst);
466  return Inst;
467 }
468 
470  bool IsTypeAlias) {
471  bool Invalid = false;
473  if (DI->getType()->isInstantiationDependentType() ||
474  DI->getType()->isVariablyModifiedType()) {
475  DI = SemaRef.SubstType(DI, TemplateArgs,
476  D->getLocation(), D->getDeclName());
477  if (!DI) {
478  Invalid = true;
479  DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
480  }
481  } else {
482  SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
483  }
484 
485  // HACK: g++ has a bug where it gets the value kind of ?: wrong.
486  // libstdc++ relies upon this bug in its implementation of common_type.
487  // If we happen to be processing that implementation, fake up the g++ ?:
488  // semantics. See LWG issue 2141 for more information on the bug.
489  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
490  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
491  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
492  DT->isReferenceType() &&
493  RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
494  RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
495  D->getIdentifier() && D->getIdentifier()->isStr("type") &&
497  // Fold it to the (non-reference) type which g++ would have produced.
498  DI = SemaRef.Context.getTrivialTypeSourceInfo(
499  DI->getType().getNonReferenceType());
500 
501  // Create the new typedef
502  TypedefNameDecl *Typedef;
503  if (IsTypeAlias)
504  Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
505  D->getLocation(), D->getIdentifier(), DI);
506  else
507  Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
508  D->getLocation(), D->getIdentifier(), DI);
509  if (Invalid)
510  Typedef->setInvalidDecl();
511 
512  // If the old typedef was the name for linkage purposes of an anonymous
513  // tag decl, re-establish that relationship for the new typedef.
514  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
515  TagDecl *oldTag = oldTagType->getDecl();
516  if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
517  TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
518  assert(!newTag->hasNameForLinkage());
519  newTag->setTypedefNameForAnonDecl(Typedef);
520  }
521  }
522 
524  NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
525  TemplateArgs);
526  if (!InstPrev)
527  return nullptr;
528 
529  TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
530 
531  // If the typedef types are not identical, reject them.
532  SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
533 
534  Typedef->setPreviousDecl(InstPrevTypedef);
535  }
536 
537  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
538 
539  Typedef->setAccess(D->getAccess());
540 
541  return Typedef;
542 }
543 
544 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
545  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
546  if (Typedef)
547  Owner->addDecl(Typedef);
548  return Typedef;
549 }
550 
551 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
552  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
553  if (Typedef)
554  Owner->addDecl(Typedef);
555  return Typedef;
556 }
557 
558 Decl *
559 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
560  // Create a local instantiation scope for this type alias template, which
561  // will contain the instantiations of the template parameters.
563 
564  TemplateParameterList *TempParams = D->getTemplateParameters();
565  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
566  if (!InstParams)
567  return nullptr;
568 
569  TypeAliasDecl *Pattern = D->getTemplatedDecl();
570 
571  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
572  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
573  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
574  if (!Found.empty()) {
575  PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
576  }
577  }
578 
579  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
580  InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
581  if (!AliasInst)
582  return nullptr;
583 
585  = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
586  D->getDeclName(), InstParams, AliasInst);
587  AliasInst->setDescribedAliasTemplate(Inst);
588  if (PrevAliasTemplate)
589  Inst->setPreviousDecl(PrevAliasTemplate);
590 
591  Inst->setAccess(D->getAccess());
592 
593  if (!PrevAliasTemplate)
595 
596  Owner->addDecl(Inst);
597 
598  return Inst;
599 }
600 
602  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
603 }
604 
606  bool InstantiatingVarTemplate) {
607 
608  // Do substitution on the type of the declaration
609  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
610  TemplateArgs,
611  D->getTypeSpecStartLoc(),
612  D->getDeclName());
613  if (!DI)
614  return nullptr;
615 
616  if (DI->getType()->isFunctionType()) {
617  SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
618  << D->isStaticDataMember() << DI->getType();
619  return nullptr;
620  }
621 
622  DeclContext *DC = Owner;
623  if (D->isLocalExternDecl())
625 
626  // Build the instantiated declaration.
627  VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
628  D->getLocation(), D->getIdentifier(),
629  DI->getType(), DI, D->getStorageClass());
630 
631  // In ARC, infer 'retaining' for variables of retainable type.
632  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
633  SemaRef.inferObjCARCLifetime(Var))
634  Var->setInvalidDecl();
635 
636  // Substitute the nested name specifier, if any.
637  if (SubstQualifier(D, Var))
638  return nullptr;
639 
640  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
641  StartingScope, InstantiatingVarTemplate);
642 
643  if (D->isNRVOVariable()) {
644  QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
645  if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
646  Var->setNRVOVariable(true);
647  }
648 
649  Var->setImplicit(D->isImplicit());
650 
651  return Var;
652 }
653 
654 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
655  AccessSpecDecl* AD
656  = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
658  Owner->addHiddenDecl(AD);
659  return AD;
660 }
661 
662 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
663  bool Invalid = false;
665  if (DI->getType()->isInstantiationDependentType() ||
666  DI->getType()->isVariablyModifiedType()) {
667  DI = SemaRef.SubstType(DI, TemplateArgs,
668  D->getLocation(), D->getDeclName());
669  if (!DI) {
670  DI = D->getTypeSourceInfo();
671  Invalid = true;
672  } else if (DI->getType()->isFunctionType()) {
673  // C++ [temp.arg.type]p3:
674  // If a declaration acquires a function type through a type
675  // dependent on a template-parameter and this causes a
676  // declaration that does not use the syntactic form of a
677  // function declarator to have function type, the program is
678  // ill-formed.
679  SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
680  << DI->getType();
681  Invalid = true;
682  }
683  } else {
684  SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
685  }
686 
687  Expr *BitWidth = D->getBitWidth();
688  if (Invalid)
689  BitWidth = nullptr;
690  else if (BitWidth) {
691  // The bit-width expression is a constant expression.
692  EnterExpressionEvaluationContext Unevaluated(SemaRef,
694 
695  ExprResult InstantiatedBitWidth
696  = SemaRef.SubstExpr(BitWidth, TemplateArgs);
697  if (InstantiatedBitWidth.isInvalid()) {
698  Invalid = true;
699  BitWidth = nullptr;
700  } else
701  BitWidth = InstantiatedBitWidth.getAs<Expr>();
702  }
703 
704  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
705  DI->getType(), DI,
706  cast<RecordDecl>(Owner),
707  D->getLocation(),
708  D->isMutable(),
709  BitWidth,
710  D->getInClassInitStyle(),
711  D->getInnerLocStart(),
712  D->getAccess(),
713  nullptr);
714  if (!Field) {
715  cast<Decl>(Owner)->setInvalidDecl();
716  return nullptr;
717  }
718 
719  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
720 
721  if (Field->hasAttrs())
722  SemaRef.CheckAlignasUnderalignment(Field);
723 
724  if (Invalid)
725  Field->setInvalidDecl();
726 
727  if (!Field->getDeclName()) {
728  // Keep track of where this decl came from.
730  }
731  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
732  if (Parent->isAnonymousStructOrUnion() &&
733  Parent->getRedeclContext()->isFunctionOrMethod())
734  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
735  }
736 
737  Field->setImplicit(D->isImplicit());
738  Field->setAccess(D->getAccess());
739  Owner->addDecl(Field);
740 
741  return Field;
742 }
743 
744 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
745  bool Invalid = false;
747 
748  if (DI->getType()->isVariablyModifiedType()) {
749  SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
750  << D;
751  Invalid = true;
752  } else if (DI->getType()->isInstantiationDependentType()) {
753  DI = SemaRef.SubstType(DI, TemplateArgs,
754  D->getLocation(), D->getDeclName());
755  if (!DI) {
756  DI = D->getTypeSourceInfo();
757  Invalid = true;
758  } else if (DI->getType()->isFunctionType()) {
759  // C++ [temp.arg.type]p3:
760  // If a declaration acquires a function type through a type
761  // dependent on a template-parameter and this causes a
762  // declaration that does not use the syntactic form of a
763  // function declarator to have function type, the program is
764  // ill-formed.
765  SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
766  << DI->getType();
767  Invalid = true;
768  }
769  } else {
770  SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
771  }
772 
774  SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
775  DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
776 
777  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
778  StartingScope);
779 
780  if (Invalid)
781  Property->setInvalidDecl();
782 
783  Property->setAccess(D->getAccess());
784  Owner->addDecl(Property);
785 
786  return Property;
787 }
788 
789 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
790  NamedDecl **NamedChain =
791  new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
792 
793  int i = 0;
794  for (auto *PI : D->chain()) {
795  NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
796  TemplateArgs);
797  if (!Next)
798  return nullptr;
799 
800  NamedChain[i++] = Next;
801  }
802 
803  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
805  SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
806  {NamedChain, D->getChainingSize()});
807 
808  for (const auto *Attr : D->attrs())
809  IndirectField->addAttr(Attr->clone(SemaRef.Context));
810 
811  IndirectField->setImplicit(D->isImplicit());
812  IndirectField->setAccess(D->getAccess());
813  Owner->addDecl(IndirectField);
814  return IndirectField;
815 }
816 
817 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
818  // Handle friend type expressions by simply substituting template
819  // parameters into the pattern type and checking the result.
820  if (TypeSourceInfo *Ty = D->getFriendType()) {
821  TypeSourceInfo *InstTy;
822  // If this is an unsupported friend, don't bother substituting template
823  // arguments into it. The actual type referred to won't be used by any
824  // parts of Clang, and may not be valid for instantiating. Just use the
825  // same info for the instantiated friend.
826  if (D->isUnsupportedFriend()) {
827  InstTy = Ty;
828  } else {
829  InstTy = SemaRef.SubstType(Ty, TemplateArgs,
830  D->getLocation(), DeclarationName());
831  }
832  if (!InstTy)
833  return nullptr;
834 
835  FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
836  D->getFriendLoc(), InstTy);
837  if (!FD)
838  return nullptr;
839 
840  FD->setAccess(AS_public);
842  Owner->addDecl(FD);
843  return FD;
844  }
845 
846  NamedDecl *ND = D->getFriendDecl();
847  assert(ND && "friend decl must be a decl or a type!");
848 
849  // All of the Visit implementations for the various potential friend
850  // declarations have to be carefully written to work for friend
851  // objects, with the most important detail being that the target
852  // decl should almost certainly not be placed in Owner.
853  Decl *NewND = Visit(ND);
854  if (!NewND) return nullptr;
855 
856  FriendDecl *FD =
857  FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
858  cast<NamedDecl>(NewND), D->getFriendLoc());
859  FD->setAccess(AS_public);
861  Owner->addDecl(FD);
862  return FD;
863 }
864 
865 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
866  Expr *AssertExpr = D->getAssertExpr();
867 
868  // The expression in a static assertion is a constant expression.
869  EnterExpressionEvaluationContext Unevaluated(SemaRef,
871 
872  ExprResult InstantiatedAssertExpr
873  = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
874  if (InstantiatedAssertExpr.isInvalid())
875  return nullptr;
876 
877  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
878  InstantiatedAssertExpr.get(),
879  D->getMessage(),
880  D->getRParenLoc(),
881  D->isFailed());
882 }
883 
884 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
885  EnumDecl *PrevDecl = nullptr;
886  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
887  NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
888  PatternPrev,
889  TemplateArgs);
890  if (!Prev) return nullptr;
891  PrevDecl = cast<EnumDecl>(Prev);
892  }
893 
894  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
895  D->getLocation(), D->getIdentifier(),
896  PrevDecl, D->isScoped(),
897  D->isScopedUsingClassTag(), D->isFixed());
898  if (D->isFixed()) {
899  if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
900  // If we have type source information for the underlying type, it means it
901  // has been explicitly set by the user. Perform substitution on it before
902  // moving on.
903  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
904  TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
905  DeclarationName());
906  if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
907  Enum->setIntegerType(SemaRef.Context.IntTy);
908  else
909  Enum->setIntegerTypeSourceInfo(NewTI);
910  } else {
911  assert(!D->getIntegerType()->isDependentType()
912  && "Dependent type without type source info");
913  Enum->setIntegerType(D->getIntegerType());
914  }
915  }
916 
917  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
918 
919  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
920  Enum->setAccess(D->getAccess());
921  // Forward the mangling number from the template to the instantiated decl.
922  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
923  // See if the old tag was defined along with a declarator.
924  // If it did, mark the new tag as being associated with that declarator.
926  SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
927  // See if the old tag was defined along with a typedef.
928  // If it did, mark the new tag as being associated with that typedef.
930  SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
931  if (SubstQualifier(D, Enum)) return nullptr;
932  Owner->addDecl(Enum);
933 
934  EnumDecl *Def = D->getDefinition();
935  if (Def && Def != D) {
936  // If this is an out-of-line definition of an enum member template, check
937  // that the underlying types match in the instantiation of both
938  // declarations.
939  if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
940  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
941  QualType DefnUnderlying =
942  SemaRef.SubstType(TI->getType(), TemplateArgs,
943  UnderlyingLoc, DeclarationName());
944  SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
945  DefnUnderlying,
946  /*EnumUnderlyingIsImplicit=*/false, Enum);
947  }
948  }
949 
950  // C++11 [temp.inst]p1: The implicit instantiation of a class template
951  // specialization causes the implicit instantiation of the declarations, but
952  // not the definitions of scoped member enumerations.
953  //
954  // DR1484 clarifies that enumeration definitions inside of a template
955  // declaration aren't considered entities that can be separately instantiated
956  // from the rest of the entity they are declared inside of.
957  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
959  InstantiateEnumDefinition(Enum, Def);
960  }
961 
962  return Enum;
963 }
964 
966  EnumDecl *Enum, EnumDecl *Pattern) {
967  Enum->startDefinition();
968 
969  // Update the location to refer to the definition.
970  Enum->setLocation(Pattern->getLocation());
971 
972  SmallVector<Decl*, 4> Enumerators;
973 
974  EnumConstantDecl *LastEnumConst = nullptr;
975  for (auto *EC : Pattern->enumerators()) {
976  // The specified value for the enumerator.
977  ExprResult Value((Expr *)nullptr);
978  if (Expr *UninstValue = EC->getInitExpr()) {
979  // The enumerator's value expression is a constant expression.
980  EnterExpressionEvaluationContext Unevaluated(SemaRef,
982 
983  Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
984  }
985 
986  // Drop the initial value and continue.
987  bool isInvalid = false;
988  if (Value.isInvalid()) {
989  Value = nullptr;
990  isInvalid = true;
991  }
992 
993  EnumConstantDecl *EnumConst
994  = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
995  EC->getLocation(), EC->getIdentifier(),
996  Value.get());
997 
998  if (isInvalid) {
999  if (EnumConst)
1000  EnumConst->setInvalidDecl();
1001  Enum->setInvalidDecl();
1002  }
1003 
1004  if (EnumConst) {
1005  SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1006 
1007  EnumConst->setAccess(Enum->getAccess());
1008  Enum->addDecl(EnumConst);
1009  Enumerators.push_back(EnumConst);
1010  LastEnumConst = EnumConst;
1011 
1012  if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1013  !Enum->isScoped()) {
1014  // If the enumeration is within a function or method, record the enum
1015  // constant as a local.
1016  SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1017  }
1018  }
1019  }
1020 
1021  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1022  Enumerators,
1023  nullptr, nullptr);
1024 }
1025 
1026 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1027  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1028 }
1029 
1030 Decl *
1031 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1032  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1033 }
1034 
1035 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1036  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1037 
1038  // Create a local instantiation scope for this class template, which
1039  // will contain the instantiations of the template parameters.
1040  LocalInstantiationScope Scope(SemaRef);
1041  TemplateParameterList *TempParams = D->getTemplateParameters();
1042  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1043  if (!InstParams)
1044  return nullptr;
1045 
1046  CXXRecordDecl *Pattern = D->getTemplatedDecl();
1047 
1048  // Instantiate the qualifier. We have to do this first in case
1049  // we're a friend declaration, because if we are then we need to put
1050  // the new declaration in the appropriate context.
1051  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1052  if (QualifierLoc) {
1053  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1054  TemplateArgs);
1055  if (!QualifierLoc)
1056  return nullptr;
1057  }
1058 
1059  CXXRecordDecl *PrevDecl = nullptr;
1060  ClassTemplateDecl *PrevClassTemplate = nullptr;
1061 
1062  if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1063  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1064  if (!Found.empty()) {
1065  PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1066  if (PrevClassTemplate)
1067  PrevDecl = PrevClassTemplate->getTemplatedDecl();
1068  }
1069  }
1070 
1071  // If this isn't a friend, then it's a member template, in which
1072  // case we just want to build the instantiation in the
1073  // specialization. If it is a friend, we want to build it in
1074  // the appropriate context.
1075  DeclContext *DC = Owner;
1076  if (isFriend) {
1077  if (QualifierLoc) {
1078  CXXScopeSpec SS;
1079  SS.Adopt(QualifierLoc);
1080  DC = SemaRef.computeDeclContext(SS);
1081  if (!DC) return nullptr;
1082  } else {
1083  DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1084  Pattern->getDeclContext(),
1085  TemplateArgs);
1086  }
1087 
1088  // Look for a previous declaration of the template in the owning
1089  // context.
1090  LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1092  SemaRef.LookupQualifiedName(R, DC);
1093 
1094  if (R.isSingleResult()) {
1095  PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1096  if (PrevClassTemplate)
1097  PrevDecl = PrevClassTemplate->getTemplatedDecl();
1098  }
1099 
1100  if (!PrevClassTemplate && QualifierLoc) {
1101  SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1102  << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1103  << QualifierLoc.getSourceRange();
1104  return nullptr;
1105  }
1106 
1107  bool AdoptedPreviousTemplateParams = false;
1108  if (PrevClassTemplate) {
1109  bool Complain = true;
1110 
1111  // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1112  // template for struct std::tr1::__detail::_Map_base, where the
1113  // template parameters of the friend declaration don't match the
1114  // template parameters of the original declaration. In this one
1115  // case, we don't complain about the ill-formed friend
1116  // declaration.
1117  if (isFriend && Pattern->getIdentifier() &&
1118  Pattern->getIdentifier()->isStr("_Map_base") &&
1119  DC->isNamespace() &&
1120  cast<NamespaceDecl>(DC)->getIdentifier() &&
1121  cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1122  DeclContext *DCParent = DC->getParent();
1123  if (DCParent->isNamespace() &&
1124  cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1125  cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1126  if (cast<Decl>(DCParent)->isInStdNamespace())
1127  Complain = false;
1128  }
1129  }
1130 
1131  TemplateParameterList *PrevParams
1132  = PrevClassTemplate->getTemplateParameters();
1133 
1134  // Make sure the parameter lists match.
1135  if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1136  Complain,
1138  if (Complain)
1139  return nullptr;
1140 
1141  AdoptedPreviousTemplateParams = true;
1142  InstParams = PrevParams;
1143  }
1144 
1145  // Do some additional validation, then merge default arguments
1146  // from the existing declarations.
1147  if (!AdoptedPreviousTemplateParams &&
1148  SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1150  return nullptr;
1151  }
1152  }
1153 
1154  CXXRecordDecl *RecordInst
1155  = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1156  Pattern->getLocStart(), Pattern->getLocation(),
1157  Pattern->getIdentifier(), PrevDecl,
1158  /*DelayTypeCreation=*/true);
1159 
1160  if (QualifierLoc)
1161  RecordInst->setQualifierInfo(QualifierLoc);
1162 
1163  ClassTemplateDecl *Inst
1164  = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1165  D->getIdentifier(), InstParams, RecordInst,
1166  PrevClassTemplate);
1167  RecordInst->setDescribedClassTemplate(Inst);
1168 
1169  if (isFriend) {
1170  if (PrevClassTemplate)
1171  Inst->setAccess(PrevClassTemplate->getAccess());
1172  else
1173  Inst->setAccess(D->getAccess());
1174 
1175  Inst->setObjectOfFriendDecl();
1176  // TODO: do we want to track the instantiation progeny of this
1177  // friend target decl?
1178  } else {
1179  Inst->setAccess(D->getAccess());
1180  if (!PrevClassTemplate)
1182  }
1183 
1184  // Trigger creation of the type for the instantiation.
1185  SemaRef.Context.getInjectedClassNameType(RecordInst,
1187 
1188  // Finish handling of friends.
1189  if (isFriend) {
1190  DC->makeDeclVisibleInContext(Inst);
1191  Inst->setLexicalDeclContext(Owner);
1192  RecordInst->setLexicalDeclContext(Owner);
1193  return Inst;
1194  }
1195 
1196  if (D->isOutOfLine()) {
1197  Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1198  RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1199  }
1200 
1201  Owner->addDecl(Inst);
1202 
1203  if (!PrevClassTemplate) {
1204  // Queue up any out-of-line partial specializations of this member
1205  // class template; the client will force their instantiation once
1206  // the enclosing class has been instantiated.
1208  D->getPartialSpecializations(PartialSpecs);
1209  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1210  if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1211  OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1212  }
1213 
1214  return Inst;
1215 }
1216 
1217 Decl *
1218 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1220  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1221 
1222  // Lookup the already-instantiated declaration in the instantiation
1223  // of the class template and return that.
1225  = Owner->lookup(ClassTemplate->getDeclName());
1226  if (Found.empty())
1227  return nullptr;
1228 
1229  ClassTemplateDecl *InstClassTemplate
1230  = dyn_cast<ClassTemplateDecl>(Found.front());
1231  if (!InstClassTemplate)
1232  return nullptr;
1233 
1235  = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1236  return Result;
1237 
1238  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1239 }
1240 
1241 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1242  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1243  "Only static data member templates are allowed.");
1244 
1245  // Create a local instantiation scope for this variable template, which
1246  // will contain the instantiations of the template parameters.
1247  LocalInstantiationScope Scope(SemaRef);
1248  TemplateParameterList *TempParams = D->getTemplateParameters();
1249  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1250  if (!InstParams)
1251  return nullptr;
1252 
1253  VarDecl *Pattern = D->getTemplatedDecl();
1254  VarTemplateDecl *PrevVarTemplate = nullptr;
1255 
1256  if (getPreviousDeclForInstantiation(Pattern)) {
1257  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1258  if (!Found.empty())
1259  PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1260  }
1261 
1262  VarDecl *VarInst =
1263  cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1264  /*InstantiatingVarTemplate=*/true));
1265  if (!VarInst) return nullptr;
1266 
1267  DeclContext *DC = Owner;
1268 
1270  SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1271  VarInst);
1272  VarInst->setDescribedVarTemplate(Inst);
1273  Inst->setPreviousDecl(PrevVarTemplate);
1274 
1275  Inst->setAccess(D->getAccess());
1276  if (!PrevVarTemplate)
1278 
1279  if (D->isOutOfLine()) {
1280  Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1281  VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1282  }
1283 
1284  Owner->addDecl(Inst);
1285 
1286  if (!PrevVarTemplate) {
1287  // Queue up any out-of-line partial specializations of this member
1288  // variable template; the client will force their instantiation once
1289  // the enclosing class has been instantiated.
1291  D->getPartialSpecializations(PartialSpecs);
1292  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1293  if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1294  OutOfLineVarPartialSpecs.push_back(
1295  std::make_pair(Inst, PartialSpecs[I]));
1296  }
1297 
1298  return Inst;
1299 }
1300 
1301 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1303  assert(D->isStaticDataMember() &&
1304  "Only static data member templates are allowed.");
1305 
1306  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1307 
1308  // Lookup the already-instantiated declaration and return that.
1309  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1310  assert(!Found.empty() && "Instantiation found nothing?");
1311 
1312  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1313  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1314 
1316  InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1317  return Result;
1318 
1319  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1320 }
1321 
1322 Decl *
1323 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1324  // Create a local instantiation scope for this function template, which
1325  // will contain the instantiations of the template parameters and then get
1326  // merged with the local instantiation scope for the function template
1327  // itself.
1328  LocalInstantiationScope Scope(SemaRef);
1329 
1330  TemplateParameterList *TempParams = D->getTemplateParameters();
1331  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1332  if (!InstParams)
1333  return nullptr;
1334 
1335  FunctionDecl *Instantiated = nullptr;
1336  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1337  Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1338  InstParams));
1339  else
1340  Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1341  D->getTemplatedDecl(),
1342  InstParams));
1343 
1344  if (!Instantiated)
1345  return nullptr;
1346 
1347  // Link the instantiated function template declaration to the function
1348  // template from which it was instantiated.
1349  FunctionTemplateDecl *InstTemplate
1350  = Instantiated->getDescribedFunctionTemplate();
1351  InstTemplate->setAccess(D->getAccess());
1352  assert(InstTemplate &&
1353  "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1354 
1355  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1356 
1357  // Link the instantiation back to the pattern *unless* this is a
1358  // non-definition friend declaration.
1359  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1360  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1361  InstTemplate->setInstantiatedFromMemberTemplate(D);
1362 
1363  // Make declarations visible in the appropriate context.
1364  if (!isFriend) {
1365  Owner->addDecl(InstTemplate);
1366  } else if (InstTemplate->getDeclContext()->isRecord() &&
1368  SemaRef.CheckFriendAccess(InstTemplate);
1369  }
1370 
1371  return InstTemplate;
1372 }
1373 
1374 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1375  CXXRecordDecl *PrevDecl = nullptr;
1376  if (D->isInjectedClassName())
1377  PrevDecl = cast<CXXRecordDecl>(Owner);
1378  else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1379  NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1380  PatternPrev,
1381  TemplateArgs);
1382  if (!Prev) return nullptr;
1383  PrevDecl = cast<CXXRecordDecl>(Prev);
1384  }
1385 
1386  CXXRecordDecl *Record
1387  = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1388  D->getLocStart(), D->getLocation(),
1389  D->getIdentifier(), PrevDecl);
1390 
1391  // Substitute the nested name specifier, if any.
1392  if (SubstQualifier(D, Record))
1393  return nullptr;
1394 
1395  Record->setImplicit(D->isImplicit());
1396  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1397  // the tag decls introduced by friend class declarations don't have an access
1398  // specifier. Remove once this area of the code gets sorted out.
1399  if (D->getAccess() != AS_none)
1400  Record->setAccess(D->getAccess());
1401  if (!D->isInjectedClassName())
1403 
1404  // If the original function was part of a friend declaration,
1405  // inherit its namespace state.
1406  if (D->getFriendObjectKind())
1407  Record->setObjectOfFriendDecl();
1408 
1409  // Make sure that anonymous structs and unions are recorded.
1410  if (D->isAnonymousStructOrUnion())
1411  Record->setAnonymousStructOrUnion(true);
1412 
1413  if (D->isLocalClass())
1414  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1415 
1416  // Forward the mangling number from the template to the instantiated decl.
1417  SemaRef.Context.setManglingNumber(Record,
1418  SemaRef.Context.getManglingNumber(D));
1419 
1420  // See if the old tag was defined along with a declarator.
1421  // If it did, mark the new tag as being associated with that declarator.
1423  SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1424 
1425  // See if the old tag was defined along with a typedef.
1426  // If it did, mark the new tag as being associated with that typedef.
1428  SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1429 
1430  Owner->addDecl(Record);
1431 
1432  // DR1484 clarifies that the members of a local class are instantiated as part
1433  // of the instantiation of their enclosing entity.
1434  if (D->isCompleteDefinition() && D->isLocalClass()) {
1436  SavedPendingLocalImplicitInstantiations(SemaRef);
1437 
1438  SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1440  /*Complain=*/true);
1441 
1442  SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1444 
1445  // This class may have local implicit instantiations that need to be
1446  // performed within this scope.
1447  SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
1448  }
1449 
1450  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1451 
1452  return Record;
1453 }
1454 
1455 /// \brief Adjust the given function type for an instantiation of the
1456 /// given declaration, to cope with modifications to the function's type that
1457 /// aren't reflected in the type-source information.
1458 ///
1459 /// \param D The declaration we're instantiating.
1460 /// \param TInfo The already-instantiated type.
1462  FunctionDecl *D,
1463  TypeSourceInfo *TInfo) {
1464  const FunctionProtoType *OrigFunc
1465  = D->getType()->castAs<FunctionProtoType>();
1466  const FunctionProtoType *NewFunc
1467  = TInfo->getType()->castAs<FunctionProtoType>();
1468  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1469  return TInfo->getType();
1470 
1471  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1472  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1473  return Context.getFunctionType(NewFunc->getReturnType(),
1474  NewFunc->getParamTypes(), NewEPI);
1475 }
1476 
1477 /// Normal class members are of more specific types and therefore
1478 /// don't make it here. This function serves two purposes:
1479 /// 1) instantiating function templates
1480 /// 2) substituting friend declarations
1482  TemplateParameterList *TemplateParams) {
1483  // Check whether there is already a function template specialization for
1484  // this declaration.
1485  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1486  if (FunctionTemplate && !TemplateParams) {
1487  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1488 
1489  void *InsertPos = nullptr;
1490  FunctionDecl *SpecFunc
1491  = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1492 
1493  // If we already have a function template specialization, return it.
1494  if (SpecFunc)
1495  return SpecFunc;
1496  }
1497 
1498  bool isFriend;
1499  if (FunctionTemplate)
1500  isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1501  else
1502  isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1503 
1504  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1505  Owner->isFunctionOrMethod() ||
1506  !(isa<Decl>(Owner) &&
1507  cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1508  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1509 
1511  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1512  if (!TInfo)
1513  return nullptr;
1514  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1515 
1516  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1517  if (QualifierLoc) {
1518  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1519  TemplateArgs);
1520  if (!QualifierLoc)
1521  return nullptr;
1522  }
1523 
1524  // If we're instantiating a local function declaration, put the result
1525  // in the enclosing namespace; otherwise we need to find the instantiated
1526  // context.
1527  DeclContext *DC;
1528  if (D->isLocalExternDecl()) {
1529  DC = Owner;
1530  SemaRef.adjustContextForLocalExternDecl(DC);
1531  } else if (isFriend && QualifierLoc) {
1532  CXXScopeSpec SS;
1533  SS.Adopt(QualifierLoc);
1534  DC = SemaRef.computeDeclContext(SS);
1535  if (!DC) return nullptr;
1536  } else {
1537  DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1538  TemplateArgs);
1539  }
1540 
1541  FunctionDecl *Function =
1542  FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1543  D->getNameInfo(), T, TInfo,
1546  D->isConstexpr());
1547  Function->setRangeEnd(D->getSourceRange().getEnd());
1548 
1549  if (D->isInlined())
1550  Function->setImplicitlyInline();
1551 
1552  if (QualifierLoc)
1553  Function->setQualifierInfo(QualifierLoc);
1554 
1555  if (D->isLocalExternDecl())
1556  Function->setLocalExternDecl();
1557 
1558  DeclContext *LexicalDC = Owner;
1559  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1560  assert(D->getDeclContext()->isFileContext());
1561  LexicalDC = D->getDeclContext();
1562  }
1563 
1564  Function->setLexicalDeclContext(LexicalDC);
1565 
1566  // Attach the parameters
1567  for (unsigned P = 0; P < Params.size(); ++P)
1568  if (Params[P])
1569  Params[P]->setOwningFunction(Function);
1570  Function->setParams(Params);
1571 
1572  SourceLocation InstantiateAtPOI;
1573  if (TemplateParams) {
1574  // Our resulting instantiation is actually a function template, since we
1575  // are substituting only the outer template parameters. For example, given
1576  //
1577  // template<typename T>
1578  // struct X {
1579  // template<typename U> friend void f(T, U);
1580  // };
1581  //
1582  // X<int> x;
1583  //
1584  // We are instantiating the friend function template "f" within X<int>,
1585  // which means substituting int for T, but leaving "f" as a friend function
1586  // template.
1587  // Build the function template itself.
1588  FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1589  Function->getLocation(),
1590  Function->getDeclName(),
1591  TemplateParams, Function);
1592  Function->setDescribedFunctionTemplate(FunctionTemplate);
1593 
1594  FunctionTemplate->setLexicalDeclContext(LexicalDC);
1595 
1596  if (isFriend && D->isThisDeclarationADefinition()) {
1597  // TODO: should we remember this connection regardless of whether
1598  // the friend declaration provided a body?
1599  FunctionTemplate->setInstantiatedFromMemberTemplate(
1601  }
1602  } else if (FunctionTemplate) {
1603  // Record this function template specialization.
1604  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1605  Function->setFunctionTemplateSpecialization(FunctionTemplate,
1607  Innermost),
1608  /*InsertPos=*/nullptr);
1609  } else if (isFriend) {
1610  // Note, we need this connection even if the friend doesn't have a body.
1611  // Its body may exist but not have been attached yet due to deferred
1612  // parsing.
1613  // FIXME: It might be cleaner to set this when attaching the body to the
1614  // friend function declaration, however that would require finding all the
1615  // instantiations and modifying them.
1616  Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1617  }
1618 
1619  if (InitFunctionInstantiation(Function, D))
1620  Function->setInvalidDecl();
1621 
1622  bool isExplicitSpecialization = false;
1623 
1625  SemaRef, Function->getDeclName(), SourceLocation(),
1626  D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1629 
1632  assert(isFriend && "non-friend has dependent specialization info?");
1633 
1634  // This needs to be set now for future sanity.
1635  Function->setObjectOfFriendDecl();
1636 
1637  // Instantiate the explicit template arguments.
1638  TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1639  Info->getRAngleLoc());
1640  if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1641  ExplicitArgs, TemplateArgs))
1642  return nullptr;
1643 
1644  // Map the candidate templates to their instantiations.
1645  for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1646  Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1647  Info->getTemplate(I),
1648  TemplateArgs);
1649  if (!Temp) return nullptr;
1650 
1651  Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1652  }
1653 
1654  if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1655  &ExplicitArgs,
1656  Previous))
1657  Function->setInvalidDecl();
1658 
1659  isExplicitSpecialization = true;
1660 
1661  } else if (TemplateParams || !FunctionTemplate) {
1662  // Look only into the namespace where the friend would be declared to
1663  // find a previous declaration. This is the innermost enclosing namespace,
1664  // as described in ActOnFriendFunctionDecl.
1665  SemaRef.LookupQualifiedName(Previous, DC);
1666 
1667  // In C++, the previous declaration we find might be a tag type
1668  // (class or enum). In this case, the new declaration will hide the
1669  // tag type. Note that this does does not apply if we're declaring a
1670  // typedef (C++ [dcl.typedef]p4).
1671  if (Previous.isSingleTagDecl())
1672  Previous.clear();
1673  }
1674 
1675  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1676  isExplicitSpecialization);
1677 
1678  NamedDecl *PrincipalDecl = (TemplateParams
1679  ? cast<NamedDecl>(FunctionTemplate)
1680  : Function);
1681 
1682  // If the original function was part of a friend declaration,
1683  // inherit its namespace state and add it to the owner.
1684  if (isFriend) {
1685  PrincipalDecl->setObjectOfFriendDecl();
1686  DC->makeDeclVisibleInContext(PrincipalDecl);
1687 
1688  bool QueuedInstantiation = false;
1689 
1690  // C++11 [temp.friend]p4 (DR329):
1691  // When a function is defined in a friend function declaration in a class
1692  // template, the function is instantiated when the function is odr-used.
1693  // The same restrictions on multiple declarations and definitions that
1694  // apply to non-template function declarations and definitions also apply
1695  // to these implicit definitions.
1696  if (D->isThisDeclarationADefinition()) {
1697  // Check for a function body.
1698  const FunctionDecl *Definition = nullptr;
1699  if (Function->isDefined(Definition) &&
1700  Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1701  SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1702  << Function->getDeclName();
1703  SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1704  }
1705  // Check for redefinitions due to other instantiations of this or
1706  // a similar friend function.
1707  else for (auto R : Function->redecls()) {
1708  if (R == Function)
1709  continue;
1710 
1711  // If some prior declaration of this function has been used, we need
1712  // to instantiate its definition.
1713  if (!QueuedInstantiation && R->isUsed(false)) {
1714  if (MemberSpecializationInfo *MSInfo =
1715  Function->getMemberSpecializationInfo()) {
1716  if (MSInfo->getPointOfInstantiation().isInvalid()) {
1717  SourceLocation Loc = R->getLocation(); // FIXME
1718  MSInfo->setPointOfInstantiation(Loc);
1719  SemaRef.PendingLocalImplicitInstantiations.push_back(
1720  std::make_pair(Function, Loc));
1721  QueuedInstantiation = true;
1722  }
1723  }
1724  }
1725 
1726  // If some prior declaration of this function was a friend with an
1727  // uninstantiated definition, reject it.
1728  if (R->getFriendObjectKind()) {
1729  if (const FunctionDecl *RPattern =
1731  if (RPattern->isDefined(RPattern)) {
1732  SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1733  << Function->getDeclName();
1734  SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1735  break;
1736  }
1737  }
1738  }
1739  }
1740  }
1741  }
1742 
1743  if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1744  DC->makeDeclVisibleInContext(PrincipalDecl);
1745 
1746  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1747  PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1748  PrincipalDecl->setNonMemberOperator();
1749 
1750  assert(!D->isDefaulted() && "only methods should be defaulted");
1751  return Function;
1752 }
1753 
1754 Decl *
1756  TemplateParameterList *TemplateParams,
1757  bool IsClassScopeSpecialization) {
1758  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1759  if (FunctionTemplate && !TemplateParams) {
1760  // We are creating a function template specialization from a function
1761  // template. Check whether there is already a function template
1762  // specialization for this particular set of template arguments.
1763  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1764 
1765  void *InsertPos = nullptr;
1766  FunctionDecl *SpecFunc
1767  = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1768 
1769  // If we already have a function template specialization, return it.
1770  if (SpecFunc)
1771  return SpecFunc;
1772  }
1773 
1774  bool isFriend;
1775  if (FunctionTemplate)
1776  isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1777  else
1778  isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1779 
1780  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1781  !(isa<Decl>(Owner) &&
1782  cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1783  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1784 
1785  // Instantiate enclosing template arguments for friends.
1787  unsigned NumTempParamLists = 0;
1788  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1789  TempParamLists.resize(NumTempParamLists);
1790  for (unsigned I = 0; I != NumTempParamLists; ++I) {
1792  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1793  if (!InstParams)
1794  return nullptr;
1795  TempParamLists[I] = InstParams;
1796  }
1797  }
1798 
1800  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1801  if (!TInfo)
1802  return nullptr;
1803  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1804 
1805  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1806  if (QualifierLoc) {
1807  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1808  TemplateArgs);
1809  if (!QualifierLoc)
1810  return nullptr;
1811  }
1812 
1813  DeclContext *DC = Owner;
1814  if (isFriend) {
1815  if (QualifierLoc) {
1816  CXXScopeSpec SS;
1817  SS.Adopt(QualifierLoc);
1818  DC = SemaRef.computeDeclContext(SS);
1819 
1820  if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1821  return nullptr;
1822  } else {
1823  DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1824  D->getDeclContext(),
1825  TemplateArgs);
1826  }
1827  if (!DC) return nullptr;
1828  }
1829 
1830  // Build the instantiated method declaration.
1831  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1832  CXXMethodDecl *Method = nullptr;
1833 
1834  SourceLocation StartLoc = D->getInnerLocStart();
1835  DeclarationNameInfo NameInfo
1836  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1837  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1838  Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1839  StartLoc, NameInfo, T, TInfo,
1840  Constructor->isExplicit(),
1841  Constructor->isInlineSpecified(),
1842  false, Constructor->isConstexpr());
1843  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1844  Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1845  StartLoc, NameInfo, T, TInfo,
1846  Destructor->isInlineSpecified(),
1847  false);
1848  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1849  Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1850  StartLoc, NameInfo, T, TInfo,
1851  Conversion->isInlineSpecified(),
1852  Conversion->isExplicit(),
1853  Conversion->isConstexpr(),
1854  Conversion->getLocEnd());
1855  } else {
1856  StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1857  Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1858  StartLoc, NameInfo, T, TInfo,
1859  SC, D->isInlineSpecified(),
1860  D->isConstexpr(), D->getLocEnd());
1861  }
1862 
1863  if (D->isInlined())
1864  Method->setImplicitlyInline();
1865 
1866  if (QualifierLoc)
1867  Method->setQualifierInfo(QualifierLoc);
1868 
1869  if (TemplateParams) {
1870  // Our resulting instantiation is actually a function template, since we
1871  // are substituting only the outer template parameters. For example, given
1872  //
1873  // template<typename T>
1874  // struct X {
1875  // template<typename U> void f(T, U);
1876  // };
1877  //
1878  // X<int> x;
1879  //
1880  // We are instantiating the member template "f" within X<int>, which means
1881  // substituting int for T, but leaving "f" as a member function template.
1882  // Build the function template itself.
1883  FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1884  Method->getLocation(),
1885  Method->getDeclName(),
1886  TemplateParams, Method);
1887  if (isFriend) {
1888  FunctionTemplate->setLexicalDeclContext(Owner);
1889  FunctionTemplate->setObjectOfFriendDecl();
1890  } else if (D->isOutOfLine())
1891  FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1892  Method->setDescribedFunctionTemplate(FunctionTemplate);
1893  } else if (FunctionTemplate) {
1894  // Record this function template specialization.
1895  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1896  Method->setFunctionTemplateSpecialization(FunctionTemplate,
1898  Innermost),
1899  /*InsertPos=*/nullptr);
1900  } else if (!isFriend) {
1901  // Record that this is an instantiation of a member function.
1902  Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1903  }
1904 
1905  // If we are instantiating a member function defined
1906  // out-of-line, the instantiation will have the same lexical
1907  // context (which will be a namespace scope) as the template.
1908  if (isFriend) {
1909  if (NumTempParamLists)
1910  Method->setTemplateParameterListsInfo(
1911  SemaRef.Context,
1912  llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
1913 
1914  Method->setLexicalDeclContext(Owner);
1915  Method->setObjectOfFriendDecl();
1916  } else if (D->isOutOfLine())
1917  Method->setLexicalDeclContext(D->getLexicalDeclContext());
1918 
1919  // Attach the parameters
1920  for (unsigned P = 0; P < Params.size(); ++P)
1921  Params[P]->setOwningFunction(Method);
1922  Method->setParams(Params);
1923 
1924  if (InitMethodInstantiation(Method, D))
1925  Method->setInvalidDecl();
1926 
1927  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1929 
1930  if (!FunctionTemplate || TemplateParams || isFriend) {
1931  SemaRef.LookupQualifiedName(Previous, Record);
1932 
1933  // In C++, the previous declaration we find might be a tag type
1934  // (class or enum). In this case, the new declaration will hide the
1935  // tag type. Note that this does does not apply if we're declaring a
1936  // typedef (C++ [dcl.typedef]p4).
1937  if (Previous.isSingleTagDecl())
1938  Previous.clear();
1939  }
1940 
1941  if (!IsClassScopeSpecialization)
1942  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1943 
1944  if (D->isPure())
1945  SemaRef.CheckPureMethod(Method, SourceRange());
1946 
1947  // Propagate access. For a non-friend declaration, the access is
1948  // whatever we're propagating from. For a friend, it should be the
1949  // previous declaration we just found.
1950  if (isFriend && Method->getPreviousDecl())
1951  Method->setAccess(Method->getPreviousDecl()->getAccess());
1952  else
1953  Method->setAccess(D->getAccess());
1954  if (FunctionTemplate)
1955  FunctionTemplate->setAccess(Method->getAccess());
1956 
1957  SemaRef.CheckOverrideControl(Method);
1958 
1959  // If a function is defined as defaulted or deleted, mark it as such now.
1960  if (D->isExplicitlyDefaulted())
1961  SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1962  if (D->isDeletedAsWritten())
1963  SemaRef.SetDeclDeleted(Method, Method->getLocation());
1964 
1965  // If there's a function template, let our caller handle it.
1966  if (FunctionTemplate) {
1967  // do nothing
1968 
1969  // Don't hide a (potentially) valid declaration with an invalid one.
1970  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1971  // do nothing
1972 
1973  // Otherwise, check access to friends and make them visible.
1974  } else if (isFriend) {
1975  // We only need to re-check access for methods which we didn't
1976  // manage to match during parsing.
1977  if (!D->getPreviousDecl())
1978  SemaRef.CheckFriendAccess(Method);
1979 
1980  Record->makeDeclVisibleInContext(Method);
1981 
1982  // Otherwise, add the declaration. We don't need to do this for
1983  // class-scope specializations because we'll have matched them with
1984  // the appropriate template.
1985  } else if (!IsClassScopeSpecialization) {
1986  Owner->addDecl(Method);
1987  }
1988 
1989  return Method;
1990 }
1991 
1992 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1993  return VisitCXXMethodDecl(D);
1994 }
1995 
1996 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1997  return VisitCXXMethodDecl(D);
1998 }
1999 
2000 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2001  return VisitCXXMethodDecl(D);
2002 }
2003 
2004 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2005  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2006  /*ExpectParameterPack=*/ false);
2007 }
2008 
2009 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2010  TemplateTypeParmDecl *D) {
2011  // TODO: don't always clone when decls are refcounted.
2012  assert(D->getTypeForDecl()->isTemplateTypeParmType());
2013 
2014  TemplateTypeParmDecl *Inst =
2015  TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
2016  D->getLocStart(), D->getLocation(),
2017  D->getDepth() - TemplateArgs.getNumLevels(),
2018  D->getIndex(), D->getIdentifier(),
2020  D->isParameterPack());
2021  Inst->setAccess(AS_public);
2022 
2023  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2024  TypeSourceInfo *InstantiatedDefaultArg =
2025  SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2026  D->getDefaultArgumentLoc(), D->getDeclName());
2027  if (InstantiatedDefaultArg)
2028  Inst->setDefaultArgument(InstantiatedDefaultArg);
2029  }
2030 
2031  // Introduce this template parameter's instantiation into the instantiation
2032  // scope.
2033  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2034 
2035  return Inst;
2036 }
2037 
2038 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2040  // Substitute into the type of the non-type template parameter.
2041  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2042  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2043  SmallVector<QualType, 4> ExpandedParameterPackTypes;
2044  bool IsExpandedParameterPack = false;
2045  TypeSourceInfo *DI;
2046  QualType T;
2047  bool Invalid = false;
2048 
2049  if (D->isExpandedParameterPack()) {
2050  // The non-type template parameter pack is an already-expanded pack
2051  // expansion of types. Substitute into each of the expanded types.
2052  ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2053  ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2054  for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2056  TemplateArgs,
2057  D->getLocation(),
2058  D->getDeclName());
2059  if (!NewDI)
2060  return nullptr;
2061 
2062  ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2063  QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
2064  D->getLocation());
2065  if (NewT.isNull())
2066  return nullptr;
2067  ExpandedParameterPackTypes.push_back(NewT);
2068  }
2069 
2070  IsExpandedParameterPack = true;
2071  DI = D->getTypeSourceInfo();
2072  T = DI->getType();
2073  } else if (D->isPackExpansion()) {
2074  // The non-type template parameter pack's type is a pack expansion of types.
2075  // Determine whether we need to expand this parameter pack into separate
2076  // types.
2078  TypeLoc Pattern = Expansion.getPatternLoc();
2080  SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2081 
2082  // Determine whether the set of unexpanded parameter packs can and should
2083  // be expanded.
2084  bool Expand = true;
2085  bool RetainExpansion = false;
2086  Optional<unsigned> OrigNumExpansions
2087  = Expansion.getTypePtr()->getNumExpansions();
2088  Optional<unsigned> NumExpansions = OrigNumExpansions;
2089  if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2090  Pattern.getSourceRange(),
2091  Unexpanded,
2092  TemplateArgs,
2093  Expand, RetainExpansion,
2094  NumExpansions))
2095  return nullptr;
2096 
2097  if (Expand) {
2098  for (unsigned I = 0; I != *NumExpansions; ++I) {
2099  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2100  TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2101  D->getLocation(),
2102  D->getDeclName());
2103  if (!NewDI)
2104  return nullptr;
2105 
2106  ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2108  NewDI->getType(),
2109  D->getLocation());
2110  if (NewT.isNull())
2111  return nullptr;
2112  ExpandedParameterPackTypes.push_back(NewT);
2113  }
2114 
2115  // Note that we have an expanded parameter pack. The "type" of this
2116  // expanded parameter pack is the original expansion type, but callers
2117  // will end up using the expanded parameter pack types for type-checking.
2118  IsExpandedParameterPack = true;
2119  DI = D->getTypeSourceInfo();
2120  T = DI->getType();
2121  } else {
2122  // We cannot fully expand the pack expansion now, so substitute into the
2123  // pattern and create a new pack expansion type.
2124  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2125  TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2126  D->getLocation(),
2127  D->getDeclName());
2128  if (!NewPattern)
2129  return nullptr;
2130 
2131  DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2132  NumExpansions);
2133  if (!DI)
2134  return nullptr;
2135 
2136  T = DI->getType();
2137  }
2138  } else {
2139  // Simple case: substitution into a parameter that is not a parameter pack.
2140  DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2141  D->getLocation(), D->getDeclName());
2142  if (!DI)
2143  return nullptr;
2144 
2145  // Check that this type is acceptable for a non-type template parameter.
2146  T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
2147  D->getLocation());
2148  if (T.isNull()) {
2149  T = SemaRef.Context.IntTy;
2150  Invalid = true;
2151  }
2152  }
2153 
2154  NonTypeTemplateParmDecl *Param;
2155  if (IsExpandedParameterPack)
2157  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2158  D->getDepth() - TemplateArgs.getNumLevels(), D->getPosition(),
2159  D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2160  ExpandedParameterPackTypesAsWritten);
2161  else
2162  Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2163  D->getInnerLocStart(),
2164  D->getLocation(),
2165  D->getDepth() - TemplateArgs.getNumLevels(),
2166  D->getPosition(),
2167  D->getIdentifier(), T,
2168  D->isParameterPack(), DI);
2169 
2170  Param->setAccess(AS_public);
2171  if (Invalid)
2172  Param->setInvalidDecl();
2173 
2174  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2175  EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
2177  ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2178  if (!Value.isInvalid())
2179  Param->setDefaultArgument(Value.get());
2180  }
2181 
2182  // Introduce this template parameter's instantiation into the instantiation
2183  // scope.
2184  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2185  return Param;
2186 }
2187 
2189  Sema &S,
2190  TemplateParameterList *Params,
2192  for (const auto &P : *Params) {
2193  if (P->isTemplateParameterPack())
2194  continue;
2195  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2196  S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2197  Unexpanded);
2198  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2199  collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2200  Unexpanded);
2201  }
2202 }
2203 
2204 Decl *
2205 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2207  // Instantiate the template parameter list of the template template parameter.
2208  TemplateParameterList *TempParams = D->getTemplateParameters();
2209  TemplateParameterList *InstParams;
2211 
2212  bool IsExpandedParameterPack = false;
2213 
2214  if (D->isExpandedParameterPack()) {
2215  // The template template parameter pack is an already-expanded pack
2216  // expansion of template parameters. Substitute into each of the expanded
2217  // parameters.
2218  ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2219  for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2220  I != N; ++I) {
2221  LocalInstantiationScope Scope(SemaRef);
2222  TemplateParameterList *Expansion =
2224  if (!Expansion)
2225  return nullptr;
2226  ExpandedParams.push_back(Expansion);
2227  }
2228 
2229  IsExpandedParameterPack = true;
2230  InstParams = TempParams;
2231  } else if (D->isPackExpansion()) {
2232  // The template template parameter pack expands to a pack of template
2233  // template parameters. Determine whether we need to expand this parameter
2234  // pack into separate parameters.
2237  Unexpanded);
2238 
2239  // Determine whether the set of unexpanded parameter packs can and should
2240  // be expanded.
2241  bool Expand = true;
2242  bool RetainExpansion = false;
2243  Optional<unsigned> NumExpansions;
2244  if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2245  TempParams->getSourceRange(),
2246  Unexpanded,
2247  TemplateArgs,
2248  Expand, RetainExpansion,
2249  NumExpansions))
2250  return nullptr;
2251 
2252  if (Expand) {
2253  for (unsigned I = 0; I != *NumExpansions; ++I) {
2254  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2255  LocalInstantiationScope Scope(SemaRef);
2256  TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2257  if (!Expansion)
2258  return nullptr;
2259  ExpandedParams.push_back(Expansion);
2260  }
2261 
2262  // Note that we have an expanded parameter pack. The "type" of this
2263  // expanded parameter pack is the original expansion type, but callers
2264  // will end up using the expanded parameter pack types for type-checking.
2265  IsExpandedParameterPack = true;
2266  InstParams = TempParams;
2267  } else {
2268  // We cannot fully expand the pack expansion now, so just substitute
2269  // into the pattern.
2270  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2271 
2272  LocalInstantiationScope Scope(SemaRef);
2273  InstParams = SubstTemplateParams(TempParams);
2274  if (!InstParams)
2275  return nullptr;
2276  }
2277  } else {
2278  // Perform the actual substitution of template parameters within a new,
2279  // local instantiation scope.
2280  LocalInstantiationScope Scope(SemaRef);
2281  InstParams = SubstTemplateParams(TempParams);
2282  if (!InstParams)
2283  return nullptr;
2284  }
2285 
2286  // Build the template template parameter.
2287  TemplateTemplateParmDecl *Param;
2288  if (IsExpandedParameterPack)
2289  Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2290  D->getLocation(),
2291  D->getDepth() - TemplateArgs.getNumLevels(),
2292  D->getPosition(),
2293  D->getIdentifier(), InstParams,
2294  ExpandedParams);
2295  else
2296  Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2297  D->getLocation(),
2298  D->getDepth() - TemplateArgs.getNumLevels(),
2299  D->getPosition(),
2300  D->isParameterPack(),
2301  D->getIdentifier(), InstParams);
2302  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2303  NestedNameSpecifierLoc QualifierLoc =
2305  QualifierLoc =
2306  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2307  TemplateName TName = SemaRef.SubstTemplateName(
2308  QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2309  D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2310  if (!TName.isNull())
2311  Param->setDefaultArgument(
2312  SemaRef.Context,
2316  }
2317  Param->setAccess(AS_public);
2318 
2319  // Introduce this template parameter's instantiation into the instantiation
2320  // scope.
2321  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2322 
2323  return Param;
2324 }
2325 
2326 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2327  // Using directives are never dependent (and never contain any types or
2328  // expressions), so they require no explicit instantiation work.
2329 
2330  UsingDirectiveDecl *Inst
2331  = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2333  D->getQualifierLoc(),
2334  D->getIdentLocation(),
2335  D->getNominatedNamespace(),
2336  D->getCommonAncestor());
2337 
2338  // Add the using directive to its declaration context
2339  // only if this is not a function or method.
2340  if (!Owner->isFunctionOrMethod())
2341  Owner->addDecl(Inst);
2342 
2343  return Inst;
2344 }
2345 
2346 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2347 
2348  // The nested name specifier may be dependent, for example
2349  // template <typename T> struct t {
2350  // struct s1 { T f1(); };
2351  // struct s2 : s1 { using s1::f1; };
2352  // };
2353  // template struct t<int>;
2354  // Here, in using s1::f1, s1 refers to t<T>::s1;
2355  // we need to substitute for t<int>::s1.
2356  NestedNameSpecifierLoc QualifierLoc
2358  TemplateArgs);
2359  if (!QualifierLoc)
2360  return nullptr;
2361 
2362  // For an inheriting constructor declaration, the name of the using
2363  // declaration is the name of a constructor in this class, not in the
2364  // base class.
2365  DeclarationNameInfo NameInfo = D->getNameInfo();
2367  if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2369  SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2370 
2371  // We only need to do redeclaration lookups if we're in a class
2372  // scope (in fact, it's not really even possible in non-class
2373  // scopes).
2374  bool CheckRedeclaration = Owner->isRecord();
2375 
2376  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2378 
2379  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2380  D->getUsingLoc(),
2381  QualifierLoc,
2382  NameInfo,
2383  D->hasTypename());
2384 
2385  CXXScopeSpec SS;
2386  SS.Adopt(QualifierLoc);
2387  if (CheckRedeclaration) {
2388  Prev.setHideTags(false);
2389  SemaRef.LookupQualifiedName(Prev, Owner);
2390 
2391  // Check for invalid redeclarations.
2392  if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2393  D->hasTypename(), SS,
2394  D->getLocation(), Prev))
2395  NewUD->setInvalidDecl();
2396 
2397  }
2398 
2399  if (!NewUD->isInvalidDecl() &&
2400  SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2401  D->getLocation()))
2402  NewUD->setInvalidDecl();
2403 
2404  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2405  NewUD->setAccess(D->getAccess());
2406  Owner->addDecl(NewUD);
2407 
2408  // Don't process the shadow decls for an invalid decl.
2409  if (NewUD->isInvalidDecl())
2410  return NewUD;
2411 
2412  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2413  SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2414 
2415  bool isFunctionScope = Owner->isFunctionOrMethod();
2416 
2417  // Process the shadow decls.
2418  for (auto *Shadow : D->shadows()) {
2419  // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2420  // reconstruct it in the case where it matters.
2421  NamedDecl *OldTarget = Shadow->getTargetDecl();
2422  if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2423  if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2424  OldTarget = BaseShadow;
2425 
2426  NamedDecl *InstTarget =
2427  cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2428  Shadow->getLocation(), OldTarget, TemplateArgs));
2429  if (!InstTarget)
2430  return nullptr;
2431 
2432  UsingShadowDecl *PrevDecl = nullptr;
2433  if (CheckRedeclaration) {
2434  if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2435  continue;
2436  } else if (UsingShadowDecl *OldPrev =
2438  PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2439  Shadow->getLocation(), OldPrev, TemplateArgs));
2440  }
2441 
2442  UsingShadowDecl *InstShadow =
2443  SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2444  PrevDecl);
2445  SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2446 
2447  if (isFunctionScope)
2448  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2449  }
2450 
2451  return NewUD;
2452 }
2453 
2454 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2455  // Ignore these; we handle them in bulk when processing the UsingDecl.
2456  return nullptr;
2457 }
2458 
2459 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2461  // Ignore these; we handle them in bulk when processing the UsingDecl.
2462  return nullptr;
2463 }
2464 
2465 Decl * TemplateDeclInstantiator
2466  ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2467  NestedNameSpecifierLoc QualifierLoc
2469  TemplateArgs);
2470  if (!QualifierLoc)
2471  return nullptr;
2472 
2473  CXXScopeSpec SS;
2474  SS.Adopt(QualifierLoc);
2475 
2476  // Since NameInfo refers to a typename, it cannot be a C++ special name.
2477  // Hence, no transformation is required for it.
2478  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2479  NamedDecl *UD =
2480  SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2481  D->getUsingLoc(), SS, NameInfo, nullptr,
2482  /*instantiation*/ true,
2483  /*typename*/ true, D->getTypenameLoc());
2484  if (UD)
2485  SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2486 
2487  return UD;
2488 }
2489 
2490 Decl * TemplateDeclInstantiator
2491  ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2492  NestedNameSpecifierLoc QualifierLoc
2493  = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2494  if (!QualifierLoc)
2495  return nullptr;
2496 
2497  CXXScopeSpec SS;
2498  SS.Adopt(QualifierLoc);
2499 
2500  DeclarationNameInfo NameInfo
2501  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2502 
2503  NamedDecl *UD =
2504  SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2505  D->getUsingLoc(), SS, NameInfo, nullptr,
2506  /*instantiation*/ true,
2507  /*typename*/ false, SourceLocation());
2508  if (UD)
2509  SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2510 
2511  return UD;
2512 }
2513 
2514 
2515 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2517  CXXMethodDecl *OldFD = Decl->getSpecialization();
2518  CXXMethodDecl *NewFD =
2519  cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2520  if (!NewFD)
2521  return nullptr;
2522 
2525 
2526  TemplateArgumentListInfo TemplateArgs;
2527  TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2528  if (Decl->hasExplicitTemplateArgs()) {
2529  TemplateArgs = Decl->templateArgs();
2530  TemplateArgsPtr = &TemplateArgs;
2531  }
2532 
2533  SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2534  if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2535  Previous)) {
2536  NewFD->setInvalidDecl();
2537  return NewFD;
2538  }
2539 
2540  // Associate the specialization with the pattern.
2541  FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2542  assert(Specialization && "Class scope Specialization is null");
2543  SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2544 
2545  return NewFD;
2546 }
2547 
2548 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2549  OMPThreadPrivateDecl *D) {
2551  for (auto *I : D->varlists()) {
2552  Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2553  assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2554  Vars.push_back(Var);
2555  }
2556 
2557  OMPThreadPrivateDecl *TD =
2558  SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2559 
2560  TD->setAccess(AS_public);
2561  Owner->addDecl(TD);
2562 
2563  return TD;
2564 }
2565 
2566 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2568  // Instantiate type and check if it is allowed.
2569  QualType SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2570  D->getLocation(),
2571  ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
2572  D->getLocation(), DeclarationName())));
2573  if (SubstReductionType.isNull())
2574  return nullptr;
2575  bool IsCorrect = !SubstReductionType.isNull();
2576  // Create instantiated copy.
2577  std::pair<QualType, SourceLocation> ReductionTypes[] = {
2578  std::make_pair(SubstReductionType, D->getLocation())};
2579  auto *PrevDeclInScope = D->getPrevDeclInScope();
2580  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2581  PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2582  SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2583  ->get<Decl *>());
2584  }
2585  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2586  /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2587  PrevDeclInScope);
2588  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2589  if (isDeclWithinFunction(NewDRD))
2590  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2591  Expr *SubstCombiner = nullptr;
2592  Expr *SubstInitializer = nullptr;
2593  // Combiners instantiation sequence.
2594  if (D->getCombiner()) {
2596  /*S=*/nullptr, NewDRD);
2597  const char *Names[] = {"omp_in", "omp_out"};
2598  for (auto &Name : Names) {
2599  DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2600  auto OldLookup = D->lookup(DN);
2601  auto Lookup = NewDRD->lookup(DN);
2602  if (!OldLookup.empty() && !Lookup.empty()) {
2603  assert(Lookup.size() == 1 && OldLookup.size() == 1);
2604  SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldLookup.front(),
2605  Lookup.front());
2606  }
2607  }
2608  SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
2609  SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
2610  // Initializers instantiation sequence.
2611  if (D->getInitializer()) {
2613  /*S=*/nullptr, NewDRD);
2614  const char *Names[] = {"omp_orig", "omp_priv"};
2615  for (auto &Name : Names) {
2616  DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2617  auto OldLookup = D->lookup(DN);
2618  auto Lookup = NewDRD->lookup(DN);
2619  if (!OldLookup.empty() && !Lookup.empty()) {
2620  assert(Lookup.size() == 1 && OldLookup.size() == 1);
2622  OldLookup.front(), Lookup.front());
2623  }
2624  }
2625  SubstInitializer =
2626  SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
2628  SubstInitializer);
2629  }
2630  IsCorrect = IsCorrect && SubstCombiner &&
2631  (!D->getInitializer() || SubstInitializer);
2632  } else
2633  IsCorrect = false;
2634 
2635  (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
2636  IsCorrect);
2637 
2638  return NewDRD;
2639 }
2640 
2641 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2642  OMPCapturedExprDecl * /*D*/) {
2643  llvm_unreachable("Should not be met in templates");
2644 }
2645 
2647  return VisitFunctionDecl(D, nullptr);
2648 }
2649 
2651  return VisitCXXMethodDecl(D, nullptr);
2652 }
2653 
2654 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2655  llvm_unreachable("There are only CXXRecordDecls in C++");
2656 }
2657 
2658 Decl *
2659 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2661  // As a MS extension, we permit class-scope explicit specialization
2662  // of member class templates.
2663  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2664  assert(ClassTemplate->getDeclContext()->isRecord() &&
2666  "can only instantiate an explicit specialization "
2667  "for a member class template");
2668 
2669  // Lookup the already-instantiated declaration in the instantiation
2670  // of the class template. FIXME: Diagnose or assert if this fails?
2672  = Owner->lookup(ClassTemplate->getDeclName());
2673  if (Found.empty())
2674  return nullptr;
2675  ClassTemplateDecl *InstClassTemplate
2676  = dyn_cast<ClassTemplateDecl>(Found.front());
2677  if (!InstClassTemplate)
2678  return nullptr;
2679 
2680  // Substitute into the template arguments of the class template explicit
2681  // specialization.
2683  castAs<TemplateSpecializationTypeLoc>();
2684  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2685  Loc.getRAngleLoc());
2687  for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2688  ArgLocs.push_back(Loc.getArgLoc(I));
2689  if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2690  InstTemplateArgs, TemplateArgs))
2691  return nullptr;
2692 
2693  // Check that the template argument list is well-formed for this
2694  // class template.
2696  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2697  D->getLocation(),
2698  InstTemplateArgs,
2699  false,
2700  Converted))
2701  return nullptr;
2702 
2703  // Figure out where to insert this class template explicit specialization
2704  // in the member template's set of class template explicit specializations.
2705  void *InsertPos = nullptr;
2707  InstClassTemplate->findSpecialization(Converted, InsertPos);
2708 
2709  // Check whether we've already seen a conflicting instantiation of this
2710  // declaration (for instance, if there was a prior implicit instantiation).
2711  bool Ignored;
2712  if (PrevDecl &&
2713  SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2714  D->getSpecializationKind(),
2715  PrevDecl,
2716  PrevDecl->getSpecializationKind(),
2717  PrevDecl->getPointOfInstantiation(),
2718  Ignored))
2719  return nullptr;
2720 
2721  // If PrevDecl was a definition and D is also a definition, diagnose.
2722  // This happens in cases like:
2723  //
2724  // template<typename T, typename U>
2725  // struct Outer {
2726  // template<typename X> struct Inner;
2727  // template<> struct Inner<T> {};
2728  // template<> struct Inner<U> {};
2729  // };
2730  //
2731  // Outer<int, int> outer; // error: the explicit specializations of Inner
2732  // // have the same signature.
2733  if (PrevDecl && PrevDecl->getDefinition() &&
2735  SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2736  SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2737  diag::note_previous_definition);
2738  return nullptr;
2739  }
2740 
2741  // Create the class template partial specialization declaration.
2744  D->getTagKind(),
2745  Owner,
2746  D->getLocStart(),
2747  D->getLocation(),
2748  InstClassTemplate,
2749  Converted,
2750  PrevDecl);
2751 
2752  // Add this partial specialization to the set of class template partial
2753  // specializations.
2754  if (!PrevDecl)
2755  InstClassTemplate->AddSpecialization(InstD, InsertPos);
2756 
2757  // Substitute the nested name specifier, if any.
2758  if (SubstQualifier(D, InstD))
2759  return nullptr;
2760 
2761  // Build the canonical type that describes the converted template
2762  // arguments of the class template explicit specialization.
2763  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2764  TemplateName(InstClassTemplate), Converted,
2765  SemaRef.Context.getRecordType(InstD));
2766 
2767  // Build the fully-sugared type for this class template
2768  // specialization as the user wrote in the specialization
2769  // itself. This means that we'll pretty-print the type retrieved
2770  // from the specialization's declaration the way that the user
2771  // actually wrote the specialization, rather than formatting the
2772  // name based on the "canonical" representation used to store the
2773  // template arguments in the specialization.
2775  TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2776  CanonType);
2777 
2778  InstD->setAccess(D->getAccess());
2779  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2781  InstD->setTypeAsWritten(WrittenTy);
2782  InstD->setExternLoc(D->getExternLoc());
2784 
2785  Owner->addDecl(InstD);
2786 
2787  // Instantiate the members of the class-scope explicit specialization eagerly.
2788  // We don't have support for lazy instantiation of an explicit specialization
2789  // yet, and MSVC eagerly instantiates in this case.
2790  if (D->isThisDeclarationADefinition() &&
2791  SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2793  /*Complain=*/true))
2794  return nullptr;
2795 
2796  return InstD;
2797 }
2798 
2801 
2802  TemplateArgumentListInfo VarTemplateArgsInfo;
2803  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2804  assert(VarTemplate &&
2805  "A template specialization without specialized template?");
2806 
2807  // Substitute the current template arguments.
2808  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2809  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2810  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2811 
2812  if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2813  TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2814  return nullptr;
2815 
2816  // Check that the template argument list is well-formed for this template.
2818  if (SemaRef.CheckTemplateArgumentList(
2819  VarTemplate, VarTemplate->getLocStart(),
2820  const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2821  Converted))
2822  return nullptr;
2823 
2824  // Find the variable template specialization declaration that
2825  // corresponds to these arguments.
2826  void *InsertPos = nullptr;
2827  if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2828  Converted, InsertPos))
2829  // If we already have a variable template specialization, return it.
2830  return VarSpec;
2831 
2832  return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2833  VarTemplateArgsInfo, Converted);
2834 }
2835 
2837  VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2838  const TemplateArgumentListInfo &TemplateArgsInfo,
2839  ArrayRef<TemplateArgument> Converted) {
2840 
2841  // Do substitution on the type of the declaration
2842  TypeSourceInfo *DI =
2843  SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2844  D->getTypeSpecStartLoc(), D->getDeclName());
2845  if (!DI)
2846  return nullptr;
2847 
2848  if (DI->getType()->isFunctionType()) {
2849  SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2850  << D->isStaticDataMember() << DI->getType();
2851  return nullptr;
2852  }
2853 
2854  // Build the instantiated declaration
2856  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2857  VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
2858  Var->setTemplateArgsInfo(TemplateArgsInfo);
2859  if (InsertPos)
2860  VarTemplate->AddSpecialization(Var, InsertPos);
2861 
2862  // Substitute the nested name specifier, if any.
2863  if (SubstQualifier(D, Var))
2864  return nullptr;
2865 
2866  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2867  Owner, StartingScope);
2868 
2869  return Var;
2870 }
2871 
2872 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2873  llvm_unreachable("@defs is not supported in Objective-C++");
2874 }
2875 
2876 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2877  // FIXME: We need to be able to instantiate FriendTemplateDecls.
2878  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2880  "cannot instantiate %0 yet");
2881  SemaRef.Diag(D->getLocation(), DiagID)
2882  << D->getDeclKindName();
2883 
2884  return nullptr;
2885 }
2886 
2888  llvm_unreachable("Unexpected decl");
2889 }
2890 
2891 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2892  const MultiLevelTemplateArgumentList &TemplateArgs) {
2893  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2894  if (D->isInvalidDecl())
2895  return nullptr;
2896 
2897  return Instantiator.Visit(D);
2898 }
2899 
2900 /// \brief Instantiates a nested template parameter list in the current
2901 /// instantiation context.
2902 ///
2903 /// \param L The parameter list to instantiate
2904 ///
2905 /// \returns NULL if there was an error
2908  // Get errors for all the parameters before bailing out.
2909  bool Invalid = false;
2910 
2911  unsigned N = L->size();
2912  typedef SmallVector<NamedDecl *, 8> ParamVector;
2913  ParamVector Params;
2914  Params.reserve(N);
2915  for (auto &P : *L) {
2916  NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
2917  Params.push_back(D);
2918  Invalid = Invalid || !D || D->isInvalidDecl();
2919  }
2920 
2921  // Clean up if we had an error.
2922  if (Invalid)
2923  return nullptr;
2924 
2925  TemplateParameterList *InstL
2926  = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2927  L->getLAngleLoc(), Params,
2928  L->getRAngleLoc());
2929  return InstL;
2930 }
2931 
2932 /// \brief Instantiate the declaration of a class template partial
2933 /// specialization.
2934 ///
2935 /// \param ClassTemplate the (instantiated) class template that is partially
2936 // specialized by the instantiation of \p PartialSpec.
2937 ///
2938 /// \param PartialSpec the (uninstantiated) class template partial
2939 /// specialization that we are instantiating.
2940 ///
2941 /// \returns The instantiated partial specialization, if successful; otherwise,
2942 /// NULL to indicate an error.
2945  ClassTemplateDecl *ClassTemplate,
2947  // Create a local instantiation scope for this class template partial
2948  // specialization, which will contain the instantiations of the template
2949  // parameters.
2950  LocalInstantiationScope Scope(SemaRef);
2951 
2952  // Substitute into the template parameters of the class template partial
2953  // specialization.
2954  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2955  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2956  if (!InstParams)
2957  return nullptr;
2958 
2959  // Substitute into the template arguments of the class template partial
2960  // specialization.
2961  const ASTTemplateArgumentListInfo *TemplArgInfo
2962  = PartialSpec->getTemplateArgsAsWritten();
2963  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2964  TemplArgInfo->RAngleLoc);
2965  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2966  TemplArgInfo->NumTemplateArgs,
2967  InstTemplateArgs, TemplateArgs))
2968  return nullptr;
2969 
2970  // Check that the template argument list is well-formed for this
2971  // class template.
2973  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2974  PartialSpec->getLocation(),
2975  InstTemplateArgs,
2976  false,
2977  Converted))
2978  return nullptr;
2979 
2980  // Figure out where to insert this class template partial specialization
2981  // in the member template's set of class template partial specializations.
2982  void *InsertPos = nullptr;
2984  = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2985 
2986  // Build the canonical type that describes the converted template
2987  // arguments of the class template partial specialization.
2988  QualType CanonType
2989  = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2990  Converted);
2991 
2992  // Build the fully-sugared type for this class template
2993  // specialization as the user wrote in the specialization
2994  // itself. This means that we'll pretty-print the type retrieved
2995  // from the specialization's declaration the way that the user
2996  // actually wrote the specialization, rather than formatting the
2997  // name based on the "canonical" representation used to store the
2998  // template arguments in the specialization.
2999  TypeSourceInfo *WrittenTy
3001  TemplateName(ClassTemplate),
3002  PartialSpec->getLocation(),
3003  InstTemplateArgs,
3004  CanonType);
3005 
3006  if (PrevDecl) {
3007  // We've already seen a partial specialization with the same template
3008  // parameters and template arguments. This can happen, for example, when
3009  // substituting the outer template arguments ends up causing two
3010  // class template partial specializations of a member class template
3011  // to have identical forms, e.g.,
3012  //
3013  // template<typename T, typename U>
3014  // struct Outer {
3015  // template<typename X, typename Y> struct Inner;
3016  // template<typename Y> struct Inner<T, Y>;
3017  // template<typename Y> struct Inner<U, Y>;
3018  // };
3019  //
3020  // Outer<int, int> outer; // error: the partial specializations of Inner
3021  // // have the same signature.
3022  SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3023  << WrittenTy->getType();
3024  SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3025  << SemaRef.Context.getTypeDeclType(PrevDecl);
3026  return nullptr;
3027  }
3028 
3029 
3030  // Create the class template partial specialization declaration.
3033  PartialSpec->getTagKind(),
3034  Owner,
3035  PartialSpec->getLocStart(),
3036  PartialSpec->getLocation(),
3037  InstParams,
3038  ClassTemplate,
3039  Converted,
3040  InstTemplateArgs,
3041  CanonType,
3042  nullptr);
3043  // Substitute the nested name specifier, if any.
3044  if (SubstQualifier(PartialSpec, InstPartialSpec))
3045  return nullptr;
3046 
3047  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3048  InstPartialSpec->setTypeAsWritten(WrittenTy);
3049 
3050  // Add this partial specialization to the set of class template partial
3051  // specializations.
3052  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3053  /*InsertPos=*/nullptr);
3054  return InstPartialSpec;
3055 }
3056 
3057 /// \brief Instantiate the declaration of a variable template partial
3058 /// specialization.
3059 ///
3060 /// \param VarTemplate the (instantiated) variable template that is partially
3061 /// specialized by the instantiation of \p PartialSpec.
3062 ///
3063 /// \param PartialSpec the (uninstantiated) variable template partial
3064 /// specialization that we are instantiating.
3065 ///
3066 /// \returns The instantiated partial specialization, if successful; otherwise,
3067 /// NULL to indicate an error.
3070  VarTemplateDecl *VarTemplate,
3071  VarTemplatePartialSpecializationDecl *PartialSpec) {
3072  // Create a local instantiation scope for this variable template partial
3073  // specialization, which will contain the instantiations of the template
3074  // parameters.
3075  LocalInstantiationScope Scope(SemaRef);
3076 
3077  // Substitute into the template parameters of the variable template partial
3078  // specialization.
3079  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3080  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3081  if (!InstParams)
3082  return nullptr;
3083 
3084  // Substitute into the template arguments of the variable template partial
3085  // specialization.
3086  const ASTTemplateArgumentListInfo *TemplArgInfo
3087  = PartialSpec->getTemplateArgsAsWritten();
3088  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3089  TemplArgInfo->RAngleLoc);
3090  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3091  TemplArgInfo->NumTemplateArgs,
3092  InstTemplateArgs, TemplateArgs))
3093  return nullptr;
3094 
3095  // Check that the template argument list is well-formed for this
3096  // class template.
3098  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3099  InstTemplateArgs, false, Converted))
3100  return nullptr;
3101 
3102  // Figure out where to insert this variable template partial specialization
3103  // in the member template's set of variable template partial specializations.
3104  void *InsertPos = nullptr;
3105  VarTemplateSpecializationDecl *PrevDecl =
3106  VarTemplate->findPartialSpecialization(Converted, InsertPos);
3107 
3108  // Build the canonical type that describes the converted template
3109  // arguments of the variable template partial specialization.
3110  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3111  TemplateName(VarTemplate), Converted);
3112 
3113  // Build the fully-sugared type for this variable template
3114  // specialization as the user wrote in the specialization
3115  // itself. This means that we'll pretty-print the type retrieved
3116  // from the specialization's declaration the way that the user
3117  // actually wrote the specialization, rather than formatting the
3118  // name based on the "canonical" representation used to store the
3119  // template arguments in the specialization.
3121  TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3122  CanonType);
3123 
3124  if (PrevDecl) {
3125  // We've already seen a partial specialization with the same template
3126  // parameters and template arguments. This can happen, for example, when
3127  // substituting the outer template arguments ends up causing two
3128  // variable template partial specializations of a member variable template
3129  // to have identical forms, e.g.,
3130  //
3131  // template<typename T, typename U>
3132  // struct Outer {
3133  // template<typename X, typename Y> pair<X,Y> p;
3134  // template<typename Y> pair<T, Y> p;
3135  // template<typename Y> pair<U, Y> p;
3136  // };
3137  //
3138  // Outer<int, int> outer; // error: the partial specializations of Inner
3139  // // have the same signature.
3140  SemaRef.Diag(PartialSpec->getLocation(),
3141  diag::err_var_partial_spec_redeclared)
3142  << WrittenTy->getType();
3143  SemaRef.Diag(PrevDecl->getLocation(),
3144  diag::note_var_prev_partial_spec_here);
3145  return nullptr;
3146  }
3147 
3148  // Do substitution on the type of the declaration
3149  TypeSourceInfo *DI = SemaRef.SubstType(
3150  PartialSpec->getTypeSourceInfo(), TemplateArgs,
3151  PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3152  if (!DI)
3153  return nullptr;
3154 
3155  if (DI->getType()->isFunctionType()) {
3156  SemaRef.Diag(PartialSpec->getLocation(),
3157  diag::err_variable_instantiates_to_function)
3158  << PartialSpec->isStaticDataMember() << DI->getType();
3159  return nullptr;
3160  }
3161 
3162  // Create the variable template partial specialization declaration.
3163  VarTemplatePartialSpecializationDecl *InstPartialSpec =
3165  SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3166  PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3167  DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3168 
3169  // Substitute the nested name specifier, if any.
3170  if (SubstQualifier(PartialSpec, InstPartialSpec))
3171  return nullptr;
3172 
3173  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3174  InstPartialSpec->setTypeAsWritten(WrittenTy);
3175 
3176  // Add this partial specialization to the set of variable template partial
3177  // specializations. The instantiation of the initializer is not necessary.
3178  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3179 
3180  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3181  LateAttrs, Owner, StartingScope);
3182 
3183  return InstPartialSpec;
3184 }
3185 
3189  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3190  assert(OldTInfo && "substituting function without type source info");
3191  assert(Params.empty() && "parameter vector is non-empty at start");
3192 
3193  CXXRecordDecl *ThisContext = nullptr;
3194  unsigned ThisTypeQuals = 0;
3195  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3196  ThisContext = cast<CXXRecordDecl>(Owner);
3197  ThisTypeQuals = Method->getTypeQualifiers();
3198  }
3199 
3200  TypeSourceInfo *NewTInfo
3201  = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3202  D->getTypeSpecStartLoc(),
3203  D->getDeclName(),
3204  ThisContext, ThisTypeQuals);
3205  if (!NewTInfo)
3206  return nullptr;
3207 
3208  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3209  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3210  if (NewTInfo != OldTInfo) {
3211  // Get parameters from the new type info.
3212  TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3213  FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3214  unsigned NewIdx = 0;
3215  for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3216  OldIdx != NumOldParams; ++OldIdx) {
3217  ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3219 
3220  Optional<unsigned> NumArgumentsInExpansion;
3221  if (OldParam->isParameterPack())
3222  NumArgumentsInExpansion =
3223  SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3224  TemplateArgs);
3225  if (!NumArgumentsInExpansion) {
3226  // Simple case: normal parameter, or a parameter pack that's
3227  // instantiated to a (still-dependent) parameter pack.
3228  ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3229  Params.push_back(NewParam);
3230  Scope->InstantiatedLocal(OldParam, NewParam);
3231  } else {
3232  // Parameter pack expansion: make the instantiation an argument pack.
3233  Scope->MakeInstantiatedLocalArgPack(OldParam);
3234  for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3235  ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3236  Params.push_back(NewParam);
3237  Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3238  }
3239  }
3240  }
3241  } else {
3242  // The function type itself was not dependent and therefore no
3243  // substitution occurred. However, we still need to instantiate
3244  // the function parameters themselves.
3245  const FunctionProtoType *OldProto =
3246  cast<FunctionProtoType>(OldProtoLoc.getType());
3247  for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3248  ++i) {
3249  ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3250  if (!OldParam) {
3251  Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3252  D, D->getLocation(), OldProto->getParamType(i)));
3253  continue;
3254  }
3255 
3256  ParmVarDecl *Parm =
3257  cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3258  if (!Parm)
3259  return nullptr;
3260  Params.push_back(Parm);
3261  }
3262  }
3263  } else {
3264  // If the type of this function, after ignoring parentheses, is not
3265  // *directly* a function type, then we're instantiating a function that
3266  // was declared via a typedef or with attributes, e.g.,
3267  //
3268  // typedef int functype(int, int);
3269  // functype func;
3270  // int __cdecl meth(int, int);
3271  //
3272  // In this case, we'll just go instantiate the ParmVarDecls that we
3273  // synthesized in the method declaration.
3274  SmallVector<QualType, 4> ParamTypes;
3275  Sema::ExtParameterInfoBuilder ExtParamInfos;
3276  if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3277  TemplateArgs, ParamTypes, &Params,
3278  ExtParamInfos))
3279  return nullptr;
3280  }
3281 
3282  return NewTInfo;
3283 }
3284 
3285 /// Introduce the instantiated function parameters into the local
3286 /// instantiation scope, and set the parameter names to those used
3287 /// in the template.
3289  const FunctionDecl *PatternDecl,
3291  const MultiLevelTemplateArgumentList &TemplateArgs) {
3292  unsigned FParamIdx = 0;
3293  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3294  const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3295  if (!PatternParam->isParameterPack()) {
3296  // Simple case: not a parameter pack.
3297  assert(FParamIdx < Function->getNumParams());
3298  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3299  FunctionParam->setDeclName(PatternParam->getDeclName());
3300  // If the parameter's type is not dependent, update it to match the type
3301  // in the pattern. They can differ in top-level cv-qualifiers, and we want
3302  // the pattern's type here. If the type is dependent, they can't differ,
3303  // per core issue 1668. Substitute into the type from the pattern, in case
3304  // it's instantiation-dependent.
3305  // FIXME: Updating the type to work around this is at best fragile.
3306  if (!PatternDecl->getType()->isDependentType()) {
3307  QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3308  FunctionParam->getLocation(),
3309  FunctionParam->getDeclName());
3310  if (T.isNull())
3311  return true;
3312  FunctionParam->setType(T);
3313  }
3314 
3315  Scope.InstantiatedLocal(PatternParam, FunctionParam);
3316  ++FParamIdx;
3317  continue;
3318  }
3319 
3320  // Expand the parameter pack.
3321  Scope.MakeInstantiatedLocalArgPack(PatternParam);
3322  Optional<unsigned> NumArgumentsInExpansion
3323  = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3324  assert(NumArgumentsInExpansion &&
3325  "should only be called when all template arguments are known");
3326  QualType PatternType =
3327  PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3328  for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3329  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3330  FunctionParam->setDeclName(PatternParam->getDeclName());
3331  if (!PatternDecl->getType()->isDependentType()) {
3332  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3333  QualType T = S.SubstType(PatternType, TemplateArgs,
3334  FunctionParam->getLocation(),
3335  FunctionParam->getDeclName());
3336  if (T.isNull())
3337  return true;
3338  FunctionParam->setType(T);
3339  }
3340 
3341  Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3342  ++FParamIdx;
3343  }
3344  }
3345 
3346  return false;
3347 }
3348 
3350  FunctionDecl *Decl) {
3351  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3352  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3353  return;
3354 
3355  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3357  if (Inst.isInvalid()) {
3358  // We hit the instantiation depth limit. Clear the exception specification
3359  // so that our callers don't have to cope with EST_Uninstantiated.
3360  UpdateExceptionSpec(Decl, EST_None);
3361  return;
3362  }
3363 
3364  // Enter the scope of this instantiation. We don't use
3365  // PushDeclContext because we don't have a scope.
3366  Sema::ContextRAII savedContext(*this, Decl);
3368 
3369  MultiLevelTemplateArgumentList TemplateArgs =
3370  getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3371 
3372  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3373  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3374  TemplateArgs)) {
3375  UpdateExceptionSpec(Decl, EST_None);
3376  return;
3377  }
3378 
3379  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3380  TemplateArgs);
3381 }
3382 
3383 /// \brief Initializes the common fields of an instantiation function
3384 /// declaration (New) from the corresponding fields of its template (Tmpl).
3385 ///
3386 /// \returns true if there was an error
3387 bool
3389  FunctionDecl *Tmpl) {
3390  if (Tmpl->isDeleted())
3391  New->setDeletedAsWritten();
3392 
3393  // Forward the mangling number from the template to the instantiated decl.
3394  SemaRef.Context.setManglingNumber(New,
3395  SemaRef.Context.getManglingNumber(Tmpl));
3396 
3397  // If we are performing substituting explicitly-specified template arguments
3398  // or deduced template arguments into a function template and we reach this
3399  // point, we are now past the point where SFINAE applies and have committed
3400  // to keeping the new function template specialization. We therefore
3401  // convert the active template instantiation for the function template
3402  // into a template instantiation for this specific function template
3403  // specialization, which is not a SFINAE context, so that we diagnose any
3404  // further errors in the declaration itself.
3405  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3406  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3407  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3408  ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3409  if (FunctionTemplateDecl *FunTmpl
3410  = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3411  assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3412  "Deduction from the wrong function template?");
3413  (void) FunTmpl;
3414  ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3415  ActiveInst.Entity = New;
3416  }
3417  }
3418 
3419  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3420  assert(Proto && "Function template without prototype?");
3421 
3422  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3424 
3425  // DR1330: In C++11, defer instantiation of a non-trivial
3426  // exception specification.
3427  // DR1484: Local classes and their members are instantiated along with the
3428  // containing function.
3429  if (SemaRef.getLangOpts().CPlusPlus11 &&
3430  EPI.ExceptionSpec.Type != EST_None &&
3433  !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3434  FunctionDecl *ExceptionSpecTemplate = Tmpl;
3436  ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3438  if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3439  NewEST = EST_Unevaluated;
3440 
3441  // Mark the function has having an uninstantiated exception specification.
3442  const FunctionProtoType *NewProto
3443  = New->getType()->getAs<FunctionProtoType>();
3444  assert(NewProto && "Template instantiation without function prototype?");
3445  EPI = NewProto->getExtProtoInfo();
3446  EPI.ExceptionSpec.Type = NewEST;
3447  EPI.ExceptionSpec.SourceDecl = New;
3448  EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3449  New->setType(SemaRef.Context.getFunctionType(
3450  NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3451  } else {
3452  SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3453  }
3454  }
3455 
3456  // Get the definition. Leaves the variable unchanged if undefined.
3457  const FunctionDecl *Definition = Tmpl;
3458  Tmpl->isDefined(Definition);
3459 
3460  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3461  LateAttrs, StartingScope);
3462 
3463  return false;
3464 }
3465 
3466 /// \brief Initializes common fields of an instantiated method
3467 /// declaration (New) from the corresponding fields of its template
3468 /// (Tmpl).
3469 ///
3470 /// \returns true if there was an error
3471 bool
3473  CXXMethodDecl *Tmpl) {
3474  if (InitFunctionInstantiation(New, Tmpl))
3475  return true;
3476 
3477  New->setAccess(Tmpl->getAccess());
3478  if (Tmpl->isVirtualAsWritten())
3479  New->setVirtualAsWritten(true);
3480 
3481  // FIXME: New needs a pointer to Tmpl
3482  return false;
3483 }
3484 
3485 /// \brief Instantiate the definition of the given function from its
3486 /// template.
3487 ///
3488 /// \param PointOfInstantiation the point at which the instantiation was
3489 /// required. Note that this is not precisely a "point of instantiation"
3490 /// for the function, but it's close.
3491 ///
3492 /// \param Function the already-instantiated declaration of a
3493 /// function template specialization or member function of a class template
3494 /// specialization.
3495 ///
3496 /// \param Recursive if true, recursively instantiates any functions that
3497 /// are required by this instantiation.
3498 ///
3499 /// \param DefinitionRequired if true, then we are performing an explicit
3500 /// instantiation where the body of the function is required. Complain if
3501 /// there is no such body.
3503  FunctionDecl *Function,
3504  bool Recursive,
3505  bool DefinitionRequired,
3506  bool AtEndOfTU) {
3507  if (Function->isInvalidDecl() || Function->isDefined())
3508  return;
3509 
3510  // Never instantiate an explicit specialization except if it is a class scope
3511  // explicit specialization.
3514  return;
3515 
3516  // Find the function body that we'll be substituting.
3517  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3518  assert(PatternDecl && "instantiating a non-template");
3519 
3520  Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3521  assert(PatternDecl && "template definition is not a template");
3522  if (!Pattern) {
3523  // Try to find a defaulted definition
3524  PatternDecl->isDefined(PatternDecl);
3525  }
3526  assert(PatternDecl && "template definition is not a template");
3527 
3528  // Postpone late parsed template instantiations.
3529  if (PatternDecl->isLateTemplateParsed() &&
3530  !LateTemplateParser) {
3531  PendingInstantiations.push_back(
3532  std::make_pair(Function, PointOfInstantiation));
3533  return;
3534  }
3535 
3536  // If we're performing recursive template instantiation, create our own
3537  // queue of pending implicit instantiations that we will instantiate later,
3538  // while we're still within our own instantiation context.
3539  // This has to happen before LateTemplateParser below is called, so that
3540  // it marks vtables used in late parsed templates as used.
3542  SavedPendingLocalImplicitInstantiations(*this);
3544  SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3545 
3546  // Call the LateTemplateParser callback if there is a need to late parse
3547  // a templated function definition.
3548  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3549  LateTemplateParser) {
3550  // FIXME: Optimize to allow individual templates to be deserialized.
3551  if (PatternDecl->isFromASTFile())
3552  ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3553 
3554  LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3555  assert(LPT && "missing LateParsedTemplate");
3556  LateTemplateParser(OpaqueParser, *LPT);
3557  Pattern = PatternDecl->getBody(PatternDecl);
3558  }
3559 
3560  // FIXME: Check that the definition is visible before trying to instantiate
3561  // it. This requires us to track the instantiation stack in order to know
3562  // which definitions should be visible.
3563 
3564  if (!Pattern && !PatternDecl->isDefaulted()) {
3565  if (DefinitionRequired) {
3566  if (Function->getPrimaryTemplate())
3567  Diag(PointOfInstantiation,
3568  diag::err_explicit_instantiation_undefined_func_template)
3569  << Function->getPrimaryTemplate();
3570  else
3571  Diag(PointOfInstantiation,
3572  diag::err_explicit_instantiation_undefined_member)
3573  << 1 << Function->getDeclName() << Function->getDeclContext();
3574 
3575  if (PatternDecl)
3576  Diag(PatternDecl->getLocation(),
3577  diag::note_explicit_instantiation_here);
3578  Function->setInvalidDecl();
3579  } else if (Function->getTemplateSpecializationKind()
3581  assert(!Recursive);
3582  PendingInstantiations.push_back(
3583  std::make_pair(Function, PointOfInstantiation));
3584  } else if (Function->getTemplateSpecializationKind()
3586  if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
3587  Diag(PointOfInstantiation, diag::warn_func_template_missing)
3588  << Function;
3589  Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3590  if (getLangOpts().CPlusPlus11)
3591  Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3592  << Function;
3593  }
3594  }
3595 
3596  return;
3597  }
3598 
3599  // C++1y [temp.explicit]p10:
3600  // Except for inline functions, declarations with types deduced from their
3601  // initializer or return value, and class template specializations, other
3602  // explicit instantiation declarations have the effect of suppressing the
3603  // implicit instantiation of the entity to which they refer.
3604  if (Function->getTemplateSpecializationKind() ==
3606  !PatternDecl->isInlined() &&
3607  !PatternDecl->getReturnType()->getContainedAutoType())
3608  return;
3609 
3610  if (PatternDecl->isInlined()) {
3611  // Function, and all later redeclarations of it (from imported modules,
3612  // for instance), are now implicitly inline.
3613  for (auto *D = Function->getMostRecentDecl(); /**/;
3614  D = D->getPreviousDecl()) {
3615  D->setImplicitlyInline();
3616  if (D == Function)
3617  break;
3618  }
3619  }
3620 
3621  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3622  if (Inst.isInvalid())
3623  return;
3624  PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3625  "instantiating function definition");
3626 
3627  // Copy the inner loc start from the pattern.
3628  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3629 
3630  EnterExpressionEvaluationContext EvalContext(*this,
3632 
3633  // Introduce a new scope where local variable instantiations will be
3634  // recorded, unless we're actually a member function within a local
3635  // class, in which case we need to merge our results with the parent
3636  // scope (of the enclosing function).
3637  bool MergeWithParentScope = false;
3638  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3639  MergeWithParentScope = Rec->isLocalClass();
3640 
3641  LocalInstantiationScope Scope(*this, MergeWithParentScope);
3642 
3643  if (PatternDecl->isDefaulted())
3644  SetDeclDefaulted(Function, PatternDecl->getLocation());
3645  else {
3646  MultiLevelTemplateArgumentList TemplateArgs =
3647  getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3648 
3649  // Substitute into the qualifier; we can get a substitution failure here
3650  // through evil use of alias templates.
3651  // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3652  // of the) lexical context of the pattern?
3653  SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3654 
3655  ActOnStartOfFunctionDef(nullptr, Function);
3656 
3657  // Enter the scope of this instantiation. We don't use
3658  // PushDeclContext because we don't have a scope.
3659  Sema::ContextRAII savedContext(*this, Function);
3660 
3661  if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3662  TemplateArgs))
3663  return;
3664 
3665  // If this is a constructor, instantiate the member initializers.
3666  if (const CXXConstructorDecl *Ctor =
3667  dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3668  InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3669  TemplateArgs);
3670  }
3671 
3672  // Instantiate the function body.
3673  StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3674 
3675  if (Body.isInvalid())
3676  Function->setInvalidDecl();
3677 
3678  ActOnFinishFunctionBody(Function, Body.get(),
3679  /*IsInstantiation=*/true);
3680 
3681  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3682 
3683  if (auto *Listener = getASTMutationListener())
3684  Listener->FunctionDefinitionInstantiated(Function);
3685 
3686  savedContext.pop();
3687  }
3688 
3689  DeclGroupRef DG(Function);
3690  Consumer.HandleTopLevelDecl(DG);
3691 
3692  // This class may have local implicit instantiations that need to be
3693  // instantiation within this scope.
3694  PerformPendingInstantiations(/*LocalOnly=*/true);
3695  Scope.Exit();
3696 
3697  if (Recursive) {
3698  // Define any pending vtables.
3699  DefineUsedVTables();
3700 
3701  // Instantiate any pending implicit instantiations found during the
3702  // instantiation of this template.
3703  PerformPendingInstantiations();
3704 
3705  // PendingInstantiations and VTableUses are restored through
3706  // SavePendingInstantiationsAndVTableUses's destructor.
3707  }
3708 }
3709 
3711  VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3712  const TemplateArgumentList &TemplateArgList,
3713  const TemplateArgumentListInfo &TemplateArgsInfo,
3715  SourceLocation PointOfInstantiation, void *InsertPos,
3716  LateInstantiatedAttrVec *LateAttrs,
3717  LocalInstantiationScope *StartingScope) {
3718  if (FromVar->isInvalidDecl())
3719  return nullptr;
3720 
3721  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3722  if (Inst.isInvalid())
3723  return nullptr;
3724 
3725  MultiLevelTemplateArgumentList TemplateArgLists;
3726  TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3727 
3728  // Instantiate the first declaration of the variable template: for a partial
3729  // specialization of a static data member template, the first declaration may
3730  // or may not be the declaration in the class; if it's in the class, we want
3731  // to instantiate a member in the class (a declaration), and if it's outside,
3732  // we want to instantiate a definition.
3733  //
3734  // If we're instantiating an explicitly-specialized member template or member
3735  // partial specialization, don't do this. The member specialization completely
3736  // replaces the original declaration in this case.
3737  bool IsMemberSpec = false;
3738  if (VarTemplatePartialSpecializationDecl *PartialSpec =
3739  dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3740  IsMemberSpec = PartialSpec->isMemberSpecialization();
3741  else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3742  IsMemberSpec = FromTemplate->isMemberSpecialization();
3743  if (!IsMemberSpec)
3744  FromVar = FromVar->getFirstDecl();
3745 
3746  MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3747  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3748  MultiLevelList);
3749 
3750  // TODO: Set LateAttrs and StartingScope ...
3751 
3752  return cast_or_null<VarTemplateSpecializationDecl>(
3753  Instantiator.VisitVarTemplateSpecializationDecl(
3754  VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3755 }
3756 
3757 /// \brief Instantiates a variable template specialization by completing it
3758 /// with appropriate type information and initializer.
3760  VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3761  const MultiLevelTemplateArgumentList &TemplateArgs) {
3762 
3763  // Do substitution on the type of the declaration
3764  TypeSourceInfo *DI =
3765  SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3766  PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3767  if (!DI)
3768  return nullptr;
3769 
3770  // Update the type of this variable template specialization.
3771  VarSpec->setType(DI->getType());
3772 
3773  // Instantiate the initializer.
3774  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3775 
3776  return VarSpec;
3777 }
3778 
3779 /// BuildVariableInstantiation - Used after a new variable has been created.
3780 /// Sets basic variable data and decides whether to postpone the
3781 /// variable instantiation.
3783  VarDecl *NewVar, VarDecl *OldVar,
3784  const MultiLevelTemplateArgumentList &TemplateArgs,
3785  LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3786  LocalInstantiationScope *StartingScope,
3787  bool InstantiatingVarTemplate) {
3788 
3789  // If we are instantiating a local extern declaration, the
3790  // instantiation belongs lexically to the containing function.
3791  // If we are instantiating a static data member defined
3792  // out-of-line, the instantiation will have the same lexical
3793  // context (which will be a namespace scope) as the template.
3794  if (OldVar->isLocalExternDecl()) {
3795  NewVar->setLocalExternDecl();
3796  NewVar->setLexicalDeclContext(Owner);
3797  } else if (OldVar->isOutOfLine())
3798  NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3799  NewVar->setTSCSpec(OldVar->getTSCSpec());
3800  NewVar->setInitStyle(OldVar->getInitStyle());
3801  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3802  NewVar->setConstexpr(OldVar->isConstexpr());
3803  NewVar->setInitCapture(OldVar->isInitCapture());
3805  OldVar->isPreviousDeclInSameBlockScope());
3806  NewVar->setAccess(OldVar->getAccess());
3807 
3808  if (!OldVar->isStaticDataMember()) {
3809  if (OldVar->isUsed(false))
3810  NewVar->setIsUsed();
3811  NewVar->setReferenced(OldVar->isReferenced());
3812  }
3813 
3814  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3815 
3817  *this, NewVar->getDeclName(), NewVar->getLocation(),
3818  NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3821 
3822  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3823  (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3824  OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3825  // We have a previous declaration. Use that one, so we merge with the
3826  // right type.
3827  if (NamedDecl *NewPrev = FindInstantiatedDecl(
3828  NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3829  Previous.addDecl(NewPrev);
3830  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3831  OldVar->hasLinkage())
3832  LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3833  CheckVariableDeclaration(NewVar, Previous);
3834 
3835  if (!InstantiatingVarTemplate) {
3836  NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3837  if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3838  NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3839  }
3840 
3841  if (!OldVar->isOutOfLine()) {
3842  if (NewVar->getDeclContext()->isFunctionOrMethod())
3843  CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3844  }
3845 
3846  // Link instantiations of static data members back to the template from
3847  // which they were instantiated.
3848  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3849  NewVar->setInstantiationOfStaticDataMember(OldVar,
3850  TSK_ImplicitInstantiation);
3851 
3852  // Forward the mangling number from the template to the instantiated decl.
3855 
3856  // Delay instantiation of the initializer for variable templates or inline
3857  // static data members until a definition of the variable is needed. We need
3858  // it right away if the type contains 'auto'.
3859  if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3860  !InstantiatingVarTemplate &&
3861  !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) ||
3862  NewVar->getType()->isUndeducedType())
3863  InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3864 
3865  // Diagnose unused local variables with dependent types, where the diagnostic
3866  // will have been deferred.
3867  if (!NewVar->isInvalidDecl() &&
3868  NewVar->getDeclContext()->isFunctionOrMethod() &&
3869  OldVar->getType()->isDependentType())
3870  DiagnoseUnusedDecl(NewVar);
3871 }
3872 
3873 /// \brief Instantiate the initializer of a variable.
3875  VarDecl *Var, VarDecl *OldVar,
3876  const MultiLevelTemplateArgumentList &TemplateArgs) {
3877  // We propagate the 'inline' flag with the initializer, because it
3878  // would otherwise imply that the variable is a definition for a
3879  // non-static data member.
3880  if (OldVar->isInlineSpecified())
3881  Var->setInlineSpecified();
3882  else if (OldVar->isInline())
3883  Var->setImplicitlyInline();
3884 
3885  if (Var->getAnyInitializer())
3886  // We already have an initializer in the class.
3887  return;
3888 
3889  if (OldVar->getInit()) {
3890  if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3891  PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3892  else
3893  PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3894 
3895  // Instantiate the initializer.
3896  ExprResult Init;
3897 
3898  {
3899  ContextRAII SwitchContext(*this, Var->getDeclContext());
3900  Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
3901  OldVar->getInitStyle() == VarDecl::CallInit);
3902  }
3903 
3904  if (!Init.isInvalid()) {
3905  bool TypeMayContainAuto = true;
3906  Expr *InitExpr = Init.get();
3907 
3908  if (Var->hasAttr<DLLImportAttr>() &&
3909  (!InitExpr ||
3910  !InitExpr->isConstantInitializer(getASTContext(), false))) {
3911  // Do not dynamically initialize dllimport variables.
3912  } else if (InitExpr) {
3913  bool DirectInit = OldVar->isDirectInit();
3914  AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3915  } else
3916  ActOnUninitializedDecl(Var, TypeMayContainAuto);
3917  } else {
3918  // FIXME: Not too happy about invalidating the declaration
3919  // because of a bogus initializer.
3920  Var->setInvalidDecl();
3921  }
3922 
3923  PopExpressionEvaluationContext();
3924  } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3925  !Var->isCXXForRangeDecl())
3926  ActOnUninitializedDecl(Var, false);
3927 }
3928 
3929 /// \brief Instantiate the definition of the given variable from its
3930 /// template.
3931 ///
3932 /// \param PointOfInstantiation the point at which the instantiation was
3933 /// required. Note that this is not precisely a "point of instantiation"
3934 /// for the function, but it's close.
3935 ///
3936 /// \param Var the already-instantiated declaration of a static member
3937 /// variable of a class template specialization.
3938 ///
3939 /// \param Recursive if true, recursively instantiates any functions that
3940 /// are required by this instantiation.
3941 ///
3942 /// \param DefinitionRequired if true, then we are performing an explicit
3943 /// instantiation where an out-of-line definition of the member variable
3944 /// is required. Complain if there is no such definition.
3946  SourceLocation PointOfInstantiation,
3947  VarDecl *Var,
3948  bool Recursive,
3949  bool DefinitionRequired) {
3950  InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3951  DefinitionRequired);
3952 }
3953 
3955  VarDecl *Var, bool Recursive,
3956  bool DefinitionRequired, bool AtEndOfTU) {
3957  if (Var->isInvalidDecl())
3958  return;
3959 
3961  dyn_cast<VarTemplateSpecializationDecl>(Var);
3962  VarDecl *PatternDecl = nullptr, *Def = nullptr;
3963  MultiLevelTemplateArgumentList TemplateArgs =
3964  getTemplateInstantiationArgs(Var);
3965 
3966  if (VarSpec) {
3967  // If this is a variable template specialization, make sure that it is
3968  // non-dependent, then find its instantiation pattern.
3969  bool InstantiationDependent = false;
3971  VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3972  "Only instantiate variable template specializations that are "
3973  "not type-dependent");
3974  (void)InstantiationDependent;
3975 
3976  // Find the variable initialization that we'll be substituting. If the
3977  // pattern was instantiated from a member template, look back further to
3978  // find the real pattern.
3979  assert(VarSpec->getSpecializedTemplate() &&
3980  "Specialization without specialized template?");
3981  llvm::PointerUnion<VarTemplateDecl *,
3982  VarTemplatePartialSpecializationDecl *> PatternPtr =
3984  if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3986  PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3988  Tmpl->getInstantiatedFromMember()) {
3989  if (Tmpl->isMemberSpecialization())
3990  break;
3991 
3992  Tmpl = From;
3993  }
3994  PatternDecl = Tmpl;
3995  } else {
3996  VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3997  while (VarTemplateDecl *From =
3999  if (Tmpl->isMemberSpecialization())
4000  break;
4001 
4002  Tmpl = From;
4003  }
4004  PatternDecl = Tmpl->getTemplatedDecl();
4005  }
4006 
4007  // If this is a static data member template, there might be an
4008  // uninstantiated initializer on the declaration. If so, instantiate
4009  // it now.
4010  if (PatternDecl->isStaticDataMember() &&
4011  (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4012  !Var->hasInit()) {
4013  // FIXME: Factor out the duplicated instantiation context setup/tear down
4014  // code here.
4015  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4016  if (Inst.isInvalid())
4017  return;
4018  PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4019  "instantiating variable initializer");
4020 
4021  // If we're performing recursive template instantiation, create our own
4022  // queue of pending implicit instantiations that we will instantiate
4023  // later, while we're still within our own instantiation context.
4025  SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4026 
4027  LocalInstantiationScope Local(*this);
4028 
4029  // Enter the scope of this instantiation. We don't use
4030  // PushDeclContext because we don't have a scope.
4031  ContextRAII PreviousContext(*this, Var->getDeclContext());
4032  InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4033  PreviousContext.pop();
4034 
4035  // FIXME: Need to inform the ASTConsumer that we instantiated the
4036  // initializer?
4037 
4038  // This variable may have local implicit instantiations that need to be
4039  // instantiated within this scope.
4040  PerformPendingInstantiations(/*LocalOnly=*/true);
4041 
4042  Local.Exit();
4043 
4044  if (Recursive) {
4045  // Define any newly required vtables.
4046  DefineUsedVTables();
4047 
4048  // Instantiate any pending implicit instantiations found during the
4049  // instantiation of this template.
4050  PerformPendingInstantiations();
4051 
4052  // PendingInstantiations and VTableUses are restored through
4053  // SavePendingInstantiationsAndVTableUses's destructor.
4054  }
4055  }
4056 
4057  // Find actual definition
4058  Def = PatternDecl->getDefinition(getASTContext());
4059  } else {
4060  // If this is a static data member, find its out-of-line definition.
4061  assert(Var->isStaticDataMember() && "not a static data member?");
4062  PatternDecl = Var->getInstantiatedFromStaticDataMember();
4063 
4064  assert(PatternDecl && "data member was not instantiated from a template?");
4065  assert(PatternDecl->isStaticDataMember() && "not a static data member?");
4066  Def = PatternDecl->getDefinition();
4067  }
4068 
4069  // FIXME: Check that the definition is visible before trying to instantiate
4070  // it. This requires us to track the instantiation stack in order to know
4071  // which definitions should be visible.
4072 
4073  // If we don't have a definition of the variable template, we won't perform
4074  // any instantiation. Rather, we rely on the user to instantiate this
4075  // definition (or provide a specialization for it) in another translation
4076  // unit.
4077  if (!Def) {
4078  if (DefinitionRequired) {
4079  if (VarSpec)
4080  Diag(PointOfInstantiation,
4081  diag::err_explicit_instantiation_undefined_var_template) << Var;
4082  else
4083  Diag(PointOfInstantiation,
4084  diag::err_explicit_instantiation_undefined_member)
4085  << 2 << Var->getDeclName() << Var->getDeclContext();
4086  Diag(PatternDecl->getLocation(),
4087  diag::note_explicit_instantiation_here);
4088  if (VarSpec)
4089  Var->setInvalidDecl();
4090  } else if (Var->getTemplateSpecializationKind()
4092  PendingInstantiations.push_back(
4093  std::make_pair(Var, PointOfInstantiation));
4094  } else if (Var->getTemplateSpecializationKind()
4096  // Warn about missing definition at the end of translation unit.
4097  if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
4098  Diag(PointOfInstantiation, diag::warn_var_template_missing)
4099  << Var;
4100  Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4101  if (getLangOpts().CPlusPlus11)
4102  Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4103  }
4104  }
4105 
4106  return;
4107  }
4108 
4110 
4111  // Never instantiate an explicit specialization.
4112  if (TSK == TSK_ExplicitSpecialization)
4113  return;
4114 
4115  // C++11 [temp.explicit]p10:
4116  // Except for inline functions, [...] explicit instantiation declarations
4117  // have the effect of suppressing the implicit instantiation of the entity
4118  // to which they refer.
4120  return;
4121 
4122  // Make sure to pass the instantiated variable to the consumer at the end.
4123  struct PassToConsumerRAII {
4124  ASTConsumer &Consumer;
4125  VarDecl *Var;
4126 
4127  PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4128  : Consumer(Consumer), Var(Var) { }
4129 
4130  ~PassToConsumerRAII() {
4132  }
4133  } PassToConsumerRAII(Consumer, Var);
4134 
4135  // If we already have a definition, we're done.
4136  if (VarDecl *Def = Var->getDefinition()) {
4137  // We may be explicitly instantiating something we've already implicitly
4138  // instantiated.
4140  PointOfInstantiation);
4141  return;
4142  }
4143 
4144  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4145  if (Inst.isInvalid())
4146  return;
4147  PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4148  "instantiating variable definition");
4149 
4150  // If we're performing recursive template instantiation, create our own
4151  // queue of pending implicit instantiations that we will instantiate later,
4152  // while we're still within our own instantiation context.
4154  SavedPendingLocalImplicitInstantiations(*this);
4156  SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4157 
4158  // Enter the scope of this instantiation. We don't use
4159  // PushDeclContext because we don't have a scope.
4160  ContextRAII PreviousContext(*this, Var->getDeclContext());
4161  LocalInstantiationScope Local(*this);
4162 
4163  VarDecl *OldVar = Var;
4164  if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4165  // We're instantiating an inline static data member whose definition was
4166  // provided inside the class.
4167  // FIXME: Update record?
4168  InstantiateVariableInitializer(Var, Def, TemplateArgs);
4169  } else if (!VarSpec) {
4170  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4171  TemplateArgs));
4172  } else if (Var->isStaticDataMember() &&
4173  Var->getLexicalDeclContext()->isRecord()) {
4174  // We need to instantiate the definition of a static data member template,
4175  // and all we have is the in-class declaration of it. Instantiate a separate
4176  // declaration of the definition.
4177  TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4178  TemplateArgs);
4179  Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4180  VarSpec->getSpecializedTemplate(), Def, nullptr,
4181  VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4182  if (Var) {
4183  llvm::PointerUnion<VarTemplateDecl *,
4184  VarTemplatePartialSpecializationDecl *> PatternPtr =
4187  PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4188  cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4189  Partial, &VarSpec->getTemplateInstantiationArgs());
4190 
4191  // Merge the definition with the declaration.
4192  LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4193  LookupOrdinaryName, ForRedeclaration);
4194  R.addDecl(OldVar);
4195  MergeVarDecl(Var, R);
4196 
4197  // Attach the initializer.
4198  InstantiateVariableInitializer(Var, Def, TemplateArgs);
4199  }
4200  } else
4201  // Complete the existing variable's definition with an appropriately
4202  // substituted type and initializer.
4203  Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4204 
4205  PreviousContext.pop();
4206 
4207  if (Var) {
4208  PassToConsumerRAII.Var = Var;
4210  OldVar->getPointOfInstantiation());
4211  }
4212 
4213  // This variable may have local implicit instantiations that need to be
4214  // instantiated within this scope.
4215  PerformPendingInstantiations(/*LocalOnly=*/true);
4216 
4217  Local.Exit();
4218 
4219  if (Recursive) {
4220  // Define any newly required vtables.
4221  DefineUsedVTables();
4222 
4223  // Instantiate any pending implicit instantiations found during the
4224  // instantiation of this template.
4225  PerformPendingInstantiations();
4226 
4227  // PendingInstantiations and VTableUses are restored through
4228  // SavePendingInstantiationsAndVTableUses's destructor.
4229  }
4230 }
4231 
4232 void
4234  const CXXConstructorDecl *Tmpl,
4235  const MultiLevelTemplateArgumentList &TemplateArgs) {
4236 
4238  bool AnyErrors = Tmpl->isInvalidDecl();
4239 
4240  // Instantiate all the initializers.
4241  for (const auto *Init : Tmpl->inits()) {
4242  // Only instantiate written initializers, let Sema re-construct implicit
4243  // ones.
4244  if (!Init->isWritten())
4245  continue;
4246 
4247  SourceLocation EllipsisLoc;
4248 
4249  if (Init->isPackExpansion()) {
4250  // This is a pack expansion. We should expand it now.
4251  TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4253  collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4254  collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4255  bool ShouldExpand = false;
4256  bool RetainExpansion = false;
4257  Optional<unsigned> NumExpansions;
4258  if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4259  BaseTL.getSourceRange(),
4260  Unexpanded,
4261  TemplateArgs, ShouldExpand,
4262  RetainExpansion,
4263  NumExpansions)) {
4264  AnyErrors = true;
4265  New->setInvalidDecl();
4266  continue;
4267  }
4268  assert(ShouldExpand && "Partial instantiation of base initializer?");
4269 
4270  // Loop over all of the arguments in the argument pack(s),
4271  for (unsigned I = 0; I != *NumExpansions; ++I) {
4272  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4273 
4274  // Instantiate the initializer.
4275  ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4276  /*CXXDirectInit=*/true);
4277  if (TempInit.isInvalid()) {
4278  AnyErrors = true;
4279  break;
4280  }
4281 
4282  // Instantiate the base type.
4283  TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4284  TemplateArgs,
4285  Init->getSourceLocation(),
4286  New->getDeclName());
4287  if (!BaseTInfo) {
4288  AnyErrors = true;
4289  break;
4290  }
4291 
4292  // Build the initializer.
4293  MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4294  BaseTInfo, TempInit.get(),
4295  New->getParent(),
4296  SourceLocation());
4297  if (NewInit.isInvalid()) {
4298  AnyErrors = true;
4299  break;
4300  }
4301 
4302  NewInits.push_back(NewInit.get());
4303  }
4304 
4305  continue;
4306  }
4307 
4308  // Instantiate the initializer.
4309  ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4310  /*CXXDirectInit=*/true);
4311  if (TempInit.isInvalid()) {
4312  AnyErrors = true;
4313  continue;
4314  }
4315 
4316  MemInitResult NewInit;
4317  if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4318  TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4319  TemplateArgs,
4320  Init->getSourceLocation(),
4321  New->getDeclName());
4322  if (!TInfo) {
4323  AnyErrors = true;
4324  New->setInvalidDecl();
4325  continue;
4326  }
4327 
4328  if (Init->isBaseInitializer())
4329  NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4330  New->getParent(), EllipsisLoc);
4331  else
4332  NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4333  cast<CXXRecordDecl>(CurContext->getParent()));
4334  } else if (Init->isMemberInitializer()) {
4335  FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4336  Init->getMemberLocation(),
4337  Init->getMember(),
4338  TemplateArgs));
4339  if (!Member) {
4340  AnyErrors = true;
4341  New->setInvalidDecl();
4342  continue;
4343  }
4344 
4345  NewInit = BuildMemberInitializer(Member, TempInit.get(),
4346  Init->getSourceLocation());
4347  } else if (Init->isIndirectMemberInitializer()) {
4348  IndirectFieldDecl *IndirectMember =
4349  cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4350  Init->getMemberLocation(),
4351  Init->getIndirectMember(), TemplateArgs));
4352 
4353  if (!IndirectMember) {
4354  AnyErrors = true;
4355  New->setInvalidDecl();
4356  continue;
4357  }
4358 
4359  NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4360  Init->getSourceLocation());
4361  }
4362 
4363  if (NewInit.isInvalid()) {
4364  AnyErrors = true;
4365  New->setInvalidDecl();
4366  } else {
4367  NewInits.push_back(NewInit.get());
4368  }
4369  }
4370 
4371  // Assign all the initializers to the new constructor.
4372  ActOnMemInitializers(New,
4373  /*FIXME: ColonLoc */
4374  SourceLocation(),
4375  NewInits,
4376  AnyErrors);
4377 }
4378 
4379 // TODO: this could be templated if the various decl types used the
4380 // same method name.
4382  ClassTemplateDecl *Instance) {
4383  Pattern = Pattern->getCanonicalDecl();
4384 
4385  do {
4386  Instance = Instance->getCanonicalDecl();
4387  if (Pattern == Instance) return true;
4388  Instance = Instance->getInstantiatedFromMemberTemplate();
4389  } while (Instance);
4390 
4391  return false;
4392 }
4393 
4395  FunctionTemplateDecl *Instance) {
4396  Pattern = Pattern->getCanonicalDecl();
4397 
4398  do {
4399  Instance = Instance->getCanonicalDecl();
4400  if (Pattern == Instance) return true;
4401  Instance = Instance->getInstantiatedFromMemberTemplate();
4402  } while (Instance);
4403 
4404  return false;
4405 }
4406 
4407 static bool
4410  Pattern
4411  = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4412  do {
4413  Instance = cast<ClassTemplatePartialSpecializationDecl>(
4414  Instance->getCanonicalDecl());
4415  if (Pattern == Instance)
4416  return true;
4417  Instance = Instance->getInstantiatedFromMember();
4418  } while (Instance);
4419 
4420  return false;
4421 }
4422 
4423 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4424  CXXRecordDecl *Instance) {
4425  Pattern = Pattern->getCanonicalDecl();
4426 
4427  do {
4428  Instance = Instance->getCanonicalDecl();
4429  if (Pattern == Instance) return true;
4430  Instance = Instance->getInstantiatedFromMemberClass();
4431  } while (Instance);
4432 
4433  return false;
4434 }
4435 
4436 static bool isInstantiationOf(FunctionDecl *Pattern,
4437  FunctionDecl *Instance) {
4438  Pattern = Pattern->getCanonicalDecl();
4439 
4440  do {
4441  Instance = Instance->getCanonicalDecl();
4442  if (Pattern == Instance) return true;
4443  Instance = Instance->getInstantiatedFromMemberFunction();
4444  } while (Instance);
4445 
4446  return false;
4447 }
4448 
4449 static bool isInstantiationOf(EnumDecl *Pattern,
4450  EnumDecl *Instance) {
4451  Pattern = Pattern->getCanonicalDecl();
4452 
4453  do {
4454  Instance = Instance->getCanonicalDecl();
4455  if (Pattern == Instance) return true;
4456  Instance = Instance->getInstantiatedFromMemberEnum();
4457  } while (Instance);
4458 
4459  return false;
4460 }
4461 
4462 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4463  UsingShadowDecl *Instance,
4464  ASTContext &C) {
4466  Pattern);
4467 }
4468 
4469 static bool isInstantiationOf(UsingDecl *Pattern,
4470  UsingDecl *Instance,
4471  ASTContext &C) {
4472  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4473 }
4474 
4476  UsingDecl *Instance,
4477  ASTContext &C) {
4478  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4479 }
4480 
4482  UsingDecl *Instance,
4483  ASTContext &C) {
4484  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4485 }
4486 
4488  VarDecl *Instance) {
4489  assert(Instance->isStaticDataMember());
4490 
4491  Pattern = Pattern->getCanonicalDecl();
4492 
4493  do {
4494  Instance = Instance->getCanonicalDecl();
4495  if (Pattern == Instance) return true;
4496  Instance = Instance->getInstantiatedFromStaticDataMember();
4497  } while (Instance);
4498 
4499  return false;
4500 }
4501 
4502 // Other is the prospective instantiation
4503 // D is the prospective pattern
4504 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4505  if (D->getKind() != Other->getKind()) {
4507  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4508  if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4509  return isInstantiationOf(UUD, UD, Ctx);
4510  }
4511  }
4512 
4513  if (UnresolvedUsingValueDecl *UUD
4514  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4515  if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4516  return isInstantiationOf(UUD, UD, Ctx);
4517  }
4518  }
4519 
4520  return false;
4521  }
4522 
4523  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4524  return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4525 
4526  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4527  return isInstantiationOf(cast<FunctionDecl>(D), Function);
4528 
4529  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4530  return isInstantiationOf(cast<EnumDecl>(D), Enum);
4531 
4532  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4533  if (Var->isStaticDataMember())
4534  return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4535 
4536  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4537  return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4538 
4539  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4540  return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4541 
4543  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4544  return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4545  PartialSpec);
4546 
4547  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4548  if (!Field->getDeclName()) {
4549  // This is an unnamed field.
4551  cast<FieldDecl>(D));
4552  }
4553  }
4554 
4555  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4556  return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4557 
4558  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4559  return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4560 
4561  return D->getDeclName() && isa<NamedDecl>(Other) &&
4562  D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4563 }
4564 
4565 template<typename ForwardIterator>
4567  NamedDecl *D,
4568  ForwardIterator first,
4569  ForwardIterator last) {
4570  for (; first != last; ++first)
4571  if (isInstantiationOf(Ctx, D, *first))
4572  return cast<NamedDecl>(*first);
4573 
4574  return nullptr;
4575 }
4576 
4577 /// \brief Finds the instantiation of the given declaration context
4578 /// within the current instantiation.
4579 ///
4580 /// \returns NULL if there was an error
4582  const MultiLevelTemplateArgumentList &TemplateArgs) {
4583  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4584  Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4585  return cast_or_null<DeclContext>(ID);
4586  } else return DC;
4587 }
4588 
4589 /// \brief Find the instantiation of the given declaration within the
4590 /// current instantiation.
4591 ///
4592 /// This routine is intended to be used when \p D is a declaration
4593 /// referenced from within a template, that needs to mapped into the
4594 /// corresponding declaration within an instantiation. For example,
4595 /// given:
4596 ///
4597 /// \code
4598 /// template<typename T>
4599 /// struct X {
4600 /// enum Kind {
4601 /// KnownValue = sizeof(T)
4602 /// };
4603 ///
4604 /// bool getKind() const { return KnownValue; }
4605 /// };
4606 ///
4607 /// template struct X<int>;
4608 /// \endcode
4609 ///
4610 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4611 /// \p EnumConstantDecl for \p KnownValue (which refers to
4612 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4613 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4614 /// this mapping from within the instantiation of <tt>X<int></tt>.
4616  const MultiLevelTemplateArgumentList &TemplateArgs) {
4617  DeclContext *ParentDC = D->getDeclContext();
4618  // FIXME: Parmeters of pointer to functions (y below) that are themselves
4619  // parameters (p below) can have their ParentDC set to the translation-unit
4620  // - thus we can not consistently check if the ParentDC of such a parameter
4621  // is Dependent or/and a FunctionOrMethod.
4622  // For e.g. this code, during Template argument deduction tries to
4623  // find an instantiated decl for (T y) when the ParentDC for y is
4624  // the translation unit.
4625  // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4626  // float baz(float(*)()) { return 0.0; }
4627  // Foo(baz);
4628  // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4629  // it gets here, always has a FunctionOrMethod as its ParentDC??
4630  // For now:
4631  // - as long as we have a ParmVarDecl whose parent is non-dependent and
4632  // whose type is not instantiation dependent, do nothing to the decl
4633  // - otherwise find its instantiated decl.
4634  if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4635  !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4636  return D;
4637  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4638  isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4639  (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4640  (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4641  // D is a local of some kind. Look into the map of local
4642  // declarations to their instantiations.
4643  if (CurrentInstantiationScope) {
4644  if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4645  if (Decl *FD = Found->dyn_cast<Decl *>())
4646  return cast<NamedDecl>(FD);
4647 
4648  int PackIdx = ArgumentPackSubstitutionIndex;
4649  assert(PackIdx != -1 &&
4650  "found declaration pack but not pack expanding");
4651  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4652  return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4653  }
4654  }
4655 
4656  // If we're performing a partial substitution during template argument
4657  // deduction, we may not have values for template parameters yet. They
4658  // just map to themselves.
4659  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4660  isa<TemplateTemplateParmDecl>(D))
4661  return D;
4662 
4663  if (D->isInvalidDecl())
4664  return nullptr;
4665 
4666  // Normally this function only searches for already instantiated declaration
4667  // however we have to make an exclusion for local types used before
4668  // definition as in the code:
4669  //
4670  // template<typename T> void f1() {
4671  // void g1(struct x1);
4672  // struct x1 {};
4673  // }
4674  //
4675  // In this case instantiation of the type of 'g1' requires definition of
4676  // 'x1', which is defined later. Error recovery may produce an enum used
4677  // before definition. In these cases we need to instantiate relevant
4678  // declarations here.
4679  bool NeedInstantiate = false;
4680  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4681  NeedInstantiate = RD->isLocalClass();
4682  else
4683  NeedInstantiate = isa<EnumDecl>(D);
4684  if (NeedInstantiate) {
4685  Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4686  CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4687  return cast<TypeDecl>(Inst);
4688  }
4689 
4690  // If we didn't find the decl, then we must have a label decl that hasn't
4691  // been found yet. Lazily instantiate it and return it now.
4692  assert(isa<LabelDecl>(D));
4693 
4694  Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4695  assert(Inst && "Failed to instantiate label??");
4696 
4697  CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4698  return cast<LabelDecl>(Inst);
4699  }
4700 
4701  // For variable template specializations, update those that are still
4702  // type-dependent.
4703  if (VarTemplateSpecializationDecl *VarSpec =
4704  dyn_cast<VarTemplateSpecializationDecl>(D)) {
4705  bool InstantiationDependent = false;
4706  const TemplateArgumentListInfo &VarTemplateArgs =
4707  VarSpec->getTemplateArgsInfo();
4709  VarTemplateArgs, InstantiationDependent))
4710  D = cast<NamedDecl>(
4711  SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4712  return D;
4713  }
4714 
4715  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4716  if (!Record->isDependentContext())
4717  return D;
4718 
4719  // Determine whether this record is the "templated" declaration describing
4720  // a class template or class template partial specialization.
4721  ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4722  if (ClassTemplate)
4723  ClassTemplate = ClassTemplate->getCanonicalDecl();
4724  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4725  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4726  ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4727 
4728  // Walk the current context to find either the record or an instantiation of
4729  // it.
4730  DeclContext *DC = CurContext;
4731  while (!DC->isFileContext()) {
4732  // If we're performing substitution while we're inside the template
4733  // definition, we'll find our own context. We're done.
4734  if (DC->Equals(Record))
4735  return Record;
4736 
4737  if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4738  // Check whether we're in the process of instantiating a class template
4739  // specialization of the template we're mapping.
4740  if (ClassTemplateSpecializationDecl *InstSpec
4741  = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4742  ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4743  if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4744  return InstRecord;
4745  }
4746 
4747  // Check whether we're in the process of instantiating a member class.
4748  if (isInstantiationOf(Record, InstRecord))
4749  return InstRecord;
4750  }
4751 
4752  // Move to the outer template scope.
4753  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4754  if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4755  DC = FD->getLexicalDeclContext();
4756  continue;
4757  }
4758  }
4759 
4760  DC = DC->getParent();
4761  }
4762 
4763  // Fall through to deal with other dependent record types (e.g.,
4764  // anonymous unions in class templates).
4765  }
4766 
4767  if (!ParentDC->isDependentContext())
4768  return D;
4769 
4770  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4771  if (!ParentDC)
4772  return nullptr;
4773 
4774  if (ParentDC != D->getDeclContext()) {
4775  // We performed some kind of instantiation in the parent context,
4776  // so now we need to look into the instantiated parent context to
4777  // find the instantiation of the declaration D.
4778 
4779  // If our context used to be dependent, we may need to instantiate
4780  // it before performing lookup into that context.
4781  bool IsBeingInstantiated = false;
4782  if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4783  if (!Spec->isDependentContext()) {
4784  QualType T = Context.getTypeDeclType(Spec);
4785  const RecordType *Tag = T->getAs<RecordType>();
4786  assert(Tag && "type of non-dependent record is not a RecordType");
4787  if (Tag->isBeingDefined())
4788  IsBeingInstantiated = true;
4789  if (!Tag->isBeingDefined() &&
4790  RequireCompleteType(Loc, T, diag::err_incomplete_type))
4791  return nullptr;
4792 
4793  ParentDC = Tag->getDecl();
4794  }
4795  }
4796 
4797  NamedDecl *Result = nullptr;
4798  if (D->getDeclName()) {
4799  DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4800  Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4801  } else {
4802  // Since we don't have a name for the entity we're looking for,
4803  // our only option is to walk through all of the declarations to
4804  // find that name. This will occur in a few cases:
4805  //
4806  // - anonymous struct/union within a template
4807  // - unnamed class/struct/union/enum within a template
4808  //
4809  // FIXME: Find a better way to find these instantiations!
4810  Result = findInstantiationOf(Context, D,
4811  ParentDC->decls_begin(),
4812  ParentDC->decls_end());
4813  }
4814 
4815  if (!Result) {
4816  if (isa<UsingShadowDecl>(D)) {
4817  // UsingShadowDecls can instantiate to nothing because of using hiding.
4818  } else if (Diags.hasErrorOccurred()) {
4819  // We've already complained about something, so most likely this
4820  // declaration failed to instantiate. There's no point in complaining
4821  // further, since this is normal in invalid code.
4822  } else if (IsBeingInstantiated) {
4823  // The class in which this member exists is currently being
4824  // instantiated, and we haven't gotten around to instantiating this
4825  // member yet. This can happen when the code uses forward declarations
4826  // of member classes, and introduces ordering dependencies via
4827  // template instantiation.
4828  Diag(Loc, diag::err_member_not_yet_instantiated)
4829  << D->getDeclName()
4830  << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4831  Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4832  } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4833  // This enumeration constant was found when the template was defined,
4834  // but can't be found in the instantiation. This can happen if an
4835  // unscoped enumeration member is explicitly specialized.
4836  EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4837  EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4838  TemplateArgs));
4839  assert(Spec->getTemplateSpecializationKind() ==
4841  Diag(Loc, diag::err_enumerator_does_not_exist)
4842  << D->getDeclName()
4843  << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4844  Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4845  << Context.getTypeDeclType(Spec);
4846  } else {
4847  // We should have found something, but didn't.
4848  llvm_unreachable("Unable to find instantiation of declaration!");
4849  }
4850  }
4851 
4852  D = Result;
4853  }
4854 
4855  return D;
4856 }
4857 
4858 /// \brief Performs template instantiation for all implicit template
4859 /// instantiations we have seen until this point.
4861  while (!PendingLocalImplicitInstantiations.empty() ||
4862  (!LocalOnly && !PendingInstantiations.empty())) {
4864 
4865  if (PendingLocalImplicitInstantiations.empty()) {
4866  Inst = PendingInstantiations.front();
4867  PendingInstantiations.pop_front();
4868  } else {
4869  Inst = PendingLocalImplicitInstantiations.front();
4870  PendingLocalImplicitInstantiations.pop_front();
4871  }
4872 
4873  // Instantiate function definitions
4874  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4875  bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4877  InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4878  DefinitionRequired, true);
4879  continue;
4880  }
4881 
4882  // Instantiate variable definitions
4883  VarDecl *Var = cast<VarDecl>(Inst.first);
4884 
4885  assert((Var->isStaticDataMember() ||
4886  isa<VarTemplateSpecializationDecl>(Var)) &&
4887  "Not a static data member, nor a variable template"
4888  " specialization?");
4889 
4890  // Don't try to instantiate declarations if the most recent redeclaration
4891  // is invalid.
4892  if (Var->getMostRecentDecl()->isInvalidDecl())
4893  continue;
4894 
4895  // Check if the most recent declaration has changed the specialization kind
4896  // and removed the need for implicit instantiation.
4898  case TSK_Undeclared:
4899  llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4902  continue; // No longer need to instantiate this type.
4904  // We only need an instantiation if the pending instantiation *is* the
4905  // explicit instantiation.
4906  if (Var != Var->getMostRecentDecl()) continue;
4907  case TSK_ImplicitInstantiation:
4908  break;
4909  }
4910 
4911  PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4912  "instantiating variable definition");
4913  bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4915 
4916  // Instantiate static data member definitions or variable template
4917  // specializations.
4918  InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4919  DefinitionRequired, true);
4920  }
4921 }
4922 
4924  const MultiLevelTemplateArgumentList &TemplateArgs) {
4925  for (auto DD : Pattern->ddiags()) {
4926  switch (DD->getKind()) {
4928  HandleDependentAccessCheck(*DD, TemplateArgs);
4929  break;
4930  }
4931  }
4932 }
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
ddiag_range ddiags() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
iterator begin() const
Definition: DeclBase.h:1103
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
no exception specification
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
Definition: DeclTemplate.h:946
SourceLocation getIdentLocation() const
Returns the location of this using declaration's identifier.
Definition: DeclCXX.h:2687
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Definition: ASTConsumer.h:114
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:3321
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2256
A (possibly-)qualified type.
Definition: Type.h:598
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
void InstantiatedLocal(const Decl *D, Decl *Inst)
bool isInvalid() const
Definition: Ownership.h:160
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
SourceLocation getExternLoc() const
Gets the location of the extern keyword, if present.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
Definition: ASTConsumer.h:36
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:178
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef< Expr * > Uniforms, ArrayRef< Expr * > Aligneds, ArrayRef< Expr * > Alignments, ArrayRef< Expr * > Linears, ArrayRef< unsigned > LinModifiers, ArrayRef< Expr * > Steps, SourceRange SR)
Called on well-formed '#pragma omp declare simd' after parsing of the associated method/function.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2705
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
DeclarationName getCXXConstructorName(CanQualType Ty)
getCXXConstructorName - Returns the name of a C++ constructor for the given Type. ...
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:1780
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:96
const LangOptions & getLangOpts() const
Definition: Sema.h:1062
CXXMethodDecl * getSpecialization() const
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3199
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:5971
bool isParameterPack() const
Returns whether this is a parameter pack.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:3818
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
static bool isDeclWithinFunction(const Decl *D)
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function...
Definition: Decl.cpp:3323
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2481
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:3535
TypedefDecl - Represents the declaration of a typedef-name via the 'typedef' type specifier...
Definition: Decl.h:2681
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition: Sema.h:819
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsExplicitSpecialization)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:8637
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
QualType getUnderlyingType() const
Definition: Decl.h:2649
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:3053
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1139
void setRangeEnd(SourceLocation E)
Definition: Decl.h:1753
TypeLoc getPatternLoc() const
Definition: TypeLoc.h:1972
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2008
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1595
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Defines the C++ template declaration subclasses.
StringRef P
Decl * InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias)
PtrTy get() const
Definition: Ownership.h:164
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:7081
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1598
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:922
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1421
QualType getRecordType(const RecordDecl *Decl) const
Declaration of a variable template.
const Expr * getInit() const
Definition: Decl.h:1139
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:471
A container of type source information.
Definition: Decl.h:62
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:7037
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists...
Definition: Decl.h:3153
void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo)
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1184
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=None)
Definition: DeclFriend.cpp:27
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2187
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Get the template arguments as written.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
InClassInitStyle getInClassInitStyle() const
getInClassInitStyle - Get the kind of (C++11) in-class initializer which this field has...
Definition: Decl.h:2400
Represents a #pragma comment line.
Definition: Decl.h:109
void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template...
const TemplateArgumentLoc * getArgumentArray() const
Definition: TemplateBase.h:547
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:125
const TemplateArgumentListInfo & templateArgs() const
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:543
FriendDecl - Represents the declaration of a friend entity, which can be a function, a type, or a templated function or type.
Definition: DeclFriend.h:40
void InstantiatedLocalPackArg(const Decl *D, ParmVarDecl *Inst)
RAII object that enters a new expression evaluation context.
Definition: Sema.h:9606
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isExplicit, bool isConstexpr, SourceLocation EndLocation)
Definition: DeclCXX.cpp:2004
bool SubstQualifier(const DeclaratorDecl *OldDecl, DeclaratorDecl *NewDecl)
bool isInlineSpecified() const
Definition: Decl.h:1261
SourceLocation getRParenLoc() const
Definition: DeclCXX.h:3355
static void instantiateDependentAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion)
void setClassScopeSpecializationPattern(FunctionDecl *FD, FunctionDecl *Pattern)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3167
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, unsigned ThisTypeQuals)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:191
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:2320
Represents a variable template specialization, which refers to a variable template with a given set o...
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:4695
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:572
static void instantiateDependentCUDALaunchBoundsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const CUDALaunchBoundsAttr &Attr, Decl *New)
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:49
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:3241
decl_iterator decls_end() const
Definition: DeclBase.h:1455
static void instantiateDependentAssumeAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AssumeAlignedAttr *Aligned, Decl *New)
bool isSingleTagDecl() const
Asks if the result is a single tag decl.
Definition: Sema/Lookup.h:514
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:2734
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1377
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:130
void AddParameterABIAttr(SourceRange AttrRange, Decl *D, ParameterABI ABI, unsigned SpellingListIndex)
Defines the clang::Expr interface and subclasses for C++ expressions.
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:707
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:564
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
TypeSourceInfo * getFriendType() const
If this friend declaration names an (untemplated but possibly dependent) type, return the type; other...
Definition: DeclFriend.h:107
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef< std::pair< QualType, SourceLocation >> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare reduction'.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:14111
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3253
DeclarationName getName() const
getName - Returns the embedded declaration name.
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3182
Represents a class template specialization, which refers to a class template with a given set of temp...
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3146
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:7008
bool isScopedUsingClassTag() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3193
StringLiteral * getMessage()
Definition: DeclCXX.h:3350
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:3699
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
void setManglingNumber(const NamedDecl *ND, unsigned Number)
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1789
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
A C++ nested-name-specifier augmented with source location information.
ExprResult ExprEmpty()
Definition: Ownership.h:274
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1067
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3276
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:2789
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2266
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, unsigned SpellingListIndex, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:11993
bool isReferenceType() const
Definition: Type.h:5491
QualType getReturnType() const
Definition: Decl.h:2034
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2293
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:899
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2871
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:54
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, AttributeList *Attr)
Definition: SemaDecl.cpp:14778
Decl * VisitVarTemplateSpecializationDecl(VarTemplateDecl *VarTemplate, VarDecl *FromVar, void *InsertPos, const TemplateArgumentListInfo &TemplateArgsInfo, ArrayRef< TemplateArgument > Converted)
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:1837
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3544
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:2964
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1306
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:678
TagKind getTagKind() const
Definition: Decl.h:2930
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1295
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
void Exit()
Exit this local instantiation scope early.
Definition: Template.h:261
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
SourceLocation getNamespaceKeyLocation() const
Returns the location of the namespace keyword.
Definition: DeclCXX.h:2684
unsigned size() const
Definition: DeclTemplate.h:92
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:103
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
Declaration of a function specialization at template class scope.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1199
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:5816
IdentifierTable & Idents
Definition: ASTContext.h:459
bool isThisDeclarationADefinition() const
isThisDeclarationADefinition() - Return true if this declaration is a completion definition of the ty...
Definition: Decl.h:2865
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:947
Expr * getUnderlyingExpr() const
Definition: Type.h:3598
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted per C++0x.
Definition: Decl.h:1858
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Represents a C++ using-declaration.
Definition: DeclCXX.h:3039
FunctionTemplateDecl * getCanonicalDecl() override
Definition: DeclTemplate.h:914
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, unsigned SpellingListIndex)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
Expr * getInitializer()
Get initializer expression (if specified) of the declare reduction construct.
Definition: DeclOpenMP.h:143
Represents the results of name lookup.
Definition: Sema/Lookup.h:30
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:2978
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer)
Finish current declare reduction construct initializer.
IdentifierInfo * getSetterId() const
Definition: DeclCXX.h:3415
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class...
Definition: Decl.cpp:3673
void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1462
A convenient class for passing around template argument information.
Definition: TemplateBase.h:523
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Get the template arguments as written.
QualType getReturnType() const
Definition: Type.h:3009
Look up all declarations in a scope with the given name, including resolved using declarations...
Definition: Sema.h:2729
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1838
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:1853
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl)
Initializes the common fields of an instantiation function declaration (New) from the corresponding f...
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:503
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, AttributeList *AttrList, bool IsInstantiation, bool HasTypenameKeyword, SourceLocation TypenameLoc)
Builds a using declaration.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:585
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:147
RecordDecl * getDecl() const
Definition: Type.h:3716
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3128
bool isOverloadedOperator() const
isOverloadedOperator - Whether this function declaration represents an C++ overloaded operator...
Definition: Decl.h:2093
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
void setSpecializationKind(TemplateSpecializationKind TSK)
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
CXXRecordDecl * getCanonicalDecl() override
Definition: DeclCXX.h:654
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1039
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:540
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:509
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:1898
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1800
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:2133
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &Converted)
Check that the given template arguments can be be provided to the given template, converting the argu...
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3068
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Sema/Lookup.h:410
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1206
detail::InMemoryDirectory::const_iterator I
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:3160
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getType() const
Definition: Decl.h:599
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, bool isConstexprSpecified=false)
Definition: Decl.h:1720
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
SourceLocation getAliasLoc() const
Returns the location of the alias name, i.e.
Definition: DeclCXX.h:2802
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:6785
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:2756
void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
bool isDefined(const FunctionDecl *&Definition) const
isDefined - Returns true if the function is defined at all, including a deleted definition.
Definition: Decl.cpp:2479
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3069
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
A helper class for building up ExtParameterInfos.
Definition: Sema.h:7104
TypeSourceInfo * getExpansionTypeSourceInfo(unsigned I) const
Retrieve a particular expansion type source info within an expanded parameter pack.
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:1841
unsigned getNumExpansionTemplateParameters() const
Retrieves the number of expansion template parameters in an expanded parameter pack.
TypeSourceInfo * getTypeAsWritten() const
Gets the type of this specialization as it was written by the user, if it was so written.
bool isStatic() const
Definition: DeclCXX.cpp:1475
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
Definition: TemplateBase.h:591
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false)
BuildVariableInstantiation - Used after a new variable has been created.
ExtInfo getExtInfo() const
Definition: Type.h:3018
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:263
bool isNamespace() const
Definition: DeclBase.h:1291
TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x alias-declaration.
Definition: Decl.h:2701
void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
QualType getParamType(unsigned i) const
Definition: Type.h:3272
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3073
static void instantiateDependentEnableIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const EnableIfAttr *A, const Decl *Tmpl, Decl *New)
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3304
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1281
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2593
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Determine whether this parameter is actually a function parameter pack.
Definition: Decl.cpp:2422
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition: DeclCXX.h:2780
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:5487
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:646
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:462
unsigned getChainingSize() const
Definition: Decl.h:2546
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, FunctionDecl *D, TypeSourceInfo *TInfo)
Adjust the given function type for an instantiation of the given declaration, to cope with modificati...
ASTContext * Context
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1643
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Expr * getCombiner()
Get combiner expression of the declare reduction construct.
Definition: DeclOpenMP.h:136
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1616
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:225
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2063
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isImplicitlyDeclared)
Definition: DeclCXX.cpp:1972
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1909
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2276
const Type * getTypeForDecl() const
Definition: Decl.h:2590
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:2927
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5749
Expr - This represents one expression.
Definition: Expr.h:105
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition: Decl.h:1203
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template...
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
bool isDeletedAsWritten() const
Definition: Decl.h:1910
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner)
Finish current declare reduction construct initializer.
StateNode * Previous
Declaration of a template type parameter.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:588
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
OMPDeclareReductionDecl * getPrevDeclInScope()
Get reference to previous declare reduction construct in the same scope with the same name...
Definition: DeclOpenMP.cpp:76
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, ClassTemplateDecl *PrevDecl)
Create a class template node.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template...
Expr * getBitWidth() const
Definition: Decl.h:2375
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:2540
static DeclT * getPreviousDeclForInstantiation(DeclT *D)
Get the previous declaration of a declaration for the purposes of template instantiation.
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, bool AllowParamOrMoveConstructible)
Definition: SemaStmt.cpp:2724
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2011
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3280
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional< unsigned > NumExpansions, bool ExpectParameterPack)
void CheckAlignasUnderalignment(Decl *D)
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
bool isFailed() const
Definition: DeclCXX.h:3353
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Represents the type decltype(expr) (C++11).
Definition: Type.h:3590
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given function template specialization.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
Defines the clang::TypeLoc interface and its subclasses.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2083
void setConstexpr(bool IC)
Definition: Decl.h:1279
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:13455
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:748
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3188
StorageClass
Storage classes.
Definition: Specifiers.h:201
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1774
bool isFunctionOrMethod() const
Definition: DeclBase.h:1263
Declaration of an alias template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1214
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
void setTypeAsWritten(TypeSourceInfo *T)
Sets the type of this specialization as it was written by the user.
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6732
NamedDecl * getInstantiatedFromUsingDecl(UsingDecl *Inst)
If the given using decl Inst is an instantiation of a (possibly unresolved) using decl from a templat...
SourceLocation getUsingLoc() const
Returns the source location of the 'using' keyword.
Definition: DeclCXX.h:3292
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1066
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
SourceLocation getFriendLoc() const
Retrieves the location of the 'friend' keyword.
Definition: DeclFriend.h:125
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2461
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:147
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:2957
shadow_range shadows() const
Definition: DeclCXX.h:3136
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:671
static void instantiateOMPDeclareSimdDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareSimdDeclAttr &Attr, Decl *New)
Instantiation of 'declare simd' attribute and its arguments.
static void instantiateDependentModeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const ModeAttr &Attr, Decl *New)
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
bool isTemplateTypeParmType() const
Definition: Type.h:5643
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:2961
VarDecl * getCanonicalDecl() override
Definition: Decl.cpp:1908
const Expr * getAnyInitializer() const
getAnyInitializer - Get the initializer for this variable, no matter which declaration it is attached...
Definition: Decl.h:1129
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1883
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:156
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:1832
unsigned getNumExpansionTypes() const
Retrieves the number of expansion types in an expanded parameter pack.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:94
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3083
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc)
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3016
Stmt * getBody(const FunctionDecl *&Definition) const
getBody - Retrieve the body (definition) of the function.
Definition: Decl.cpp:2491
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1479
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:236
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1579
IdentifierInfo * getGetterId() const
Definition: DeclCXX.h:3413
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3153
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:144
A stack object to be created when performing template instantiation.
Definition: Sema.h:6822
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:3748
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument's source information, if any.
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs)
ClassTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *D)
Find a class template partial specialization which was instantiated from the given member partial spe...
Encodes a location in the source.
enumerator_range enumerators() const
Definition: Decl.h:3109
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2742
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:262
This represents '#pragma omp declare reduction ...' directive.
Definition: DeclOpenMP.h:102
Pseudo declaration for capturing expressions.
Definition: DeclOpenMP.h:171
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
const TemplateArgumentListInfo & getTemplateArgsInfo() const
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
SourceRange getBraceRange() const
Definition: Decl.h:2846
void InstantiateStaticDataMemberDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false)
Instantiate the definition of the given variable from its template.
void setExternLoc(SourceLocation Loc)
Sets the location of the extern keyword.
const std::string ID
reference front() const
Definition: DeclBase.h:1109
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2727
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ASTContext & getASTContext() const
Definition: Sema.h:1069
SourceLocation getTargetNameLoc() const
Returns the location of the identifier in the named namespace.
Definition: DeclCXX.h:2808
LabelDecl - Represents the declaration of a label.
Definition: Decl.h:424
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3185
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1736
unsigned getDepth() const
Retrieve the depth of the template parameter.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
static bool isInstantiationOf(ClassTemplateDecl *Pattern, ClassTemplateDecl *Instance)
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
EnumDecl * getCanonicalDecl() override
Definition: Decl.h:3060
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:1989
bool isMemberSpecialization()
Determines whether this variable template partial specialization was a specialization of a member par...
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
static void instantiateDependentAlignValueAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignValueAttr *Aligned, Decl *New)
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template...
void setDeclName(DeclarationName N)
Set the name of this declaration.
Definition: Decl.h:261
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:3356
SourceLocation getUsingLoc() const
Returns the source location of the 'using' keyword.
Definition: DeclCXX.h:3211
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:539
Decl * VisitVarDecl(VarDecl *D, bool InstantiatingVarTemplate)
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:956
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5849
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:165
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1407
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:609
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:159
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:144
const IdentifierInfo * getIdentifier() const
Definition: Type.h:4580
bool isFileContext() const
Definition: DeclBase.h:1279
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:3327
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
Definition: Decl.cpp:2249
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2067
Attr * clone(ASTContext &C) const
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:542
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
unsigned getManglingNumber(const NamedDecl *ND) const
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1302
void setVirtualAsWritten(bool V)
Definition: Decl.h:1833
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Represents a pack expansion of types.
Definition: Type.h:4641
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:4157
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2294
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1285
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2609
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Whether this is an anonymous struct or union.
Definition: Decl.h:3320
Represents a template argument.
Definition: TemplateBase.h:40
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1310
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument. ...
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3169
static bool isInvalid(LocType Loc, bool *Invalid)
SourceLocation getColonLoc() const
The location of the colon following the access specifier.
Definition: DeclCXX.h:122
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:2063
static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, const FunctionDecl *PatternDecl, LocalInstantiationScope &Scope, const MultiLevelTemplateArgumentList &TemplateArgs)
Introduce the instantiated function parameters into the local instantiation scope, and set the parameter names to those used in the template.
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:2719
void setImplicitlyInline()
Flag that this function is implicitly inline.
Definition: Decl.h:2076
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3091
Decl * VisitFunctionDecl(FunctionDecl *D, TemplateParameterList *TemplateParams)
Normal class members are of more specific types and therefore don't make it here. ...
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:10916
not evaluated yet, for special member function
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool isUnsupportedFriend() const
Determines if this friend kind is unsupported.
Definition: DeclFriend.h:156
LocalInstantiationScope * cloneScopes(LocalInstantiationScope *Outermost)
Clone this scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:274
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1135
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
A template instantiation that is currently in progress.
Definition: Sema.h:6608
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:1956
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool EnumUnderlyingIsImplicit, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:12010
IndirectFieldDecl - An instance of this class is created to represent a field injected from an anonym...
Definition: Decl.h:2521
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1056
DeclContext * getCommonAncestor()
Returns the common ancestor context of this using-directive and its nominated namespace.
Definition: DeclCXX.h:2676
static NamedDecl * findInstantiationOf(ASTContext &Ctx, NamedDecl *D, ForwardIterator first, ForwardIterator last)
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:155
bool hasWrittenPrototype() const
Definition: Decl.h:1875
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3268
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2042
DeclarationName - The name of a declaration.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void AddNSConsumedAttr(SourceRange AttrRange, Decl *D, unsigned SpellingListIndex, bool isNSConsumed, bool isTemplateInstantiation)
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:1911
bool isThisDeclarationADefinition() const
isThisDeclarationADefinition - Returns whether this specific declaration of the function is also a de...
Definition: Decl.h:1814
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:693
EnumDecl - Represents an enum.
Definition: Decl.h:3013
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:582
void setInlineSpecified()
Definition: Decl.h:1265
detail::InMemoryDirectory::const_iterator E
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:141
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid)
Called at the end of '#pragma omp declare reduction'.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1966
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1300
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template...
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:3627
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:3980
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setInitCapture(bool IC)
Definition: Decl.h:1288
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5432
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant...
Definition: Expr.cpp:2614
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:127
bool empty() const
Return true if no decls were found.
Definition: Sema/Lookup.h:323
void setImplicitlyInline()
Definition: Decl.h:1270
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition: Type.h:3163
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3707
TypeSourceInfo * SubstFunctionType(FunctionDecl *D, SmallVectorImpl< ParmVarDecl * > &Params)
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:427
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
SourceManager & getSourceManager() const
Definition: Sema.h:1067
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:3590
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
Definition: DeclTemplate.h:799
NamedDecl * getFriendDecl() const
If this friend declaration doesn't name a type, return the inner declaration.
Definition: DeclFriend.h:120
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:151
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos)
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1649
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3273
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:14308
bool isNull() const
Determine whether this template name is NULL.
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3137
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2317
bool isFunctionType() const
Definition: Type.h:5479
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
ClassTemplateDecl * getCanonicalDecl() override
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition: DeclCXX.h:3076
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO)...
Definition: Decl.h:1227
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare reduction' construct.
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition: Decl.h:1198
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, bool isConstexpr, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1540
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1240
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1296
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:379
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition: DeclCXX.cpp:1293
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1058
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition: DeclCXX.h:3295
OMPThreadPrivateDecl * CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef< Expr * > VarList)
Builds a new OpenMPThreadPrivateDecl and checks its correctness.
void setInnerLocStart(SourceLocation L)
Definition: Decl.h:686
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement...
Definition: Decl.h:1237
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
A template argument list.
Definition: DeclTemplate.h:173
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
Call-style initialization (C++98)
Definition: Decl.h:779
Represents a field declaration created by an @defs(...).
Definition: DeclObjC.h:1916
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:4108
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:952
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2281
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member...
Definition: Decl.cpp:2065
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition: Sema.h:814
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1270
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition: DeclCXX.h:3299
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:4129
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:500
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs)
Find the instantiation of the given declaration within the current instantiation. ...
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1258
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:311
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, Expr *MinBlocks, unsigned SpellingListIndex)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration. ...
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:159
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:2237
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Declaration of a class template.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1276
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:353
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
SourceLocation getAccessSpecifierLoc() const
The location of the access specifier.
Definition: DeclCXX.h:117
unsigned getIndex() const
Retrieve the index of the template parameter.
static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, VarDecl *Instance)
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1330
SourceRange getSourceRange() const override LLVM_READONLY
Definition: Decl.cpp:3346
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:3072
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
FriendDecl * CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo)
Perform semantic analysis of the given friend type declaration.
CanQualType IntTy
Definition: ASTContext.h:901
bool isRecord() const
Definition: DeclBase.h:1287
static OpaquePtr make(QualTypeP)
Definition: Ownership.h:55
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:166
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition: DeclCXX.h:2654
Optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
Definition: Sema.h:799
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition: DeclCXX.h:3221
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:685
Contains a late templated function.
Definition: Sema.h:9643
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3308
varlist_range varlists()
Definition: DeclOpenMP.h:77
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:3394
TemplateParameterList * getTemplateParameterList(unsigned index) const
Definition: Decl.h:717
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:1455
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluted - Return true if this expression might be usable in a constant expr...
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:6910
A trivial tuple used to represent a source range.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:3149
ASTContext & Context
Definition: Sema.h:299
FunctionDecl * getCanonicalDecl() override
Definition: Decl.cpp:2676
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:1746
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization, retrieves the function from which it was instantiated.
Definition: Decl.cpp:3046
EnumDecl * getDefinition() const
Definition: Decl.h:3082
Represents a C++ namespace alias.
Definition: DeclCXX.h:2718
Declaration of a friend template.
Represents C++ using-directive.
Definition: DeclCXX.h:2615
Represents a #pragma detect_mismatch line.
Definition: Decl.h:143
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:2644
void setTypeAsWritten(TypeSourceInfo *T)
Sets the type of this specialization as it was written by the user.
void setNRVOVariable(bool NRVO)
Definition: Decl.h:1230
NamespaceDecl * getStdNamespace() const
void setType(QualType newType)
Definition: Decl.h:600
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:470
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared, bool isConstexpr, InheritedConstructor Inherited=InheritedConstructor())
Definition: DeclCXX.cpp:1833
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:135
bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl)
Initializes common fields of an instantiated method declaration (New) from the corresponding fields o...
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:1911
Decl * VisitCXXMethodDecl(CXXMethodDecl *D, TemplateParameterList *TemplateParams, bool IsClassScopeSpecialization=false)
This represents '#pragma omp threadprivate ...' directive.
Definition: DeclOpenMP.h:39
FunctionDecl * getClassScopeSpecializationPattern() const
Retrieve the class scope template pattern that this function template specialization is instantiated ...
Definition: Decl.cpp:3178
Optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:4672
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3187
Declaration of a template function.
Definition: DeclTemplate.h:838
void clear()
Clears out any current state.
Definition: Sema/Lookup.h:538
Attr - This represents one attribute.
Definition: Attr.h:45
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:2835
SourceLocation getNamespaceLoc() const
Returns the location of the namespace keyword.
Definition: DeclCXX.h:2805
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
Perform substitution on the type T with a given set of template arguments.
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3228
bool isMutable() const
isMutable - Determines whether this field is mutable (C++ only).
Definition: Decl.h:2358
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:714
A RAII object to temporarily push a declaration context.
Definition: Sema.h:634
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:1580
bool hasInit() const
Definition: Decl.cpp:2040