Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//===----------------------------------------------------------------------===/
7
//
8
//  This file implements C++ template instantiation for declarations.
9
//
10
//===----------------------------------------------------------------------===/
11
12
#include "TreeTransform.h"
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTMutationListener.h"
16
#include "clang/AST/DeclTemplate.h"
17
#include "clang/AST/DeclVisitor.h"
18
#include "clang/AST/DependentDiagnostic.h"
19
#include "clang/AST/Expr.h"
20
#include "clang/AST/ExprCXX.h"
21
#include "clang/AST/PrettyDeclStackTrace.h"
22
#include "clang/AST/TypeLoc.h"
23
#include "clang/Basic/SourceManager.h"
24
#include "clang/Basic/TargetInfo.h"
25
#include "clang/Sema/EnterExpressionEvaluationContext.h"
26
#include "clang/Sema/Initialization.h"
27
#include "clang/Sema/Lookup.h"
28
#include "clang/Sema/ScopeInfo.h"
29
#include "clang/Sema/SemaInternal.h"
30
#include "clang/Sema/Template.h"
31
#include "clang/Sema/TemplateInstCallback.h"
32
#include "llvm/Support/TimeProfiler.h"
33
#include <optional>
34
35
using namespace clang;
36
37
0
static bool isDeclWithinFunction(const Decl *D) {
38
0
  const DeclContext *DC = D->getDeclContext();
39
0
  if (DC->isFunctionOrMethod())
40
0
    return true;
41
42
0
  if (DC->isRecord())
43
0
    return cast<CXXRecordDecl>(DC)->isLocalClass();
44
45
0
  return false;
46
0
}
47
48
template<typename DeclT>
49
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
50
0
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
51
0
  if (!OldDecl->getQualifierLoc())
52
0
    return false;
53
54
0
  assert((NewDecl->getFriendObjectKind() ||
55
0
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
56
0
         "non-friend with qualified name defined in dependent context");
57
0
  Sema::ContextRAII SavedContext(
58
0
      SemaRef,
59
0
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
60
0
                                    ? NewDecl->getLexicalDeclContext()
61
0
                                    : OldDecl->getLexicalDeclContext()));
62
63
0
  NestedNameSpecifierLoc NewQualifierLoc
64
0
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
65
0
                                            TemplateArgs);
66
67
0
  if (!NewQualifierLoc)
68
0
    return true;
69
70
0
  NewDecl->setQualifierInfo(NewQualifierLoc);
71
0
  return false;
72
0
}
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::DeclaratorDecl>(clang::Sema&, clang::DeclaratorDecl const*, clang::DeclaratorDecl*, clang::MultiLevelTemplateArgumentList const&)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::TagDecl>(clang::Sema&, clang::TagDecl const*, clang::TagDecl*, clang::MultiLevelTemplateArgumentList const&)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, clang::FunctionDecl*, clang::MultiLevelTemplateArgumentList const&)
73
74
bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
75
0
                                              DeclaratorDecl *NewDecl) {
76
0
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
77
0
}
78
79
bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
80
0
                                              TagDecl *NewDecl) {
81
0
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82
0
}
83
84
// Include attribute instantiation code.
85
#include "clang/Sema/AttrTemplateInstantiate.inc"
86
87
static void instantiateDependentAlignedAttr(
88
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
89
0
    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
90
0
  if (Aligned->isAlignmentExpr()) {
91
    // The alignment expression is a constant expression.
92
0
    EnterExpressionEvaluationContext Unevaluated(
93
0
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
94
0
    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
95
0
    if (!Result.isInvalid())
96
0
      S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
97
0
  } else {
98
0
    if (TypeSourceInfo *Result =
99
0
            S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
100
0
                        Aligned->getLocation(), DeclarationName())) {
101
0
      if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
102
0
                                      Aligned->getLocation(),
103
0
                                      Result->getTypeLoc().getSourceRange()))
104
0
        S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
105
0
    }
106
0
  }
107
0
}
108
109
static void instantiateDependentAlignedAttr(
110
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
111
0
    const AlignedAttr *Aligned, Decl *New) {
112
0
  if (!Aligned->isPackExpansion()) {
113
0
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
114
0
    return;
115
0
  }
116
117
0
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
118
0
  if (Aligned->isAlignmentExpr())
119
0
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
120
0
                                      Unexpanded);
121
0
  else
122
0
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
123
0
                                      Unexpanded);
124
0
  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
125
126
  // Determine whether we can expand this attribute pack yet.
127
0
  bool Expand = true, RetainExpansion = false;
128
0
  std::optional<unsigned> NumExpansions;
129
  // FIXME: Use the actual location of the ellipsis.
130
0
  SourceLocation EllipsisLoc = Aligned->getLocation();
131
0
  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
132
0
                                        Unexpanded, TemplateArgs, Expand,
133
0
                                        RetainExpansion, NumExpansions))
134
0
    return;
135
136
0
  if (!Expand) {
137
0
    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
138
0
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
139
0
  } else {
140
0
    for (unsigned I = 0; I != *NumExpansions; ++I) {
141
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
142
0
      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
143
0
    }
144
0
  }
145
0
}
146
147
static void instantiateDependentAssumeAlignedAttr(
148
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
149
0
    const AssumeAlignedAttr *Aligned, Decl *New) {
150
  // The alignment expression is a constant expression.
151
0
  EnterExpressionEvaluationContext Unevaluated(
152
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
153
154
0
  Expr *E, *OE = nullptr;
155
0
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
156
0
  if (Result.isInvalid())
157
0
    return;
158
0
  E = Result.getAs<Expr>();
159
160
0
  if (Aligned->getOffset()) {
161
0
    Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
162
0
    if (Result.isInvalid())
163
0
      return;
164
0
    OE = Result.getAs<Expr>();
165
0
  }
166
167
0
  S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
168
0
}
169
170
static void instantiateDependentAlignValueAttr(
171
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172
0
    const AlignValueAttr *Aligned, Decl *New) {
173
  // The alignment expression is a constant expression.
174
0
  EnterExpressionEvaluationContext Unevaluated(
175
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
176
0
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
177
0
  if (!Result.isInvalid())
178
0
    S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
179
0
}
180
181
static void instantiateDependentAllocAlignAttr(
182
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
183
0
    const AllocAlignAttr *Align, Decl *New) {
184
0
  Expr *Param = IntegerLiteral::Create(
185
0
      S.getASTContext(),
186
0
      llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
187
0
      S.getASTContext().UnsignedLongLongTy, Align->getLocation());
188
0
  S.AddAllocAlignAttr(New, *Align, Param);
189
0
}
190
191
static void instantiateDependentAnnotationAttr(
192
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
193
0
    const AnnotateAttr *Attr, Decl *New) {
194
0
  EnterExpressionEvaluationContext Unevaluated(
195
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
196
197
  // If the attribute has delayed arguments it will have to instantiate those
198
  // and handle them as new arguments for the attribute.
199
0
  bool HasDelayedArgs = Attr->delayedArgs_size();
200
201
0
  ArrayRef<Expr *> ArgsToInstantiate =
202
0
      HasDelayedArgs
203
0
          ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
204
0
          : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
205
206
0
  SmallVector<Expr *, 4> Args;
207
0
  if (S.SubstExprs(ArgsToInstantiate,
208
0
                   /*IsCall=*/false, TemplateArgs, Args))
209
0
    return;
210
211
0
  StringRef Str = Attr->getAnnotation();
212
0
  if (HasDelayedArgs) {
213
0
    if (Args.size() < 1) {
214
0
      S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
215
0
          << Attr << 1;
216
0
      return;
217
0
    }
218
219
0
    if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
220
0
      return;
221
222
0
    llvm::SmallVector<Expr *, 4> ActualArgs;
223
0
    ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
224
0
    std::swap(Args, ActualArgs);
225
0
  }
226
0
  S.AddAnnotationAttr(New, *Attr, Str, Args);
227
0
}
228
229
static Expr *instantiateDependentFunctionAttrCondition(
230
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
231
0
    const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
232
0
  Expr *Cond = nullptr;
233
0
  {
234
0
    Sema::ContextRAII SwitchContext(S, New);
235
0
    EnterExpressionEvaluationContext Unevaluated(
236
0
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
237
0
    ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
238
0
    if (Result.isInvalid())
239
0
      return nullptr;
240
0
    Cond = Result.getAs<Expr>();
241
0
  }
242
0
  if (!Cond->isTypeDependent()) {
243
0
    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
244
0
    if (Converted.isInvalid())
245
0
      return nullptr;
246
0
    Cond = Converted.get();
247
0
  }
248
249
0
  SmallVector<PartialDiagnosticAt, 8> Diags;
250
0
  if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
251
0
      !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
252
0
    S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
253
0
    for (const auto &P : Diags)
254
0
      S.Diag(P.first, P.second);
255
0
    return nullptr;
256
0
  }
257
0
  return Cond;
258
0
}
259
260
static void instantiateDependentEnableIfAttr(
261
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
262
0
    const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
263
0
  Expr *Cond = instantiateDependentFunctionAttrCondition(
264
0
      S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
265
266
0
  if (Cond)
267
0
    New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
268
0
                                                      Cond, EIA->getMessage()));
269
0
}
270
271
static void instantiateDependentDiagnoseIfAttr(
272
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
273
0
    const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
274
0
  Expr *Cond = instantiateDependentFunctionAttrCondition(
275
0
      S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
276
277
0
  if (Cond)
278
0
    New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
279
0
        S.getASTContext(), *DIA, Cond, DIA->getMessage(),
280
0
        DIA->getDiagnosticType(), DIA->getArgDependent(), New));
281
0
}
282
283
// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
284
// template A as the base and arguments from TemplateArgs.
285
static void instantiateDependentCUDALaunchBoundsAttr(
286
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
287
0
    const CUDALaunchBoundsAttr &Attr, Decl *New) {
288
  // The alignment expression is a constant expression.
289
0
  EnterExpressionEvaluationContext Unevaluated(
290
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
291
292
0
  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
293
0
  if (Result.isInvalid())
294
0
    return;
295
0
  Expr *MaxThreads = Result.getAs<Expr>();
296
297
0
  Expr *MinBlocks = nullptr;
298
0
  if (Attr.getMinBlocks()) {
299
0
    Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
300
0
    if (Result.isInvalid())
301
0
      return;
302
0
    MinBlocks = Result.getAs<Expr>();
303
0
  }
304
305
0
  Expr *MaxBlocks = nullptr;
306
0
  if (Attr.getMaxBlocks()) {
307
0
    Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
308
0
    if (Result.isInvalid())
309
0
      return;
310
0
    MaxBlocks = Result.getAs<Expr>();
311
0
  }
312
313
0
  S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
314
0
}
315
316
static void
317
instantiateDependentModeAttr(Sema &S,
318
                             const MultiLevelTemplateArgumentList &TemplateArgs,
319
0
                             const ModeAttr &Attr, Decl *New) {
320
0
  S.AddModeAttr(New, Attr, Attr.getMode(),
321
0
                /*InInstantiation=*/true);
322
0
}
323
324
/// Instantiation of 'declare simd' attribute and its arguments.
325
static void instantiateOMPDeclareSimdDeclAttr(
326
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
327
0
    const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
328
  // Allow 'this' in clauses with varlists.
329
0
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
330
0
    New = FTD->getTemplatedDecl();
331
0
  auto *FD = cast<FunctionDecl>(New);
332
0
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
333
0
  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
334
0
  SmallVector<unsigned, 4> LinModifiers;
335
336
0
  auto SubstExpr = [&](Expr *E) -> ExprResult {
337
0
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
338
0
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
339
0
        Sema::ContextRAII SavedContext(S, FD);
340
0
        LocalInstantiationScope Local(S);
341
0
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
342
0
          Local.InstantiatedLocal(
343
0
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
344
0
        return S.SubstExpr(E, TemplateArgs);
345
0
      }
346
0
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
347
0
                                     FD->isCXXInstanceMember());
348
0
    return S.SubstExpr(E, TemplateArgs);
349
0
  };
350
351
  // Substitute a single OpenMP clause, which is a potentially-evaluated
352
  // full-expression.
353
0
  auto Subst = [&](Expr *E) -> ExprResult {
354
0
    EnterExpressionEvaluationContext Evaluated(
355
0
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
356
0
    ExprResult Res = SubstExpr(E);
357
0
    if (Res.isInvalid())
358
0
      return Res;
359
0
    return S.ActOnFinishFullExpr(Res.get(), false);
360
0
  };
361
362
0
  ExprResult Simdlen;
363
0
  if (auto *E = Attr.getSimdlen())
364
0
    Simdlen = Subst(E);
365
366
0
  if (Attr.uniforms_size() > 0) {
367
0
    for(auto *E : Attr.uniforms()) {
368
0
      ExprResult Inst = Subst(E);
369
0
      if (Inst.isInvalid())
370
0
        continue;
371
0
      Uniforms.push_back(Inst.get());
372
0
    }
373
0
  }
374
375
0
  auto AI = Attr.alignments_begin();
376
0
  for (auto *E : Attr.aligneds()) {
377
0
    ExprResult Inst = Subst(E);
378
0
    if (Inst.isInvalid())
379
0
      continue;
380
0
    Aligneds.push_back(Inst.get());
381
0
    Inst = ExprEmpty();
382
0
    if (*AI)
383
0
      Inst = S.SubstExpr(*AI, TemplateArgs);
384
0
    Alignments.push_back(Inst.get());
385
0
    ++AI;
386
0
  }
387
388
0
  auto SI = Attr.steps_begin();
389
0
  for (auto *E : Attr.linears()) {
390
0
    ExprResult Inst = Subst(E);
391
0
    if (Inst.isInvalid())
392
0
      continue;
393
0
    Linears.push_back(Inst.get());
394
0
    Inst = ExprEmpty();
395
0
    if (*SI)
396
0
      Inst = S.SubstExpr(*SI, TemplateArgs);
397
0
    Steps.push_back(Inst.get());
398
0
    ++SI;
399
0
  }
400
0
  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
401
0
  (void)S.ActOnOpenMPDeclareSimdDirective(
402
0
      S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
403
0
      Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
404
0
      Attr.getRange());
405
0
}
406
407
/// Instantiation of 'declare variant' attribute and its arguments.
408
static void instantiateOMPDeclareVariantAttr(
409
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
410
0
    const OMPDeclareVariantAttr &Attr, Decl *New) {
411
  // Allow 'this' in clauses with varlists.
412
0
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
413
0
    New = FTD->getTemplatedDecl();
414
0
  auto *FD = cast<FunctionDecl>(New);
415
0
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
416
417
0
  auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
418
0
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
419
0
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
420
0
        Sema::ContextRAII SavedContext(S, FD);
421
0
        LocalInstantiationScope Local(S);
422
0
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
423
0
          Local.InstantiatedLocal(
424
0
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
425
0
        return S.SubstExpr(E, TemplateArgs);
426
0
      }
427
0
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
428
0
                                     FD->isCXXInstanceMember());
429
0
    return S.SubstExpr(E, TemplateArgs);
430
0
  };
431
432
  // Substitute a single OpenMP clause, which is a potentially-evaluated
433
  // full-expression.
434
0
  auto &&Subst = [&SubstExpr, &S](Expr *E) {
435
0
    EnterExpressionEvaluationContext Evaluated(
436
0
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
437
0
    ExprResult Res = SubstExpr(E);
438
0
    if (Res.isInvalid())
439
0
      return Res;
440
0
    return S.ActOnFinishFullExpr(Res.get(), false);
441
0
  };
442
443
0
  ExprResult VariantFuncRef;
444
0
  if (Expr *E = Attr.getVariantFuncRef()) {
445
    // Do not mark function as is used to prevent its emission if this is the
446
    // only place where it is used.
447
0
    EnterExpressionEvaluationContext Unevaluated(
448
0
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
449
0
    VariantFuncRef = Subst(E);
450
0
  }
451
452
  // Copy the template version of the OMPTraitInfo and run substitute on all
453
  // score and condition expressiosn.
454
0
  OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
455
0
  TI = *Attr.getTraitInfos();
456
457
  // Try to substitute template parameters in score and condition expressions.
458
0
  auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
459
0
    if (E) {
460
0
      EnterExpressionEvaluationContext Unevaluated(
461
0
          S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
462
0
      ExprResult ER = Subst(E);
463
0
      if (ER.isUsable())
464
0
        E = ER.get();
465
0
      else
466
0
        return true;
467
0
    }
468
0
    return false;
469
0
  };
470
0
  if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
471
0
    return;
472
473
0
  Expr *E = VariantFuncRef.get();
474
475
  // Check function/variant ref for `omp declare variant` but not for `omp
476
  // begin declare variant` (which use implicit attributes).
477
0
  std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
478
0
      S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
479
0
                                          Attr.appendArgs_size(),
480
0
                                          Attr.getRange());
481
482
0
  if (!DeclVarData)
483
0
    return;
484
485
0
  E = DeclVarData->second;
486
0
  FD = DeclVarData->first;
487
488
0
  if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
489
0
    if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
490
0
      if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
491
0
        if (!VariantFTD->isThisDeclarationADefinition())
492
0
          return;
493
0
        Sema::TentativeAnalysisScope Trap(S);
494
0
        const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
495
0
            S.Context, TemplateArgs.getInnermost());
496
497
0
        auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
498
0
                                                         New->getLocation());
499
0
        if (!SubstFD)
500
0
          return;
501
0
        QualType NewType = S.Context.mergeFunctionTypes(
502
0
            SubstFD->getType(), FD->getType(),
503
0
            /* OfBlockPointer */ false,
504
0
            /* Unqualified */ false, /* AllowCXX */ true);
505
0
        if (NewType.isNull())
506
0
          return;
507
0
        S.InstantiateFunctionDefinition(
508
0
            New->getLocation(), SubstFD, /* Recursive */ true,
509
0
            /* DefinitionRequired */ false, /* AtEndOfTU */ false);
510
0
        SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
511
0
        E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
512
0
                                SourceLocation(), SubstFD,
513
0
                                /* RefersToEnclosingVariableOrCapture */ false,
514
0
                                /* NameLoc */ SubstFD->getLocation(),
515
0
                                SubstFD->getType(), ExprValueKind::VK_PRValue);
516
0
      }
517
0
    }
518
0
  }
519
520
0
  SmallVector<Expr *, 8> NothingExprs;
521
0
  SmallVector<Expr *, 8> NeedDevicePtrExprs;
522
0
  SmallVector<OMPInteropInfo, 4> AppendArgs;
523
524
0
  for (Expr *E : Attr.adjustArgsNothing()) {
525
0
    ExprResult ER = Subst(E);
526
0
    if (ER.isInvalid())
527
0
      continue;
528
0
    NothingExprs.push_back(ER.get());
529
0
  }
530
0
  for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
531
0
    ExprResult ER = Subst(E);
532
0
    if (ER.isInvalid())
533
0
      continue;
534
0
    NeedDevicePtrExprs.push_back(ER.get());
535
0
  }
536
0
  for (OMPInteropInfo &II : Attr.appendArgs()) {
537
    // When prefer_type is implemented for append_args handle them here too.
538
0
    AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
539
0
  }
540
541
0
  S.ActOnOpenMPDeclareVariantDirective(
542
0
      FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
543
0
      SourceLocation(), Attr.getRange());
544
0
}
545
546
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
547
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
548
0
    const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
549
  // Both min and max expression are constant expressions.
550
0
  EnterExpressionEvaluationContext Unevaluated(
551
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
552
553
0
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
554
0
  if (Result.isInvalid())
555
0
    return;
556
0
  Expr *MinExpr = Result.getAs<Expr>();
557
558
0
  Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
559
0
  if (Result.isInvalid())
560
0
    return;
561
0
  Expr *MaxExpr = Result.getAs<Expr>();
562
563
0
  S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
564
0
}
565
566
ExplicitSpecifier Sema::instantiateExplicitSpecifier(
567
0
    const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
568
0
  if (!ES.getExpr())
569
0
    return ES;
570
0
  Expr *OldCond = ES.getExpr();
571
0
  Expr *Cond = nullptr;
572
0
  {
573
0
    EnterExpressionEvaluationContext Unevaluated(
574
0
        *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
575
0
    ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
576
0
    if (SubstResult.isInvalid()) {
577
0
      return ExplicitSpecifier::Invalid();
578
0
    }
579
0
    Cond = SubstResult.get();
580
0
  }
581
0
  ExplicitSpecifier Result(Cond, ES.getKind());
582
0
  if (!Cond->isTypeDependent())
583
0
    tryResolveExplicitSpecifier(Result);
584
0
  return Result;
585
0
}
586
587
static void instantiateDependentAMDGPUWavesPerEUAttr(
588
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
589
0
    const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
590
  // Both min and max expression are constant expressions.
591
0
  EnterExpressionEvaluationContext Unevaluated(
592
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
593
594
0
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
595
0
  if (Result.isInvalid())
596
0
    return;
597
0
  Expr *MinExpr = Result.getAs<Expr>();
598
599
0
  Expr *MaxExpr = nullptr;
600
0
  if (auto Max = Attr.getMax()) {
601
0
    Result = S.SubstExpr(Max, TemplateArgs);
602
0
    if (Result.isInvalid())
603
0
      return;
604
0
    MaxExpr = Result.getAs<Expr>();
605
0
  }
606
607
0
  S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
608
0
}
609
610
// This doesn't take any template parameters, but we have a custom action that
611
// needs to happen when the kernel itself is instantiated. We need to run the
612
// ItaniumMangler to mark the names required to name this kernel.
613
static void instantiateDependentSYCLKernelAttr(
614
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
615
0
    const SYCLKernelAttr &Attr, Decl *New) {
616
0
  New->addAttr(Attr.clone(S.getASTContext()));
617
0
}
618
619
/// Determine whether the attribute A might be relevant to the declaration D.
620
/// If not, we can skip instantiating it. The attribute may or may not have
621
/// been instantiated yet.
622
0
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
623
  // 'preferred_name' is only relevant to the matching specialization of the
624
  // template.
625
0
  if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
626
0
    QualType T = PNA->getTypedefType();
627
0
    const auto *RD = cast<CXXRecordDecl>(D);
628
0
    if (!T->isDependentType() && !RD->isDependentContext() &&
629
0
        !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
630
0
      return false;
631
0
    for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
632
0
      if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
633
0
                                PNA->getTypedefType()))
634
0
        return false;
635
0
    return true;
636
0
  }
637
638
0
  if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
639
0
    const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
640
0
    switch (BA->getID()) {
641
0
    case Builtin::BIforward:
642
      // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
643
      // type and returns an lvalue reference type. The library implementation
644
      // will produce an error in this case; don't get in its way.
645
0
      if (FD && FD->getNumParams() >= 1 &&
646
0
          FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
647
0
          FD->getReturnType()->isLValueReferenceType()) {
648
0
        return false;
649
0
      }
650
0
      [[fallthrough]];
651
0
    case Builtin::BImove:
652
0
    case Builtin::BImove_if_noexcept:
653
      // HACK: Super-old versions of libc++ (3.1 and earlier) provide
654
      // std::forward and std::move overloads that sometimes return by value
655
      // instead of by reference when building in C++98 mode. Don't treat such
656
      // cases as builtins.
657
0
      if (FD && !FD->getReturnType()->isReferenceType())
658
0
        return false;
659
0
      break;
660
0
    }
661
0
  }
662
663
0
  return true;
664
0
}
665
666
static void instantiateDependentHLSLParamModifierAttr(
667
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
668
0
    const HLSLParamModifierAttr *Attr, Decl *New) {
669
0
  ParmVarDecl *P = cast<ParmVarDecl>(New);
670
0
  P->addAttr(Attr->clone(S.getASTContext()));
671
0
  P->setType(S.getASTContext().getLValueReferenceType(P->getType()));
672
0
}
673
674
void Sema::InstantiateAttrsForDecl(
675
    const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
676
    Decl *New, LateInstantiatedAttrVec *LateAttrs,
677
0
    LocalInstantiationScope *OuterMostScope) {
678
0
  if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
679
    // FIXME: This function is called multiple times for the same template
680
    // specialization. We should only instantiate attributes that were added
681
    // since the previous instantiation.
682
0
    for (const auto *TmplAttr : Tmpl->attrs()) {
683
0
      if (!isRelevantAttr(*this, New, TmplAttr))
684
0
        continue;
685
686
      // FIXME: If any of the special case versions from InstantiateAttrs become
687
      // applicable to template declaration, we'll need to add them here.
688
0
      CXXThisScopeRAII ThisScope(
689
0
          *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
690
0
          Qualifiers(), ND->isCXXInstanceMember());
691
692
0
      Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
693
0
          TmplAttr, Context, *this, TemplateArgs);
694
0
      if (NewAttr && isRelevantAttr(*this, New, NewAttr))
695
0
        New->addAttr(NewAttr);
696
0
    }
697
0
  }
698
0
}
699
700
static Sema::RetainOwnershipKind
701
0
attrToRetainOwnershipKind(const Attr *A) {
702
0
  switch (A->getKind()) {
703
0
  case clang::attr::CFConsumed:
704
0
    return Sema::RetainOwnershipKind::CF;
705
0
  case clang::attr::OSConsumed:
706
0
    return Sema::RetainOwnershipKind::OS;
707
0
  case clang::attr::NSConsumed:
708
0
    return Sema::RetainOwnershipKind::NS;
709
0
  default:
710
0
    llvm_unreachable("Wrong argument supplied");
711
0
  }
712
0
}
713
714
void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
715
                            const Decl *Tmpl, Decl *New,
716
                            LateInstantiatedAttrVec *LateAttrs,
717
0
                            LocalInstantiationScope *OuterMostScope) {
718
0
  for (const auto *TmplAttr : Tmpl->attrs()) {
719
0
    if (!isRelevantAttr(*this, New, TmplAttr))
720
0
      continue;
721
722
    // FIXME: This should be generalized to more than just the AlignedAttr.
723
0
    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
724
0
    if (Aligned && Aligned->isAlignmentDependent()) {
725
0
      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
726
0
      continue;
727
0
    }
728
729
0
    if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
730
0
      instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
731
0
      continue;
732
0
    }
733
734
0
    if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
735
0
      instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
736
0
      continue;
737
0
    }
738
739
0
    if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
740
0
      instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
741
0
      continue;
742
0
    }
743
744
0
    if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
745
0
      instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
746
0
      continue;
747
0
    }
748
749
0
    if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
750
0
      instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
751
0
                                       cast<FunctionDecl>(New));
752
0
      continue;
753
0
    }
754
755
0
    if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
756
0
      instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
757
0
                                         cast<FunctionDecl>(New));
758
0
      continue;
759
0
    }
760
761
0
    if (const auto *CUDALaunchBounds =
762
0
            dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
763
0
      instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
764
0
                                               *CUDALaunchBounds, New);
765
0
      continue;
766
0
    }
767
768
0
    if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
769
0
      instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
770
0
      continue;
771
0
    }
772
773
0
    if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
774
0
      instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
775
0
      continue;
776
0
    }
777
778
0
    if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
779
0
      instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
780
0
      continue;
781
0
    }
782
783
0
    if (const auto *AMDGPUFlatWorkGroupSize =
784
0
            dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
785
0
      instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
786
0
          *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
787
0
    }
788
789
0
    if (const auto *AMDGPUFlatWorkGroupSize =
790
0
            dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
791
0
      instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
792
0
                                               *AMDGPUFlatWorkGroupSize, New);
793
0
    }
794
795
0
    if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
796
0
      instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
797
0
                                                New);
798
0
      continue;
799
0
    }
800
801
    // Existing DLL attribute on the instantiation takes precedence.
802
0
    if (TmplAttr->getKind() == attr::DLLExport ||
803
0
        TmplAttr->getKind() == attr::DLLImport) {
804
0
      if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
805
0
        continue;
806
0
      }
807
0
    }
808
809
0
    if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
810
0
      AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
811
0
      continue;
812
0
    }
813
814
0
    if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
815
0
        isa<CFConsumedAttr>(TmplAttr)) {
816
0
      AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
817
0
                       /*template instantiation=*/true);
818
0
      continue;
819
0
    }
820
821
0
    if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
822
0
      if (!New->hasAttr<PointerAttr>())
823
0
        New->addAttr(A->clone(Context));
824
0
      continue;
825
0
    }
826
827
0
    if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
828
0
      if (!New->hasAttr<OwnerAttr>())
829
0
        New->addAttr(A->clone(Context));
830
0
      continue;
831
0
    }
832
833
0
    if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
834
0
      instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
835
0
      continue;
836
0
    }
837
838
0
    assert(!TmplAttr->isPackExpansion());
839
0
    if (TmplAttr->isLateParsed() && LateAttrs) {
840
      // Late parsed attributes must be instantiated and attached after the
841
      // enclosing class has been instantiated.  See Sema::InstantiateClass.
842
0
      LocalInstantiationScope *Saved = nullptr;
843
0
      if (CurrentInstantiationScope)
844
0
        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
845
0
      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
846
0
    } else {
847
      // Allow 'this' within late-parsed attributes.
848
0
      auto *ND = cast<NamedDecl>(New);
849
0
      auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
850
0
      CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
851
0
                                 ND->isCXXInstanceMember());
852
853
0
      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
854
0
                                                         *this, TemplateArgs);
855
0
      if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
856
0
        New->addAttr(NewAttr);
857
0
    }
858
0
  }
859
0
}
860
861
/// Update instantiation attributes after template was late parsed.
862
///
863
/// Some attributes are evaluated based on the body of template. If it is
864
/// late parsed, such attributes cannot be evaluated when declaration is
865
/// instantiated. This function is used to update instantiation attributes when
866
/// template definition is ready.
867
0
void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
868
0
  for (const auto *Attr : Pattern->attrs()) {
869
0
    if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
870
0
      if (!Inst->hasAttr<StrictFPAttr>())
871
0
        Inst->addAttr(A->clone(getASTContext()));
872
0
      continue;
873
0
    }
874
0
  }
875
0
}
876
877
/// In the MS ABI, we need to instantiate default arguments of dllexported
878
/// default constructors along with the constructor definition. This allows IR
879
/// gen to emit a constructor closure which calls the default constructor with
880
/// its default arguments.
881
0
void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
882
0
  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
883
0
         Ctor->isDefaultConstructor());
884
0
  unsigned NumParams = Ctor->getNumParams();
885
0
  if (NumParams == 0)
886
0
    return;
887
0
  DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
888
0
  if (!Attr)
889
0
    return;
890
0
  for (unsigned I = 0; I != NumParams; ++I) {
891
0
    (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
892
0
                                   Ctor->getParamDecl(I));
893
0
    CleanupVarDeclMarking();
894
0
  }
895
0
}
896
897
/// Get the previous declaration of a declaration for the purposes of template
898
/// instantiation. If this finds a previous declaration, then the previous
899
/// declaration of the instantiation of D should be an instantiation of the
900
/// result of this function.
901
template<typename DeclT>
902
0
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
903
0
  DeclT *Result = D->getPreviousDecl();
904
905
  // If the declaration is within a class, and the previous declaration was
906
  // merged from a different definition of that class, then we don't have a
907
  // previous declaration for the purpose of template instantiation.
908
0
  if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
909
0
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
910
0
    return nullptr;
911
912
0
  return Result;
913
0
}
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::TypedefNameDecl* getPreviousDeclForInstantiation<clang::TypedefNameDecl>(clang::TypedefNameDecl*)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::EnumDecl* getPreviousDeclForInstantiation<clang::EnumDecl>(clang::EnumDecl*)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::CXXRecordDecl* getPreviousDeclForInstantiation<clang::CXXRecordDecl>(clang::CXXRecordDecl*)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::VarDecl* getPreviousDeclForInstantiation<clang::VarDecl>(clang::VarDecl*)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::FunctionTemplateDecl* getPreviousDeclForInstantiation<clang::FunctionTemplateDecl>(clang::FunctionTemplateDecl*)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::UsingShadowDecl* getPreviousDeclForInstantiation<clang::UsingShadowDecl>(clang::UsingShadowDecl*)
914
915
Decl *
916
0
TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
917
0
  llvm_unreachable("Translation units cannot be instantiated");
918
0
}
919
920
0
Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
921
0
  llvm_unreachable("HLSL buffer declarations cannot be instantiated");
922
0
}
923
924
Decl *
925
0
TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
926
0
  llvm_unreachable("pragma comment cannot be instantiated");
927
0
}
928
929
Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
930
0
    PragmaDetectMismatchDecl *D) {
931
0
  llvm_unreachable("pragma comment cannot be instantiated");
932
0
}
933
934
Decl *
935
0
TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
936
0
  llvm_unreachable("extern \"C\" context cannot be instantiated");
937
0
}
938
939
0
Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
940
0
  llvm_unreachable("GUID declaration cannot be instantiated");
941
0
}
942
943
Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
944
0
    UnnamedGlobalConstantDecl *D) {
945
0
  llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
946
0
}
947
948
Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
949
0
    TemplateParamObjectDecl *D) {
950
0
  llvm_unreachable("template parameter objects cannot be instantiated");
951
0
}
952
953
Decl *
954
0
TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
955
0
  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
956
0
                                      D->getIdentifier());
957
0
  Owner->addDecl(Inst);
958
0
  return Inst;
959
0
}
960
961
Decl *
962
0
TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
963
0
  llvm_unreachable("Namespaces cannot be instantiated");
964
0
}
965
966
Decl *
967
0
TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
968
0
  NamespaceAliasDecl *Inst
969
0
    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
970
0
                                 D->getNamespaceLoc(),
971
0
                                 D->getAliasLoc(),
972
0
                                 D->getIdentifier(),
973
0
                                 D->getQualifierLoc(),
974
0
                                 D->getTargetNameLoc(),
975
0
                                 D->getNamespace());
976
0
  Owner->addDecl(Inst);
977
0
  return Inst;
978
0
}
979
980
Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
981
0
                                                           bool IsTypeAlias) {
982
0
  bool Invalid = false;
983
0
  TypeSourceInfo *DI = D->getTypeSourceInfo();
984
0
  if (DI->getType()->isInstantiationDependentType() ||
985
0
      DI->getType()->isVariablyModifiedType()) {
986
0
    DI = SemaRef.SubstType(DI, TemplateArgs,
987
0
                           D->getLocation(), D->getDeclName());
988
0
    if (!DI) {
989
0
      Invalid = true;
990
0
      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
991
0
    }
992
0
  } else {
993
0
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
994
0
  }
995
996
  // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
997
  // libstdc++ relies upon this bug in its implementation of common_type.  If we
998
  // happen to be processing that implementation, fake up the g++ ?:
999
  // semantics. See LWG issue 2141 for more information on the bug.  The bugs
1000
  // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1001
0
  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1002
0
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1003
0
  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1004
0
      DT->isReferenceType() &&
1005
0
      RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1006
0
      RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1007
0
      D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1008
0
      SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1009
    // Fold it to the (non-reference) type which g++ would have produced.
1010
0
    DI = SemaRef.Context.getTrivialTypeSourceInfo(
1011
0
      DI->getType().getNonReferenceType());
1012
1013
  // Create the new typedef
1014
0
  TypedefNameDecl *Typedef;
1015
0
  if (IsTypeAlias)
1016
0
    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1017
0
                                    D->getLocation(), D->getIdentifier(), DI);
1018
0
  else
1019
0
    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1020
0
                                  D->getLocation(), D->getIdentifier(), DI);
1021
0
  if (Invalid)
1022
0
    Typedef->setInvalidDecl();
1023
1024
  // If the old typedef was the name for linkage purposes of an anonymous
1025
  // tag decl, re-establish that relationship for the new typedef.
1026
0
  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1027
0
    TagDecl *oldTag = oldTagType->getDecl();
1028
0
    if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1029
0
      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1030
0
      assert(!newTag->hasNameForLinkage());
1031
0
      newTag->setTypedefNameForAnonDecl(Typedef);
1032
0
    }
1033
0
  }
1034
1035
0
  if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1036
0
    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1037
0
                                                       TemplateArgs);
1038
0
    if (!InstPrev)
1039
0
      return nullptr;
1040
1041
0
    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1042
1043
    // If the typedef types are not identical, reject them.
1044
0
    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1045
1046
0
    Typedef->setPreviousDecl(InstPrevTypedef);
1047
0
  }
1048
1049
0
  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1050
1051
0
  if (D->getUnderlyingType()->getAs<DependentNameType>())
1052
0
    SemaRef.inferGslPointerAttribute(Typedef);
1053
1054
0
  Typedef->setAccess(D->getAccess());
1055
0
  Typedef->setReferenced(D->isReferenced());
1056
1057
0
  return Typedef;
1058
0
}
1059
1060
0
Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1061
0
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1062
0
  if (Typedef)
1063
0
    Owner->addDecl(Typedef);
1064
0
  return Typedef;
1065
0
}
1066
1067
0
Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1068
0
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1069
0
  if (Typedef)
1070
0
    Owner->addDecl(Typedef);
1071
0
  return Typedef;
1072
0
}
1073
1074
Decl *
1075
0
TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1076
  // Create a local instantiation scope for this type alias template, which
1077
  // will contain the instantiations of the template parameters.
1078
0
  LocalInstantiationScope Scope(SemaRef);
1079
1080
0
  TemplateParameterList *TempParams = D->getTemplateParameters();
1081
0
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1082
0
  if (!InstParams)
1083
0
    return nullptr;
1084
1085
0
  TypeAliasDecl *Pattern = D->getTemplatedDecl();
1086
1087
0
  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1088
0
  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1089
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1090
0
    if (!Found.empty()) {
1091
0
      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1092
0
    }
1093
0
  }
1094
1095
0
  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1096
0
    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1097
0
  if (!AliasInst)
1098
0
    return nullptr;
1099
1100
0
  TypeAliasTemplateDecl *Inst
1101
0
    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1102
0
                                    D->getDeclName(), InstParams, AliasInst);
1103
0
  AliasInst->setDescribedAliasTemplate(Inst);
1104
0
  if (PrevAliasTemplate)
1105
0
    Inst->setPreviousDecl(PrevAliasTemplate);
1106
1107
0
  Inst->setAccess(D->getAccess());
1108
1109
0
  if (!PrevAliasTemplate)
1110
0
    Inst->setInstantiatedFromMemberTemplate(D);
1111
1112
0
  Owner->addDecl(Inst);
1113
1114
0
  return Inst;
1115
0
}
1116
1117
0
Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1118
0
  auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1119
0
                                    D->getIdentifier());
1120
0
  NewBD->setReferenced(D->isReferenced());
1121
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1122
0
  return NewBD;
1123
0
}
1124
1125
0
Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1126
  // Transform the bindings first.
1127
0
  SmallVector<BindingDecl*, 16> NewBindings;
1128
0
  for (auto *OldBD : D->bindings())
1129
0
    NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1130
0
  ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1131
1132
0
  auto *NewDD = cast_or_null<DecompositionDecl>(
1133
0
      VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1134
1135
0
  if (!NewDD || NewDD->isInvalidDecl())
1136
0
    for (auto *NewBD : NewBindings)
1137
0
      NewBD->setInvalidDecl();
1138
1139
0
  return NewDD;
1140
0
}
1141
1142
0
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1143
0
  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1144
0
}
1145
1146
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1147
                                             bool InstantiatingVarTemplate,
1148
0
                                             ArrayRef<BindingDecl*> *Bindings) {
1149
1150
  // Do substitution on the type of the declaration
1151
0
  TypeSourceInfo *DI = SemaRef.SubstType(
1152
0
      D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1153
0
      D->getDeclName(), /*AllowDeducedTST*/true);
1154
0
  if (!DI)
1155
0
    return nullptr;
1156
1157
0
  if (DI->getType()->isFunctionType()) {
1158
0
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1159
0
      << D->isStaticDataMember() << DI->getType();
1160
0
    return nullptr;
1161
0
  }
1162
1163
0
  DeclContext *DC = Owner;
1164
0
  if (D->isLocalExternDecl())
1165
0
    SemaRef.adjustContextForLocalExternDecl(DC);
1166
1167
  // Build the instantiated declaration.
1168
0
  VarDecl *Var;
1169
0
  if (Bindings)
1170
0
    Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1171
0
                                    D->getLocation(), DI->getType(), DI,
1172
0
                                    D->getStorageClass(), *Bindings);
1173
0
  else
1174
0
    Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1175
0
                          D->getLocation(), D->getIdentifier(), DI->getType(),
1176
0
                          DI, D->getStorageClass());
1177
1178
  // In ARC, infer 'retaining' for variables of retainable type.
1179
0
  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1180
0
      SemaRef.inferObjCARCLifetime(Var))
1181
0
    Var->setInvalidDecl();
1182
1183
0
  if (SemaRef.getLangOpts().OpenCL)
1184
0
    SemaRef.deduceOpenCLAddressSpace(Var);
1185
1186
  // Substitute the nested name specifier, if any.
1187
0
  if (SubstQualifier(D, Var))
1188
0
    return nullptr;
1189
1190
0
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1191
0
                                     StartingScope, InstantiatingVarTemplate);
1192
0
  if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1193
0
    QualType RT;
1194
0
    if (auto *F = dyn_cast<FunctionDecl>(DC))
1195
0
      RT = F->getReturnType();
1196
0
    else if (isa<BlockDecl>(DC))
1197
0
      RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1198
0
               ->getReturnType();
1199
0
    else
1200
0
      llvm_unreachable("Unknown context type");
1201
1202
    // This is the last chance we have of checking copy elision eligibility
1203
    // for functions in dependent contexts. The sema actions for building
1204
    // the return statement during template instantiation will have no effect
1205
    // regarding copy elision, since NRVO propagation runs on the scope exit
1206
    // actions, and these are not run on instantiation.
1207
    // This might run through some VarDecls which were returned from non-taken
1208
    // 'if constexpr' branches, and these will end up being constructed on the
1209
    // return slot even if they will never be returned, as a sort of accidental
1210
    // 'optimization'. Notably, functions with 'auto' return types won't have it
1211
    // deduced by this point. Coupled with the limitation described
1212
    // previously, this makes it very hard to support copy elision for these.
1213
0
    Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1214
0
    bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1215
0
    Var->setNRVOVariable(NRVO);
1216
0
  }
1217
1218
0
  Var->setImplicit(D->isImplicit());
1219
1220
0
  if (Var->isStaticLocal())
1221
0
    SemaRef.CheckStaticLocalForDllExport(Var);
1222
1223
0
  if (Var->getTLSKind())
1224
0
    SemaRef.CheckThreadLocalForLargeAlignment(Var);
1225
1226
0
  return Var;
1227
0
}
1228
1229
0
Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1230
0
  AccessSpecDecl* AD
1231
0
    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1232
0
                             D->getAccessSpecifierLoc(), D->getColonLoc());
1233
0
  Owner->addHiddenDecl(AD);
1234
0
  return AD;
1235
0
}
1236
1237
0
Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1238
0
  bool Invalid = false;
1239
0
  TypeSourceInfo *DI = D->getTypeSourceInfo();
1240
0
  if (DI->getType()->isInstantiationDependentType() ||
1241
0
      DI->getType()->isVariablyModifiedType())  {
1242
0
    DI = SemaRef.SubstType(DI, TemplateArgs,
1243
0
                           D->getLocation(), D->getDeclName());
1244
0
    if (!DI) {
1245
0
      DI = D->getTypeSourceInfo();
1246
0
      Invalid = true;
1247
0
    } else if (DI->getType()->isFunctionType()) {
1248
      // C++ [temp.arg.type]p3:
1249
      //   If a declaration acquires a function type through a type
1250
      //   dependent on a template-parameter and this causes a
1251
      //   declaration that does not use the syntactic form of a
1252
      //   function declarator to have function type, the program is
1253
      //   ill-formed.
1254
0
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1255
0
        << DI->getType();
1256
0
      Invalid = true;
1257
0
    }
1258
0
  } else {
1259
0
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1260
0
  }
1261
1262
0
  Expr *BitWidth = D->getBitWidth();
1263
0
  if (Invalid)
1264
0
    BitWidth = nullptr;
1265
0
  else if (BitWidth) {
1266
    // The bit-width expression is a constant expression.
1267
0
    EnterExpressionEvaluationContext Unevaluated(
1268
0
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1269
1270
0
    ExprResult InstantiatedBitWidth
1271
0
      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1272
0
    if (InstantiatedBitWidth.isInvalid()) {
1273
0
      Invalid = true;
1274
0
      BitWidth = nullptr;
1275
0
    } else
1276
0
      BitWidth = InstantiatedBitWidth.getAs<Expr>();
1277
0
  }
1278
1279
0
  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1280
0
                                            DI->getType(), DI,
1281
0
                                            cast<RecordDecl>(Owner),
1282
0
                                            D->getLocation(),
1283
0
                                            D->isMutable(),
1284
0
                                            BitWidth,
1285
0
                                            D->getInClassInitStyle(),
1286
0
                                            D->getInnerLocStart(),
1287
0
                                            D->getAccess(),
1288
0
                                            nullptr);
1289
0
  if (!Field) {
1290
0
    cast<Decl>(Owner)->setInvalidDecl();
1291
0
    return nullptr;
1292
0
  }
1293
1294
0
  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1295
1296
0
  if (Field->hasAttrs())
1297
0
    SemaRef.CheckAlignasUnderalignment(Field);
1298
1299
0
  if (Invalid)
1300
0
    Field->setInvalidDecl();
1301
1302
0
  if (!Field->getDeclName()) {
1303
    // Keep track of where this decl came from.
1304
0
    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1305
0
  }
1306
0
  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1307
0
    if (Parent->isAnonymousStructOrUnion() &&
1308
0
        Parent->getRedeclContext()->isFunctionOrMethod())
1309
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1310
0
  }
1311
1312
0
  Field->setImplicit(D->isImplicit());
1313
0
  Field->setAccess(D->getAccess());
1314
0
  Owner->addDecl(Field);
1315
1316
0
  return Field;
1317
0
}
1318
1319
0
Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1320
0
  bool Invalid = false;
1321
0
  TypeSourceInfo *DI = D->getTypeSourceInfo();
1322
1323
0
  if (DI->getType()->isVariablyModifiedType()) {
1324
0
    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1325
0
      << D;
1326
0
    Invalid = true;
1327
0
  } else if (DI->getType()->isInstantiationDependentType())  {
1328
0
    DI = SemaRef.SubstType(DI, TemplateArgs,
1329
0
                           D->getLocation(), D->getDeclName());
1330
0
    if (!DI) {
1331
0
      DI = D->getTypeSourceInfo();
1332
0
      Invalid = true;
1333
0
    } else if (DI->getType()->isFunctionType()) {
1334
      // C++ [temp.arg.type]p3:
1335
      //   If a declaration acquires a function type through a type
1336
      //   dependent on a template-parameter and this causes a
1337
      //   declaration that does not use the syntactic form of a
1338
      //   function declarator to have function type, the program is
1339
      //   ill-formed.
1340
0
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1341
0
      << DI->getType();
1342
0
      Invalid = true;
1343
0
    }
1344
0
  } else {
1345
0
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1346
0
  }
1347
1348
0
  MSPropertyDecl *Property = MSPropertyDecl::Create(
1349
0
      SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1350
0
      DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1351
1352
0
  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1353
0
                           StartingScope);
1354
1355
0
  if (Invalid)
1356
0
    Property->setInvalidDecl();
1357
1358
0
  Property->setAccess(D->getAccess());
1359
0
  Owner->addDecl(Property);
1360
1361
0
  return Property;
1362
0
}
1363
1364
0
Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1365
0
  NamedDecl **NamedChain =
1366
0
    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1367
1368
0
  int i = 0;
1369
0
  for (auto *PI : D->chain()) {
1370
0
    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1371
0
                                              TemplateArgs);
1372
0
    if (!Next)
1373
0
      return nullptr;
1374
1375
0
    NamedChain[i++] = Next;
1376
0
  }
1377
1378
0
  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1379
0
  IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1380
0
      SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1381
0
      {NamedChain, D->getChainingSize()});
1382
1383
0
  for (const auto *Attr : D->attrs())
1384
0
    IndirectField->addAttr(Attr->clone(SemaRef.Context));
1385
1386
0
  IndirectField->setImplicit(D->isImplicit());
1387
0
  IndirectField->setAccess(D->getAccess());
1388
0
  Owner->addDecl(IndirectField);
1389
0
  return IndirectField;
1390
0
}
1391
1392
0
Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1393
  // Handle friend type expressions by simply substituting template
1394
  // parameters into the pattern type and checking the result.
1395
0
  if (TypeSourceInfo *Ty = D->getFriendType()) {
1396
0
    TypeSourceInfo *InstTy;
1397
    // If this is an unsupported friend, don't bother substituting template
1398
    // arguments into it. The actual type referred to won't be used by any
1399
    // parts of Clang, and may not be valid for instantiating. Just use the
1400
    // same info for the instantiated friend.
1401
0
    if (D->isUnsupportedFriend()) {
1402
0
      InstTy = Ty;
1403
0
    } else {
1404
0
      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1405
0
                                 D->getLocation(), DeclarationName());
1406
0
    }
1407
0
    if (!InstTy)
1408
0
      return nullptr;
1409
1410
0
    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1411
0
                                                 D->getFriendLoc(), InstTy);
1412
0
    if (!FD)
1413
0
      return nullptr;
1414
1415
0
    FD->setAccess(AS_public);
1416
0
    FD->setUnsupportedFriend(D->isUnsupportedFriend());
1417
0
    Owner->addDecl(FD);
1418
0
    return FD;
1419
0
  }
1420
1421
0
  NamedDecl *ND = D->getFriendDecl();
1422
0
  assert(ND && "friend decl must be a decl or a type!");
1423
1424
  // All of the Visit implementations for the various potential friend
1425
  // declarations have to be carefully written to work for friend
1426
  // objects, with the most important detail being that the target
1427
  // decl should almost certainly not be placed in Owner.
1428
0
  Decl *NewND = Visit(ND);
1429
0
  if (!NewND) return nullptr;
1430
1431
0
  FriendDecl *FD =
1432
0
    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1433
0
                       cast<NamedDecl>(NewND), D->getFriendLoc());
1434
0
  FD->setAccess(AS_public);
1435
0
  FD->setUnsupportedFriend(D->isUnsupportedFriend());
1436
0
  Owner->addDecl(FD);
1437
0
  return FD;
1438
0
}
1439
1440
0
Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1441
0
  Expr *AssertExpr = D->getAssertExpr();
1442
1443
  // The expression in a static assertion is a constant expression.
1444
0
  EnterExpressionEvaluationContext Unevaluated(
1445
0
      SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1446
1447
0
  ExprResult InstantiatedAssertExpr
1448
0
    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1449
0
  if (InstantiatedAssertExpr.isInvalid())
1450
0
    return nullptr;
1451
1452
0
  ExprResult InstantiatedMessageExpr =
1453
0
      SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1454
0
  if (InstantiatedMessageExpr.isInvalid())
1455
0
    return nullptr;
1456
1457
0
  return SemaRef.BuildStaticAssertDeclaration(
1458
0
      D->getLocation(), InstantiatedAssertExpr.get(),
1459
0
      InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1460
0
}
1461
1462
0
Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1463
0
  EnumDecl *PrevDecl = nullptr;
1464
0
  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1465
0
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1466
0
                                                   PatternPrev,
1467
0
                                                   TemplateArgs);
1468
0
    if (!Prev) return nullptr;
1469
0
    PrevDecl = cast<EnumDecl>(Prev);
1470
0
  }
1471
1472
0
  EnumDecl *Enum =
1473
0
      EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1474
0
                       D->getLocation(), D->getIdentifier(), PrevDecl,
1475
0
                       D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1476
0
  if (D->isFixed()) {
1477
0
    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1478
      // If we have type source information for the underlying type, it means it
1479
      // has been explicitly set by the user. Perform substitution on it before
1480
      // moving on.
1481
0
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1482
0
      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1483
0
                                                DeclarationName());
1484
0
      if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1485
0
        Enum->setIntegerType(SemaRef.Context.IntTy);
1486
0
      else
1487
0
        Enum->setIntegerTypeSourceInfo(NewTI);
1488
0
    } else {
1489
0
      assert(!D->getIntegerType()->isDependentType()
1490
0
             && "Dependent type without type source info");
1491
0
      Enum->setIntegerType(D->getIntegerType());
1492
0
    }
1493
0
  }
1494
1495
0
  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1496
1497
0
  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1498
0
  Enum->setAccess(D->getAccess());
1499
  // Forward the mangling number from the template to the instantiated decl.
1500
0
  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1501
  // See if the old tag was defined along with a declarator.
1502
  // If it did, mark the new tag as being associated with that declarator.
1503
0
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1504
0
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1505
  // See if the old tag was defined along with a typedef.
1506
  // If it did, mark the new tag as being associated with that typedef.
1507
0
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1508
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1509
0
  if (SubstQualifier(D, Enum)) return nullptr;
1510
0
  Owner->addDecl(Enum);
1511
1512
0
  EnumDecl *Def = D->getDefinition();
1513
0
  if (Def && Def != D) {
1514
    // If this is an out-of-line definition of an enum member template, check
1515
    // that the underlying types match in the instantiation of both
1516
    // declarations.
1517
0
    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1518
0
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1519
0
      QualType DefnUnderlying =
1520
0
        SemaRef.SubstType(TI->getType(), TemplateArgs,
1521
0
                          UnderlyingLoc, DeclarationName());
1522
0
      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1523
0
                                     DefnUnderlying, /*IsFixed=*/true, Enum);
1524
0
    }
1525
0
  }
1526
1527
  // C++11 [temp.inst]p1: The implicit instantiation of a class template
1528
  // specialization causes the implicit instantiation of the declarations, but
1529
  // not the definitions of scoped member enumerations.
1530
  //
1531
  // DR1484 clarifies that enumeration definitions inside of a template
1532
  // declaration aren't considered entities that can be separately instantiated
1533
  // from the rest of the entity they are declared inside of.
1534
0
  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1535
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1536
0
    InstantiateEnumDefinition(Enum, Def);
1537
0
  }
1538
1539
0
  return Enum;
1540
0
}
1541
1542
void TemplateDeclInstantiator::InstantiateEnumDefinition(
1543
0
    EnumDecl *Enum, EnumDecl *Pattern) {
1544
0
  Enum->startDefinition();
1545
1546
  // Update the location to refer to the definition.
1547
0
  Enum->setLocation(Pattern->getLocation());
1548
1549
0
  SmallVector<Decl*, 4> Enumerators;
1550
1551
0
  EnumConstantDecl *LastEnumConst = nullptr;
1552
0
  for (auto *EC : Pattern->enumerators()) {
1553
    // The specified value for the enumerator.
1554
0
    ExprResult Value((Expr *)nullptr);
1555
0
    if (Expr *UninstValue = EC->getInitExpr()) {
1556
      // The enumerator's value expression is a constant expression.
1557
0
      EnterExpressionEvaluationContext Unevaluated(
1558
0
          SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1559
1560
0
      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1561
0
    }
1562
1563
    // Drop the initial value and continue.
1564
0
    bool isInvalid = false;
1565
0
    if (Value.isInvalid()) {
1566
0
      Value = nullptr;
1567
0
      isInvalid = true;
1568
0
    }
1569
1570
0
    EnumConstantDecl *EnumConst
1571
0
      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1572
0
                                  EC->getLocation(), EC->getIdentifier(),
1573
0
                                  Value.get());
1574
1575
0
    if (isInvalid) {
1576
0
      if (EnumConst)
1577
0
        EnumConst->setInvalidDecl();
1578
0
      Enum->setInvalidDecl();
1579
0
    }
1580
1581
0
    if (EnumConst) {
1582
0
      SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1583
1584
0
      EnumConst->setAccess(Enum->getAccess());
1585
0
      Enum->addDecl(EnumConst);
1586
0
      Enumerators.push_back(EnumConst);
1587
0
      LastEnumConst = EnumConst;
1588
1589
0
      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1590
0
          !Enum->isScoped()) {
1591
        // If the enumeration is within a function or method, record the enum
1592
        // constant as a local.
1593
0
        SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1594
0
      }
1595
0
    }
1596
0
  }
1597
1598
0
  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1599
0
                        Enumerators, nullptr, ParsedAttributesView());
1600
0
}
1601
1602
0
Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1603
0
  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1604
0
}
1605
1606
Decl *
1607
0
TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1608
0
  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1609
0
}
1610
1611
0
Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1612
0
  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1613
1614
  // Create a local instantiation scope for this class template, which
1615
  // will contain the instantiations of the template parameters.
1616
0
  LocalInstantiationScope Scope(SemaRef);
1617
0
  TemplateParameterList *TempParams = D->getTemplateParameters();
1618
0
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1619
0
  if (!InstParams)
1620
0
    return nullptr;
1621
1622
0
  CXXRecordDecl *Pattern = D->getTemplatedDecl();
1623
1624
  // Instantiate the qualifier.  We have to do this first in case
1625
  // we're a friend declaration, because if we are then we need to put
1626
  // the new declaration in the appropriate context.
1627
0
  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1628
0
  if (QualifierLoc) {
1629
0
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1630
0
                                                       TemplateArgs);
1631
0
    if (!QualifierLoc)
1632
0
      return nullptr;
1633
0
  }
1634
1635
0
  CXXRecordDecl *PrevDecl = nullptr;
1636
0
  ClassTemplateDecl *PrevClassTemplate = nullptr;
1637
1638
0
  if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1639
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1640
0
    if (!Found.empty()) {
1641
0
      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1642
0
      if (PrevClassTemplate)
1643
0
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1644
0
    }
1645
0
  }
1646
1647
  // If this isn't a friend, then it's a member template, in which
1648
  // case we just want to build the instantiation in the
1649
  // specialization.  If it is a friend, we want to build it in
1650
  // the appropriate context.
1651
0
  DeclContext *DC = Owner;
1652
0
  if (isFriend) {
1653
0
    if (QualifierLoc) {
1654
0
      CXXScopeSpec SS;
1655
0
      SS.Adopt(QualifierLoc);
1656
0
      DC = SemaRef.computeDeclContext(SS);
1657
0
      if (!DC) return nullptr;
1658
0
    } else {
1659
0
      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1660
0
                                           Pattern->getDeclContext(),
1661
0
                                           TemplateArgs);
1662
0
    }
1663
1664
    // Look for a previous declaration of the template in the owning
1665
    // context.
1666
0
    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1667
0
                   Sema::LookupOrdinaryName,
1668
0
                   SemaRef.forRedeclarationInCurContext());
1669
0
    SemaRef.LookupQualifiedName(R, DC);
1670
1671
0
    if (R.isSingleResult()) {
1672
0
      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1673
0
      if (PrevClassTemplate)
1674
0
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1675
0
    }
1676
1677
0
    if (!PrevClassTemplate && QualifierLoc) {
1678
0
      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1679
0
          << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1680
0
          << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1681
0
      return nullptr;
1682
0
    }
1683
0
  }
1684
1685
0
  CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1686
0
      SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1687
0
      Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1688
0
      /*DelayTypeCreation=*/true);
1689
0
  if (QualifierLoc)
1690
0
    RecordInst->setQualifierInfo(QualifierLoc);
1691
1692
0
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1693
0
                                                              StartingScope);
1694
1695
0
  ClassTemplateDecl *Inst
1696
0
    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1697
0
                                D->getIdentifier(), InstParams, RecordInst);
1698
0
  RecordInst->setDescribedClassTemplate(Inst);
1699
1700
0
  if (isFriend) {
1701
0
    assert(!Owner->isDependentContext());
1702
0
    Inst->setLexicalDeclContext(Owner);
1703
0
    RecordInst->setLexicalDeclContext(Owner);
1704
1705
0
    if (PrevClassTemplate) {
1706
0
      Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1707
0
      RecordInst->setTypeForDecl(
1708
0
          PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1709
0
      const ClassTemplateDecl *MostRecentPrevCT =
1710
0
          PrevClassTemplate->getMostRecentDecl();
1711
0
      TemplateParameterList *PrevParams =
1712
0
          MostRecentPrevCT->getTemplateParameters();
1713
1714
      // Make sure the parameter lists match.
1715
0
      if (!SemaRef.TemplateParameterListsAreEqual(
1716
0
              RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1717
0
              PrevParams, true, Sema::TPL_TemplateMatch))
1718
0
        return nullptr;
1719
1720
      // Do some additional validation, then merge default arguments
1721
      // from the existing declarations.
1722
0
      if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1723
0
                                             Sema::TPC_ClassTemplate))
1724
0
        return nullptr;
1725
1726
0
      Inst->setAccess(PrevClassTemplate->getAccess());
1727
0
    } else {
1728
0
      Inst->setAccess(D->getAccess());
1729
0
    }
1730
1731
0
    Inst->setObjectOfFriendDecl();
1732
    // TODO: do we want to track the instantiation progeny of this
1733
    // friend target decl?
1734
0
  } else {
1735
0
    Inst->setAccess(D->getAccess());
1736
0
    if (!PrevClassTemplate)
1737
0
      Inst->setInstantiatedFromMemberTemplate(D);
1738
0
  }
1739
1740
0
  Inst->setPreviousDecl(PrevClassTemplate);
1741
1742
  // Trigger creation of the type for the instantiation.
1743
0
  SemaRef.Context.getInjectedClassNameType(
1744
0
      RecordInst, Inst->getInjectedClassNameSpecialization());
1745
1746
  // Finish handling of friends.
1747
0
  if (isFriend) {
1748
0
    DC->makeDeclVisibleInContext(Inst);
1749
0
    return Inst;
1750
0
  }
1751
1752
0
  if (D->isOutOfLine()) {
1753
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1754
0
    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1755
0
  }
1756
1757
0
  Owner->addDecl(Inst);
1758
1759
0
  if (!PrevClassTemplate) {
1760
    // Queue up any out-of-line partial specializations of this member
1761
    // class template; the client will force their instantiation once
1762
    // the enclosing class has been instantiated.
1763
0
    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1764
0
    D->getPartialSpecializations(PartialSpecs);
1765
0
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1766
0
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1767
0
        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1768
0
  }
1769
1770
0
  return Inst;
1771
0
}
1772
1773
Decl *
1774
TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1775
0
                                   ClassTemplatePartialSpecializationDecl *D) {
1776
0
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1777
1778
  // Lookup the already-instantiated declaration in the instantiation
1779
  // of the class template and return that.
1780
0
  DeclContext::lookup_result Found
1781
0
    = Owner->lookup(ClassTemplate->getDeclName());
1782
0
  if (Found.empty())
1783
0
    return nullptr;
1784
1785
0
  ClassTemplateDecl *InstClassTemplate
1786
0
    = dyn_cast<ClassTemplateDecl>(Found.front());
1787
0
  if (!InstClassTemplate)
1788
0
    return nullptr;
1789
1790
0
  if (ClassTemplatePartialSpecializationDecl *Result
1791
0
        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1792
0
    return Result;
1793
1794
0
  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1795
0
}
1796
1797
0
Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1798
0
  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1799
0
         "Only static data member templates are allowed.");
1800
1801
  // Create a local instantiation scope for this variable template, which
1802
  // will contain the instantiations of the template parameters.
1803
0
  LocalInstantiationScope Scope(SemaRef);
1804
0
  TemplateParameterList *TempParams = D->getTemplateParameters();
1805
0
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1806
0
  if (!InstParams)
1807
0
    return nullptr;
1808
1809
0
  VarDecl *Pattern = D->getTemplatedDecl();
1810
0
  VarTemplateDecl *PrevVarTemplate = nullptr;
1811
1812
0
  if (getPreviousDeclForInstantiation(Pattern)) {
1813
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1814
0
    if (!Found.empty())
1815
0
      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1816
0
  }
1817
1818
0
  VarDecl *VarInst =
1819
0
      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1820
0
                                         /*InstantiatingVarTemplate=*/true));
1821
0
  if (!VarInst) return nullptr;
1822
1823
0
  DeclContext *DC = Owner;
1824
1825
0
  VarTemplateDecl *Inst = VarTemplateDecl::Create(
1826
0
      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1827
0
      VarInst);
1828
0
  VarInst->setDescribedVarTemplate(Inst);
1829
0
  Inst->setPreviousDecl(PrevVarTemplate);
1830
1831
0
  Inst->setAccess(D->getAccess());
1832
0
  if (!PrevVarTemplate)
1833
0
    Inst->setInstantiatedFromMemberTemplate(D);
1834
1835
0
  if (D->isOutOfLine()) {
1836
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1837
0
    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1838
0
  }
1839
1840
0
  Owner->addDecl(Inst);
1841
1842
0
  if (!PrevVarTemplate) {
1843
    // Queue up any out-of-line partial specializations of this member
1844
    // variable template; the client will force their instantiation once
1845
    // the enclosing class has been instantiated.
1846
0
    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1847
0
    D->getPartialSpecializations(PartialSpecs);
1848
0
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1849
0
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1850
0
        OutOfLineVarPartialSpecs.push_back(
1851
0
            std::make_pair(Inst, PartialSpecs[I]));
1852
0
  }
1853
1854
0
  return Inst;
1855
0
}
1856
1857
Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1858
0
    VarTemplatePartialSpecializationDecl *D) {
1859
0
  assert(D->isStaticDataMember() &&
1860
0
         "Only static data member templates are allowed.");
1861
1862
0
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1863
1864
  // Lookup the already-instantiated declaration and return that.
1865
0
  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1866
0
  assert(!Found.empty() && "Instantiation found nothing?");
1867
1868
0
  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1869
0
  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1870
1871
0
  if (VarTemplatePartialSpecializationDecl *Result =
1872
0
          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1873
0
    return Result;
1874
1875
0
  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1876
0
}
1877
1878
Decl *
1879
0
TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1880
  // Create a local instantiation scope for this function template, which
1881
  // will contain the instantiations of the template parameters and then get
1882
  // merged with the local instantiation scope for the function template
1883
  // itself.
1884
0
  LocalInstantiationScope Scope(SemaRef);
1885
0
  Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
1886
1887
0
  TemplateParameterList *TempParams = D->getTemplateParameters();
1888
0
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1889
0
  if (!InstParams)
1890
0
    return nullptr;
1891
1892
0
  FunctionDecl *Instantiated = nullptr;
1893
0
  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1894
0
    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1895
0
                                                                 InstParams));
1896
0
  else
1897
0
    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1898
0
                                                          D->getTemplatedDecl(),
1899
0
                                                                InstParams));
1900
1901
0
  if (!Instantiated)
1902
0
    return nullptr;
1903
1904
  // Link the instantiated function template declaration to the function
1905
  // template from which it was instantiated.
1906
0
  FunctionTemplateDecl *InstTemplate
1907
0
    = Instantiated->getDescribedFunctionTemplate();
1908
0
  InstTemplate->setAccess(D->getAccess());
1909
0
  assert(InstTemplate &&
1910
0
         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1911
1912
0
  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1913
1914
  // Link the instantiation back to the pattern *unless* this is a
1915
  // non-definition friend declaration.
1916
0
  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1917
0
      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1918
0
    InstTemplate->setInstantiatedFromMemberTemplate(D);
1919
1920
  // Make declarations visible in the appropriate context.
1921
0
  if (!isFriend) {
1922
0
    Owner->addDecl(InstTemplate);
1923
0
  } else if (InstTemplate->getDeclContext()->isRecord() &&
1924
0
             !getPreviousDeclForInstantiation(D)) {
1925
0
    SemaRef.CheckFriendAccess(InstTemplate);
1926
0
  }
1927
1928
0
  return InstTemplate;
1929
0
}
1930
1931
0
Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1932
0
  CXXRecordDecl *PrevDecl = nullptr;
1933
0
  if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1934
0
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1935
0
                                                   PatternPrev,
1936
0
                                                   TemplateArgs);
1937
0
    if (!Prev) return nullptr;
1938
0
    PrevDecl = cast<CXXRecordDecl>(Prev);
1939
0
  }
1940
1941
0
  CXXRecordDecl *Record = nullptr;
1942
0
  bool IsInjectedClassName = D->isInjectedClassName();
1943
0
  if (D->isLambda())
1944
0
    Record = CXXRecordDecl::CreateLambda(
1945
0
        SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1946
0
        D->getLambdaDependencyKind(), D->isGenericLambda(),
1947
0
        D->getLambdaCaptureDefault());
1948
0
  else
1949
0
    Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1950
0
                                   D->getBeginLoc(), D->getLocation(),
1951
0
                                   D->getIdentifier(), PrevDecl,
1952
0
                                   /*DelayTypeCreation=*/IsInjectedClassName);
1953
  // Link the type of the injected-class-name to that of the outer class.
1954
0
  if (IsInjectedClassName)
1955
0
    (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1956
1957
  // Substitute the nested name specifier, if any.
1958
0
  if (SubstQualifier(D, Record))
1959
0
    return nullptr;
1960
1961
0
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1962
0
                                                              StartingScope);
1963
1964
0
  Record->setImplicit(D->isImplicit());
1965
  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1966
  // the tag decls introduced by friend class declarations don't have an access
1967
  // specifier. Remove once this area of the code gets sorted out.
1968
0
  if (D->getAccess() != AS_none)
1969
0
    Record->setAccess(D->getAccess());
1970
0
  if (!IsInjectedClassName)
1971
0
    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1972
1973
  // If the original function was part of a friend declaration,
1974
  // inherit its namespace state.
1975
0
  if (D->getFriendObjectKind())
1976
0
    Record->setObjectOfFriendDecl();
1977
1978
  // Make sure that anonymous structs and unions are recorded.
1979
0
  if (D->isAnonymousStructOrUnion())
1980
0
    Record->setAnonymousStructOrUnion(true);
1981
1982
0
  if (D->isLocalClass())
1983
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1984
1985
  // Forward the mangling number from the template to the instantiated decl.
1986
0
  SemaRef.Context.setManglingNumber(Record,
1987
0
                                    SemaRef.Context.getManglingNumber(D));
1988
1989
  // See if the old tag was defined along with a declarator.
1990
  // If it did, mark the new tag as being associated with that declarator.
1991
0
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1992
0
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1993
1994
  // See if the old tag was defined along with a typedef.
1995
  // If it did, mark the new tag as being associated with that typedef.
1996
0
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1997
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1998
1999
0
  Owner->addDecl(Record);
2000
2001
  // DR1484 clarifies that the members of a local class are instantiated as part
2002
  // of the instantiation of their enclosing entity.
2003
0
  if (D->isCompleteDefinition() && D->isLocalClass()) {
2004
0
    Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2005
2006
0
    SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2007
0
                             TSK_ImplicitInstantiation,
2008
0
                             /*Complain=*/true);
2009
2010
    // For nested local classes, we will instantiate the members when we
2011
    // reach the end of the outermost (non-nested) local class.
2012
0
    if (!D->isCXXClassMember())
2013
0
      SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2014
0
                                      TSK_ImplicitInstantiation);
2015
2016
    // This class may have local implicit instantiations that need to be
2017
    // performed within this scope.
2018
0
    LocalInstantiations.perform();
2019
0
  }
2020
2021
0
  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2022
2023
0
  if (IsInjectedClassName)
2024
0
    assert(Record->isInjectedClassName() && "Broken injected-class-name");
2025
2026
0
  return Record;
2027
0
}
2028
2029
/// Adjust the given function type for an instantiation of the
2030
/// given declaration, to cope with modifications to the function's type that
2031
/// aren't reflected in the type-source information.
2032
///
2033
/// \param D The declaration we're instantiating.
2034
/// \param TInfo The already-instantiated type.
2035
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2036
                                                   FunctionDecl *D,
2037
0
                                                   TypeSourceInfo *TInfo) {
2038
0
  const FunctionProtoType *OrigFunc
2039
0
    = D->getType()->castAs<FunctionProtoType>();
2040
0
  const FunctionProtoType *NewFunc
2041
0
    = TInfo->getType()->castAs<FunctionProtoType>();
2042
0
  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2043
0
    return TInfo->getType();
2044
2045
0
  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2046
0
  NewEPI.ExtInfo = OrigFunc->getExtInfo();
2047
0
  return Context.getFunctionType(NewFunc->getReturnType(),
2048
0
                                 NewFunc->getParamTypes(), NewEPI);
2049
0
}
2050
2051
/// Normal class members are of more specific types and therefore
2052
/// don't make it here.  This function serves three purposes:
2053
///   1) instantiating function templates
2054
///   2) substituting friend and local function declarations
2055
///   3) substituting deduction guide declarations for nested class templates
2056
Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2057
    FunctionDecl *D, TemplateParameterList *TemplateParams,
2058
0
    RewriteKind FunctionRewriteKind) {
2059
  // Check whether there is already a function template specialization for
2060
  // this declaration.
2061
0
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2062
0
  if (FunctionTemplate && !TemplateParams) {
2063
0
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2064
2065
0
    void *InsertPos = nullptr;
2066
0
    FunctionDecl *SpecFunc
2067
0
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2068
2069
    // If we already have a function template specialization, return it.
2070
0
    if (SpecFunc)
2071
0
      return SpecFunc;
2072
0
  }
2073
2074
0
  bool isFriend;
2075
0
  if (FunctionTemplate)
2076
0
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2077
0
  else
2078
0
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2079
2080
0
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2081
0
    Owner->isFunctionOrMethod() ||
2082
0
    !(isa<Decl>(Owner) &&
2083
0
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2084
0
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2085
2086
0
  ExplicitSpecifier InstantiatedExplicitSpecifier;
2087
0
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2088
0
    InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2089
0
        TemplateArgs, DGuide->getExplicitSpecifier());
2090
0
    if (InstantiatedExplicitSpecifier.isInvalid())
2091
0
      return nullptr;
2092
0
  }
2093
2094
0
  SmallVector<ParmVarDecl *, 4> Params;
2095
0
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2096
0
  if (!TInfo)
2097
0
    return nullptr;
2098
0
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2099
2100
0
  if (TemplateParams && TemplateParams->size()) {
2101
0
    auto *LastParam =
2102
0
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2103
0
    if (LastParam && LastParam->isImplicit() &&
2104
0
        LastParam->hasTypeConstraint()) {
2105
      // In abbreviated templates, the type-constraints of invented template
2106
      // type parameters are instantiated with the function type, invalidating
2107
      // the TemplateParameterList which relied on the template type parameter
2108
      // not having a type constraint. Recreate the TemplateParameterList with
2109
      // the updated parameter list.
2110
0
      TemplateParams = TemplateParameterList::Create(
2111
0
          SemaRef.Context, TemplateParams->getTemplateLoc(),
2112
0
          TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2113
0
          TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2114
0
    }
2115
0
  }
2116
2117
0
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2118
0
  if (QualifierLoc) {
2119
0
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2120
0
                                                       TemplateArgs);
2121
0
    if (!QualifierLoc)
2122
0
      return nullptr;
2123
0
  }
2124
2125
0
  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2126
2127
  // If we're instantiating a local function declaration, put the result
2128
  // in the enclosing namespace; otherwise we need to find the instantiated
2129
  // context.
2130
0
  DeclContext *DC;
2131
0
  if (D->isLocalExternDecl()) {
2132
0
    DC = Owner;
2133
0
    SemaRef.adjustContextForLocalExternDecl(DC);
2134
0
  } else if (isFriend && QualifierLoc) {
2135
0
    CXXScopeSpec SS;
2136
0
    SS.Adopt(QualifierLoc);
2137
0
    DC = SemaRef.computeDeclContext(SS);
2138
0
    if (!DC) return nullptr;
2139
0
  } else {
2140
0
    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2141
0
                                         TemplateArgs);
2142
0
  }
2143
2144
0
  DeclarationNameInfo NameInfo
2145
0
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2146
2147
0
  if (FunctionRewriteKind != RewriteKind::None)
2148
0
    adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2149
2150
0
  FunctionDecl *Function;
2151
0
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2152
0
    Function = CXXDeductionGuideDecl::Create(
2153
0
        SemaRef.Context, DC, D->getInnerLocStart(),
2154
0
        InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2155
0
        D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2156
0
        DGuide->getDeductionCandidateKind());
2157
0
    Function->setAccess(D->getAccess());
2158
0
  } else {
2159
0
    Function = FunctionDecl::Create(
2160
0
        SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2161
0
        D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2162
0
        D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2163
0
        TrailingRequiresClause);
2164
0
    Function->setFriendConstraintRefersToEnclosingTemplate(
2165
0
        D->FriendConstraintRefersToEnclosingTemplate());
2166
0
    Function->setRangeEnd(D->getSourceRange().getEnd());
2167
0
  }
2168
2169
0
  if (D->isInlined())
2170
0
    Function->setImplicitlyInline();
2171
2172
0
  if (QualifierLoc)
2173
0
    Function->setQualifierInfo(QualifierLoc);
2174
2175
0
  if (D->isLocalExternDecl())
2176
0
    Function->setLocalExternDecl();
2177
2178
0
  DeclContext *LexicalDC = Owner;
2179
0
  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2180
0
    assert(D->getDeclContext()->isFileContext());
2181
0
    LexicalDC = D->getDeclContext();
2182
0
  }
2183
0
  else if (D->isLocalExternDecl()) {
2184
0
    LexicalDC = SemaRef.CurContext;
2185
0
  }
2186
2187
0
  Function->setLexicalDeclContext(LexicalDC);
2188
2189
  // Attach the parameters
2190
0
  for (unsigned P = 0; P < Params.size(); ++P)
2191
0
    if (Params[P])
2192
0
      Params[P]->setOwningFunction(Function);
2193
0
  Function->setParams(Params);
2194
2195
0
  if (TrailingRequiresClause)
2196
0
    Function->setTrailingRequiresClause(TrailingRequiresClause);
2197
2198
0
  if (TemplateParams) {
2199
    // Our resulting instantiation is actually a function template, since we
2200
    // are substituting only the outer template parameters. For example, given
2201
    //
2202
    //   template<typename T>
2203
    //   struct X {
2204
    //     template<typename U> friend void f(T, U);
2205
    //   };
2206
    //
2207
    //   X<int> x;
2208
    //
2209
    // We are instantiating the friend function template "f" within X<int>,
2210
    // which means substituting int for T, but leaving "f" as a friend function
2211
    // template.
2212
    // Build the function template itself.
2213
0
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2214
0
                                                    Function->getLocation(),
2215
0
                                                    Function->getDeclName(),
2216
0
                                                    TemplateParams, Function);
2217
0
    Function->setDescribedFunctionTemplate(FunctionTemplate);
2218
2219
0
    FunctionTemplate->setLexicalDeclContext(LexicalDC);
2220
2221
0
    if (isFriend && D->isThisDeclarationADefinition()) {
2222
0
      FunctionTemplate->setInstantiatedFromMemberTemplate(
2223
0
                                           D->getDescribedFunctionTemplate());
2224
0
    }
2225
0
  } else if (FunctionTemplate) {
2226
    // Record this function template specialization.
2227
0
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2228
0
    Function->setFunctionTemplateSpecialization(FunctionTemplate,
2229
0
                            TemplateArgumentList::CreateCopy(SemaRef.Context,
2230
0
                                                             Innermost),
2231
0
                                                /*InsertPos=*/nullptr);
2232
0
  } else if (isFriend && D->isThisDeclarationADefinition()) {
2233
    // Do not connect the friend to the template unless it's actually a
2234
    // definition. We don't want non-template functions to be marked as being
2235
    // template instantiations.
2236
0
    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2237
0
  } else if (!isFriend) {
2238
    // If this is not a function template, and this is not a friend (that is,
2239
    // this is a locally declared function), save the instantiation relationship
2240
    // for the purposes of constraint instantiation.
2241
0
    Function->setInstantiatedFromDecl(D);
2242
0
  }
2243
2244
0
  if (isFriend) {
2245
0
    Function->setObjectOfFriendDecl();
2246
0
    if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2247
0
      FT->setObjectOfFriendDecl();
2248
0
  }
2249
2250
0
  if (InitFunctionInstantiation(Function, D))
2251
0
    Function->setInvalidDecl();
2252
2253
0
  bool IsExplicitSpecialization = false;
2254
2255
0
  LookupResult Previous(
2256
0
      SemaRef, Function->getDeclName(), SourceLocation(),
2257
0
      D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2258
0
                             : Sema::LookupOrdinaryName,
2259
0
      D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2260
0
                             : SemaRef.forRedeclarationInCurContext());
2261
2262
0
  if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2263
0
          D->getDependentSpecializationInfo()) {
2264
0
    assert(isFriend && "dependent specialization info on "
2265
0
                       "non-member non-friend function?");
2266
2267
    // Instantiate the explicit template arguments.
2268
0
    TemplateArgumentListInfo ExplicitArgs;
2269
0
    if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2270
0
      ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2271
0
      ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2272
0
      if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2273
0
                                         ExplicitArgs))
2274
0
        return nullptr;
2275
0
    }
2276
2277
    // Map the candidates for the primary template to their instantiations.
2278
0
    for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2279
0
      if (NamedDecl *ND =
2280
0
              SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2281
0
        Previous.addDecl(ND);
2282
0
      else
2283
0
        return nullptr;
2284
0
    }
2285
2286
0
    if (SemaRef.CheckFunctionTemplateSpecialization(
2287
0
            Function,
2288
0
            DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2289
0
            Previous))
2290
0
      Function->setInvalidDecl();
2291
2292
0
    IsExplicitSpecialization = true;
2293
0
  } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2294
0
                 D->getTemplateSpecializationArgsAsWritten()) {
2295
    // The name of this function was written as a template-id.
2296
0
    SemaRef.LookupQualifiedName(Previous, DC);
2297
2298
    // Instantiate the explicit template arguments.
2299
0
    TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2300
0
                                          ArgsWritten->getRAngleLoc());
2301
0
    if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2302
0
                                       ExplicitArgs))
2303
0
      return nullptr;
2304
2305
0
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2306
0
                                                    &ExplicitArgs,
2307
0
                                                    Previous))
2308
0
      Function->setInvalidDecl();
2309
2310
0
    IsExplicitSpecialization = true;
2311
0
  } else if (TemplateParams || !FunctionTemplate) {
2312
    // Look only into the namespace where the friend would be declared to
2313
    // find a previous declaration. This is the innermost enclosing namespace,
2314
    // as described in ActOnFriendFunctionDecl.
2315
0
    SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2316
2317
    // In C++, the previous declaration we find might be a tag type
2318
    // (class or enum). In this case, the new declaration will hide the
2319
    // tag type. Note that this does not apply if we're declaring a
2320
    // typedef (C++ [dcl.typedef]p4).
2321
0
    if (Previous.isSingleTagDecl())
2322
0
      Previous.clear();
2323
2324
    // Filter out previous declarations that don't match the scope. The only
2325
    // effect this has is to remove declarations found in inline namespaces
2326
    // for friend declarations with unqualified names.
2327
0
    if (isFriend && !QualifierLoc) {
2328
0
      SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2329
0
                                   /*ConsiderLinkage=*/ true,
2330
0
                                   QualifierLoc.hasQualifier());
2331
0
    }
2332
0
  }
2333
2334
  // Per [temp.inst], default arguments in function declarations at local scope
2335
  // are instantiated along with the enclosing declaration. For example:
2336
  //
2337
  //   template<typename T>
2338
  //   void ft() {
2339
  //     void f(int = []{ return T::value; }());
2340
  //   }
2341
  //   template void ft<int>(); // error: type 'int' cannot be used prior
2342
  //                                      to '::' because it has no members
2343
  //
2344
  // The error is issued during instantiation of ft<int>() because substitution
2345
  // into the default argument fails; the default argument is instantiated even
2346
  // though it is never used.
2347
0
  if (Function->isLocalExternDecl()) {
2348
0
    for (ParmVarDecl *PVD : Function->parameters()) {
2349
0
      if (!PVD->hasDefaultArg())
2350
0
        continue;
2351
0
      if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2352
        // If substitution fails, the default argument is set to a
2353
        // RecoveryExpr that wraps the uninstantiated default argument so
2354
        // that downstream diagnostics are omitted.
2355
0
        Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2356
0
        ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2357
0
            UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2358
0
            { UninstExpr }, UninstExpr->getType());
2359
0
        if (ErrorResult.isUsable())
2360
0
          PVD->setDefaultArg(ErrorResult.get());
2361
0
      }
2362
0
    }
2363
0
  }
2364
2365
0
  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2366
0
                                   IsExplicitSpecialization,
2367
0
                                   Function->isThisDeclarationADefinition());
2368
2369
  // Check the template parameter list against the previous declaration. The
2370
  // goal here is to pick up default arguments added since the friend was
2371
  // declared; we know the template parameter lists match, since otherwise
2372
  // we would not have picked this template as the previous declaration.
2373
0
  if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2374
0
    SemaRef.CheckTemplateParameterList(
2375
0
        TemplateParams,
2376
0
        FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2377
0
        Function->isThisDeclarationADefinition()
2378
0
            ? Sema::TPC_FriendFunctionTemplateDefinition
2379
0
            : Sema::TPC_FriendFunctionTemplate);
2380
0
  }
2381
2382
  // If we're introducing a friend definition after the first use, trigger
2383
  // instantiation.
2384
  // FIXME: If this is a friend function template definition, we should check
2385
  // to see if any specializations have been used.
2386
0
  if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2387
0
    if (MemberSpecializationInfo *MSInfo =
2388
0
            Function->getMemberSpecializationInfo()) {
2389
0
      if (MSInfo->getPointOfInstantiation().isInvalid()) {
2390
0
        SourceLocation Loc = D->getLocation(); // FIXME
2391
0
        MSInfo->setPointOfInstantiation(Loc);
2392
0
        SemaRef.PendingLocalImplicitInstantiations.push_back(
2393
0
            std::make_pair(Function, Loc));
2394
0
      }
2395
0
    }
2396
0
  }
2397
2398
0
  if (D->isExplicitlyDefaulted()) {
2399
0
    if (SubstDefaultedFunction(Function, D))
2400
0
      return nullptr;
2401
0
  }
2402
0
  if (D->isDeleted())
2403
0
    SemaRef.SetDeclDeleted(Function, D->getLocation());
2404
2405
0
  NamedDecl *PrincipalDecl =
2406
0
      (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2407
2408
  // If this declaration lives in a different context from its lexical context,
2409
  // add it to the corresponding lookup table.
2410
0
  if (isFriend ||
2411
0
      (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2412
0
    DC->makeDeclVisibleInContext(PrincipalDecl);
2413
2414
0
  if (Function->isOverloadedOperator() && !DC->isRecord() &&
2415
0
      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2416
0
    PrincipalDecl->setNonMemberOperator();
2417
2418
0
  return Function;
2419
0
}
2420
2421
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2422
    CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2423
0
    RewriteKind FunctionRewriteKind) {
2424
0
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2425
0
  if (FunctionTemplate && !TemplateParams) {
2426
    // We are creating a function template specialization from a function
2427
    // template. Check whether there is already a function template
2428
    // specialization for this particular set of template arguments.
2429
0
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2430
2431
0
    void *InsertPos = nullptr;
2432
0
    FunctionDecl *SpecFunc
2433
0
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2434
2435
    // If we already have a function template specialization, return it.
2436
0
    if (SpecFunc)
2437
0
      return SpecFunc;
2438
0
  }
2439
2440
0
  bool isFriend;
2441
0
  if (FunctionTemplate)
2442
0
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2443
0
  else
2444
0
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2445
2446
0
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2447
0
    !(isa<Decl>(Owner) &&
2448
0
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2449
0
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2450
2451
0
  Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
2452
0
      SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2453
2454
  // Instantiate enclosing template arguments for friends.
2455
0
  SmallVector<TemplateParameterList *, 4> TempParamLists;
2456
0
  unsigned NumTempParamLists = 0;
2457
0
  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2458
0
    TempParamLists.resize(NumTempParamLists);
2459
0
    for (unsigned I = 0; I != NumTempParamLists; ++I) {
2460
0
      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2461
0
      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2462
0
      if (!InstParams)
2463
0
        return nullptr;
2464
0
      TempParamLists[I] = InstParams;
2465
0
    }
2466
0
  }
2467
2468
0
  auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2469
  // deduction guides need this
2470
0
  const bool CouldInstantiate =
2471
0
      InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2472
0
      !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2473
2474
  // Delay the instantiation of the explicit-specifier until after the
2475
  // constraints are checked during template argument deduction.
2476
0
  if (CouldInstantiate ||
2477
0
      SemaRef.CodeSynthesisContexts.back().Kind !=
2478
0
          Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) {
2479
0
    InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2480
0
        TemplateArgs, InstantiatedExplicitSpecifier);
2481
2482
0
    if (InstantiatedExplicitSpecifier.isInvalid())
2483
0
      return nullptr;
2484
0
  } else {
2485
0
    InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2486
0
  }
2487
2488
  // Implicit destructors/constructors created for local classes in
2489
  // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2490
  // Unfortunately there isn't enough context in those functions to
2491
  // conditionally populate the TSI without breaking non-template related use
2492
  // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2493
  // a proper transformation.
2494
0
  if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2495
0
      !D->getTypeSourceInfo() &&
2496
0
      isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2497
0
    TypeSourceInfo *TSI =
2498
0
        SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2499
0
    D->setTypeSourceInfo(TSI);
2500
0
  }
2501
2502
0
  SmallVector<ParmVarDecl *, 4> Params;
2503
0
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2504
0
  if (!TInfo)
2505
0
    return nullptr;
2506
0
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2507
2508
0
  if (TemplateParams && TemplateParams->size()) {
2509
0
    auto *LastParam =
2510
0
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2511
0
    if (LastParam && LastParam->isImplicit() &&
2512
0
        LastParam->hasTypeConstraint()) {
2513
      // In abbreviated templates, the type-constraints of invented template
2514
      // type parameters are instantiated with the function type, invalidating
2515
      // the TemplateParameterList which relied on the template type parameter
2516
      // not having a type constraint. Recreate the TemplateParameterList with
2517
      // the updated parameter list.
2518
0
      TemplateParams = TemplateParameterList::Create(
2519
0
          SemaRef.Context, TemplateParams->getTemplateLoc(),
2520
0
          TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2521
0
          TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2522
0
    }
2523
0
  }
2524
2525
0
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2526
0
  if (QualifierLoc) {
2527
0
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2528
0
                                                 TemplateArgs);
2529
0
    if (!QualifierLoc)
2530
0
      return nullptr;
2531
0
  }
2532
2533
0
  DeclContext *DC = Owner;
2534
0
  if (isFriend) {
2535
0
    if (QualifierLoc) {
2536
0
      CXXScopeSpec SS;
2537
0
      SS.Adopt(QualifierLoc);
2538
0
      DC = SemaRef.computeDeclContext(SS);
2539
2540
0
      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2541
0
        return nullptr;
2542
0
    } else {
2543
0
      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2544
0
                                           D->getDeclContext(),
2545
0
                                           TemplateArgs);
2546
0
    }
2547
0
    if (!DC) return nullptr;
2548
0
  }
2549
2550
0
  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2551
0
  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2552
2553
0
  DeclarationNameInfo NameInfo
2554
0
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2555
2556
0
  if (FunctionRewriteKind != RewriteKind::None)
2557
0
    adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2558
2559
  // Build the instantiated method declaration.
2560
0
  CXXMethodDecl *Method = nullptr;
2561
2562
0
  SourceLocation StartLoc = D->getInnerLocStart();
2563
0
  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2564
0
    Method = CXXConstructorDecl::Create(
2565
0
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2566
0
        InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2567
0
        Constructor->isInlineSpecified(), false,
2568
0
        Constructor->getConstexprKind(), InheritedConstructor(),
2569
0
        TrailingRequiresClause);
2570
0
    Method->setRangeEnd(Constructor->getEndLoc());
2571
0
  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2572
0
    Method = CXXDestructorDecl::Create(
2573
0
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2574
0
        Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2575
0
        Destructor->getConstexprKind(), TrailingRequiresClause);
2576
0
    Method->setIneligibleOrNotSelected(true);
2577
0
    Method->setRangeEnd(Destructor->getEndLoc());
2578
0
    Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2579
0
        SemaRef.Context.getCanonicalType(
2580
0
            SemaRef.Context.getTypeDeclType(Record))));
2581
0
  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2582
0
    Method = CXXConversionDecl::Create(
2583
0
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2584
0
        Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2585
0
        InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2586
0
        Conversion->getEndLoc(), TrailingRequiresClause);
2587
0
  } else {
2588
0
    StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2589
0
    Method = CXXMethodDecl::Create(
2590
0
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2591
0
        D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2592
0
        D->getEndLoc(), TrailingRequiresClause);
2593
0
  }
2594
2595
0
  if (D->isInlined())
2596
0
    Method->setImplicitlyInline();
2597
2598
0
  if (QualifierLoc)
2599
0
    Method->setQualifierInfo(QualifierLoc);
2600
2601
0
  if (TemplateParams) {
2602
    // Our resulting instantiation is actually a function template, since we
2603
    // are substituting only the outer template parameters. For example, given
2604
    //
2605
    //   template<typename T>
2606
    //   struct X {
2607
    //     template<typename U> void f(T, U);
2608
    //   };
2609
    //
2610
    //   X<int> x;
2611
    //
2612
    // We are instantiating the member template "f" within X<int>, which means
2613
    // substituting int for T, but leaving "f" as a member function template.
2614
    // Build the function template itself.
2615
0
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2616
0
                                                    Method->getLocation(),
2617
0
                                                    Method->getDeclName(),
2618
0
                                                    TemplateParams, Method);
2619
0
    if (isFriend) {
2620
0
      FunctionTemplate->setLexicalDeclContext(Owner);
2621
0
      FunctionTemplate->setObjectOfFriendDecl();
2622
0
    } else if (D->isOutOfLine())
2623
0
      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2624
0
    Method->setDescribedFunctionTemplate(FunctionTemplate);
2625
0
  } else if (FunctionTemplate) {
2626
    // Record this function template specialization.
2627
0
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2628
0
    Method->setFunctionTemplateSpecialization(FunctionTemplate,
2629
0
                         TemplateArgumentList::CreateCopy(SemaRef.Context,
2630
0
                                                          Innermost),
2631
0
                                              /*InsertPos=*/nullptr);
2632
0
  } else if (!isFriend) {
2633
    // Record that this is an instantiation of a member function.
2634
0
    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2635
0
  }
2636
2637
  // If we are instantiating a member function defined
2638
  // out-of-line, the instantiation will have the same lexical
2639
  // context (which will be a namespace scope) as the template.
2640
0
  if (isFriend) {
2641
0
    if (NumTempParamLists)
2642
0
      Method->setTemplateParameterListsInfo(
2643
0
          SemaRef.Context,
2644
0
          llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2645
2646
0
    Method->setLexicalDeclContext(Owner);
2647
0
    Method->setObjectOfFriendDecl();
2648
0
  } else if (D->isOutOfLine())
2649
0
    Method->setLexicalDeclContext(D->getLexicalDeclContext());
2650
2651
  // Attach the parameters
2652
0
  for (unsigned P = 0; P < Params.size(); ++P)
2653
0
    Params[P]->setOwningFunction(Method);
2654
0
  Method->setParams(Params);
2655
2656
0
  if (InitMethodInstantiation(Method, D))
2657
0
    Method->setInvalidDecl();
2658
2659
0
  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2660
0
                        Sema::ForExternalRedeclaration);
2661
2662
0
  bool IsExplicitSpecialization = false;
2663
2664
  // If the name of this function was written as a template-id, instantiate
2665
  // the explicit template arguments.
2666
0
  if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2667
0
          D->getDependentSpecializationInfo()) {
2668
    // Instantiate the explicit template arguments.
2669
0
    TemplateArgumentListInfo ExplicitArgs;
2670
0
    if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2671
0
      ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2672
0
      ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2673
0
      if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2674
0
                                         ExplicitArgs))
2675
0
        return nullptr;
2676
0
    }
2677
2678
    // Map the candidates for the primary template to their instantiations.
2679
0
    for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2680
0
      if (NamedDecl *ND =
2681
0
              SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2682
0
        Previous.addDecl(ND);
2683
0
      else
2684
0
        return nullptr;
2685
0
    }
2686
2687
0
    if (SemaRef.CheckFunctionTemplateSpecialization(
2688
0
            Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2689
0
            Previous))
2690
0
      Method->setInvalidDecl();
2691
2692
0
    IsExplicitSpecialization = true;
2693
0
  } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2694
0
                 D->getTemplateSpecializationArgsAsWritten()) {
2695
0
    SemaRef.LookupQualifiedName(Previous, DC);
2696
2697
0
    TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2698
0
                                          ArgsWritten->getRAngleLoc());
2699
2700
0
    if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2701
0
                                       ExplicitArgs))
2702
0
      return nullptr;
2703
2704
0
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2705
0
                                                    &ExplicitArgs,
2706
0
                                                    Previous))
2707
0
      Method->setInvalidDecl();
2708
2709
0
    IsExplicitSpecialization = true;
2710
0
  } else if (!FunctionTemplate || TemplateParams || isFriend) {
2711
0
    SemaRef.LookupQualifiedName(Previous, Record);
2712
2713
    // In C++, the previous declaration we find might be a tag type
2714
    // (class or enum). In this case, the new declaration will hide the
2715
    // tag type. Note that this does not apply if we're declaring a
2716
    // typedef (C++ [dcl.typedef]p4).
2717
0
    if (Previous.isSingleTagDecl())
2718
0
      Previous.clear();
2719
0
  }
2720
2721
  // Per [temp.inst], default arguments in member functions of local classes
2722
  // are instantiated along with the member function declaration. For example:
2723
  //
2724
  //   template<typename T>
2725
  //   void ft() {
2726
  //     struct lc {
2727
  //       int operator()(int p = []{ return T::value; }());
2728
  //     };
2729
  //   }
2730
  //   template void ft<int>(); // error: type 'int' cannot be used prior
2731
  //                                      to '::'because it has no members
2732
  //
2733
  // The error is issued during instantiation of ft<int>()::lc::operator()
2734
  // because substitution into the default argument fails; the default argument
2735
  // is instantiated even though it is never used.
2736
0
  if (D->isInLocalScopeForInstantiation()) {
2737
0
    for (unsigned P = 0; P < Params.size(); ++P) {
2738
0
      if (!Params[P]->hasDefaultArg())
2739
0
        continue;
2740
0
      if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2741
        // If substitution fails, the default argument is set to a
2742
        // RecoveryExpr that wraps the uninstantiated default argument so
2743
        // that downstream diagnostics are omitted.
2744
0
        Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2745
0
        ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2746
0
            UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2747
0
            { UninstExpr }, UninstExpr->getType());
2748
0
        if (ErrorResult.isUsable())
2749
0
          Params[P]->setDefaultArg(ErrorResult.get());
2750
0
      }
2751
0
    }
2752
0
  }
2753
2754
0
  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2755
0
                                   IsExplicitSpecialization,
2756
0
                                   Method->isThisDeclarationADefinition());
2757
2758
0
  if (D->isPure())
2759
0
    SemaRef.CheckPureMethod(Method, SourceRange());
2760
2761
  // Propagate access.  For a non-friend declaration, the access is
2762
  // whatever we're propagating from.  For a friend, it should be the
2763
  // previous declaration we just found.
2764
0
  if (isFriend && Method->getPreviousDecl())
2765
0
    Method->setAccess(Method->getPreviousDecl()->getAccess());
2766
0
  else
2767
0
    Method->setAccess(D->getAccess());
2768
0
  if (FunctionTemplate)
2769
0
    FunctionTemplate->setAccess(Method->getAccess());
2770
2771
0
  SemaRef.CheckOverrideControl(Method);
2772
2773
  // If a function is defined as defaulted or deleted, mark it as such now.
2774
0
  if (D->isExplicitlyDefaulted()) {
2775
0
    if (SubstDefaultedFunction(Method, D))
2776
0
      return nullptr;
2777
0
  }
2778
0
  if (D->isDeletedAsWritten())
2779
0
    SemaRef.SetDeclDeleted(Method, Method->getLocation());
2780
2781
  // If this is an explicit specialization, mark the implicitly-instantiated
2782
  // template specialization as being an explicit specialization too.
2783
  // FIXME: Is this necessary?
2784
0
  if (IsExplicitSpecialization && !isFriend)
2785
0
    SemaRef.CompleteMemberSpecialization(Method, Previous);
2786
2787
  // If the method is a special member function, we need to mark it as
2788
  // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2789
  // At the end of the class instantiation, we calculate eligibility again and
2790
  // then we adjust trivility if needed.
2791
  // We need this check to happen only after the method parameters are set,
2792
  // because being e.g. a copy constructor depends on the instantiated
2793
  // arguments.
2794
0
  if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2795
0
    if (Constructor->isDefaultConstructor() ||
2796
0
        Constructor->isCopyOrMoveConstructor())
2797
0
      Method->setIneligibleOrNotSelected(true);
2798
0
  } else if (Method->isCopyAssignmentOperator() ||
2799
0
             Method->isMoveAssignmentOperator()) {
2800
0
    Method->setIneligibleOrNotSelected(true);
2801
0
  }
2802
2803
  // If there's a function template, let our caller handle it.
2804
0
  if (FunctionTemplate) {
2805
    // do nothing
2806
2807
  // Don't hide a (potentially) valid declaration with an invalid one.
2808
0
  } else if (Method->isInvalidDecl() && !Previous.empty()) {
2809
    // do nothing
2810
2811
  // Otherwise, check access to friends and make them visible.
2812
0
  } else if (isFriend) {
2813
    // We only need to re-check access for methods which we didn't
2814
    // manage to match during parsing.
2815
0
    if (!D->getPreviousDecl())
2816
0
      SemaRef.CheckFriendAccess(Method);
2817
2818
0
    Record->makeDeclVisibleInContext(Method);
2819
2820
  // Otherwise, add the declaration.  We don't need to do this for
2821
  // class-scope specializations because we'll have matched them with
2822
  // the appropriate template.
2823
0
  } else {
2824
0
    Owner->addDecl(Method);
2825
0
  }
2826
2827
  // PR17480: Honor the used attribute to instantiate member function
2828
  // definitions
2829
0
  if (Method->hasAttr<UsedAttr>()) {
2830
0
    if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2831
0
      SourceLocation Loc;
2832
0
      if (const MemberSpecializationInfo *MSInfo =
2833
0
              A->getMemberSpecializationInfo())
2834
0
        Loc = MSInfo->getPointOfInstantiation();
2835
0
      else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2836
0
        Loc = Spec->getPointOfInstantiation();
2837
0
      SemaRef.MarkFunctionReferenced(Loc, Method);
2838
0
    }
2839
0
  }
2840
2841
0
  return Method;
2842
0
}
2843
2844
0
Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2845
0
  return VisitCXXMethodDecl(D);
2846
0
}
2847
2848
0
Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2849
0
  return VisitCXXMethodDecl(D);
2850
0
}
2851
2852
0
Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2853
0
  return VisitCXXMethodDecl(D);
2854
0
}
2855
2856
0
Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2857
0
  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2858
0
                                  std::nullopt,
2859
0
                                  /*ExpectParameterPack=*/false);
2860
0
}
2861
2862
Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2863
0
                                                    TemplateTypeParmDecl *D) {
2864
0
  assert(D->getTypeForDecl()->isTemplateTypeParmType());
2865
2866
0
  std::optional<unsigned> NumExpanded;
2867
2868
0
  if (const TypeConstraint *TC = D->getTypeConstraint()) {
2869
0
    if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2870
0
      assert(TC->getTemplateArgsAsWritten() &&
2871
0
             "type parameter can only be an expansion when explicit arguments "
2872
0
             "are specified");
2873
      // The template type parameter pack's type is a pack expansion of types.
2874
      // Determine whether we need to expand this parameter pack into separate
2875
      // types.
2876
0
      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2877
0
      for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2878
0
        SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2879
2880
      // Determine whether the set of unexpanded parameter packs can and should
2881
      // be expanded.
2882
0
      bool Expand = true;
2883
0
      bool RetainExpansion = false;
2884
0
      if (SemaRef.CheckParameterPacksForExpansion(
2885
0
              cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2886
0
                  ->getEllipsisLoc(),
2887
0
              SourceRange(TC->getConceptNameLoc(),
2888
0
                          TC->hasExplicitTemplateArgs() ?
2889
0
                          TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2890
0
                          TC->getConceptNameInfo().getEndLoc()),
2891
0
              Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2892
0
        return nullptr;
2893
0
    }
2894
0
  }
2895
2896
0
  TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2897
0
      SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2898
0
      D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2899
0
      D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2900
0
      D->hasTypeConstraint(), NumExpanded);
2901
2902
0
  Inst->setAccess(AS_public);
2903
0
  Inst->setImplicit(D->isImplicit());
2904
0
  if (auto *TC = D->getTypeConstraint()) {
2905
0
    if (!D->isImplicit()) {
2906
      // Invented template parameter type constraints will be instantiated
2907
      // with the corresponding auto-typed parameter as it might reference
2908
      // other parameters.
2909
0
      if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2910
0
                                      EvaluateConstraints))
2911
0
        return nullptr;
2912
0
    }
2913
0
  }
2914
0
  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2915
0
    TypeSourceInfo *InstantiatedDefaultArg =
2916
0
        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2917
0
                          D->getDefaultArgumentLoc(), D->getDeclName());
2918
0
    if (InstantiatedDefaultArg)
2919
0
      Inst->setDefaultArgument(InstantiatedDefaultArg);
2920
0
  }
2921
2922
  // Introduce this template parameter's instantiation into the instantiation
2923
  // scope.
2924
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2925
2926
0
  return Inst;
2927
0
}
2928
2929
Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2930
0
                                                 NonTypeTemplateParmDecl *D) {
2931
  // Substitute into the type of the non-type template parameter.
2932
0
  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2933
0
  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2934
0
  SmallVector<QualType, 4> ExpandedParameterPackTypes;
2935
0
  bool IsExpandedParameterPack = false;
2936
0
  TypeSourceInfo *DI;
2937
0
  QualType T;
2938
0
  bool Invalid = false;
2939
2940
0
  if (D->isExpandedParameterPack()) {
2941
    // The non-type template parameter pack is an already-expanded pack
2942
    // expansion of types. Substitute into each of the expanded types.
2943
0
    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2944
0
    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2945
0
    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2946
0
      TypeSourceInfo *NewDI =
2947
0
          SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2948
0
                            D->getLocation(), D->getDeclName());
2949
0
      if (!NewDI)
2950
0
        return nullptr;
2951
2952
0
      QualType NewT =
2953
0
          SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2954
0
      if (NewT.isNull())
2955
0
        return nullptr;
2956
2957
0
      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2958
0
      ExpandedParameterPackTypes.push_back(NewT);
2959
0
    }
2960
2961
0
    IsExpandedParameterPack = true;
2962
0
    DI = D->getTypeSourceInfo();
2963
0
    T = DI->getType();
2964
0
  } else if (D->isPackExpansion()) {
2965
    // The non-type template parameter pack's type is a pack expansion of types.
2966
    // Determine whether we need to expand this parameter pack into separate
2967
    // types.
2968
0
    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2969
0
    TypeLoc Pattern = Expansion.getPatternLoc();
2970
0
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2971
0
    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2972
2973
    // Determine whether the set of unexpanded parameter packs can and should
2974
    // be expanded.
2975
0
    bool Expand = true;
2976
0
    bool RetainExpansion = false;
2977
0
    std::optional<unsigned> OrigNumExpansions =
2978
0
        Expansion.getTypePtr()->getNumExpansions();
2979
0
    std::optional<unsigned> NumExpansions = OrigNumExpansions;
2980
0
    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2981
0
                                                Pattern.getSourceRange(),
2982
0
                                                Unexpanded,
2983
0
                                                TemplateArgs,
2984
0
                                                Expand, RetainExpansion,
2985
0
                                                NumExpansions))
2986
0
      return nullptr;
2987
2988
0
    if (Expand) {
2989
0
      for (unsigned I = 0; I != *NumExpansions; ++I) {
2990
0
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2991
0
        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2992
0
                                                  D->getLocation(),
2993
0
                                                  D->getDeclName());
2994
0
        if (!NewDI)
2995
0
          return nullptr;
2996
2997
0
        QualType NewT =
2998
0
            SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2999
0
        if (NewT.isNull())
3000
0
          return nullptr;
3001
3002
0
        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3003
0
        ExpandedParameterPackTypes.push_back(NewT);
3004
0
      }
3005
3006
      // Note that we have an expanded parameter pack. The "type" of this
3007
      // expanded parameter pack is the original expansion type, but callers
3008
      // will end up using the expanded parameter pack types for type-checking.
3009
0
      IsExpandedParameterPack = true;
3010
0
      DI = D->getTypeSourceInfo();
3011
0
      T = DI->getType();
3012
0
    } else {
3013
      // We cannot fully expand the pack expansion now, so substitute into the
3014
      // pattern and create a new pack expansion type.
3015
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3016
0
      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3017
0
                                                     D->getLocation(),
3018
0
                                                     D->getDeclName());
3019
0
      if (!NewPattern)
3020
0
        return nullptr;
3021
3022
0
      SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3023
0
      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3024
0
                                      NumExpansions);
3025
0
      if (!DI)
3026
0
        return nullptr;
3027
3028
0
      T = DI->getType();
3029
0
    }
3030
0
  } else {
3031
    // Simple case: substitution into a parameter that is not a parameter pack.
3032
0
    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3033
0
                           D->getLocation(), D->getDeclName());
3034
0
    if (!DI)
3035
0
      return nullptr;
3036
3037
    // Check that this type is acceptable for a non-type template parameter.
3038
0
    T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
3039
0
    if (T.isNull()) {
3040
0
      T = SemaRef.Context.IntTy;
3041
0
      Invalid = true;
3042
0
    }
3043
0
  }
3044
3045
0
  NonTypeTemplateParmDecl *Param;
3046
0
  if (IsExpandedParameterPack)
3047
0
    Param = NonTypeTemplateParmDecl::Create(
3048
0
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3049
0
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3050
0
        D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3051
0
        ExpandedParameterPackTypesAsWritten);
3052
0
  else
3053
0
    Param = NonTypeTemplateParmDecl::Create(
3054
0
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3055
0
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3056
0
        D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3057
3058
0
  if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3059
0
    if (AutoLoc.isConstrained()) {
3060
0
      SourceLocation EllipsisLoc;
3061
0
      if (IsExpandedParameterPack)
3062
0
        EllipsisLoc =
3063
0
            DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3064
0
      else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3065
0
                   D->getPlaceholderTypeConstraint()))
3066
0
        EllipsisLoc = Constraint->getEllipsisLoc();
3067
      // Note: We attach the uninstantiated constriant here, so that it can be
3068
      // instantiated relative to the top level, like all our other
3069
      // constraints.
3070
0
      if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3071
0
                                       /*OrigConstrainedParm=*/D, EllipsisLoc))
3072
0
        Invalid = true;
3073
0
    }
3074
3075
0
  Param->setAccess(AS_public);
3076
0
  Param->setImplicit(D->isImplicit());
3077
0
  if (Invalid)
3078
0
    Param->setInvalidDecl();
3079
3080
0
  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3081
0
    EnterExpressionEvaluationContext ConstantEvaluated(
3082
0
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3083
0
    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
3084
0
    if (!Value.isInvalid())
3085
0
      Param->setDefaultArgument(Value.get());
3086
0
  }
3087
3088
  // Introduce this template parameter's instantiation into the instantiation
3089
  // scope.
3090
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3091
0
  return Param;
3092
0
}
3093
3094
static void collectUnexpandedParameterPacks(
3095
    Sema &S,
3096
    TemplateParameterList *Params,
3097
0
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3098
0
  for (const auto &P : *Params) {
3099
0
    if (P->isTemplateParameterPack())
3100
0
      continue;
3101
0
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3102
0
      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3103
0
                                        Unexpanded);
3104
0
    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3105
0
      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3106
0
                                      Unexpanded);
3107
0
  }
3108
0
}
3109
3110
Decl *
3111
TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3112
0
                                                  TemplateTemplateParmDecl *D) {
3113
  // Instantiate the template parameter list of the template template parameter.
3114
0
  TemplateParameterList *TempParams = D->getTemplateParameters();
3115
0
  TemplateParameterList *InstParams;
3116
0
  SmallVector<TemplateParameterList*, 8> ExpandedParams;
3117
3118
0
  bool IsExpandedParameterPack = false;
3119
3120
0
  if (D->isExpandedParameterPack()) {
3121
    // The template template parameter pack is an already-expanded pack
3122
    // expansion of template parameters. Substitute into each of the expanded
3123
    // parameters.
3124
0
    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3125
0
    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3126
0
         I != N; ++I) {
3127
0
      LocalInstantiationScope Scope(SemaRef);
3128
0
      TemplateParameterList *Expansion =
3129
0
        SubstTemplateParams(D->getExpansionTemplateParameters(I));
3130
0
      if (!Expansion)
3131
0
        return nullptr;
3132
0
      ExpandedParams.push_back(Expansion);
3133
0
    }
3134
3135
0
    IsExpandedParameterPack = true;
3136
0
    InstParams = TempParams;
3137
0
  } else if (D->isPackExpansion()) {
3138
    // The template template parameter pack expands to a pack of template
3139
    // template parameters. Determine whether we need to expand this parameter
3140
    // pack into separate parameters.
3141
0
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3142
0
    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3143
0
                                    Unexpanded);
3144
3145
    // Determine whether the set of unexpanded parameter packs can and should
3146
    // be expanded.
3147
0
    bool Expand = true;
3148
0
    bool RetainExpansion = false;
3149
0
    std::optional<unsigned> NumExpansions;
3150
0
    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3151
0
                                                TempParams->getSourceRange(),
3152
0
                                                Unexpanded,
3153
0
                                                TemplateArgs,
3154
0
                                                Expand, RetainExpansion,
3155
0
                                                NumExpansions))
3156
0
      return nullptr;
3157
3158
0
    if (Expand) {
3159
0
      for (unsigned I = 0; I != *NumExpansions; ++I) {
3160
0
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3161
0
        LocalInstantiationScope Scope(SemaRef);
3162
0
        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3163
0
        if (!Expansion)
3164
0
          return nullptr;
3165
0
        ExpandedParams.push_back(Expansion);
3166
0
      }
3167
3168
      // Note that we have an expanded parameter pack. The "type" of this
3169
      // expanded parameter pack is the original expansion type, but callers
3170
      // will end up using the expanded parameter pack types for type-checking.
3171
0
      IsExpandedParameterPack = true;
3172
0
      InstParams = TempParams;
3173
0
    } else {
3174
      // We cannot fully expand the pack expansion now, so just substitute
3175
      // into the pattern.
3176
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3177
3178
0
      LocalInstantiationScope Scope(SemaRef);
3179
0
      InstParams = SubstTemplateParams(TempParams);
3180
0
      if (!InstParams)
3181
0
        return nullptr;
3182
0
    }
3183
0
  } else {
3184
    // Perform the actual substitution of template parameters within a new,
3185
    // local instantiation scope.
3186
0
    LocalInstantiationScope Scope(SemaRef);
3187
0
    InstParams = SubstTemplateParams(TempParams);
3188
0
    if (!InstParams)
3189
0
      return nullptr;
3190
0
  }
3191
3192
  // Build the template template parameter.
3193
0
  TemplateTemplateParmDecl *Param;
3194
0
  if (IsExpandedParameterPack)
3195
0
    Param = TemplateTemplateParmDecl::Create(
3196
0
        SemaRef.Context, Owner, D->getLocation(),
3197
0
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3198
0
        D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3199
0
  else
3200
0
    Param = TemplateTemplateParmDecl::Create(
3201
0
        SemaRef.Context, Owner, D->getLocation(),
3202
0
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3203
0
        D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3204
0
  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3205
0
    NestedNameSpecifierLoc QualifierLoc =
3206
0
        D->getDefaultArgument().getTemplateQualifierLoc();
3207
0
    QualifierLoc =
3208
0
        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3209
0
    TemplateName TName = SemaRef.SubstTemplateName(
3210
0
        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3211
0
        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3212
0
    if (!TName.isNull())
3213
0
      Param->setDefaultArgument(
3214
0
          SemaRef.Context,
3215
0
          TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3216
0
                              D->getDefaultArgument().getTemplateQualifierLoc(),
3217
0
                              D->getDefaultArgument().getTemplateNameLoc()));
3218
0
  }
3219
0
  Param->setAccess(AS_public);
3220
0
  Param->setImplicit(D->isImplicit());
3221
3222
  // Introduce this template parameter's instantiation into the instantiation
3223
  // scope.
3224
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3225
3226
0
  return Param;
3227
0
}
3228
3229
0
Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3230
  // Using directives are never dependent (and never contain any types or
3231
  // expressions), so they require no explicit instantiation work.
3232
3233
0
  UsingDirectiveDecl *Inst
3234
0
    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3235
0
                                 D->getNamespaceKeyLocation(),
3236
0
                                 D->getQualifierLoc(),
3237
0
                                 D->getIdentLocation(),
3238
0
                                 D->getNominatedNamespace(),
3239
0
                                 D->getCommonAncestor());
3240
3241
  // Add the using directive to its declaration context
3242
  // only if this is not a function or method.
3243
0
  if (!Owner->isFunctionOrMethod())
3244
0
    Owner->addDecl(Inst);
3245
3246
0
  return Inst;
3247
0
}
3248
3249
Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3250
                                                    BaseUsingDecl *Inst,
3251
0
                                                    LookupResult *Lookup) {
3252
3253
0
  bool isFunctionScope = Owner->isFunctionOrMethod();
3254
3255
0
  for (auto *Shadow : D->shadows()) {
3256
    // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3257
    // reconstruct it in the case where it matters. Hm, can we extract it from
3258
    // the DeclSpec when parsing and save it in the UsingDecl itself?
3259
0
    NamedDecl *OldTarget = Shadow->getTargetDecl();
3260
0
    if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3261
0
      if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3262
0
        OldTarget = BaseShadow;
3263
3264
0
    NamedDecl *InstTarget = nullptr;
3265
0
    if (auto *EmptyD =
3266
0
            dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3267
0
      InstTarget = UnresolvedUsingIfExistsDecl::Create(
3268
0
          SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3269
0
    } else {
3270
0
      InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3271
0
          Shadow->getLocation(), OldTarget, TemplateArgs));
3272
0
    }
3273
0
    if (!InstTarget)
3274
0
      return nullptr;
3275
3276
0
    UsingShadowDecl *PrevDecl = nullptr;
3277
0
    if (Lookup &&
3278
0
        SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3279
0
      continue;
3280
3281
0
    if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3282
0
      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3283
0
          Shadow->getLocation(), OldPrev, TemplateArgs));
3284
3285
0
    UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3286
0
        /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3287
0
    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3288
3289
0
    if (isFunctionScope)
3290
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3291
0
  }
3292
3293
0
  return Inst;
3294
0
}
3295
3296
0
Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3297
3298
  // The nested name specifier may be dependent, for example
3299
  //     template <typename T> struct t {
3300
  //       struct s1 { T f1(); };
3301
  //       struct s2 : s1 { using s1::f1; };
3302
  //     };
3303
  //     template struct t<int>;
3304
  // Here, in using s1::f1, s1 refers to t<T>::s1;
3305
  // we need to substitute for t<int>::s1.
3306
0
  NestedNameSpecifierLoc QualifierLoc
3307
0
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3308
0
                                          TemplateArgs);
3309
0
  if (!QualifierLoc)
3310
0
    return nullptr;
3311
3312
  // For an inheriting constructor declaration, the name of the using
3313
  // declaration is the name of a constructor in this class, not in the
3314
  // base class.
3315
0
  DeclarationNameInfo NameInfo = D->getNameInfo();
3316
0
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3317
0
    if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3318
0
      NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3319
0
          SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3320
3321
  // We only need to do redeclaration lookups if we're in a class scope (in
3322
  // fact, it's not really even possible in non-class scopes).
3323
0
  bool CheckRedeclaration = Owner->isRecord();
3324
0
  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3325
0
                    Sema::ForVisibleRedeclaration);
3326
3327
0
  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3328
0
                                       D->getUsingLoc(),
3329
0
                                       QualifierLoc,
3330
0
                                       NameInfo,
3331
0
                                       D->hasTypename());
3332
3333
0
  CXXScopeSpec SS;
3334
0
  SS.Adopt(QualifierLoc);
3335
0
  if (CheckRedeclaration) {
3336
0
    Prev.setHideTags(false);
3337
0
    SemaRef.LookupQualifiedName(Prev, Owner);
3338
3339
    // Check for invalid redeclarations.
3340
0
    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3341
0
                                            D->hasTypename(), SS,
3342
0
                                            D->getLocation(), Prev))
3343
0
      NewUD->setInvalidDecl();
3344
0
  }
3345
3346
0
  if (!NewUD->isInvalidDecl() &&
3347
0
      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3348
0
                                      NameInfo, D->getLocation(), nullptr, D))
3349
0
    NewUD->setInvalidDecl();
3350
3351
0
  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3352
0
  NewUD->setAccess(D->getAccess());
3353
0
  Owner->addDecl(NewUD);
3354
3355
  // Don't process the shadow decls for an invalid decl.
3356
0
  if (NewUD->isInvalidDecl())
3357
0
    return NewUD;
3358
3359
  // If the using scope was dependent, or we had dependent bases, we need to
3360
  // recheck the inheritance
3361
0
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3362
0
    SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3363
3364
0
  return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3365
0
}
3366
3367
0
Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3368
  // Cannot be a dependent type, but still could be an instantiation
3369
0
  EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3370
0
      D->getLocation(), D->getEnumDecl(), TemplateArgs));
3371
3372
0
  if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3373
0
    return nullptr;
3374
3375
0
  TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3376
0
                                          D->getLocation(), D->getDeclName());
3377
0
  UsingEnumDecl *NewUD =
3378
0
      UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3379
0
                            D->getEnumLoc(), D->getLocation(), TSI);
3380
3381
0
  SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3382
0
  NewUD->setAccess(D->getAccess());
3383
0
  Owner->addDecl(NewUD);
3384
3385
  // Don't process the shadow decls for an invalid decl.
3386
0
  if (NewUD->isInvalidDecl())
3387
0
    return NewUD;
3388
3389
  // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3390
  // cannot be dependent, and will therefore have been checked during template
3391
  // definition.
3392
3393
0
  return VisitBaseUsingDecls(D, NewUD, nullptr);
3394
0
}
3395
3396
0
Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3397
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
3398
0
  return nullptr;
3399
0
}
3400
3401
Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3402
0
    ConstructorUsingShadowDecl *D) {
3403
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
3404
0
  return nullptr;
3405
0
}
3406
3407
template <typename T>
3408
Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3409
0
    T *D, bool InstantiatingPackElement) {
3410
  // If this is a pack expansion, expand it now.
3411
0
  if (D->isPackExpansion() && !InstantiatingPackElement) {
3412
0
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3413
0
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3414
0
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3415
3416
    // Determine whether the set of unexpanded parameter packs can and should
3417
    // be expanded.
3418
0
    bool Expand = true;
3419
0
    bool RetainExpansion = false;
3420
0
    std::optional<unsigned> NumExpansions;
3421
0
    if (SemaRef.CheckParameterPacksForExpansion(
3422
0
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3423
0
            Expand, RetainExpansion, NumExpansions))
3424
0
      return nullptr;
3425
3426
    // This declaration cannot appear within a function template signature,
3427
    // so we can't have a partial argument list for a parameter pack.
3428
0
    assert(!RetainExpansion &&
3429
0
           "should never need to retain an expansion for UsingPackDecl");
3430
3431
0
    if (!Expand) {
3432
      // We cannot fully expand the pack expansion now, so substitute into the
3433
      // pattern and create a new pack expansion.
3434
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3435
0
      return instantiateUnresolvedUsingDecl(D, true);
3436
0
    }
3437
3438
    // Within a function, we don't have any normal way to check for conflicts
3439
    // between shadow declarations from different using declarations in the
3440
    // same pack expansion, but this is always ill-formed because all expansions
3441
    // must produce (conflicting) enumerators.
3442
    //
3443
    // Sadly we can't just reject this in the template definition because it
3444
    // could be valid if the pack is empty or has exactly one expansion.
3445
0
    if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3446
0
      SemaRef.Diag(D->getEllipsisLoc(),
3447
0
                   diag::err_using_decl_redeclaration_expansion);
3448
0
      return nullptr;
3449
0
    }
3450
3451
    // Instantiate the slices of this pack and build a UsingPackDecl.
3452
0
    SmallVector<NamedDecl*, 8> Expansions;
3453
0
    for (unsigned I = 0; I != *NumExpansions; ++I) {
3454
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3455
0
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3456
0
      if (!Slice)
3457
0
        return nullptr;
3458
      // Note that we can still get unresolved using declarations here, if we
3459
      // had arguments for all packs but the pattern also contained other
3460
      // template arguments (this only happens during partial substitution, eg
3461
      // into the body of a generic lambda in a function template).
3462
0
      Expansions.push_back(cast<NamedDecl>(Slice));
3463
0
    }
3464
3465
0
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3466
0
    if (isDeclWithinFunction(D))
3467
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3468
0
    return NewD;
3469
0
  }
3470
3471
0
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3472
0
  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3473
3474
0
  NestedNameSpecifierLoc QualifierLoc
3475
0
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3476
0
                                          TemplateArgs);
3477
0
  if (!QualifierLoc)
3478
0
    return nullptr;
3479
3480
0
  CXXScopeSpec SS;
3481
0
  SS.Adopt(QualifierLoc);
3482
3483
0
  DeclarationNameInfo NameInfo
3484
0
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3485
3486
  // Produce a pack expansion only if we're not instantiating a particular
3487
  // slice of a pack expansion.
3488
0
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3489
0
                            SemaRef.ArgumentPackSubstitutionIndex != -1;
3490
0
  SourceLocation EllipsisLoc =
3491
0
      InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3492
3493
0
  bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3494
0
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3495
0
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3496
0
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3497
0
      ParsedAttributesView(),
3498
0
      /*IsInstantiation*/ true, IsUsingIfExists);
3499
0
  if (UD) {
3500
0
    SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3501
0
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3502
0
  }
3503
3504
0
  return UD;
3505
0
}
Unexecuted instantiation: clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingTypenameDecl>(clang::UnresolvedUsingTypenameDecl*, bool)
Unexecuted instantiation: clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingValueDecl>(clang::UnresolvedUsingValueDecl*, bool)
3506
3507
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3508
0
    UnresolvedUsingTypenameDecl *D) {
3509
0
  return instantiateUnresolvedUsingDecl(D);
3510
0
}
3511
3512
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3513
0
    UnresolvedUsingValueDecl *D) {
3514
0
  return instantiateUnresolvedUsingDecl(D);
3515
0
}
3516
3517
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3518
0
    UnresolvedUsingIfExistsDecl *D) {
3519
0
  llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3520
0
}
3521
3522
0
Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3523
0
  SmallVector<NamedDecl*, 8> Expansions;
3524
0
  for (auto *UD : D->expansions()) {
3525
0
    if (NamedDecl *NewUD =
3526
0
            SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3527
0
      Expansions.push_back(NewUD);
3528
0
    else
3529
0
      return nullptr;
3530
0
  }
3531
3532
0
  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3533
0
  if (isDeclWithinFunction(D))
3534
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3535
0
  return NewD;
3536
0
}
3537
3538
Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3539
0
                                     OMPThreadPrivateDecl *D) {
3540
0
  SmallVector<Expr *, 5> Vars;
3541
0
  for (auto *I : D->varlists()) {
3542
0
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3543
0
    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3544
0
    Vars.push_back(Var);
3545
0
  }
3546
3547
0
  OMPThreadPrivateDecl *TD =
3548
0
    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3549
3550
0
  TD->setAccess(AS_public);
3551
0
  Owner->addDecl(TD);
3552
3553
0
  return TD;
3554
0
}
3555
3556
0
Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3557
0
  SmallVector<Expr *, 5> Vars;
3558
0
  for (auto *I : D->varlists()) {
3559
0
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3560
0
    assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3561
0
    Vars.push_back(Var);
3562
0
  }
3563
0
  SmallVector<OMPClause *, 4> Clauses;
3564
  // Copy map clauses from the original mapper.
3565
0
  for (OMPClause *C : D->clauselists()) {
3566
0
    OMPClause *IC = nullptr;
3567
0
    if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3568
0
      ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3569
0
      if (!NewE.isUsable())
3570
0
        continue;
3571
0
      IC = SemaRef.ActOnOpenMPAllocatorClause(
3572
0
          NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3573
0
    } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3574
0
      ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3575
0
      if (!NewE.isUsable())
3576
0
        continue;
3577
0
      IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3578
0
                                          AC->getLParenLoc(), AC->getEndLoc());
3579
      // If align clause value ends up being invalid, this can end up null.
3580
0
      if (!IC)
3581
0
        continue;
3582
0
    }
3583
0
    Clauses.push_back(IC);
3584
0
  }
3585
3586
0
  Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3587
0
      D->getLocation(), Vars, Clauses, Owner);
3588
0
  if (Res.get().isNull())
3589
0
    return nullptr;
3590
0
  return Res.get().getSingleDecl();
3591
0
}
3592
3593
0
Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3594
0
  llvm_unreachable(
3595
0
      "Requires directive cannot be instantiated within a dependent context");
3596
0
}
3597
3598
Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3599
0
    OMPDeclareReductionDecl *D) {
3600
  // Instantiate type and check if it is allowed.
3601
0
  const bool RequiresInstantiation =
3602
0
      D->getType()->isDependentType() ||
3603
0
      D->getType()->isInstantiationDependentType() ||
3604
0
      D->getType()->containsUnexpandedParameterPack();
3605
0
  QualType SubstReductionType;
3606
0
  if (RequiresInstantiation) {
3607
0
    SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3608
0
        D->getLocation(),
3609
0
        ParsedType::make(SemaRef.SubstType(
3610
0
            D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3611
0
  } else {
3612
0
    SubstReductionType = D->getType();
3613
0
  }
3614
0
  if (SubstReductionType.isNull())
3615
0
    return nullptr;
3616
0
  Expr *Combiner = D->getCombiner();
3617
0
  Expr *Init = D->getInitializer();
3618
0
  bool IsCorrect = true;
3619
  // Create instantiated copy.
3620
0
  std::pair<QualType, SourceLocation> ReductionTypes[] = {
3621
0
      std::make_pair(SubstReductionType, D->getLocation())};
3622
0
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3623
0
  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3624
0
    PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3625
0
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3626
0
            ->get<Decl *>());
3627
0
  }
3628
0
  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3629
0
      /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3630
0
      PrevDeclInScope);
3631
0
  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3632
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3633
0
  Expr *SubstCombiner = nullptr;
3634
0
  Expr *SubstInitializer = nullptr;
3635
  // Combiners instantiation sequence.
3636
0
  if (Combiner) {
3637
0
    SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3638
0
        /*S=*/nullptr, NewDRD);
3639
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3640
0
        cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3641
0
        cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3642
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3643
0
        cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3644
0
        cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3645
0
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3646
0
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3647
0
                                     ThisContext);
3648
0
    SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3649
0
    SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3650
0
  }
3651
  // Initializers instantiation sequence.
3652
0
  if (Init) {
3653
0
    VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3654
0
        /*S=*/nullptr, NewDRD);
3655
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3656
0
        cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3657
0
        cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3658
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3659
0
        cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3660
0
        cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3661
0
    if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3662
0
      SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3663
0
    } else {
3664
0
      auto *OldPrivParm =
3665
0
          cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3666
0
      IsCorrect = IsCorrect && OldPrivParm->hasInit();
3667
0
      if (IsCorrect)
3668
0
        SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3669
0
                                               TemplateArgs);
3670
0
    }
3671
0
    SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3672
0
                                                      OmpPrivParm);
3673
0
  }
3674
0
  IsCorrect = IsCorrect && SubstCombiner &&
3675
0
              (!Init ||
3676
0
               (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3677
0
                SubstInitializer) ||
3678
0
               (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3679
0
                !SubstInitializer));
3680
3681
0
  (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3682
0
      /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3683
3684
0
  return NewDRD;
3685
0
}
3686
3687
Decl *
3688
0
TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3689
  // Instantiate type and check if it is allowed.
3690
0
  const bool RequiresInstantiation =
3691
0
      D->getType()->isDependentType() ||
3692
0
      D->getType()->isInstantiationDependentType() ||
3693
0
      D->getType()->containsUnexpandedParameterPack();
3694
0
  QualType SubstMapperTy;
3695
0
  DeclarationName VN = D->getVarName();
3696
0
  if (RequiresInstantiation) {
3697
0
    SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3698
0
        D->getLocation(),
3699
0
        ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3700
0
                                           D->getLocation(), VN)));
3701
0
  } else {
3702
0
    SubstMapperTy = D->getType();
3703
0
  }
3704
0
  if (SubstMapperTy.isNull())
3705
0
    return nullptr;
3706
  // Create an instantiated copy of mapper.
3707
0
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3708
0
  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3709
0
    PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3710
0
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3711
0
            ->get<Decl *>());
3712
0
  }
3713
0
  bool IsCorrect = true;
3714
0
  SmallVector<OMPClause *, 6> Clauses;
3715
  // Instantiate the mapper variable.
3716
0
  DeclarationNameInfo DirName;
3717
0
  SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3718
0
                              /*S=*/nullptr,
3719
0
                              (*D->clauselist_begin())->getBeginLoc());
3720
0
  ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3721
0
      /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3722
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3723
0
      cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3724
0
      cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3725
0
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3726
0
  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3727
0
                                   ThisContext);
3728
  // Instantiate map clauses.
3729
0
  for (OMPClause *C : D->clauselists()) {
3730
0
    auto *OldC = cast<OMPMapClause>(C);
3731
0
    SmallVector<Expr *, 4> NewVars;
3732
0
    for (Expr *OE : OldC->varlists()) {
3733
0
      Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3734
0
      if (!NE) {
3735
0
        IsCorrect = false;
3736
0
        break;
3737
0
      }
3738
0
      NewVars.push_back(NE);
3739
0
    }
3740
0
    if (!IsCorrect)
3741
0
      break;
3742
0
    NestedNameSpecifierLoc NewQualifierLoc =
3743
0
        SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3744
0
                                            TemplateArgs);
3745
0
    CXXScopeSpec SS;
3746
0
    SS.Adopt(NewQualifierLoc);
3747
0
    DeclarationNameInfo NewNameInfo =
3748
0
        SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3749
0
    OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3750
0
                         OldC->getEndLoc());
3751
0
    OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3752
0
        OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3753
0
        OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3754
0
        OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3755
0
        NewVars, Locs);
3756
0
    Clauses.push_back(NewC);
3757
0
  }
3758
0
  SemaRef.EndOpenMPDSABlock(nullptr);
3759
0
  if (!IsCorrect)
3760
0
    return nullptr;
3761
0
  Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3762
0
      /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3763
0
      VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3764
0
  Decl *NewDMD = DG.get().getSingleDecl();
3765
0
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3766
0
  return NewDMD;
3767
0
}
3768
3769
Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3770
0
    OMPCapturedExprDecl * /*D*/) {
3771
0
  llvm_unreachable("Should not be met in templates");
3772
0
}
3773
3774
0
Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3775
0
  return VisitFunctionDecl(D, nullptr);
3776
0
}
3777
3778
Decl *
3779
0
TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3780
0
  Decl *Inst = VisitFunctionDecl(D, nullptr);
3781
0
  if (Inst && !D->getDescribedFunctionTemplate())
3782
0
    Owner->addDecl(Inst);
3783
0
  return Inst;
3784
0
}
3785
3786
0
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3787
0
  return VisitCXXMethodDecl(D, nullptr);
3788
0
}
3789
3790
0
Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3791
0
  llvm_unreachable("There are only CXXRecordDecls in C++");
3792
0
}
3793
3794
Decl *
3795
TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3796
0
    ClassTemplateSpecializationDecl *D) {
3797
  // As a MS extension, we permit class-scope explicit specialization
3798
  // of member class templates.
3799
0
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3800
0
  assert(ClassTemplate->getDeclContext()->isRecord() &&
3801
0
         D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3802
0
         "can only instantiate an explicit specialization "
3803
0
         "for a member class template");
3804
3805
  // Lookup the already-instantiated declaration in the instantiation
3806
  // of the class template.
3807
0
  ClassTemplateDecl *InstClassTemplate =
3808
0
      cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3809
0
          D->getLocation(), ClassTemplate, TemplateArgs));
3810
0
  if (!InstClassTemplate)
3811
0
    return nullptr;
3812
3813
  // Substitute into the template arguments of the class template explicit
3814
  // specialization.
3815
0
  TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3816
0
                                        castAs<TemplateSpecializationTypeLoc>();
3817
0
  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3818
0
                                            Loc.getRAngleLoc());
3819
0
  SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3820
0
  for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3821
0
    ArgLocs.push_back(Loc.getArgLoc(I));
3822
0
  if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3823
0
    return nullptr;
3824
3825
  // Check that the template argument list is well-formed for this
3826
  // class template.
3827
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3828
0
  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3829
0
                                        InstTemplateArgs, false,
3830
0
                                        SugaredConverted, CanonicalConverted,
3831
0
                                        /*UpdateArgsWithConversions=*/true))
3832
0
    return nullptr;
3833
3834
  // Figure out where to insert this class template explicit specialization
3835
  // in the member template's set of class template explicit specializations.
3836
0
  void *InsertPos = nullptr;
3837
0
  ClassTemplateSpecializationDecl *PrevDecl =
3838
0
      InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3839
3840
  // Check whether we've already seen a conflicting instantiation of this
3841
  // declaration (for instance, if there was a prior implicit instantiation).
3842
0
  bool Ignored;
3843
0
  if (PrevDecl &&
3844
0
      SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3845
0
                                                     D->getSpecializationKind(),
3846
0
                                                     PrevDecl,
3847
0
                                                     PrevDecl->getSpecializationKind(),
3848
0
                                                     PrevDecl->getPointOfInstantiation(),
3849
0
                                                     Ignored))
3850
0
    return nullptr;
3851
3852
  // If PrevDecl was a definition and D is also a definition, diagnose.
3853
  // This happens in cases like:
3854
  //
3855
  //   template<typename T, typename U>
3856
  //   struct Outer {
3857
  //     template<typename X> struct Inner;
3858
  //     template<> struct Inner<T> {};
3859
  //     template<> struct Inner<U> {};
3860
  //   };
3861
  //
3862
  //   Outer<int, int> outer; // error: the explicit specializations of Inner
3863
  //                          // have the same signature.
3864
0
  if (PrevDecl && PrevDecl->getDefinition() &&
3865
0
      D->isThisDeclarationADefinition()) {
3866
0
    SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3867
0
    SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3868
0
                 diag::note_previous_definition);
3869
0
    return nullptr;
3870
0
  }
3871
3872
  // Create the class template partial specialization declaration.
3873
0
  ClassTemplateSpecializationDecl *InstD =
3874
0
      ClassTemplateSpecializationDecl::Create(
3875
0
          SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3876
0
          D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3877
3878
  // Add this partial specialization to the set of class template partial
3879
  // specializations.
3880
0
  if (!PrevDecl)
3881
0
    InstClassTemplate->AddSpecialization(InstD, InsertPos);
3882
3883
  // Substitute the nested name specifier, if any.
3884
0
  if (SubstQualifier(D, InstD))
3885
0
    return nullptr;
3886
3887
  // Build the canonical type that describes the converted template
3888
  // arguments of the class template explicit specialization.
3889
0
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3890
0
      TemplateName(InstClassTemplate), CanonicalConverted,
3891
0
      SemaRef.Context.getRecordType(InstD));
3892
3893
  // Build the fully-sugared type for this class template
3894
  // specialization as the user wrote in the specialization
3895
  // itself. This means that we'll pretty-print the type retrieved
3896
  // from the specialization's declaration the way that the user
3897
  // actually wrote the specialization, rather than formatting the
3898
  // name based on the "canonical" representation used to store the
3899
  // template arguments in the specialization.
3900
0
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3901
0
      TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3902
0
      CanonType);
3903
3904
0
  InstD->setAccess(D->getAccess());
3905
0
  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3906
0
  InstD->setSpecializationKind(D->getSpecializationKind());
3907
0
  InstD->setTypeAsWritten(WrittenTy);
3908
0
  InstD->setExternLoc(D->getExternLoc());
3909
0
  InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3910
3911
0
  Owner->addDecl(InstD);
3912
3913
  // Instantiate the members of the class-scope explicit specialization eagerly.
3914
  // We don't have support for lazy instantiation of an explicit specialization
3915
  // yet, and MSVC eagerly instantiates in this case.
3916
  // FIXME: This is wrong in standard C++.
3917
0
  if (D->isThisDeclarationADefinition() &&
3918
0
      SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3919
0
                               TSK_ImplicitInstantiation,
3920
0
                               /*Complain=*/true))
3921
0
    return nullptr;
3922
3923
0
  return InstD;
3924
0
}
3925
3926
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3927
0
    VarTemplateSpecializationDecl *D) {
3928
3929
0
  TemplateArgumentListInfo VarTemplateArgsInfo;
3930
0
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3931
0
  assert(VarTemplate &&
3932
0
         "A template specialization without specialized template?");
3933
3934
0
  VarTemplateDecl *InstVarTemplate =
3935
0
      cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3936
0
          D->getLocation(), VarTemplate, TemplateArgs));
3937
0
  if (!InstVarTemplate)
3938
0
    return nullptr;
3939
3940
  // Substitute the current template arguments.
3941
0
  if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3942
0
          D->getTemplateArgsInfo()) {
3943
0
    VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3944
0
    VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3945
3946
0
    if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3947
0
                                       TemplateArgs, VarTemplateArgsInfo))
3948
0
      return nullptr;
3949
0
  }
3950
3951
  // Check that the template argument list is well-formed for this template.
3952
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3953
0
  if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3954
0
                                        VarTemplateArgsInfo, false,
3955
0
                                        SugaredConverted, CanonicalConverted,
3956
0
                                        /*UpdateArgsWithConversions=*/true))
3957
0
    return nullptr;
3958
3959
  // Check whether we've already seen a declaration of this specialization.
3960
0
  void *InsertPos = nullptr;
3961
0
  VarTemplateSpecializationDecl *PrevDecl =
3962
0
      InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
3963
3964
  // Check whether we've already seen a conflicting instantiation of this
3965
  // declaration (for instance, if there was a prior implicit instantiation).
3966
0
  bool Ignored;
3967
0
  if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3968
0
                      D->getLocation(), D->getSpecializationKind(), PrevDecl,
3969
0
                      PrevDecl->getSpecializationKind(),
3970
0
                      PrevDecl->getPointOfInstantiation(), Ignored))
3971
0
    return nullptr;
3972
3973
0
  return VisitVarTemplateSpecializationDecl(
3974
0
      InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
3975
0
}
3976
3977
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3978
    VarTemplateDecl *VarTemplate, VarDecl *D,
3979
    const TemplateArgumentListInfo &TemplateArgsInfo,
3980
    ArrayRef<TemplateArgument> Converted,
3981
0
    VarTemplateSpecializationDecl *PrevDecl) {
3982
3983
  // Do substitution on the type of the declaration
3984
0
  TypeSourceInfo *DI =
3985
0
      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3986
0
                        D->getTypeSpecStartLoc(), D->getDeclName());
3987
0
  if (!DI)
3988
0
    return nullptr;
3989
3990
0
  if (DI->getType()->isFunctionType()) {
3991
0
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3992
0
        << D->isStaticDataMember() << DI->getType();
3993
0
    return nullptr;
3994
0
  }
3995
3996
  // Build the instantiated declaration
3997
0
  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3998
0
      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3999
0
      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4000
0
  Var->setTemplateArgsInfo(TemplateArgsInfo);
4001
0
  if (!PrevDecl) {
4002
0
    void *InsertPos = nullptr;
4003
0
    VarTemplate->findSpecialization(Converted, InsertPos);
4004
0
    VarTemplate->AddSpecialization(Var, InsertPos);
4005
0
  }
4006
4007
0
  if (SemaRef.getLangOpts().OpenCL)
4008
0
    SemaRef.deduceOpenCLAddressSpace(Var);
4009
4010
  // Substitute the nested name specifier, if any.
4011
0
  if (SubstQualifier(D, Var))
4012
0
    return nullptr;
4013
4014
0
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4015
0
                                     StartingScope, false, PrevDecl);
4016
4017
0
  return Var;
4018
0
}
4019
4020
0
Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4021
0
  llvm_unreachable("@defs is not supported in Objective-C++");
4022
0
}
4023
4024
0
Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4025
  // FIXME: We need to be able to instantiate FriendTemplateDecls.
4026
0
  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4027
0
                                               DiagnosticsEngine::Error,
4028
0
                                               "cannot instantiate %0 yet");
4029
0
  SemaRef.Diag(D->getLocation(), DiagID)
4030
0
    << D->getDeclKindName();
4031
4032
0
  return nullptr;
4033
0
}
4034
4035
0
Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4036
0
  llvm_unreachable("Concept definitions cannot reside inside a template");
4037
0
}
4038
4039
Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4040
0
    ImplicitConceptSpecializationDecl *D) {
4041
0
  llvm_unreachable("Concept specializations cannot reside inside a template");
4042
0
}
4043
4044
Decl *
4045
0
TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4046
0
  return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4047
0
                                      D->getBeginLoc());
4048
0
}
4049
4050
0
Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4051
0
  llvm_unreachable("Unexpected decl");
4052
0
}
4053
4054
Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4055
0
                      const MultiLevelTemplateArgumentList &TemplateArgs) {
4056
0
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4057
0
  if (D->isInvalidDecl())
4058
0
    return nullptr;
4059
4060
0
  Decl *SubstD;
4061
0
  runWithSufficientStackSpace(D->getLocation(), [&] {
4062
0
    SubstD = Instantiator.Visit(D);
4063
0
  });
4064
0
  return SubstD;
4065
0
}
4066
4067
void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4068
                                                FunctionDecl *Orig, QualType &T,
4069
                                                TypeSourceInfo *&TInfo,
4070
0
                                                DeclarationNameInfo &NameInfo) {
4071
0
  assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
4072
4073
  // C++2a [class.compare.default]p3:
4074
  //   the return type is replaced with bool
4075
0
  auto *FPT = T->castAs<FunctionProtoType>();
4076
0
  T = SemaRef.Context.getFunctionType(
4077
0
      SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4078
4079
  // Update the return type in the source info too. The most straightforward
4080
  // way is to create new TypeSourceInfo for the new type. Use the location of
4081
  // the '= default' as the location of the new type.
4082
  //
4083
  // FIXME: Set the correct return type when we initially transform the type,
4084
  // rather than delaying it to now.
4085
0
  TypeSourceInfo *NewTInfo =
4086
0
      SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4087
0
  auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4088
0
  assert(OldLoc && "type of function is not a function type?");
4089
0
  auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4090
0
  for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4091
0
    NewLoc.setParam(I, OldLoc.getParam(I));
4092
0
  TInfo = NewTInfo;
4093
4094
  //   and the declarator-id is replaced with operator==
4095
0
  NameInfo.setName(
4096
0
      SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4097
0
}
4098
4099
FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4100
0
                                               FunctionDecl *Spaceship) {
4101
0
  if (Spaceship->isInvalidDecl())
4102
0
    return nullptr;
4103
4104
  // C++2a [class.compare.default]p3:
4105
  //   an == operator function is declared implicitly [...] with the same
4106
  //   access and function-definition and in the same class scope as the
4107
  //   three-way comparison operator function
4108
0
  MultiLevelTemplateArgumentList NoTemplateArgs;
4109
0
  NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4110
0
  NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4111
0
  TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4112
0
  Decl *R;
4113
0
  if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4114
0
    R = Instantiator.VisitCXXMethodDecl(
4115
0
        MD, /*TemplateParams=*/nullptr,
4116
0
        TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4117
0
  } else {
4118
0
    assert(Spaceship->getFriendObjectKind() &&
4119
0
           "defaulted spaceship is neither a member nor a friend");
4120
4121
0
    R = Instantiator.VisitFunctionDecl(
4122
0
        Spaceship, /*TemplateParams=*/nullptr,
4123
0
        TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4124
0
    if (!R)
4125
0
      return nullptr;
4126
4127
0
    FriendDecl *FD =
4128
0
        FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4129
0
                           cast<NamedDecl>(R), Spaceship->getBeginLoc());
4130
0
    FD->setAccess(AS_public);
4131
0
    RD->addDecl(FD);
4132
0
  }
4133
0
  return cast_or_null<FunctionDecl>(R);
4134
0
}
4135
4136
/// Instantiates a nested template parameter list in the current
4137
/// instantiation context.
4138
///
4139
/// \param L The parameter list to instantiate
4140
///
4141
/// \returns NULL if there was an error
4142
TemplateParameterList *
4143
0
TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4144
  // Get errors for all the parameters before bailing out.
4145
0
  bool Invalid = false;
4146
4147
0
  unsigned N = L->size();
4148
0
  typedef SmallVector<NamedDecl *, 8> ParamVector;
4149
0
  ParamVector Params;
4150
0
  Params.reserve(N);
4151
0
  for (auto &P : *L) {
4152
0
    NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4153
0
    Params.push_back(D);
4154
0
    Invalid = Invalid || !D || D->isInvalidDecl();
4155
0
  }
4156
4157
  // Clean up if we had an error.
4158
0
  if (Invalid)
4159
0
    return nullptr;
4160
4161
0
  Expr *InstRequiresClause = L->getRequiresClause();
4162
4163
0
  TemplateParameterList *InstL
4164
0
    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4165
0
                                    L->getLAngleLoc(), Params,
4166
0
                                    L->getRAngleLoc(), InstRequiresClause);
4167
0
  return InstL;
4168
0
}
4169
4170
TemplateParameterList *
4171
Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4172
                          const MultiLevelTemplateArgumentList &TemplateArgs,
4173
0
                          bool EvaluateConstraints) {
4174
0
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4175
0
  Instantiator.setEvaluateConstraints(EvaluateConstraints);
4176
0
  return Instantiator.SubstTemplateParams(Params);
4177
0
}
4178
4179
/// Instantiate the declaration of a class template partial
4180
/// specialization.
4181
///
4182
/// \param ClassTemplate the (instantiated) class template that is partially
4183
// specialized by the instantiation of \p PartialSpec.
4184
///
4185
/// \param PartialSpec the (uninstantiated) class template partial
4186
/// specialization that we are instantiating.
4187
///
4188
/// \returns The instantiated partial specialization, if successful; otherwise,
4189
/// NULL to indicate an error.
4190
ClassTemplatePartialSpecializationDecl *
4191
TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4192
                                            ClassTemplateDecl *ClassTemplate,
4193
0
                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
4194
  // Create a local instantiation scope for this class template partial
4195
  // specialization, which will contain the instantiations of the template
4196
  // parameters.
4197
0
  LocalInstantiationScope Scope(SemaRef);
4198
4199
  // Substitute into the template parameters of the class template partial
4200
  // specialization.
4201
0
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4202
0
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4203
0
  if (!InstParams)
4204
0
    return nullptr;
4205
4206
  // Substitute into the template arguments of the class template partial
4207
  // specialization.
4208
0
  const ASTTemplateArgumentListInfo *TemplArgInfo
4209
0
    = PartialSpec->getTemplateArgsAsWritten();
4210
0
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4211
0
                                            TemplArgInfo->RAngleLoc);
4212
0
  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4213
0
                                     InstTemplateArgs))
4214
0
    return nullptr;
4215
4216
  // Check that the template argument list is well-formed for this
4217
  // class template.
4218
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4219
0
  if (SemaRef.CheckTemplateArgumentList(
4220
0
          ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4221
0
          /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4222
0
    return nullptr;
4223
4224
  // Check these arguments are valid for a template partial specialization.
4225
0
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
4226
0
          PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4227
0
          CanonicalConverted))
4228
0
    return nullptr;
4229
4230
  // Figure out where to insert this class template partial specialization
4231
  // in the member template's set of class template partial specializations.
4232
0
  void *InsertPos = nullptr;
4233
0
  ClassTemplateSpecializationDecl *PrevDecl =
4234
0
      ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4235
0
                                               InsertPos);
4236
4237
  // Build the canonical type that describes the converted template
4238
  // arguments of the class template partial specialization.
4239
0
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4240
0
      TemplateName(ClassTemplate), CanonicalConverted);
4241
4242
  // Build the fully-sugared type for this class template
4243
  // specialization as the user wrote in the specialization
4244
  // itself. This means that we'll pretty-print the type retrieved
4245
  // from the specialization's declaration the way that the user
4246
  // actually wrote the specialization, rather than formatting the
4247
  // name based on the "canonical" representation used to store the
4248
  // template arguments in the specialization.
4249
0
  TypeSourceInfo *WrittenTy
4250
0
    = SemaRef.Context.getTemplateSpecializationTypeInfo(
4251
0
                                                    TemplateName(ClassTemplate),
4252
0
                                                    PartialSpec->getLocation(),
4253
0
                                                    InstTemplateArgs,
4254
0
                                                    CanonType);
4255
4256
0
  if (PrevDecl) {
4257
    // We've already seen a partial specialization with the same template
4258
    // parameters and template arguments. This can happen, for example, when
4259
    // substituting the outer template arguments ends up causing two
4260
    // class template partial specializations of a member class template
4261
    // to have identical forms, e.g.,
4262
    //
4263
    //   template<typename T, typename U>
4264
    //   struct Outer {
4265
    //     template<typename X, typename Y> struct Inner;
4266
    //     template<typename Y> struct Inner<T, Y>;
4267
    //     template<typename Y> struct Inner<U, Y>;
4268
    //   };
4269
    //
4270
    //   Outer<int, int> outer; // error: the partial specializations of Inner
4271
    //                          // have the same signature.
4272
0
    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4273
0
      << WrittenTy->getType();
4274
0
    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4275
0
      << SemaRef.Context.getTypeDeclType(PrevDecl);
4276
0
    return nullptr;
4277
0
  }
4278
4279
4280
  // Create the class template partial specialization declaration.
4281
0
  ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4282
0
      ClassTemplatePartialSpecializationDecl::Create(
4283
0
          SemaRef.Context, PartialSpec->getTagKind(), Owner,
4284
0
          PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4285
0
          ClassTemplate, CanonicalConverted, InstTemplateArgs, CanonType,
4286
0
          nullptr);
4287
  // Substitute the nested name specifier, if any.
4288
0
  if (SubstQualifier(PartialSpec, InstPartialSpec))
4289
0
    return nullptr;
4290
4291
0
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4292
0
  InstPartialSpec->setTypeAsWritten(WrittenTy);
4293
4294
  // Check the completed partial specialization.
4295
0
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4296
4297
  // Add this partial specialization to the set of class template partial
4298
  // specializations.
4299
0
  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4300
0
                                          /*InsertPos=*/nullptr);
4301
0
  return InstPartialSpec;
4302
0
}
4303
4304
/// Instantiate the declaration of a variable template partial
4305
/// specialization.
4306
///
4307
/// \param VarTemplate the (instantiated) variable template that is partially
4308
/// specialized by the instantiation of \p PartialSpec.
4309
///
4310
/// \param PartialSpec the (uninstantiated) variable template partial
4311
/// specialization that we are instantiating.
4312
///
4313
/// \returns The instantiated partial specialization, if successful; otherwise,
4314
/// NULL to indicate an error.
4315
VarTemplatePartialSpecializationDecl *
4316
TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4317
    VarTemplateDecl *VarTemplate,
4318
0
    VarTemplatePartialSpecializationDecl *PartialSpec) {
4319
  // Create a local instantiation scope for this variable template partial
4320
  // specialization, which will contain the instantiations of the template
4321
  // parameters.
4322
0
  LocalInstantiationScope Scope(SemaRef);
4323
4324
  // Substitute into the template parameters of the variable template partial
4325
  // specialization.
4326
0
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4327
0
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4328
0
  if (!InstParams)
4329
0
    return nullptr;
4330
4331
  // Substitute into the template arguments of the variable template partial
4332
  // specialization.
4333
0
  const ASTTemplateArgumentListInfo *TemplArgInfo
4334
0
    = PartialSpec->getTemplateArgsAsWritten();
4335
0
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4336
0
                                            TemplArgInfo->RAngleLoc);
4337
0
  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4338
0
                                     InstTemplateArgs))
4339
0
    return nullptr;
4340
4341
  // Check that the template argument list is well-formed for this
4342
  // class template.
4343
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4344
0
  if (SemaRef.CheckTemplateArgumentList(
4345
0
          VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4346
0
          /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4347
0
    return nullptr;
4348
4349
  // Check these arguments are valid for a template partial specialization.
4350
0
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
4351
0
          PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4352
0
          CanonicalConverted))
4353
0
    return nullptr;
4354
4355
  // Figure out where to insert this variable template partial specialization
4356
  // in the member template's set of variable template partial specializations.
4357
0
  void *InsertPos = nullptr;
4358
0
  VarTemplateSpecializationDecl *PrevDecl =
4359
0
      VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4360
0
                                             InsertPos);
4361
4362
  // Build the canonical type that describes the converted template
4363
  // arguments of the variable template partial specialization.
4364
0
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4365
0
      TemplateName(VarTemplate), CanonicalConverted);
4366
4367
  // Build the fully-sugared type for this variable template
4368
  // specialization as the user wrote in the specialization
4369
  // itself. This means that we'll pretty-print the type retrieved
4370
  // from the specialization's declaration the way that the user
4371
  // actually wrote the specialization, rather than formatting the
4372
  // name based on the "canonical" representation used to store the
4373
  // template arguments in the specialization.
4374
0
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4375
0
      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4376
0
      CanonType);
4377
4378
0
  if (PrevDecl) {
4379
    // We've already seen a partial specialization with the same template
4380
    // parameters and template arguments. This can happen, for example, when
4381
    // substituting the outer template arguments ends up causing two
4382
    // variable template partial specializations of a member variable template
4383
    // to have identical forms, e.g.,
4384
    //
4385
    //   template<typename T, typename U>
4386
    //   struct Outer {
4387
    //     template<typename X, typename Y> pair<X,Y> p;
4388
    //     template<typename Y> pair<T, Y> p;
4389
    //     template<typename Y> pair<U, Y> p;
4390
    //   };
4391
    //
4392
    //   Outer<int, int> outer; // error: the partial specializations of Inner
4393
    //                          // have the same signature.
4394
0
    SemaRef.Diag(PartialSpec->getLocation(),
4395
0
                 diag::err_var_partial_spec_redeclared)
4396
0
        << WrittenTy->getType();
4397
0
    SemaRef.Diag(PrevDecl->getLocation(),
4398
0
                 diag::note_var_prev_partial_spec_here);
4399
0
    return nullptr;
4400
0
  }
4401
4402
  // Do substitution on the type of the declaration
4403
0
  TypeSourceInfo *DI = SemaRef.SubstType(
4404
0
      PartialSpec->getTypeSourceInfo(), TemplateArgs,
4405
0
      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4406
0
  if (!DI)
4407
0
    return nullptr;
4408
4409
0
  if (DI->getType()->isFunctionType()) {
4410
0
    SemaRef.Diag(PartialSpec->getLocation(),
4411
0
                 diag::err_variable_instantiates_to_function)
4412
0
        << PartialSpec->isStaticDataMember() << DI->getType();
4413
0
    return nullptr;
4414
0
  }
4415
4416
  // Create the variable template partial specialization declaration.
4417
0
  VarTemplatePartialSpecializationDecl *InstPartialSpec =
4418
0
      VarTemplatePartialSpecializationDecl::Create(
4419
0
          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4420
0
          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4421
0
          DI, PartialSpec->getStorageClass(), CanonicalConverted,
4422
0
          InstTemplateArgs);
4423
4424
  // Substitute the nested name specifier, if any.
4425
0
  if (SubstQualifier(PartialSpec, InstPartialSpec))
4426
0
    return nullptr;
4427
4428
0
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4429
0
  InstPartialSpec->setTypeAsWritten(WrittenTy);
4430
4431
  // Check the completed partial specialization.
4432
0
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4433
4434
  // Add this partial specialization to the set of variable template partial
4435
  // specializations. The instantiation of the initializer is not necessary.
4436
0
  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4437
4438
0
  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4439
0
                                     LateAttrs, Owner, StartingScope);
4440
4441
0
  return InstPartialSpec;
4442
0
}
4443
4444
TypeSourceInfo*
4445
TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4446
0
                              SmallVectorImpl<ParmVarDecl *> &Params) {
4447
0
  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4448
0
  assert(OldTInfo && "substituting function without type source info");
4449
0
  assert(Params.empty() && "parameter vector is non-empty at start");
4450
4451
0
  CXXRecordDecl *ThisContext = nullptr;
4452
0
  Qualifiers ThisTypeQuals;
4453
0
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4454
0
    ThisContext = cast<CXXRecordDecl>(Owner);
4455
0
    ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4456
0
  }
4457
4458
0
  TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4459
0
      OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4460
0
      ThisContext, ThisTypeQuals, EvaluateConstraints);
4461
0
  if (!NewTInfo)
4462
0
    return nullptr;
4463
4464
0
  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4465
0
  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4466
0
    if (NewTInfo != OldTInfo) {
4467
      // Get parameters from the new type info.
4468
0
      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4469
0
      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4470
0
      unsigned NewIdx = 0;
4471
0
      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4472
0
           OldIdx != NumOldParams; ++OldIdx) {
4473
0
        ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4474
0
        if (!OldParam)
4475
0
          return nullptr;
4476
4477
0
        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4478
4479
0
        std::optional<unsigned> NumArgumentsInExpansion;
4480
0
        if (OldParam->isParameterPack())
4481
0
          NumArgumentsInExpansion =
4482
0
              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4483
0
                                                 TemplateArgs);
4484
0
        if (!NumArgumentsInExpansion) {
4485
          // Simple case: normal parameter, or a parameter pack that's
4486
          // instantiated to a (still-dependent) parameter pack.
4487
0
          ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4488
0
          Params.push_back(NewParam);
4489
0
          Scope->InstantiatedLocal(OldParam, NewParam);
4490
0
        } else {
4491
          // Parameter pack expansion: make the instantiation an argument pack.
4492
0
          Scope->MakeInstantiatedLocalArgPack(OldParam);
4493
0
          for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4494
0
            ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4495
0
            Params.push_back(NewParam);
4496
0
            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4497
0
          }
4498
0
        }
4499
0
      }
4500
0
    } else {
4501
      // The function type itself was not dependent and therefore no
4502
      // substitution occurred. However, we still need to instantiate
4503
      // the function parameters themselves.
4504
0
      const FunctionProtoType *OldProto =
4505
0
          cast<FunctionProtoType>(OldProtoLoc.getType());
4506
0
      for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4507
0
           ++i) {
4508
0
        ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4509
0
        if (!OldParam) {
4510
0
          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4511
0
              D, D->getLocation(), OldProto->getParamType(i)));
4512
0
          continue;
4513
0
        }
4514
4515
0
        ParmVarDecl *Parm =
4516
0
            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4517
0
        if (!Parm)
4518
0
          return nullptr;
4519
0
        Params.push_back(Parm);
4520
0
      }
4521
0
    }
4522
0
  } else {
4523
    // If the type of this function, after ignoring parentheses, is not
4524
    // *directly* a function type, then we're instantiating a function that
4525
    // was declared via a typedef or with attributes, e.g.,
4526
    //
4527
    //   typedef int functype(int, int);
4528
    //   functype func;
4529
    //   int __cdecl meth(int, int);
4530
    //
4531
    // In this case, we'll just go instantiate the ParmVarDecls that we
4532
    // synthesized in the method declaration.
4533
0
    SmallVector<QualType, 4> ParamTypes;
4534
0
    Sema::ExtParameterInfoBuilder ExtParamInfos;
4535
0
    if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4536
0
                               TemplateArgs, ParamTypes, &Params,
4537
0
                               ExtParamInfos))
4538
0
      return nullptr;
4539
0
  }
4540
4541
0
  return NewTInfo;
4542
0
}
4543
4544
/// Introduce the instantiated local variables into the local
4545
/// instantiation scope.
4546
void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4547
                                           const FunctionDecl *PatternDecl,
4548
0
                                           LocalInstantiationScope &Scope) {
4549
0
  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4550
4551
0
  for (auto *decl : PatternDecl->decls()) {
4552
0
    if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4553
0
      continue;
4554
4555
0
    VarDecl *VD = cast<VarDecl>(decl);
4556
0
    IdentifierInfo *II = VD->getIdentifier();
4557
4558
0
    auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4559
0
      VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4560
0
      return InstVD && InstVD->isLocalVarDecl() &&
4561
0
             InstVD->getIdentifier() == II;
4562
0
    });
4563
4564
0
    if (it == Function->decls().end())
4565
0
      continue;
4566
4567
0
    Scope.InstantiatedLocal(VD, *it);
4568
0
    LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4569
0
                    /*isNested=*/false, VD->getLocation(), SourceLocation(),
4570
0
                    VD->getType(), /*Invalid=*/false);
4571
0
  }
4572
0
}
4573
4574
/// Introduce the instantiated function parameters into the local
4575
/// instantiation scope, and set the parameter names to those used
4576
/// in the template.
4577
bool Sema::addInstantiatedParametersToScope(
4578
    FunctionDecl *Function, const FunctionDecl *PatternDecl,
4579
    LocalInstantiationScope &Scope,
4580
0
    const MultiLevelTemplateArgumentList &TemplateArgs) {
4581
0
  unsigned FParamIdx = 0;
4582
0
  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4583
0
    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4584
0
    if (!PatternParam->isParameterPack()) {
4585
      // Simple case: not a parameter pack.
4586
0
      assert(FParamIdx < Function->getNumParams());
4587
0
      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4588
0
      FunctionParam->setDeclName(PatternParam->getDeclName());
4589
      // If the parameter's type is not dependent, update it to match the type
4590
      // in the pattern. They can differ in top-level cv-qualifiers, and we want
4591
      // the pattern's type here. If the type is dependent, they can't differ,
4592
      // per core issue 1668. Substitute into the type from the pattern, in case
4593
      // it's instantiation-dependent.
4594
      // FIXME: Updating the type to work around this is at best fragile.
4595
0
      if (!PatternDecl->getType()->isDependentType()) {
4596
0
        QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4597
0
                               FunctionParam->getLocation(),
4598
0
                               FunctionParam->getDeclName());
4599
0
        if (T.isNull())
4600
0
          return true;
4601
0
        FunctionParam->setType(T);
4602
0
      }
4603
4604
0
      Scope.InstantiatedLocal(PatternParam, FunctionParam);
4605
0
      ++FParamIdx;
4606
0
      continue;
4607
0
    }
4608
4609
    // Expand the parameter pack.
4610
0
    Scope.MakeInstantiatedLocalArgPack(PatternParam);
4611
0
    std::optional<unsigned> NumArgumentsInExpansion =
4612
0
        getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4613
0
    if (NumArgumentsInExpansion) {
4614
0
      QualType PatternType =
4615
0
          PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4616
0
      for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4617
0
        ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4618
0
        FunctionParam->setDeclName(PatternParam->getDeclName());
4619
0
        if (!PatternDecl->getType()->isDependentType()) {
4620
0
          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4621
0
          QualType T =
4622
0
              SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4623
0
                        FunctionParam->getDeclName());
4624
0
          if (T.isNull())
4625
0
            return true;
4626
0
          FunctionParam->setType(T);
4627
0
        }
4628
4629
0
        Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4630
0
        ++FParamIdx;
4631
0
      }
4632
0
    }
4633
0
  }
4634
4635
0
  return false;
4636
0
}
4637
4638
bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4639
0
                                      ParmVarDecl *Param) {
4640
0
  assert(Param->hasUninstantiatedDefaultArg());
4641
4642
  // Instantiate the expression.
4643
  //
4644
  // FIXME: Pass in a correct Pattern argument, otherwise
4645
  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4646
  //
4647
  // template<typename T>
4648
  // struct A {
4649
  //   static int FooImpl();
4650
  //
4651
  //   template<typename Tp>
4652
  //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4653
  //   // template argument list [[T], [Tp]], should be [[Tp]].
4654
  //   friend A<Tp> Foo(int a);
4655
  // };
4656
  //
4657
  // template<typename T>
4658
  // A<T> Foo(int a = A<T>::FooImpl());
4659
0
  MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4660
0
      FD, FD->getLexicalDeclContext(), /*Final=*/false, nullptr,
4661
0
      /*RelativeToPrimary=*/true);
4662
4663
0
  if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4664
0
    return true;
4665
4666
0
  if (ASTMutationListener *L = getASTMutationListener())
4667
0
    L->DefaultArgumentInstantiated(Param);
4668
4669
0
  return false;
4670
0
}
4671
4672
void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4673
0
                                    FunctionDecl *Decl) {
4674
0
  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4675
0
  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4676
0
    return;
4677
4678
0
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4679
0
                             InstantiatingTemplate::ExceptionSpecification());
4680
0
  if (Inst.isInvalid()) {
4681
    // We hit the instantiation depth limit. Clear the exception specification
4682
    // so that our callers don't have to cope with EST_Uninstantiated.
4683
0
    UpdateExceptionSpec(Decl, EST_None);
4684
0
    return;
4685
0
  }
4686
0
  if (Inst.isAlreadyInstantiating()) {
4687
    // This exception specification indirectly depends on itself. Reject.
4688
    // FIXME: Corresponding rule in the standard?
4689
0
    Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4690
0
    UpdateExceptionSpec(Decl, EST_None);
4691
0
    return;
4692
0
  }
4693
4694
  // Enter the scope of this instantiation. We don't use
4695
  // PushDeclContext because we don't have a scope.
4696
0
  Sema::ContextRAII savedContext(*this, Decl);
4697
0
  LocalInstantiationScope Scope(*this);
4698
4699
0
  MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4700
0
      Decl, Decl->getLexicalDeclContext(), /*Final=*/false, nullptr,
4701
0
      /*RelativeToPrimary*/ true);
4702
4703
  // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4704
  // here, because for a non-defining friend declaration in a class template,
4705
  // we don't store enough information to map back to the friend declaration in
4706
  // the template.
4707
0
  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4708
0
  if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4709
0
    UpdateExceptionSpec(Decl, EST_None);
4710
0
    return;
4711
0
  }
4712
4713
0
  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4714
0
                     TemplateArgs);
4715
0
}
4716
4717
/// Initializes the common fields of an instantiation function
4718
/// declaration (New) from the corresponding fields of its template (Tmpl).
4719
///
4720
/// \returns true if there was an error
4721
bool
4722
TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4723
0
                                                    FunctionDecl *Tmpl) {
4724
0
  New->setImplicit(Tmpl->isImplicit());
4725
4726
  // Forward the mangling number from the template to the instantiated decl.
4727
0
  SemaRef.Context.setManglingNumber(New,
4728
0
                                    SemaRef.Context.getManglingNumber(Tmpl));
4729
4730
  // If we are performing substituting explicitly-specified template arguments
4731
  // or deduced template arguments into a function template and we reach this
4732
  // point, we are now past the point where SFINAE applies and have committed
4733
  // to keeping the new function template specialization. We therefore
4734
  // convert the active template instantiation for the function template
4735
  // into a template instantiation for this specific function template
4736
  // specialization, which is not a SFINAE context, so that we diagnose any
4737
  // further errors in the declaration itself.
4738
  //
4739
  // FIXME: This is a hack.
4740
0
  typedef Sema::CodeSynthesisContext ActiveInstType;
4741
0
  ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4742
0
  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4743
0
      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4744
0
    if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4745
0
      SemaRef.InstantiatingSpecializations.erase(
4746
0
          {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4747
0
      atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4748
0
      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4749
0
      ActiveInst.Entity = New;
4750
0
      atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4751
0
    }
4752
0
  }
4753
4754
0
  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4755
0
  assert(Proto && "Function template without prototype?");
4756
4757
0
  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4758
0
    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4759
4760
    // DR1330: In C++11, defer instantiation of a non-trivial
4761
    // exception specification.
4762
    // DR1484: Local classes and their members are instantiated along with the
4763
    // containing function.
4764
0
    if (SemaRef.getLangOpts().CPlusPlus11 &&
4765
0
        EPI.ExceptionSpec.Type != EST_None &&
4766
0
        EPI.ExceptionSpec.Type != EST_DynamicNone &&
4767
0
        EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4768
0
        !Tmpl->isInLocalScopeForInstantiation()) {
4769
0
      FunctionDecl *ExceptionSpecTemplate = Tmpl;
4770
0
      if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4771
0
        ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4772
0
      ExceptionSpecificationType NewEST = EST_Uninstantiated;
4773
0
      if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4774
0
        NewEST = EST_Unevaluated;
4775
4776
      // Mark the function has having an uninstantiated exception specification.
4777
0
      const FunctionProtoType *NewProto
4778
0
        = New->getType()->getAs<FunctionProtoType>();
4779
0
      assert(NewProto && "Template instantiation without function prototype?");
4780
0
      EPI = NewProto->getExtProtoInfo();
4781
0
      EPI.ExceptionSpec.Type = NewEST;
4782
0
      EPI.ExceptionSpec.SourceDecl = New;
4783
0
      EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4784
0
      New->setType(SemaRef.Context.getFunctionType(
4785
0
          NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4786
0
    } else {
4787
0
      Sema::ContextRAII SwitchContext(SemaRef, New);
4788
0
      SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4789
0
    }
4790
0
  }
4791
4792
  // Get the definition. Leaves the variable unchanged if undefined.
4793
0
  const FunctionDecl *Definition = Tmpl;
4794
0
  Tmpl->isDefined(Definition);
4795
4796
0
  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4797
0
                           LateAttrs, StartingScope);
4798
4799
0
  return false;
4800
0
}
4801
4802
/// Initializes common fields of an instantiated method
4803
/// declaration (New) from the corresponding fields of its template
4804
/// (Tmpl).
4805
///
4806
/// \returns true if there was an error
4807
bool
4808
TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4809
0
                                                  CXXMethodDecl *Tmpl) {
4810
0
  if (InitFunctionInstantiation(New, Tmpl))
4811
0
    return true;
4812
4813
0
  if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4814
0
    SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4815
4816
0
  New->setAccess(Tmpl->getAccess());
4817
0
  if (Tmpl->isVirtualAsWritten())
4818
0
    New->setVirtualAsWritten(true);
4819
4820
  // FIXME: New needs a pointer to Tmpl
4821
0
  return false;
4822
0
}
4823
4824
bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4825
0
                                                      FunctionDecl *Tmpl) {
4826
  // Transfer across any unqualified lookups.
4827
0
  if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4828
0
    SmallVector<DeclAccessPair, 32> Lookups;
4829
0
    Lookups.reserve(DFI->getUnqualifiedLookups().size());
4830
0
    bool AnyChanged = false;
4831
0
    for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4832
0
      NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4833
0
                                                  DA.getDecl(), TemplateArgs);
4834
0
      if (!D)
4835
0
        return true;
4836
0
      AnyChanged |= (D != DA.getDecl());
4837
0
      Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4838
0
    }
4839
4840
    // It's unlikely that substitution will change any declarations. Don't
4841
    // store an unnecessary copy in that case.
4842
0
    New->setDefaultedFunctionInfo(
4843
0
        AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4844
0
                         SemaRef.Context, Lookups)
4845
0
                   : DFI);
4846
0
  }
4847
4848
0
  SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4849
0
  return false;
4850
0
}
4851
4852
/// Instantiate (or find existing instantiation of) a function template with a
4853
/// given set of template arguments.
4854
///
4855
/// Usually this should not be used, and template argument deduction should be
4856
/// used in its place.
4857
FunctionDecl *
4858
Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4859
                                     const TemplateArgumentList *Args,
4860
0
                                     SourceLocation Loc) {
4861
0
  FunctionDecl *FD = FTD->getTemplatedDecl();
4862
4863
0
  sema::TemplateDeductionInfo Info(Loc);
4864
0
  InstantiatingTemplate Inst(
4865
0
      *this, Loc, FTD, Args->asArray(),
4866
0
      CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4867
0
  if (Inst.isInvalid())
4868
0
    return nullptr;
4869
4870
0
  ContextRAII SavedContext(*this, FD);
4871
0
  MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4872
0
                                       /*Final=*/false);
4873
4874
0
  return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4875
0
}
4876
4877
/// Instantiate the definition of the given function from its
4878
/// template.
4879
///
4880
/// \param PointOfInstantiation the point at which the instantiation was
4881
/// required. Note that this is not precisely a "point of instantiation"
4882
/// for the function, but it's close.
4883
///
4884
/// \param Function the already-instantiated declaration of a
4885
/// function template specialization or member function of a class template
4886
/// specialization.
4887
///
4888
/// \param Recursive if true, recursively instantiates any functions that
4889
/// are required by this instantiation.
4890
///
4891
/// \param DefinitionRequired if true, then we are performing an explicit
4892
/// instantiation where the body of the function is required. Complain if
4893
/// there is no such body.
4894
void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4895
                                         FunctionDecl *Function,
4896
                                         bool Recursive,
4897
                                         bool DefinitionRequired,
4898
0
                                         bool AtEndOfTU) {
4899
0
  if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4900
0
    return;
4901
4902
  // Never instantiate an explicit specialization except if it is a class scope
4903
  // explicit specialization.
4904
0
  TemplateSpecializationKind TSK =
4905
0
      Function->getTemplateSpecializationKindForInstantiation();
4906
0
  if (TSK == TSK_ExplicitSpecialization)
4907
0
    return;
4908
4909
  // Never implicitly instantiate a builtin; we don't actually need a function
4910
  // body.
4911
0
  if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4912
0
      !DefinitionRequired)
4913
0
    return;
4914
4915
  // Don't instantiate a definition if we already have one.
4916
0
  const FunctionDecl *ExistingDefn = nullptr;
4917
0
  if (Function->isDefined(ExistingDefn,
4918
0
                          /*CheckForPendingFriendDefinition=*/true)) {
4919
0
    if (ExistingDefn->isThisDeclarationADefinition())
4920
0
      return;
4921
4922
    // If we're asked to instantiate a function whose body comes from an
4923
    // instantiated friend declaration, attach the instantiated body to the
4924
    // corresponding declaration of the function.
4925
0
    assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4926
0
    Function = const_cast<FunctionDecl*>(ExistingDefn);
4927
0
  }
4928
4929
  // Find the function body that we'll be substituting.
4930
0
  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4931
0
  assert(PatternDecl && "instantiating a non-template");
4932
4933
0
  const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4934
0
  Stmt *Pattern = nullptr;
4935
0
  if (PatternDef) {
4936
0
    Pattern = PatternDef->getBody(PatternDef);
4937
0
    PatternDecl = PatternDef;
4938
0
    if (PatternDef->willHaveBody())
4939
0
      PatternDef = nullptr;
4940
0
  }
4941
4942
  // FIXME: We need to track the instantiation stack in order to know which
4943
  // definitions should be visible within this instantiation.
4944
0
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4945
0
                                Function->getInstantiatedFromMemberFunction(),
4946
0
                                     PatternDecl, PatternDef, TSK,
4947
0
                                     /*Complain*/DefinitionRequired)) {
4948
0
    if (DefinitionRequired)
4949
0
      Function->setInvalidDecl();
4950
0
    else if (TSK == TSK_ExplicitInstantiationDefinition ||
4951
0
             (Function->isConstexpr() && !Recursive)) {
4952
      // Try again at the end of the translation unit (at which point a
4953
      // definition will be required).
4954
0
      assert(!Recursive);
4955
0
      Function->setInstantiationIsPending(true);
4956
0
      PendingInstantiations.push_back(
4957
0
        std::make_pair(Function, PointOfInstantiation));
4958
0
    } else if (TSK == TSK_ImplicitInstantiation) {
4959
0
      if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4960
0
          !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4961
0
        Diag(PointOfInstantiation, diag::warn_func_template_missing)
4962
0
          << Function;
4963
0
        Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4964
0
        if (getLangOpts().CPlusPlus11)
4965
0
          Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4966
0
              << Function;
4967
0
      }
4968
0
    }
4969
4970
0
    return;
4971
0
  }
4972
4973
  // Postpone late parsed template instantiations.
4974
0
  if (PatternDecl->isLateTemplateParsed() &&
4975
0
      !LateTemplateParser) {
4976
0
    Function->setInstantiationIsPending(true);
4977
0
    LateParsedInstantiations.push_back(
4978
0
        std::make_pair(Function, PointOfInstantiation));
4979
0
    return;
4980
0
  }
4981
4982
0
  llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4983
0
    std::string Name;
4984
0
    llvm::raw_string_ostream OS(Name);
4985
0
    Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4986
0
                                   /*Qualified=*/true);
4987
0
    return Name;
4988
0
  });
4989
4990
  // If we're performing recursive template instantiation, create our own
4991
  // queue of pending implicit instantiations that we will instantiate later,
4992
  // while we're still within our own instantiation context.
4993
  // This has to happen before LateTemplateParser below is called, so that
4994
  // it marks vtables used in late parsed templates as used.
4995
0
  GlobalEagerInstantiationScope GlobalInstantiations(*this,
4996
0
                                                     /*Enabled=*/Recursive);
4997
0
  LocalEagerInstantiationScope LocalInstantiations(*this);
4998
4999
  // Call the LateTemplateParser callback if there is a need to late parse
5000
  // a templated function definition.
5001
0
  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5002
0
      LateTemplateParser) {
5003
    // FIXME: Optimize to allow individual templates to be deserialized.
5004
0
    if (PatternDecl->isFromASTFile())
5005
0
      ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5006
5007
0
    auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5008
0
    assert(LPTIter != LateParsedTemplateMap.end() &&
5009
0
           "missing LateParsedTemplate");
5010
0
    LateTemplateParser(OpaqueParser, *LPTIter->second);
5011
0
    Pattern = PatternDecl->getBody(PatternDecl);
5012
0
    updateAttrsForLateParsedTemplate(PatternDecl, Function);
5013
0
  }
5014
5015
  // Note, we should never try to instantiate a deleted function template.
5016
0
  assert((Pattern || PatternDecl->isDefaulted() ||
5017
0
          PatternDecl->hasSkippedBody()) &&
5018
0
         "unexpected kind of function template definition");
5019
5020
  // C++1y [temp.explicit]p10:
5021
  //   Except for inline functions, declarations with types deduced from their
5022
  //   initializer or return value, and class template specializations, other
5023
  //   explicit instantiation declarations have the effect of suppressing the
5024
  //   implicit instantiation of the entity to which they refer.
5025
0
  if (TSK == TSK_ExplicitInstantiationDeclaration &&
5026
0
      !PatternDecl->isInlined() &&
5027
0
      !PatternDecl->getReturnType()->getContainedAutoType())
5028
0
    return;
5029
5030
0
  if (PatternDecl->isInlined()) {
5031
    // Function, and all later redeclarations of it (from imported modules,
5032
    // for instance), are now implicitly inline.
5033
0
    for (auto *D = Function->getMostRecentDecl(); /**/;
5034
0
         D = D->getPreviousDecl()) {
5035
0
      D->setImplicitlyInline();
5036
0
      if (D == Function)
5037
0
        break;
5038
0
    }
5039
0
  }
5040
5041
0
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5042
0
  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5043
0
    return;
5044
0
  PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
5045
0
                                      "instantiating function definition");
5046
5047
  // The instantiation is visible here, even if it was first declared in an
5048
  // unimported module.
5049
0
  Function->setVisibleDespiteOwningModule();
5050
5051
  // Copy the source locations from the pattern.
5052
0
  Function->setLocation(PatternDecl->getLocation());
5053
0
  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5054
0
  Function->setRangeEnd(PatternDecl->getEndLoc());
5055
5056
0
  EnterExpressionEvaluationContext EvalContext(
5057
0
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5058
5059
  // Introduce a new scope where local variable instantiations will be
5060
  // recorded, unless we're actually a member function within a local
5061
  // class, in which case we need to merge our results with the parent
5062
  // scope (of the enclosing function). The exception is instantiating
5063
  // a function template specialization, since the template to be
5064
  // instantiated already has references to locals properly substituted.
5065
0
  bool MergeWithParentScope = false;
5066
0
  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5067
0
    MergeWithParentScope =
5068
0
        Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5069
5070
0
  LocalInstantiationScope Scope(*this, MergeWithParentScope);
5071
0
  auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5072
    // Special members might get their TypeSourceInfo set up w.r.t the
5073
    // PatternDecl context, in which case parameters could still be pointing
5074
    // back to the original class, make sure arguments are bound to the
5075
    // instantiated record instead.
5076
0
    assert(PatternDecl->isDefaulted() &&
5077
0
           "Special member needs to be defaulted");
5078
0
    auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5079
0
    if (!(PatternSM == Sema::CXXCopyConstructor ||
5080
0
          PatternSM == Sema::CXXCopyAssignment ||
5081
0
          PatternSM == Sema::CXXMoveConstructor ||
5082
0
          PatternSM == Sema::CXXMoveAssignment))
5083
0
      return;
5084
5085
0
    auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5086
0
    const auto *PatternRec =
5087
0
        dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5088
0
    if (!NewRec || !PatternRec)
5089
0
      return;
5090
0
    if (!PatternRec->isLambda())
5091
0
      return;
5092
5093
0
    struct SpecialMemberTypeInfoRebuilder
5094
0
        : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5095
0
      using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5096
0
      const CXXRecordDecl *OldDecl;
5097
0
      CXXRecordDecl *NewDecl;
5098
5099
0
      SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5100
0
                                     CXXRecordDecl *N)
5101
0
          : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5102
5103
0
      bool TransformExceptionSpec(SourceLocation Loc,
5104
0
                                  FunctionProtoType::ExceptionSpecInfo &ESI,
5105
0
                                  SmallVectorImpl<QualType> &Exceptions,
5106
0
                                  bool &Changed) {
5107
0
        return false;
5108
0
      }
5109
5110
0
      QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5111
0
        const RecordType *T = TL.getTypePtr();
5112
0
        RecordDecl *Record = cast_or_null<RecordDecl>(
5113
0
            getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5114
0
        if (Record != OldDecl)
5115
0
          return Base::TransformRecordType(TLB, TL);
5116
5117
0
        QualType Result = getDerived().RebuildRecordType(NewDecl);
5118
0
        if (Result.isNull())
5119
0
          return QualType();
5120
5121
0
        RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5122
0
        NewTL.setNameLoc(TL.getNameLoc());
5123
0
        return Result;
5124
0
      }
5125
0
    } IR{*this, PatternRec, NewRec};
5126
5127
0
    TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5128
0
    assert(NewSI && "Type Transform failed?");
5129
0
    Function->setType(NewSI->getType());
5130
0
    Function->setTypeSourceInfo(NewSI);
5131
5132
0
    ParmVarDecl *Parm = Function->getParamDecl(0);
5133
0
    TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5134
0
    Parm->setType(NewParmSI->getType());
5135
0
    Parm->setTypeSourceInfo(NewParmSI);
5136
0
  };
5137
5138
0
  if (PatternDecl->isDefaulted()) {
5139
0
    RebuildTypeSourceInfoForDefaultSpecialMembers();
5140
0
    SetDeclDefaulted(Function, PatternDecl->getLocation());
5141
0
  } else {
5142
0
    MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5143
0
        Function, Function->getLexicalDeclContext(), /*Final=*/false, nullptr,
5144
0
        false, PatternDecl);
5145
5146
    // Substitute into the qualifier; we can get a substitution failure here
5147
    // through evil use of alias templates.
5148
    // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5149
    // of the) lexical context of the pattern?
5150
0
    SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5151
5152
0
    ActOnStartOfFunctionDef(nullptr, Function);
5153
5154
    // Enter the scope of this instantiation. We don't use
5155
    // PushDeclContext because we don't have a scope.
5156
0
    Sema::ContextRAII savedContext(*this, Function);
5157
5158
0
    FPFeaturesStateRAII SavedFPFeatures(*this);
5159
0
    CurFPFeatures = FPOptions(getLangOpts());
5160
0
    FpPragmaStack.CurrentValue = FPOptionsOverride();
5161
5162
0
    if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5163
0
                                         TemplateArgs))
5164
0
      return;
5165
5166
0
    StmtResult Body;
5167
0
    if (PatternDecl->hasSkippedBody()) {
5168
0
      ActOnSkippedFunctionBody(Function);
5169
0
      Body = nullptr;
5170
0
    } else {
5171
0
      if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5172
        // If this is a constructor, instantiate the member initializers.
5173
0
        InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5174
0
                                   TemplateArgs);
5175
5176
        // If this is an MS ABI dllexport default constructor, instantiate any
5177
        // default arguments.
5178
0
        if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5179
0
            Ctor->isDefaultConstructor()) {
5180
0
          InstantiateDefaultCtorDefaultArgs(Ctor);
5181
0
        }
5182
0
      }
5183
5184
      // Instantiate the function body.
5185
0
      Body = SubstStmt(Pattern, TemplateArgs);
5186
5187
0
      if (Body.isInvalid())
5188
0
        Function->setInvalidDecl();
5189
0
    }
5190
    // FIXME: finishing the function body while in an expression evaluation
5191
    // context seems wrong. Investigate more.
5192
0
    ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5193
5194
0
    PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5195
5196
0
    if (auto *Listener = getASTMutationListener())
5197
0
      Listener->FunctionDefinitionInstantiated(Function);
5198
5199
0
    savedContext.pop();
5200
0
  }
5201
5202
0
  DeclGroupRef DG(Function);
5203
0
  Consumer.HandleTopLevelDecl(DG);
5204
5205
  // This class may have local implicit instantiations that need to be
5206
  // instantiation within this scope.
5207
0
  LocalInstantiations.perform();
5208
0
  Scope.Exit();
5209
0
  GlobalInstantiations.perform();
5210
0
}
5211
5212
VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5213
    VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5214
    const TemplateArgumentList &TemplateArgList,
5215
    const TemplateArgumentListInfo &TemplateArgsInfo,
5216
    SmallVectorImpl<TemplateArgument> &Converted,
5217
    SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5218
0
    LocalInstantiationScope *StartingScope) {
5219
0
  if (FromVar->isInvalidDecl())
5220
0
    return nullptr;
5221
5222
0
  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5223
0
  if (Inst.isInvalid())
5224
0
    return nullptr;
5225
5226
  // Instantiate the first declaration of the variable template: for a partial
5227
  // specialization of a static data member template, the first declaration may
5228
  // or may not be the declaration in the class; if it's in the class, we want
5229
  // to instantiate a member in the class (a declaration), and if it's outside,
5230
  // we want to instantiate a definition.
5231
  //
5232
  // If we're instantiating an explicitly-specialized member template or member
5233
  // partial specialization, don't do this. The member specialization completely
5234
  // replaces the original declaration in this case.
5235
0
  bool IsMemberSpec = false;
5236
0
  MultiLevelTemplateArgumentList MultiLevelList;
5237
0
  if (auto *PartialSpec =
5238
0
          dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5239
0
    IsMemberSpec = PartialSpec->isMemberSpecialization();
5240
0
    MultiLevelList.addOuterTemplateArguments(
5241
0
        PartialSpec, TemplateArgList.asArray(), /*Final=*/false);
5242
0
  } else {
5243
0
    assert(VarTemplate == FromVar->getDescribedVarTemplate());
5244
0
    IsMemberSpec = VarTemplate->isMemberSpecialization();
5245
0
    MultiLevelList.addOuterTemplateArguments(
5246
0
        VarTemplate, TemplateArgList.asArray(), /*Final=*/false);
5247
0
  }
5248
0
  if (!IsMemberSpec)
5249
0
    FromVar = FromVar->getFirstDecl();
5250
5251
0
  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5252
0
                                        MultiLevelList);
5253
5254
  // TODO: Set LateAttrs and StartingScope ...
5255
5256
0
  return cast_or_null<VarTemplateSpecializationDecl>(
5257
0
      Instantiator.VisitVarTemplateSpecializationDecl(
5258
0
          VarTemplate, FromVar, TemplateArgsInfo, Converted));
5259
0
}
5260
5261
/// Instantiates a variable template specialization by completing it
5262
/// with appropriate type information and initializer.
5263
VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5264
    VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5265
0
    const MultiLevelTemplateArgumentList &TemplateArgs) {
5266
0
  assert(PatternDecl->isThisDeclarationADefinition() &&
5267
0
         "don't have a definition to instantiate from");
5268
5269
  // Do substitution on the type of the declaration
5270
0
  TypeSourceInfo *DI =
5271
0
      SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5272
0
                PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5273
0
  if (!DI)
5274
0
    return nullptr;
5275
5276
  // Update the type of this variable template specialization.
5277
0
  VarSpec->setType(DI->getType());
5278
5279
  // Convert the declaration into a definition now.
5280
0
  VarSpec->setCompleteDefinition();
5281
5282
  // Instantiate the initializer.
5283
0
  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5284
5285
0
  if (getLangOpts().OpenCL)
5286
0
    deduceOpenCLAddressSpace(VarSpec);
5287
5288
0
  return VarSpec;
5289
0
}
5290
5291
/// BuildVariableInstantiation - Used after a new variable has been created.
5292
/// Sets basic variable data and decides whether to postpone the
5293
/// variable instantiation.
5294
void Sema::BuildVariableInstantiation(
5295
    VarDecl *NewVar, VarDecl *OldVar,
5296
    const MultiLevelTemplateArgumentList &TemplateArgs,
5297
    LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5298
    LocalInstantiationScope *StartingScope,
5299
    bool InstantiatingVarTemplate,
5300
0
    VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5301
  // Instantiating a partial specialization to produce a partial
5302
  // specialization.
5303
0
  bool InstantiatingVarTemplatePartialSpec =
5304
0
      isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5305
0
      isa<VarTemplatePartialSpecializationDecl>(NewVar);
5306
  // Instantiating from a variable template (or partial specialization) to
5307
  // produce a variable template specialization.
5308
0
  bool InstantiatingSpecFromTemplate =
5309
0
      isa<VarTemplateSpecializationDecl>(NewVar) &&
5310
0
      (OldVar->getDescribedVarTemplate() ||
5311
0
       isa<VarTemplatePartialSpecializationDecl>(OldVar));
5312
5313
  // If we are instantiating a local extern declaration, the
5314
  // instantiation belongs lexically to the containing function.
5315
  // If we are instantiating a static data member defined
5316
  // out-of-line, the instantiation will have the same lexical
5317
  // context (which will be a namespace scope) as the template.
5318
0
  if (OldVar->isLocalExternDecl()) {
5319
0
    NewVar->setLocalExternDecl();
5320
0
    NewVar->setLexicalDeclContext(Owner);
5321
0
  } else if (OldVar->isOutOfLine())
5322
0
    NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5323
0
  NewVar->setTSCSpec(OldVar->getTSCSpec());
5324
0
  NewVar->setInitStyle(OldVar->getInitStyle());
5325
0
  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5326
0
  NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5327
0
  NewVar->setConstexpr(OldVar->isConstexpr());
5328
0
  NewVar->setInitCapture(OldVar->isInitCapture());
5329
0
  NewVar->setPreviousDeclInSameBlockScope(
5330
0
      OldVar->isPreviousDeclInSameBlockScope());
5331
0
  NewVar->setAccess(OldVar->getAccess());
5332
5333
0
  if (!OldVar->isStaticDataMember()) {
5334
0
    if (OldVar->isUsed(false))
5335
0
      NewVar->setIsUsed();
5336
0
    NewVar->setReferenced(OldVar->isReferenced());
5337
0
  }
5338
5339
0
  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5340
5341
0
  LookupResult Previous(
5342
0
      *this, NewVar->getDeclName(), NewVar->getLocation(),
5343
0
      NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5344
0
                                  : Sema::LookupOrdinaryName,
5345
0
      NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5346
0
                                  : forRedeclarationInCurContext());
5347
5348
0
  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5349
0
      (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5350
0
       OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5351
    // We have a previous declaration. Use that one, so we merge with the
5352
    // right type.
5353
0
    if (NamedDecl *NewPrev = FindInstantiatedDecl(
5354
0
            NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5355
0
      Previous.addDecl(NewPrev);
5356
0
  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5357
0
             OldVar->hasLinkage()) {
5358
0
    LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5359
0
  } else if (PrevDeclForVarTemplateSpecialization) {
5360
0
    Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5361
0
  }
5362
0
  CheckVariableDeclaration(NewVar, Previous);
5363
5364
0
  if (!InstantiatingVarTemplate) {
5365
0
    NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5366
0
    if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5367
0
      NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5368
0
  }
5369
5370
0
  if (!OldVar->isOutOfLine()) {
5371
0
    if (NewVar->getDeclContext()->isFunctionOrMethod())
5372
0
      CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5373
0
  }
5374
5375
  // Link instantiations of static data members back to the template from
5376
  // which they were instantiated.
5377
  //
5378
  // Don't do this when instantiating a template (we link the template itself
5379
  // back in that case) nor when instantiating a static data member template
5380
  // (that's not a member specialization).
5381
0
  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5382
0
      !InstantiatingSpecFromTemplate)
5383
0
    NewVar->setInstantiationOfStaticDataMember(OldVar,
5384
0
                                               TSK_ImplicitInstantiation);
5385
5386
  // If the pattern is an (in-class) explicit specialization, then the result
5387
  // is also an explicit specialization.
5388
0
  if (VarTemplateSpecializationDecl *OldVTSD =
5389
0
          dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5390
0
    if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5391
0
        !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5392
0
      cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5393
0
          TSK_ExplicitSpecialization);
5394
0
  }
5395
5396
  // Forward the mangling number from the template to the instantiated decl.
5397
0
  Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5398
0
  Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5399
5400
  // Figure out whether to eagerly instantiate the initializer.
5401
0
  if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5402
    // We're producing a template. Don't instantiate the initializer yet.
5403
0
  } else if (NewVar->getType()->isUndeducedType()) {
5404
    // We need the type to complete the declaration of the variable.
5405
0
    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5406
0
  } else if (InstantiatingSpecFromTemplate ||
5407
0
             (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5408
0
              !NewVar->isThisDeclarationADefinition())) {
5409
    // Delay instantiation of the initializer for variable template
5410
    // specializations or inline static data members until a definition of the
5411
    // variable is needed.
5412
0
  } else {
5413
0
    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5414
0
  }
5415
5416
  // Diagnose unused local variables with dependent types, where the diagnostic
5417
  // will have been deferred.
5418
0
  if (!NewVar->isInvalidDecl() &&
5419
0
      NewVar->getDeclContext()->isFunctionOrMethod() &&
5420
0
      OldVar->getType()->isDependentType())
5421
0
    DiagnoseUnusedDecl(NewVar);
5422
0
}
5423
5424
/// Instantiate the initializer of a variable.
5425
void Sema::InstantiateVariableInitializer(
5426
    VarDecl *Var, VarDecl *OldVar,
5427
0
    const MultiLevelTemplateArgumentList &TemplateArgs) {
5428
0
  if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5429
0
    L->VariableDefinitionInstantiated(Var);
5430
5431
  // We propagate the 'inline' flag with the initializer, because it
5432
  // would otherwise imply that the variable is a definition for a
5433
  // non-static data member.
5434
0
  if (OldVar->isInlineSpecified())
5435
0
    Var->setInlineSpecified();
5436
0
  else if (OldVar->isInline())
5437
0
    Var->setImplicitlyInline();
5438
5439
0
  if (OldVar->getInit()) {
5440
0
    EnterExpressionEvaluationContext Evaluated(
5441
0
        *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5442
5443
    // Instantiate the initializer.
5444
0
    ExprResult Init;
5445
5446
0
    {
5447
0
      ContextRAII SwitchContext(*this, Var->getDeclContext());
5448
0
      Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5449
0
                              OldVar->getInitStyle() == VarDecl::CallInit);
5450
0
    }
5451
5452
0
    if (!Init.isInvalid()) {
5453
0
      Expr *InitExpr = Init.get();
5454
5455
0
      if (Var->hasAttr<DLLImportAttr>() &&
5456
0
          (!InitExpr ||
5457
0
           !InitExpr->isConstantInitializer(getASTContext(), false))) {
5458
        // Do not dynamically initialize dllimport variables.
5459
0
      } else if (InitExpr) {
5460
0
        bool DirectInit = OldVar->isDirectInit();
5461
0
        AddInitializerToDecl(Var, InitExpr, DirectInit);
5462
0
      } else
5463
0
        ActOnUninitializedDecl(Var);
5464
0
    } else {
5465
      // FIXME: Not too happy about invalidating the declaration
5466
      // because of a bogus initializer.
5467
0
      Var->setInvalidDecl();
5468
0
    }
5469
0
  } else {
5470
    // `inline` variables are a definition and declaration all in one; we won't
5471
    // pick up an initializer from anywhere else.
5472
0
    if (Var->isStaticDataMember() && !Var->isInline()) {
5473
0
      if (!Var->isOutOfLine())
5474
0
        return;
5475
5476
      // If the declaration inside the class had an initializer, don't add
5477
      // another one to the out-of-line definition.
5478
0
      if (OldVar->getFirstDecl()->hasInit())
5479
0
        return;
5480
0
    }
5481
5482
    // We'll add an initializer to a for-range declaration later.
5483
0
    if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5484
0
      return;
5485
5486
0
    ActOnUninitializedDecl(Var);
5487
0
  }
5488
5489
0
  if (getLangOpts().CUDA)
5490
0
    checkAllowedCUDAInitializer(Var);
5491
0
}
5492
5493
/// Instantiate the definition of the given variable from its
5494
/// template.
5495
///
5496
/// \param PointOfInstantiation the point at which the instantiation was
5497
/// required. Note that this is not precisely a "point of instantiation"
5498
/// for the variable, but it's close.
5499
///
5500
/// \param Var the already-instantiated declaration of a templated variable.
5501
///
5502
/// \param Recursive if true, recursively instantiates any functions that
5503
/// are required by this instantiation.
5504
///
5505
/// \param DefinitionRequired if true, then we are performing an explicit
5506
/// instantiation where a definition of the variable is required. Complain
5507
/// if there is no such definition.
5508
void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5509
                                         VarDecl *Var, bool Recursive,
5510
0
                                      bool DefinitionRequired, bool AtEndOfTU) {
5511
0
  if (Var->isInvalidDecl())
5512
0
    return;
5513
5514
  // Never instantiate an explicitly-specialized entity.
5515
0
  TemplateSpecializationKind TSK =
5516
0
      Var->getTemplateSpecializationKindForInstantiation();
5517
0
  if (TSK == TSK_ExplicitSpecialization)
5518
0
    return;
5519
5520
  // Find the pattern and the arguments to substitute into it.
5521
0
  VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5522
0
  assert(PatternDecl && "no pattern for templated variable");
5523
0
  MultiLevelTemplateArgumentList TemplateArgs =
5524
0
      getTemplateInstantiationArgs(Var);
5525
5526
0
  VarTemplateSpecializationDecl *VarSpec =
5527
0
      dyn_cast<VarTemplateSpecializationDecl>(Var);
5528
0
  if (VarSpec) {
5529
    // If this is a static data member template, there might be an
5530
    // uninstantiated initializer on the declaration. If so, instantiate
5531
    // it now.
5532
    //
5533
    // FIXME: This largely duplicates what we would do below. The difference
5534
    // is that along this path we may instantiate an initializer from an
5535
    // in-class declaration of the template and instantiate the definition
5536
    // from a separate out-of-class definition.
5537
0
    if (PatternDecl->isStaticDataMember() &&
5538
0
        (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5539
0
        !Var->hasInit()) {
5540
      // FIXME: Factor out the duplicated instantiation context setup/tear down
5541
      // code here.
5542
0
      InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5543
0
      if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5544
0
        return;
5545
0
      PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5546
0
                                          "instantiating variable initializer");
5547
5548
      // The instantiation is visible here, even if it was first declared in an
5549
      // unimported module.
5550
0
      Var->setVisibleDespiteOwningModule();
5551
5552
      // If we're performing recursive template instantiation, create our own
5553
      // queue of pending implicit instantiations that we will instantiate
5554
      // later, while we're still within our own instantiation context.
5555
0
      GlobalEagerInstantiationScope GlobalInstantiations(*this,
5556
0
                                                         /*Enabled=*/Recursive);
5557
0
      LocalInstantiationScope Local(*this);
5558
0
      LocalEagerInstantiationScope LocalInstantiations(*this);
5559
5560
      // Enter the scope of this instantiation. We don't use
5561
      // PushDeclContext because we don't have a scope.
5562
0
      ContextRAII PreviousContext(*this, Var->getDeclContext());
5563
0
      InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5564
0
      PreviousContext.pop();
5565
5566
      // This variable may have local implicit instantiations that need to be
5567
      // instantiated within this scope.
5568
0
      LocalInstantiations.perform();
5569
0
      Local.Exit();
5570
0
      GlobalInstantiations.perform();
5571
0
    }
5572
0
  } else {
5573
0
    assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5574
0
           "not a static data member?");
5575
0
  }
5576
5577
0
  VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5578
5579
  // If we don't have a definition of the variable template, we won't perform
5580
  // any instantiation. Rather, we rely on the user to instantiate this
5581
  // definition (or provide a specialization for it) in another translation
5582
  // unit.
5583
0
  if (!Def && !DefinitionRequired) {
5584
0
    if (TSK == TSK_ExplicitInstantiationDefinition) {
5585
0
      PendingInstantiations.push_back(
5586
0
        std::make_pair(Var, PointOfInstantiation));
5587
0
    } else if (TSK == TSK_ImplicitInstantiation) {
5588
      // Warn about missing definition at the end of translation unit.
5589
0
      if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5590
0
          !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5591
0
        Diag(PointOfInstantiation, diag::warn_var_template_missing)
5592
0
          << Var;
5593
0
        Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5594
0
        if (getLangOpts().CPlusPlus11)
5595
0
          Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5596
0
      }
5597
0
      return;
5598
0
    }
5599
0
  }
5600
5601
  // FIXME: We need to track the instantiation stack in order to know which
5602
  // definitions should be visible within this instantiation.
5603
  // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5604
0
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5605
0
                                     /*InstantiatedFromMember*/false,
5606
0
                                     PatternDecl, Def, TSK,
5607
0
                                     /*Complain*/DefinitionRequired))
5608
0
    return;
5609
5610
  // C++11 [temp.explicit]p10:
5611
  //   Except for inline functions, const variables of literal types, variables
5612
  //   of reference types, [...] explicit instantiation declarations
5613
  //   have the effect of suppressing the implicit instantiation of the entity
5614
  //   to which they refer.
5615
  //
5616
  // FIXME: That's not exactly the same as "might be usable in constant
5617
  // expressions", which only allows constexpr variables and const integral
5618
  // types, not arbitrary const literal types.
5619
0
  if (TSK == TSK_ExplicitInstantiationDeclaration &&
5620
0
      !Var->mightBeUsableInConstantExpressions(getASTContext()))
5621
0
    return;
5622
5623
  // Make sure to pass the instantiated variable to the consumer at the end.
5624
0
  struct PassToConsumerRAII {
5625
0
    ASTConsumer &Consumer;
5626
0
    VarDecl *Var;
5627
5628
0
    PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5629
0
      : Consumer(Consumer), Var(Var) { }
5630
5631
0
    ~PassToConsumerRAII() {
5632
0
      Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5633
0
    }
5634
0
  } PassToConsumerRAII(Consumer, Var);
5635
5636
  // If we already have a definition, we're done.
5637
0
  if (VarDecl *Def = Var->getDefinition()) {
5638
    // We may be explicitly instantiating something we've already implicitly
5639
    // instantiated.
5640
0
    Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5641
0
                                       PointOfInstantiation);
5642
0
    return;
5643
0
  }
5644
5645
0
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5646
0
  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5647
0
    return;
5648
0
  PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5649
0
                                      "instantiating variable definition");
5650
5651
  // If we're performing recursive template instantiation, create our own
5652
  // queue of pending implicit instantiations that we will instantiate later,
5653
  // while we're still within our own instantiation context.
5654
0
  GlobalEagerInstantiationScope GlobalInstantiations(*this,
5655
0
                                                     /*Enabled=*/Recursive);
5656
5657
  // Enter the scope of this instantiation. We don't use
5658
  // PushDeclContext because we don't have a scope.
5659
0
  ContextRAII PreviousContext(*this, Var->getDeclContext());
5660
0
  LocalInstantiationScope Local(*this);
5661
5662
0
  LocalEagerInstantiationScope LocalInstantiations(*this);
5663
5664
0
  VarDecl *OldVar = Var;
5665
0
  if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5666
    // We're instantiating an inline static data member whose definition was
5667
    // provided inside the class.
5668
0
    InstantiateVariableInitializer(Var, Def, TemplateArgs);
5669
0
  } else if (!VarSpec) {
5670
0
    Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5671
0
                                          TemplateArgs));
5672
0
  } else if (Var->isStaticDataMember() &&
5673
0
             Var->getLexicalDeclContext()->isRecord()) {
5674
    // We need to instantiate the definition of a static data member template,
5675
    // and all we have is the in-class declaration of it. Instantiate a separate
5676
    // declaration of the definition.
5677
0
    TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5678
0
                                          TemplateArgs);
5679
5680
0
    TemplateArgumentListInfo TemplateArgInfo;
5681
0
    if (const ASTTemplateArgumentListInfo *ArgInfo =
5682
0
            VarSpec->getTemplateArgsInfo()) {
5683
0
      TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5684
0
      TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5685
0
      for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5686
0
        TemplateArgInfo.addArgument(Arg);
5687
0
    }
5688
5689
0
    Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5690
0
        VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5691
0
        VarSpec->getTemplateArgs().asArray(), VarSpec));
5692
0
    if (Var) {
5693
0
      llvm::PointerUnion<VarTemplateDecl *,
5694
0
                         VarTemplatePartialSpecializationDecl *> PatternPtr =
5695
0
          VarSpec->getSpecializedTemplateOrPartial();
5696
0
      if (VarTemplatePartialSpecializationDecl *Partial =
5697
0
          PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5698
0
        cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5699
0
            Partial, &VarSpec->getTemplateInstantiationArgs());
5700
5701
      // Attach the initializer.
5702
0
      InstantiateVariableInitializer(Var, Def, TemplateArgs);
5703
0
    }
5704
0
  } else
5705
    // Complete the existing variable's definition with an appropriately
5706
    // substituted type and initializer.
5707
0
    Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5708
5709
0
  PreviousContext.pop();
5710
5711
0
  if (Var) {
5712
0
    PassToConsumerRAII.Var = Var;
5713
0
    Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5714
0
                                       OldVar->getPointOfInstantiation());
5715
0
  }
5716
5717
  // This variable may have local implicit instantiations that need to be
5718
  // instantiated within this scope.
5719
0
  LocalInstantiations.perform();
5720
0
  Local.Exit();
5721
0
  GlobalInstantiations.perform();
5722
0
}
5723
5724
void
5725
Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5726
                                 const CXXConstructorDecl *Tmpl,
5727
0
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
5728
5729
0
  SmallVector<CXXCtorInitializer*, 4> NewInits;
5730
0
  bool AnyErrors = Tmpl->isInvalidDecl();
5731
5732
  // Instantiate all the initializers.
5733
0
  for (const auto *Init : Tmpl->inits()) {
5734
    // Only instantiate written initializers, let Sema re-construct implicit
5735
    // ones.
5736
0
    if (!Init->isWritten())
5737
0
      continue;
5738
5739
0
    SourceLocation EllipsisLoc;
5740
5741
0
    if (Init->isPackExpansion()) {
5742
      // This is a pack expansion. We should expand it now.
5743
0
      TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5744
0
      SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5745
0
      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5746
0
      collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5747
0
      bool ShouldExpand = false;
5748
0
      bool RetainExpansion = false;
5749
0
      std::optional<unsigned> NumExpansions;
5750
0
      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5751
0
                                          BaseTL.getSourceRange(),
5752
0
                                          Unexpanded,
5753
0
                                          TemplateArgs, ShouldExpand,
5754
0
                                          RetainExpansion,
5755
0
                                          NumExpansions)) {
5756
0
        AnyErrors = true;
5757
0
        New->setInvalidDecl();
5758
0
        continue;
5759
0
      }
5760
0
      assert(ShouldExpand && "Partial instantiation of base initializer?");
5761
5762
      // Loop over all of the arguments in the argument pack(s),
5763
0
      for (unsigned I = 0; I != *NumExpansions; ++I) {
5764
0
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5765
5766
        // Instantiate the initializer.
5767
0
        ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5768
0
                                               /*CXXDirectInit=*/true);
5769
0
        if (TempInit.isInvalid()) {
5770
0
          AnyErrors = true;
5771
0
          break;
5772
0
        }
5773
5774
        // Instantiate the base type.
5775
0
        TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5776
0
                                              TemplateArgs,
5777
0
                                              Init->getSourceLocation(),
5778
0
                                              New->getDeclName());
5779
0
        if (!BaseTInfo) {
5780
0
          AnyErrors = true;
5781
0
          break;
5782
0
        }
5783
5784
        // Build the initializer.
5785
0
        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5786
0
                                                     BaseTInfo, TempInit.get(),
5787
0
                                                     New->getParent(),
5788
0
                                                     SourceLocation());
5789
0
        if (NewInit.isInvalid()) {
5790
0
          AnyErrors = true;
5791
0
          break;
5792
0
        }
5793
5794
0
        NewInits.push_back(NewInit.get());
5795
0
      }
5796
5797
0
      continue;
5798
0
    }
5799
5800
    // Instantiate the initializer.
5801
0
    ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5802
0
                                           /*CXXDirectInit=*/true);
5803
0
    if (TempInit.isInvalid()) {
5804
0
      AnyErrors = true;
5805
0
      continue;
5806
0
    }
5807
5808
0
    MemInitResult NewInit;
5809
0
    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5810
0
      TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5811
0
                                        TemplateArgs,
5812
0
                                        Init->getSourceLocation(),
5813
0
                                        New->getDeclName());
5814
0
      if (!TInfo) {
5815
0
        AnyErrors = true;
5816
0
        New->setInvalidDecl();
5817
0
        continue;
5818
0
      }
5819
5820
0
      if (Init->isBaseInitializer())
5821
0
        NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5822
0
                                       New->getParent(), EllipsisLoc);
5823
0
      else
5824
0
        NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5825
0
                                  cast<CXXRecordDecl>(CurContext->getParent()));
5826
0
    } else if (Init->isMemberInitializer()) {
5827
0
      FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5828
0
                                                     Init->getMemberLocation(),
5829
0
                                                     Init->getMember(),
5830
0
                                                     TemplateArgs));
5831
0
      if (!Member) {
5832
0
        AnyErrors = true;
5833
0
        New->setInvalidDecl();
5834
0
        continue;
5835
0
      }
5836
5837
0
      NewInit = BuildMemberInitializer(Member, TempInit.get(),
5838
0
                                       Init->getSourceLocation());
5839
0
    } else if (Init->isIndirectMemberInitializer()) {
5840
0
      IndirectFieldDecl *IndirectMember =
5841
0
         cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5842
0
                                 Init->getMemberLocation(),
5843
0
                                 Init->getIndirectMember(), TemplateArgs));
5844
5845
0
      if (!IndirectMember) {
5846
0
        AnyErrors = true;
5847
0
        New->setInvalidDecl();
5848
0
        continue;
5849
0
      }
5850
5851
0
      NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5852
0
                                       Init->getSourceLocation());
5853
0
    }
5854
5855
0
    if (NewInit.isInvalid()) {
5856
0
      AnyErrors = true;
5857
0
      New->setInvalidDecl();
5858
0
    } else {
5859
0
      NewInits.push_back(NewInit.get());
5860
0
    }
5861
0
  }
5862
5863
  // Assign all the initializers to the new constructor.
5864
0
  ActOnMemInitializers(New,
5865
                       /*FIXME: ColonLoc */
5866
0
                       SourceLocation(),
5867
0
                       NewInits,
5868
0
                       AnyErrors);
5869
0
}
5870
5871
// TODO: this could be templated if the various decl types used the
5872
// same method name.
5873
static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5874
0
                              ClassTemplateDecl *Instance) {
5875
0
  Pattern = Pattern->getCanonicalDecl();
5876
5877
0
  do {
5878
0
    Instance = Instance->getCanonicalDecl();
5879
0
    if (Pattern == Instance) return true;
5880
0
    Instance = Instance->getInstantiatedFromMemberTemplate();
5881
0
  } while (Instance);
5882
5883
0
  return false;
5884
0
}
5885
5886
static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5887
0
                              FunctionTemplateDecl *Instance) {
5888
0
  Pattern = Pattern->getCanonicalDecl();
5889
5890
0
  do {
5891
0
    Instance = Instance->getCanonicalDecl();
5892
0
    if (Pattern == Instance) return true;
5893
0
    Instance = Instance->getInstantiatedFromMemberTemplate();
5894
0
  } while (Instance);
5895
5896
0
  return false;
5897
0
}
5898
5899
static bool
5900
isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5901
0
                  ClassTemplatePartialSpecializationDecl *Instance) {
5902
0
  Pattern
5903
0
    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5904
0
  do {
5905
0
    Instance = cast<ClassTemplatePartialSpecializationDecl>(
5906
0
                                                Instance->getCanonicalDecl());
5907
0
    if (Pattern == Instance)
5908
0
      return true;
5909
0
    Instance = Instance->getInstantiatedFromMember();
5910
0
  } while (Instance);
5911
5912
0
  return false;
5913
0
}
5914
5915
static bool isInstantiationOf(CXXRecordDecl *Pattern,
5916
0
                              CXXRecordDecl *Instance) {
5917
0
  Pattern = Pattern->getCanonicalDecl();
5918
5919
0
  do {
5920
0
    Instance = Instance->getCanonicalDecl();
5921
0
    if (Pattern == Instance) return true;
5922
0
    Instance = Instance->getInstantiatedFromMemberClass();
5923
0
  } while (Instance);
5924
5925
0
  return false;
5926
0
}
5927
5928
static bool isInstantiationOf(FunctionDecl *Pattern,
5929
0
                              FunctionDecl *Instance) {
5930
0
  Pattern = Pattern->getCanonicalDecl();
5931
5932
0
  do {
5933
0
    Instance = Instance->getCanonicalDecl();
5934
0
    if (Pattern == Instance) return true;
5935
0
    Instance = Instance->getInstantiatedFromMemberFunction();
5936
0
  } while (Instance);
5937
5938
0
  return false;
5939
0
}
5940
5941
static bool isInstantiationOf(EnumDecl *Pattern,
5942
0
                              EnumDecl *Instance) {
5943
0
  Pattern = Pattern->getCanonicalDecl();
5944
5945
0
  do {
5946
0
    Instance = Instance->getCanonicalDecl();
5947
0
    if (Pattern == Instance) return true;
5948
0
    Instance = Instance->getInstantiatedFromMemberEnum();
5949
0
  } while (Instance);
5950
5951
0
  return false;
5952
0
}
5953
5954
static bool isInstantiationOf(UsingShadowDecl *Pattern,
5955
                              UsingShadowDecl *Instance,
5956
0
                              ASTContext &C) {
5957
0
  return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5958
0
                            Pattern);
5959
0
}
5960
5961
static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5962
0
                              ASTContext &C) {
5963
0
  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5964
0
}
5965
5966
template<typename T>
5967
static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5968
0
                                                 ASTContext &Ctx) {
5969
  // An unresolved using declaration can instantiate to an unresolved using
5970
  // declaration, or to a using declaration or a using declaration pack.
5971
  //
5972
  // Multiple declarations can claim to be instantiated from an unresolved
5973
  // using declaration if it's a pack expansion. We want the UsingPackDecl
5974
  // in that case, not the individual UsingDecls within the pack.
5975
0
  bool OtherIsPackExpansion;
5976
0
  NamedDecl *OtherFrom;
5977
0
  if (auto *OtherUUD = dyn_cast<T>(Other)) {
5978
0
    OtherIsPackExpansion = OtherUUD->isPackExpansion();
5979
0
    OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5980
0
  } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5981
0
    OtherIsPackExpansion = true;
5982
0
    OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5983
0
  } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5984
0
    OtherIsPackExpansion = false;
5985
0
    OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5986
0
  } else {
5987
0
    return false;
5988
0
  }
5989
0
  return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5990
0
         declaresSameEntity(OtherFrom, Pattern);
5991
0
}
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:bool isInstantiationOfUnresolvedUsingDecl<clang::UnresolvedUsingTypenameDecl>(clang::UnresolvedUsingTypenameDecl*, clang::Decl*, clang::ASTContext&)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:bool isInstantiationOfUnresolvedUsingDecl<clang::UnresolvedUsingValueDecl>(clang::UnresolvedUsingValueDecl*, clang::Decl*, clang::ASTContext&)
5992
5993
static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5994
0
                                              VarDecl *Instance) {
5995
0
  assert(Instance->isStaticDataMember());
5996
5997
0
  Pattern = Pattern->getCanonicalDecl();
5998
5999
0
  do {
6000
0
    Instance = Instance->getCanonicalDecl();
6001
0
    if (Pattern == Instance) return true;
6002
0
    Instance = Instance->getInstantiatedFromStaticDataMember();
6003
0
  } while (Instance);
6004
6005
0
  return false;
6006
0
}
6007
6008
// Other is the prospective instantiation
6009
// D is the prospective pattern
6010
0
static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
6011
0
  if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6012
0
    return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6013
6014
0
  if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6015
0
    return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6016
6017
0
  if (D->getKind() != Other->getKind())
6018
0
    return false;
6019
6020
0
  if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6021
0
    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6022
6023
0
  if (auto *Function = dyn_cast<FunctionDecl>(Other))
6024
0
    return isInstantiationOf(cast<FunctionDecl>(D), Function);
6025
6026
0
  if (auto *Enum = dyn_cast<EnumDecl>(Other))
6027
0
    return isInstantiationOf(cast<EnumDecl>(D), Enum);
6028
6029
0
  if (auto *Var = dyn_cast<VarDecl>(Other))
6030
0
    if (Var->isStaticDataMember())
6031
0
      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6032
6033
0
  if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6034
0
    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6035
6036
0
  if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6037
0
    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6038
6039
0
  if (auto *PartialSpec =
6040
0
          dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6041
0
    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6042
0
                             PartialSpec);
6043
6044
0
  if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6045
0
    if (!Field->getDeclName()) {
6046
      // This is an unnamed field.
6047
0
      return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
6048
0
                                cast<FieldDecl>(D));
6049
0
    }
6050
0
  }
6051
6052
0
  if (auto *Using = dyn_cast<UsingDecl>(Other))
6053
0
    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6054
6055
0
  if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6056
0
    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6057
6058
0
  return D->getDeclName() &&
6059
0
         D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6060
0
}
6061
6062
template<typename ForwardIterator>
6063
static NamedDecl *findInstantiationOf(ASTContext &Ctx,
6064
                                      NamedDecl *D,
6065
                                      ForwardIterator first,
6066
0
                                      ForwardIterator last) {
6067
0
  for (; first != last; ++first)
6068
0
    if (isInstantiationOf(Ctx, D, *first))
6069
0
      return cast<NamedDecl>(*first);
6070
6071
0
  return nullptr;
6072
0
}
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::NamedDecl* findInstantiationOf<clang::DeclListNode::iterator>(clang::ASTContext&, clang::NamedDecl*, clang::DeclListNode::iterator, clang::DeclListNode::iterator)
Unexecuted instantiation: SemaTemplateInstantiateDecl.cpp:clang::NamedDecl* findInstantiationOf<clang::DeclContext::decl_iterator>(clang::ASTContext&, clang::NamedDecl*, clang::DeclContext::decl_iterator, clang::DeclContext::decl_iterator)
6073
6074
/// Finds the instantiation of the given declaration context
6075
/// within the current instantiation.
6076
///
6077
/// \returns NULL if there was an error
6078
DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
6079
0
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
6080
0
  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6081
0
    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6082
0
    return cast_or_null<DeclContext>(ID);
6083
0
  } else return DC;
6084
0
}
6085
6086
/// Determine whether the given context is dependent on template parameters at
6087
/// level \p Level or below.
6088
///
6089
/// Sometimes we only substitute an inner set of template arguments and leave
6090
/// the outer templates alone. In such cases, contexts dependent only on the
6091
/// outer levels are not effectively dependent.
6092
0
static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6093
0
  if (!DC->isDependentContext())
6094
0
    return false;
6095
0
  if (!Level)
6096
0
    return true;
6097
0
  return cast<Decl>(DC)->getTemplateDepth() > Level;
6098
0
}
6099
6100
/// Find the instantiation of the given declaration within the
6101
/// current instantiation.
6102
///
6103
/// This routine is intended to be used when \p D is a declaration
6104
/// referenced from within a template, that needs to mapped into the
6105
/// corresponding declaration within an instantiation. For example,
6106
/// given:
6107
///
6108
/// \code
6109
/// template<typename T>
6110
/// struct X {
6111
///   enum Kind {
6112
///     KnownValue = sizeof(T)
6113
///   };
6114
///
6115
///   bool getKind() const { return KnownValue; }
6116
/// };
6117
///
6118
/// template struct X<int>;
6119
/// \endcode
6120
///
6121
/// In the instantiation of X<int>::getKind(), we need to map the \p
6122
/// EnumConstantDecl for \p KnownValue (which refers to
6123
/// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6124
/// \p FindInstantiatedDecl performs this mapping from within the instantiation
6125
/// of X<int>.
6126
NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6127
                          const MultiLevelTemplateArgumentList &TemplateArgs,
6128
0
                          bool FindingInstantiatedContext) {
6129
0
  DeclContext *ParentDC = D->getDeclContext();
6130
  // Determine whether our parent context depends on any of the template
6131
  // arguments we're currently substituting.
6132
0
  bool ParentDependsOnArgs = isDependentContextAtLevel(
6133
0
      ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6134
  // FIXME: Parameters of pointer to functions (y below) that are themselves
6135
  // parameters (p below) can have their ParentDC set to the translation-unit
6136
  // - thus we can not consistently check if the ParentDC of such a parameter
6137
  // is Dependent or/and a FunctionOrMethod.
6138
  // For e.g. this code, during Template argument deduction tries to
6139
  // find an instantiated decl for (T y) when the ParentDC for y is
6140
  // the translation unit.
6141
  //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6142
  //   float baz(float(*)()) { return 0.0; }
6143
  //   Foo(baz);
6144
  // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6145
  // it gets here, always has a FunctionOrMethod as its ParentDC??
6146
  // For now:
6147
  //  - as long as we have a ParmVarDecl whose parent is non-dependent and
6148
  //    whose type is not instantiation dependent, do nothing to the decl
6149
  //  - otherwise find its instantiated decl.
6150
0
  if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6151
0
      !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6152
0
    return D;
6153
0
  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6154
0
      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6155
0
      (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6156
0
                               isa<OMPDeclareReductionDecl>(ParentDC) ||
6157
0
                               isa<OMPDeclareMapperDecl>(ParentDC))) ||
6158
0
      (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6159
0
       cast<CXXRecordDecl>(D)->getTemplateDepth() >
6160
0
           TemplateArgs.getNumRetainedOuterLevels())) {
6161
    // D is a local of some kind. Look into the map of local
6162
    // declarations to their instantiations.
6163
0
    if (CurrentInstantiationScope) {
6164
0
      if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6165
0
        if (Decl *FD = Found->dyn_cast<Decl *>())
6166
0
          return cast<NamedDecl>(FD);
6167
6168
0
        int PackIdx = ArgumentPackSubstitutionIndex;
6169
0
        assert(PackIdx != -1 &&
6170
0
               "found declaration pack but not pack expanding");
6171
0
        typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6172
0
        return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6173
0
      }
6174
0
    }
6175
6176
    // If we're performing a partial substitution during template argument
6177
    // deduction, we may not have values for template parameters yet. They
6178
    // just map to themselves.
6179
0
    if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6180
0
        isa<TemplateTemplateParmDecl>(D))
6181
0
      return D;
6182
6183
0
    if (D->isInvalidDecl())
6184
0
      return nullptr;
6185
6186
    // Normally this function only searches for already instantiated declaration
6187
    // however we have to make an exclusion for local types used before
6188
    // definition as in the code:
6189
    //
6190
    //   template<typename T> void f1() {
6191
    //     void g1(struct x1);
6192
    //     struct x1 {};
6193
    //   }
6194
    //
6195
    // In this case instantiation of the type of 'g1' requires definition of
6196
    // 'x1', which is defined later. Error recovery may produce an enum used
6197
    // before definition. In these cases we need to instantiate relevant
6198
    // declarations here.
6199
0
    bool NeedInstantiate = false;
6200
0
    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6201
0
      NeedInstantiate = RD->isLocalClass();
6202
0
    else if (isa<TypedefNameDecl>(D) &&
6203
0
             isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6204
0
      NeedInstantiate = true;
6205
0
    else
6206
0
      NeedInstantiate = isa<EnumDecl>(D);
6207
0
    if (NeedInstantiate) {
6208
0
      Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6209
0
      CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6210
0
      return cast<TypeDecl>(Inst);
6211
0
    }
6212
6213
    // If we didn't find the decl, then we must have a label decl that hasn't
6214
    // been found yet.  Lazily instantiate it and return it now.
6215
0
    assert(isa<LabelDecl>(D));
6216
6217
0
    Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6218
0
    assert(Inst && "Failed to instantiate label??");
6219
6220
0
    CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6221
0
    return cast<LabelDecl>(Inst);
6222
0
  }
6223
6224
0
  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6225
0
    if (!Record->isDependentContext())
6226
0
      return D;
6227
6228
    // Determine whether this record is the "templated" declaration describing
6229
    // a class template or class template specialization.
6230
0
    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6231
0
    if (ClassTemplate)
6232
0
      ClassTemplate = ClassTemplate->getCanonicalDecl();
6233
0
    else if (ClassTemplateSpecializationDecl *Spec =
6234
0
                 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6235
0
      ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6236
6237
    // Walk the current context to find either the record or an instantiation of
6238
    // it.
6239
0
    DeclContext *DC = CurContext;
6240
0
    while (!DC->isFileContext()) {
6241
      // If we're performing substitution while we're inside the template
6242
      // definition, we'll find our own context. We're done.
6243
0
      if (DC->Equals(Record))
6244
0
        return Record;
6245
6246
0
      if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6247
        // Check whether we're in the process of instantiating a class template
6248
        // specialization of the template we're mapping.
6249
0
        if (ClassTemplateSpecializationDecl *InstSpec
6250
0
                      = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6251
0
          ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6252
0
          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6253
0
            return InstRecord;
6254
0
        }
6255
6256
        // Check whether we're in the process of instantiating a member class.
6257
0
        if (isInstantiationOf(Record, InstRecord))
6258
0
          return InstRecord;
6259
0
      }
6260
6261
      // Move to the outer template scope.
6262
0
      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6263
0
        if (FD->getFriendObjectKind() &&
6264
0
            FD->getNonTransparentDeclContext()->isFileContext()) {
6265
0
          DC = FD->getLexicalDeclContext();
6266
0
          continue;
6267
0
        }
6268
        // An implicit deduction guide acts as if it's within the class template
6269
        // specialization described by its name and first N template params.
6270
0
        auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6271
0
        if (Guide && Guide->isImplicit()) {
6272
0
          TemplateDecl *TD = Guide->getDeducedTemplate();
6273
          // Convert the arguments to an "as-written" list.
6274
0
          TemplateArgumentListInfo Args(Loc, Loc);
6275
0
          for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6276
0
                                        TD->getTemplateParameters()->size())) {
6277
0
            ArrayRef<TemplateArgument> Unpacked(Arg);
6278
0
            if (Arg.getKind() == TemplateArgument::Pack)
6279
0
              Unpacked = Arg.pack_elements();
6280
0
            for (TemplateArgument UnpackedArg : Unpacked)
6281
0
              Args.addArgument(
6282
0
                  getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6283
0
          }
6284
0
          QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6285
0
          if (T.isNull())
6286
0
            return nullptr;
6287
0
          auto *SubstRecord = T->getAsCXXRecordDecl();
6288
0
          assert(SubstRecord && "class template id not a class type?");
6289
          // Check that this template-id names the primary template and not a
6290
          // partial or explicit specialization. (In the latter cases, it's
6291
          // meaningless to attempt to find an instantiation of D within the
6292
          // specialization.)
6293
          // FIXME: The standard doesn't say what should happen here.
6294
0
          if (FindingInstantiatedContext &&
6295
0
              usesPartialOrExplicitSpecialization(
6296
0
                  Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6297
0
            Diag(Loc, diag::err_specialization_not_primary_template)
6298
0
              << T << (SubstRecord->getTemplateSpecializationKind() ==
6299
0
                           TSK_ExplicitSpecialization);
6300
0
            return nullptr;
6301
0
          }
6302
0
          DC = SubstRecord;
6303
0
          continue;
6304
0
        }
6305
0
      }
6306
6307
0
      DC = DC->getParent();
6308
0
    }
6309
6310
    // Fall through to deal with other dependent record types (e.g.,
6311
    // anonymous unions in class templates).
6312
0
  }
6313
6314
0
  if (!ParentDependsOnArgs)
6315
0
    return D;
6316
6317
0
  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6318
0
  if (!ParentDC)
6319
0
    return nullptr;
6320
6321
0
  if (ParentDC != D->getDeclContext()) {
6322
    // We performed some kind of instantiation in the parent context,
6323
    // so now we need to look into the instantiated parent context to
6324
    // find the instantiation of the declaration D.
6325
6326
    // If our context used to be dependent, we may need to instantiate
6327
    // it before performing lookup into that context.
6328
0
    bool IsBeingInstantiated = false;
6329
0
    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6330
0
      if (!Spec->isDependentContext()) {
6331
0
        QualType T = Context.getTypeDeclType(Spec);
6332
0
        const RecordType *Tag = T->getAs<RecordType>();
6333
0
        assert(Tag && "type of non-dependent record is not a RecordType");
6334
0
        if (Tag->isBeingDefined())
6335
0
          IsBeingInstantiated = true;
6336
0
        if (!Tag->isBeingDefined() &&
6337
0
            RequireCompleteType(Loc, T, diag::err_incomplete_type))
6338
0
          return nullptr;
6339
6340
0
        ParentDC = Tag->getDecl();
6341
0
      }
6342
0
    }
6343
6344
0
    NamedDecl *Result = nullptr;
6345
    // FIXME: If the name is a dependent name, this lookup won't necessarily
6346
    // find it. Does that ever matter?
6347
0
    if (auto Name = D->getDeclName()) {
6348
0
      DeclarationNameInfo NameInfo(Name, D->getLocation());
6349
0
      DeclarationNameInfo NewNameInfo =
6350
0
          SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6351
0
      Name = NewNameInfo.getName();
6352
0
      if (!Name)
6353
0
        return nullptr;
6354
0
      DeclContext::lookup_result Found = ParentDC->lookup(Name);
6355
6356
0
      Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6357
0
    } else {
6358
      // Since we don't have a name for the entity we're looking for,
6359
      // our only option is to walk through all of the declarations to
6360
      // find that name. This will occur in a few cases:
6361
      //
6362
      //   - anonymous struct/union within a template
6363
      //   - unnamed class/struct/union/enum within a template
6364
      //
6365
      // FIXME: Find a better way to find these instantiations!
6366
0
      Result = findInstantiationOf(Context, D,
6367
0
                                   ParentDC->decls_begin(),
6368
0
                                   ParentDC->decls_end());
6369
0
    }
6370
6371
0
    if (!Result) {
6372
0
      if (isa<UsingShadowDecl>(D)) {
6373
        // UsingShadowDecls can instantiate to nothing because of using hiding.
6374
0
      } else if (hasUncompilableErrorOccurred()) {
6375
        // We've already complained about some ill-formed code, so most likely
6376
        // this declaration failed to instantiate. There's no point in
6377
        // complaining further, since this is normal in invalid code.
6378
        // FIXME: Use more fine-grained 'invalid' tracking for this.
6379
0
      } else if (IsBeingInstantiated) {
6380
        // The class in which this member exists is currently being
6381
        // instantiated, and we haven't gotten around to instantiating this
6382
        // member yet. This can happen when the code uses forward declarations
6383
        // of member classes, and introduces ordering dependencies via
6384
        // template instantiation.
6385
0
        Diag(Loc, diag::err_member_not_yet_instantiated)
6386
0
          << D->getDeclName()
6387
0
          << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6388
0
        Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6389
0
      } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6390
        // This enumeration constant was found when the template was defined,
6391
        // but can't be found in the instantiation. This can happen if an
6392
        // unscoped enumeration member is explicitly specialized.
6393
0
        EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6394
0
        EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6395
0
                                                             TemplateArgs));
6396
0
        assert(Spec->getTemplateSpecializationKind() ==
6397
0
                 TSK_ExplicitSpecialization);
6398
0
        Diag(Loc, diag::err_enumerator_does_not_exist)
6399
0
          << D->getDeclName()
6400
0
          << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6401
0
        Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6402
0
          << Context.getTypeDeclType(Spec);
6403
0
      } else {
6404
        // We should have found something, but didn't.
6405
0
        llvm_unreachable("Unable to find instantiation of declaration!");
6406
0
      }
6407
0
    }
6408
6409
0
    D = Result;
6410
0
  }
6411
6412
0
  return D;
6413
0
}
6414
6415
/// Performs template instantiation for all implicit template
6416
/// instantiations we have seen until this point.
6417
46
void Sema::PerformPendingInstantiations(bool LocalOnly) {
6418
46
  std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6419
46
  while (!PendingLocalImplicitInstantiations.empty() ||
6420
46
         (!LocalOnly && !PendingInstantiations.empty())) {
6421
0
    PendingImplicitInstantiation Inst;
6422
6423
0
    if (PendingLocalImplicitInstantiations.empty()) {
6424
0
      Inst = PendingInstantiations.front();
6425
0
      PendingInstantiations.pop_front();
6426
0
    } else {
6427
0
      Inst = PendingLocalImplicitInstantiations.front();
6428
0
      PendingLocalImplicitInstantiations.pop_front();
6429
0
    }
6430
6431
    // Instantiate function definitions
6432
0
    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6433
0
      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6434
0
                                TSK_ExplicitInstantiationDefinition;
6435
0
      if (Function->isMultiVersion()) {
6436
0
        getASTContext().forEachMultiversionedFunctionVersion(
6437
0
            Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6438
0
              InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6439
0
                                            DefinitionRequired, true);
6440
0
              if (CurFD->isDefined())
6441
0
                CurFD->setInstantiationIsPending(false);
6442
0
            });
6443
0
      } else {
6444
0
        InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6445
0
                                      DefinitionRequired, true);
6446
0
        if (Function->isDefined())
6447
0
          Function->setInstantiationIsPending(false);
6448
0
      }
6449
      // Definition of a PCH-ed template declaration may be available only in the TU.
6450
0
      if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6451
0
          TUKind == TU_Prefix && Function->instantiationIsPending())
6452
0
        delayedPCHInstantiations.push_back(Inst);
6453
0
      continue;
6454
0
    }
6455
6456
    // Instantiate variable definitions
6457
0
    VarDecl *Var = cast<VarDecl>(Inst.first);
6458
6459
0
    assert((Var->isStaticDataMember() ||
6460
0
            isa<VarTemplateSpecializationDecl>(Var)) &&
6461
0
           "Not a static data member, nor a variable template"
6462
0
           " specialization?");
6463
6464
    // Don't try to instantiate declarations if the most recent redeclaration
6465
    // is invalid.
6466
0
    if (Var->getMostRecentDecl()->isInvalidDecl())
6467
0
      continue;
6468
6469
    // Check if the most recent declaration has changed the specialization kind
6470
    // and removed the need for implicit instantiation.
6471
0
    switch (Var->getMostRecentDecl()
6472
0
                ->getTemplateSpecializationKindForInstantiation()) {
6473
0
    case TSK_Undeclared:
6474
0
      llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6475
0
    case TSK_ExplicitInstantiationDeclaration:
6476
0
    case TSK_ExplicitSpecialization:
6477
0
      continue;  // No longer need to instantiate this type.
6478
0
    case TSK_ExplicitInstantiationDefinition:
6479
      // We only need an instantiation if the pending instantiation *is* the
6480
      // explicit instantiation.
6481
0
      if (Var != Var->getMostRecentDecl())
6482
0
        continue;
6483
0
      break;
6484
0
    case TSK_ImplicitInstantiation:
6485
0
      break;
6486
0
    }
6487
6488
0
    PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6489
0
                                        "instantiating variable definition");
6490
0
    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6491
0
                              TSK_ExplicitInstantiationDefinition;
6492
6493
    // Instantiate static data member definitions or variable template
6494
    // specializations.
6495
0
    InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6496
0
                                  DefinitionRequired, true);
6497
0
  }
6498
6499
46
  if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6500
0
    PendingInstantiations.swap(delayedPCHInstantiations);
6501
46
}
6502
6503
void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6504
0
                       const MultiLevelTemplateArgumentList &TemplateArgs) {
6505
0
  for (auto *DD : Pattern->ddiags()) {
6506
0
    switch (DD->getKind()) {
6507
0
    case DependentDiagnostic::Access:
6508
0
      HandleDependentAccessCheck(*DD, TemplateArgs);
6509
0
      break;
6510
0
    }
6511
0
  }
6512
0
}