Coverage Report

Created: 2021-01-23 06:44

/Users/buildslave/jenkins/workspace/coverage/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 "clang/AST/ASTConsumer.h"
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/ASTMutationListener.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/DeclVisitor.h"
17
#include "clang/AST/DependentDiagnostic.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/ExprCXX.h"
20
#include "clang/AST/PrettyDeclStackTrace.h"
21
#include "clang/AST/TypeLoc.h"
22
#include "clang/Basic/SourceManager.h"
23
#include "clang/Basic/TargetInfo.h"
24
#include "clang/Sema/Initialization.h"
25
#include "clang/Sema/Lookup.h"
26
#include "clang/Sema/SemaInternal.h"
27
#include "clang/Sema/Template.h"
28
#include "clang/Sema/TemplateInstCallback.h"
29
#include "llvm/Support/TimeProfiler.h"
30
31
using namespace clang;
32
33
2.80k
static bool isDeclWithinFunction(const Decl *D) {
34
2.80k
  const DeclContext *DC = D->getDeclContext();
35
2.80k
  if (DC->isFunctionOrMethod())
36
70
    return true;
37
38
2.73k
  if (DC->isRecord())
39
2.73k
    return cast<CXXRecordDecl>(DC)->isLocalClass();
40
41
0
  return false;
42
0
}
43
44
template<typename DeclT>
45
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
46
1.27M
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
47
1.27M
  if (!OldDecl->getQualifierLoc())
48
1.24M
    return false;
49
50
20.5k
  assert((NewDecl->getFriendObjectKind() ||
51
20.5k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
52
20.5k
         "non-friend with qualified name defined in dependent context");
53
20.5k
  Sema::ContextRAII SavedContext(
54
20.5k
      SemaRef,
55
20.5k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
56
10
                                    ? NewDecl->getLexicalDeclContext()
57
20.5k
                                    : OldDecl->getLexicalDeclContext()));
58
59
20.5k
  NestedNameSpecifierLoc NewQualifierLoc
60
20.5k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
61
20.5k
                                            TemplateArgs);
62
63
20.5k
  if (!NewQualifierLoc)
64
2
    return true;
65
66
20.5k
  NewDecl->setQualifierInfo(NewQualifierLoc);
67
20.5k
  return false;
68
20.5k
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::DeclaratorDecl>(clang::Sema&, clang::DeclaratorDecl const*, clang::DeclaratorDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
46
343k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
47
343k
  if (!OldDecl->getQualifierLoc())
48
333k
    return false;
49
50
10.3k
  assert((NewDecl->getFriendObjectKind() ||
51
10.3k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
52
10.3k
         "non-friend with qualified name defined in dependent context");
53
10.3k
  Sema::ContextRAII SavedContext(
54
10.3k
      SemaRef,
55
10.3k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
56
0
                                    ? NewDecl->getLexicalDeclContext()
57
10.3k
                                    : OldDecl->getLexicalDeclContext()));
58
59
10.3k
  NestedNameSpecifierLoc NewQualifierLoc
60
10.3k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
61
10.3k
                                            TemplateArgs);
62
63
10.3k
  if (!NewQualifierLoc)
64
1
    return true;
65
66
10.3k
  NewDecl->setQualifierInfo(NewQualifierLoc);
67
10.3k
  return false;
68
10.3k
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::TagDecl>(clang::Sema&, clang::TagDecl const*, clang::TagDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
46
751k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
47
751k
  if (!OldDecl->getQualifierLoc())
48
751k
    return false;
49
50
9
  assert((NewDecl->getFriendObjectKind() ||
51
9
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
52
9
         "non-friend with qualified name defined in dependent context");
53
9
  Sema::ContextRAII SavedContext(
54
9
      SemaRef,
55
9
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
56
0
                                    ? NewDecl->getLexicalDeclContext()
57
9
                                    : OldDecl->getLexicalDeclContext()));
58
59
9
  NestedNameSpecifierLoc NewQualifierLoc
60
9
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
61
9
                                            TemplateArgs);
62
63
9
  if (!NewQualifierLoc)
64
0
    return true;
65
66
9
  NewDecl->setQualifierInfo(NewQualifierLoc);
67
9
  return false;
68
9
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, clang::FunctionDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
46
175k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
47
175k
  if (!OldDecl->getQualifierLoc())
48
164k
    return false;
49
50
10.2k
  assert((NewDecl->getFriendObjectKind() ||
51
10.2k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
52
10.2k
         "non-friend with qualified name defined in dependent context");
53
10.2k
  Sema::ContextRAII SavedContext(
54
10.2k
      SemaRef,
55
10.2k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
56
10
                                    ? NewDecl->getLexicalDeclContext()
57
10.1k
                                    : OldDecl->getLexicalDeclContext()));
58
59
10.2k
  NestedNameSpecifierLoc NewQualifierLoc
60
10.2k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
61
10.2k
                                            TemplateArgs);
62
63
10.2k
  if (!NewQualifierLoc)
64
1
    return true;
65
66
10.2k
  NewDecl->setQualifierInfo(NewQualifierLoc);
67
10.2k
  return false;
68
10.2k
}
69
70
bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
71
343k
                                              DeclaratorDecl *NewDecl) {
72
343k
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
73
343k
}
74
75
bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
76
751k
                                              TagDecl *NewDecl) {
77
751k
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
78
751k
}
79
80
// Include attribute instantiation code.
81
#include "clang/Sema/AttrTemplateInstantiate.inc"
82
83
static void instantiateDependentAlignedAttr(
84
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85
169
    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
86
169
  if (Aligned->isAlignmentExpr()) {
87
    // The alignment expression is a constant expression.
88
169
    EnterExpressionEvaluationContext Unevaluated(
89
169
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
90
169
    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
91
169
    if (!Result.isInvalid())
92
169
      S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
93
0
  } else {
94
0
    TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
95
0
                                         TemplateArgs, Aligned->getLocation(),
96
0
                                         DeclarationName());
97
0
    if (Result)
98
0
      S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
99
0
  }
100
169
}
101
102
static void instantiateDependentAlignedAttr(
103
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
104
167
    const AlignedAttr *Aligned, Decl *New) {
105
167
  if (!Aligned->isPackExpansion()) {
106
152
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
107
152
    return;
108
152
  }
109
110
15
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
111
15
  if (Aligned->isAlignmentExpr())
112
15
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
113
15
                                      Unexpanded);
114
0
  else
115
0
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
116
0
                                      Unexpanded);
117
15
  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
118
119
  // Determine whether we can expand this attribute pack yet.
120
15
  bool Expand = true, RetainExpansion = false;
121
15
  Optional<unsigned> NumExpansions;
122
  // FIXME: Use the actual location of the ellipsis.
123
15
  SourceLocation EllipsisLoc = Aligned->getLocation();
124
15
  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
125
15
                                        Unexpanded, TemplateArgs, Expand,
126
15
                                        RetainExpansion, NumExpansions))
127
1
    return;
128
129
14
  if (!Expand) {
130
0
    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
131
0
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
132
14
  } else {
133
31
    for (unsigned I = 0; I != *NumExpansions; 
++I17
) {
134
17
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
135
17
      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
136
17
    }
137
14
  }
138
14
}
139
140
static void instantiateDependentAssumeAlignedAttr(
141
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
142
10
    const AssumeAlignedAttr *Aligned, Decl *New) {
143
  // The alignment expression is a constant expression.
144
10
  EnterExpressionEvaluationContext Unevaluated(
145
10
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
146
147
10
  Expr *E, *OE = nullptr;
148
10
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
149
10
  if (Result.isInvalid())
150
2
    return;
151
8
  E = Result.getAs<Expr>();
152
153
8
  if (Aligned->getOffset()) {
154
3
    Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
155
3
    if (Result.isInvalid())
156
0
      return;
157
3
    OE = Result.getAs<Expr>();
158
3
  }
159
160
8
  S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
161
8
}
162
163
static void instantiateDependentAlignValueAttr(
164
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
165
3
    const AlignValueAttr *Aligned, Decl *New) {
166
  // The alignment expression is a constant expression.
167
3
  EnterExpressionEvaluationContext Unevaluated(
168
3
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
169
3
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
170
3
  if (!Result.isInvalid())
171
3
    S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
172
3
}
173
174
static void instantiateDependentAllocAlignAttr(
175
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
176
8
    const AllocAlignAttr *Align, Decl *New) {
177
8
  Expr *Param = IntegerLiteral::Create(
178
8
      S.getASTContext(),
179
8
      llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
180
8
      S.getASTContext().UnsignedLongLongTy, Align->getLocation());
181
8
  S.AddAllocAlignAttr(New, *Align, Param);
182
8
}
183
184
static void instantiateDependentAnnotationAttr(
185
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
186
25
    const AnnotateAttr *Attr, Decl *New) {
187
25
  EnterExpressionEvaluationContext Unevaluated(
188
25
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
189
25
  SmallVector<Expr *, 4> Args;
190
25
  Args.reserve(Attr->args_size());
191
36
  for (auto *E : Attr->args()) {
192
36
    ExprResult Result = S.SubstExpr(E, TemplateArgs);
193
36
    if (!Result.isUsable())
194
2
      return;
195
34
    Args.push_back(Result.get());
196
34
  }
197
23
  S.AddAnnotationAttr(New, *Attr, Attr->getAnnotation(), Args);
198
23
}
199
200
static Expr *instantiateDependentFunctionAttrCondition(
201
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
202
1.42k
    const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
203
1.42k
  Expr *Cond = nullptr;
204
1.42k
  {
205
1.42k
    Sema::ContextRAII SwitchContext(S, New);
206
1.42k
    EnterExpressionEvaluationContext Unevaluated(
207
1.42k
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
208
1.42k
    ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
209
1.42k
    if (Result.isInvalid())
210
0
      return nullptr;
211
1.42k
    Cond = Result.getAs<Expr>();
212
1.42k
  }
213
1.42k
  if (!Cond->isTypeDependent()) {
214
1.42k
    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
215
1.42k
    if (Converted.isInvalid())
216
2
      return nullptr;
217
1.41k
    Cond = Converted.get();
218
1.41k
  }
219
220
1.41k
  SmallVector<PartialDiagnosticAt, 8> Diags;
221
1.41k
  if (OldCond->isValueDependent() && 
!Cond->isValueDependent()96
&&
222
96
      !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
223
0
    S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
224
0
    for (const auto &P : Diags)
225
0
      S.Diag(P.first, P.second);
226
0
    return nullptr;
227
0
  }
228
1.41k
  return Cond;
229
1.41k
}
230
231
static void instantiateDependentEnableIfAttr(
232
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
233
35
    const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
234
35
  Expr *Cond = instantiateDependentFunctionAttrCondition(
235
35
      S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
236
237
35
  if (Cond)
238
33
    New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
239
33
                                                      Cond, EIA->getMessage()));
240
35
}
241
242
static void instantiateDependentDiagnoseIfAttr(
243
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
244
1.38k
    const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
245
1.38k
  Expr *Cond = instantiateDependentFunctionAttrCondition(
246
1.38k
      S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
247
248
1.38k
  if (Cond)
249
1.38k
    New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
250
1.38k
        S.getASTContext(), *DIA, Cond, DIA->getMessage(),
251
1.38k
        DIA->getDiagnosticType(), DIA->getArgDependent(), New));
252
1.38k
}
253
254
// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
255
// template A as the base and arguments from TemplateArgs.
256
static void instantiateDependentCUDALaunchBoundsAttr(
257
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
258
6
    const CUDALaunchBoundsAttr &Attr, Decl *New) {
259
  // The alignment expression is a constant expression.
260
6
  EnterExpressionEvaluationContext Unevaluated(
261
6
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
262
263
6
  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
264
6
  if (Result.isInvalid())
265
0
    return;
266
6
  Expr *MaxThreads = Result.getAs<Expr>();
267
268
6
  Expr *MinBlocks = nullptr;
269
6
  if (Attr.getMinBlocks()) {
270
4
    Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
271
4
    if (Result.isInvalid())
272
0
      return;
273
4
    MinBlocks = Result.getAs<Expr>();
274
4
  }
275
276
6
  S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
277
6
}
278
279
static void
280
instantiateDependentModeAttr(Sema &S,
281
                             const MultiLevelTemplateArgumentList &TemplateArgs,
282
84
                             const ModeAttr &Attr, Decl *New) {
283
84
  S.AddModeAttr(New, Attr, Attr.getMode(),
284
84
                /*InInstantiation=*/true);
285
84
}
286
287
/// Instantiation of 'declare simd' attribute and its arguments.
288
static void instantiateOMPDeclareSimdDeclAttr(
289
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
290
58
    const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
291
  // Allow 'this' in clauses with varlists.
292
58
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
293
0
    New = FTD->getTemplatedDecl();
294
58
  auto *FD = cast<FunctionDecl>(New);
295
58
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
296
58
  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
297
58
  SmallVector<unsigned, 4> LinModifiers;
298
299
110
  auto SubstExpr = [&](Expr *E) -> ExprResult {
300
110
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
301
102
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
302
80
        Sema::ContextRAII SavedContext(S, FD);
303
80
        LocalInstantiationScope Local(S);
304
80
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
305
80
          Local.InstantiatedLocal(
306
80
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
307
80
        return S.SubstExpr(E, TemplateArgs);
308
80
      }
309
30
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
310
30
                                     FD->isCXXInstanceMember());
311
30
    return S.SubstExpr(E, TemplateArgs);
312
30
  };
313
314
  // Substitute a single OpenMP clause, which is a potentially-evaluated
315
  // full-expression.
316
110
  auto Subst = [&](Expr *E) -> ExprResult {
317
110
    EnterExpressionEvaluationContext Evaluated(
318
110
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
319
110
    ExprResult Res = SubstExpr(E);
320
110
    if (Res.isInvalid())
321
0
      return Res;
322
110
    return S.ActOnFinishFullExpr(Res.get(), false);
323
110
  };
324
325
58
  ExprResult Simdlen;
326
58
  if (auto *E = Attr.getSimdlen())
327
18
    Simdlen = Subst(E);
328
329
58
  if (Attr.uniforms_size() > 0) {
330
18
    for(auto *E : Attr.uniforms()) {
331
18
      ExprResult Inst = Subst(E);
332
18
      if (Inst.isInvalid())
333
0
        continue;
334
18
      Uniforms.push_back(Inst.get());
335
18
    }
336
10
  }
337
338
58
  auto AI = Attr.alignments_begin();
339
58
  for (auto *E : Attr.aligneds()) {
340
58
    ExprResult Inst = Subst(E);
341
58
    if (Inst.isInvalid())
342
0
      continue;
343
58
    Aligneds.push_back(Inst.get());
344
58
    Inst = ExprEmpty();
345
58
    if (*AI)
346
16
      Inst = S.SubstExpr(*AI, TemplateArgs);
347
58
    Alignments.push_back(Inst.get());
348
58
    ++AI;
349
58
  }
350
351
58
  auto SI = Attr.steps_begin();
352
16
  for (auto *E : Attr.linears()) {
353
16
    ExprResult Inst = Subst(E);
354
16
    if (Inst.isInvalid())
355
0
      continue;
356
16
    Linears.push_back(Inst.get());
357
16
    Inst = ExprEmpty();
358
16
    if (*SI)
359
16
      Inst = S.SubstExpr(*SI, TemplateArgs);
360
16
    Steps.push_back(Inst.get());
361
16
    ++SI;
362
16
  }
363
58
  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
364
58
  (void)S.ActOnOpenMPDeclareSimdDirective(
365
58
      S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
366
58
      Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
367
58
      Attr.getRange());
368
58
}
369
370
/// Instantiation of 'declare variant' attribute and its arguments.
371
static void instantiateOMPDeclareVariantAttr(
372
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
373
56
    const OMPDeclareVariantAttr &Attr, Decl *New) {
374
  // Allow 'this' in clauses with varlists.
375
56
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
376
0
    New = FTD->getTemplatedDecl();
377
56
  auto *FD = cast<FunctionDecl>(New);
378
56
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
379
380
78
  auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
381
78
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
382
42
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
383
0
        Sema::ContextRAII SavedContext(S, FD);
384
0
        LocalInstantiationScope Local(S);
385
0
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
386
0
          Local.InstantiatedLocal(
387
0
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
388
0
        return S.SubstExpr(E, TemplateArgs);
389
0
      }
390
78
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
391
78
                                     FD->isCXXInstanceMember());
392
78
    return S.SubstExpr(E, TemplateArgs);
393
78
  };
394
395
  // Substitute a single OpenMP clause, which is a potentially-evaluated
396
  // full-expression.
397
78
  auto &&Subst = [&SubstExpr, &S](Expr *E) {
398
78
    EnterExpressionEvaluationContext Evaluated(
399
78
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
400
78
    ExprResult Res = SubstExpr(E);
401
78
    if (Res.isInvalid())
402
0
      return Res;
403
78
    return S.ActOnFinishFullExpr(Res.get(), false);
404
78
  };
405
406
56
  ExprResult VariantFuncRef;
407
56
  if (Expr *E = Attr.getVariantFuncRef()) {
408
    // Do not mark function as is used to prevent its emission if this is the
409
    // only place where it is used.
410
56
    EnterExpressionEvaluationContext Unevaluated(
411
56
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
412
56
    VariantFuncRef = Subst(E);
413
56
  }
414
415
  // Copy the template version of the OMPTraitInfo and run substitute on all
416
  // score and condition expressiosn.
417
56
  OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
418
56
  TI = *Attr.getTraitInfos();
419
420
  // Try to substitute template parameters in score and condition expressions.
421
82
  auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
422
82
    if (E) {
423
22
      EnterExpressionEvaluationContext Unevaluated(
424
22
          S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
425
22
      ExprResult ER = Subst(E);
426
22
      if (ER.isUsable())
427
22
        E = ER.get();
428
0
      else
429
0
        return true;
430
82
    }
431
82
    return false;
432
82
  };
433
56
  if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
434
0
    return;
435
436
56
  Expr *E = VariantFuncRef.get();
437
  // Check function/variant ref for `omp declare variant` but not for `omp
438
  // begin declare variant` (which use implicit attributes).
439
56
  Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
440
56
      S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New),
441
56
                                          VariantFuncRef.get(), TI,
442
56
                                          Attr.getRange());
443
444
56
  if (!DeclVarData)
445
8
    return;
446
447
48
  E = DeclVarData.getValue().second;
448
48
  FD = DeclVarData.getValue().first;
449
450
48
  if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
451
48
    if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
452
48
      if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
453
16
        if (!VariantFTD->isThisDeclarationADefinition())
454
0
          return;
455
16
        Sema::TentativeAnalysisScope Trap(S);
456
16
        const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
457
16
            S.Context, TemplateArgs.getInnermost());
458
459
16
        auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
460
16
                                                         New->getLocation());
461
16
        if (!SubstFD)
462
0
          return;
463
16
        QualType NewType = S.Context.mergeFunctionTypes(
464
16
            SubstFD->getType(), FD->getType(),
465
16
            /* OfBlockPointer */ false,
466
16
            /* Unqualified */ false, /* AllowCXX */ true);
467
16
        if (NewType.isNull())
468
12
          return;
469
4
        S.InstantiateFunctionDefinition(
470
4
            New->getLocation(), SubstFD, /* Recursive */ true,
471
4
            /* DefinitionRequired */ false, /* AtEndOfTU */ false);
472
4
        SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
473
4
        E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
474
4
                                SourceLocation(), SubstFD,
475
4
                                /* RefersToEnclosingVariableOrCapture */ false,
476
4
                                /* NameLoc */ SubstFD->getLocation(),
477
4
                                SubstFD->getType(), ExprValueKind::VK_RValue);
478
4
      }
479
48
    }
480
48
  }
481
482
36
  S.ActOnOpenMPDeclareVariantDirective(FD, E, TI, Attr.getRange());
483
36
}
484
485
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
486
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
487
2
    const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
488
  // Both min and max expression are constant expressions.
489
2
  EnterExpressionEvaluationContext Unevaluated(
490
2
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
491
492
2
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
493
2
  if (Result.isInvalid())
494
0
    return;
495
2
  Expr *MinExpr = Result.getAs<Expr>();
496
497
2
  Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
498
2
  if (Result.isInvalid())
499
0
    return;
500
2
  Expr *MaxExpr = Result.getAs<Expr>();
501
502
2
  S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
503
2
}
504
505
static ExplicitSpecifier
506
instantiateExplicitSpecifier(Sema &S,
507
                             const MultiLevelTemplateArgumentList &TemplateArgs,
508
969k
                             ExplicitSpecifier ES, FunctionDecl *New) {
509
969k
  if (!ES.getExpr())
510
968k
    return ES;
511
372
  Expr *OldCond = ES.getExpr();
512
372
  Expr *Cond = nullptr;
513
372
  {
514
372
    EnterExpressionEvaluationContext Unevaluated(
515
372
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
516
372
    ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
517
372
    if (SubstResult.isInvalid()) {
518
142
      return ExplicitSpecifier::Invalid();
519
142
    }
520
230
    Cond = SubstResult.get();
521
230
  }
522
230
  ExplicitSpecifier Result(Cond, ES.getKind());
523
230
  if (!Cond->isTypeDependent())
524
200
    S.tryResolveExplicitSpecifier(Result);
525
230
  return Result;
526
230
}
527
528
static void instantiateDependentAMDGPUWavesPerEUAttr(
529
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
530
3
    const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
531
  // Both min and max expression are constant expressions.
532
3
  EnterExpressionEvaluationContext Unevaluated(
533
3
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
534
535
3
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
536
3
  if (Result.isInvalid())
537
0
    return;
538
3
  Expr *MinExpr = Result.getAs<Expr>();
539
540
3
  Expr *MaxExpr = nullptr;
541
3
  if (auto Max = Attr.getMax()) {
542
2
    Result = S.SubstExpr(Max, TemplateArgs);
543
2
    if (Result.isInvalid())
544
0
      return;
545
2
    MaxExpr = Result.getAs<Expr>();
546
2
  }
547
548
3
  S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
549
3
}
550
551
/// Determine whether the attribute A might be relevent to the declaration D.
552
/// If not, we can skip instantiating it. The attribute may or may not have
553
/// been instantiated yet.
554
3.54M
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
555
  // 'preferred_name' is only relevant to the matching specialization of the
556
  // template.
557
3.54M
  if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
558
29.9k
    QualType T = PNA->getTypedefType();
559
29.9k
    const auto *RD = cast<CXXRecordDecl>(D);
560
29.9k
    if (!T->isDependentType() && 
!RD->isDependentContext()29.9k
&&
561
29.9k
        !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
562
18.7k
      return false;
563
11.1k
    for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
564
6.89k
      if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
565
6.89k
                                PNA->getTypedefType()))
566
6.88k
        return false;
567
4.28k
    return true;
568
3.51M
  }
569
570
3.51M
  return true;
571
3.51M
}
572
573
void Sema::InstantiateAttrsForDecl(
574
    const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
575
    Decl *New, LateInstantiatedAttrVec *LateAttrs,
576
1.24M
    LocalInstantiationScope *OuterMostScope) {
577
1.24M
  if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
578
    // FIXME: This function is called multiple times for the same template
579
    // specialization. We should only instantiate attributes that were added
580
    // since the previous instantiation.
581
532k
    for (const auto *TmplAttr : Tmpl->attrs()) {
582
532k
      if (!isRelevantAttr(*this, New, TmplAttr))
583
19.3k
        continue;
584
585
      // FIXME: If any of the special case versions from InstantiateAttrs become
586
      // applicable to template declaration, we'll need to add them here.
587
512k
      CXXThisScopeRAII ThisScope(
588
512k
          *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
589
512k
          Qualifiers(), ND->isCXXInstanceMember());
590
591
512k
      Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
592
512k
          TmplAttr, Context, *this, TemplateArgs);
593
512k
      if (NewAttr && 
isRelevantAttr(*this, New, NewAttr)1.58k
)
594
1.58k
        New->addAttr(NewAttr);
595
512k
    }
596
1.24M
  }
597
1.24M
}
598
599
static Sema::RetainOwnershipKind
600
89
attrToRetainOwnershipKind(const Attr *A) {
601
89
  switch (A->getKind()) {
602
0
  case clang::attr::CFConsumed:
603
0
    return Sema::RetainOwnershipKind::CF;
604
0
  case clang::attr::OSConsumed:
605
0
    return Sema::RetainOwnershipKind::OS;
606
89
  case clang::attr::NSConsumed:
607
89
    return Sema::RetainOwnershipKind::NS;
608
0
  default:
609
0
    llvm_unreachable("Wrong argument supplied");
610
89
  }
611
89
}
612
613
void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
614
                            const Decl *Tmpl, Decl *New,
615
                            LateInstantiatedAttrVec *LateAttrs,
616
4.32M
                            LocalInstantiationScope *OuterMostScope) {
617
2.07M
  for (const auto *TmplAttr : Tmpl->attrs()) {
618
2.07M
    if (!isRelevantAttr(*this, New, TmplAttr))
619
6.25k
      continue;
620
621
    // FIXME: This should be generalized to more than just the AlignedAttr.
622
2.06M
    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
623
2.06M
    if (Aligned && 
Aligned->isAlignmentDependent()1.23k
) {
624
167
      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
625
167
      continue;
626
167
    }
627
628
2.06M
    if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
629
10
      instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
630
10
      continue;
631
10
    }
632
633
2.06M
    if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
634
3
      instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
635
3
      continue;
636
3
    }
637
638
2.06M
    if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
639
8
      instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
640
8
      continue;
641
8
    }
642
643
2.06M
    if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
644
25
      instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
645
25
      continue;
646
25
    }
647
648
2.06M
    if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
649
35
      instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
650
35
                                       cast<FunctionDecl>(New));
651
35
      continue;
652
35
    }
653
654
2.06M
    if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
655
1.38k
      instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
656
1.38k
                                         cast<FunctionDecl>(New));
657
1.38k
      continue;
658
1.38k
    }
659
660
2.06M
    if (const auto *CUDALaunchBounds =
661
6
            dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
662
6
      instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
663
6
                                               *CUDALaunchBounds, New);
664
6
      continue;
665
6
    }
666
667
2.06M
    if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
668
84
      instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
669
84
      continue;
670
84
    }
671
672
2.06M
    if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
673
58
      instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
674
58
      continue;
675
58
    }
676
677
2.06M
    if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
678
56
      instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
679
56
      continue;
680
56
    }
681
682
2.06M
    if (const auto *AMDGPUFlatWorkGroupSize =
683
2
            dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
684
2
      instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
685
2
          *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
686
2
    }
687
688
2.06M
    if (const auto *AMDGPUFlatWorkGroupSize =
689
3
            dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
690
3
      instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
691
3
                                               *AMDGPUFlatWorkGroupSize, New);
692
3
    }
693
694
    // Existing DLL attribute on the instantiation takes precedence.
695
2.06M
    if (TmplAttr->getKind() == attr::DLLExport ||
696
2.06M
        TmplAttr->getKind() == attr::DLLImport) {
697
1.35k
      if (New->hasAttr<DLLExportAttr>() || 
New->hasAttr<DLLImportAttr>()1.35k
) {
698
24
        continue;
699
24
      }
700
2.06M
    }
701
702
2.06M
    if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
703
6
      AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
704
6
      continue;
705
6
    }
706
707
2.06M
    if (isa<NSConsumedAttr>(TmplAttr) || 
isa<OSConsumedAttr>(TmplAttr)2.06M
||
708
2.06M
        isa<CFConsumedAttr>(TmplAttr)) {
709
89
      AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
710
89
                       /*template instantiation=*/true);
711
89
      continue;
712
89
    }
713
714
2.06M
    if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
715
1.15k
      if (!New->hasAttr<PointerAttr>())
716
1.15k
        New->addAttr(A->clone(Context));
717
1.15k
      continue;
718
1.15k
    }
719
720
2.06M
    if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
721
3.76k
      if (!New->hasAttr<OwnerAttr>())
722
3.74k
        New->addAttr(A->clone(Context));
723
3.76k
      continue;
724
3.76k
    }
725
726
2.06M
    assert(!TmplAttr->isPackExpansion());
727
2.06M
    if (TmplAttr->isLateParsed() && 
LateAttrs130
) {
728
      // Late parsed attributes must be instantiated and attached after the
729
      // enclosing class has been instantiated.  See Sema::InstantiateClass.
730
82
      LocalInstantiationScope *Saved = nullptr;
731
82
      if (CurrentInstantiationScope)
732
82
        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
733
82
      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
734
2.05M
    } else {
735
      // Allow 'this' within late-parsed attributes.
736
2.05M
      auto *ND = cast<NamedDecl>(New);
737
2.05M
      auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
738
2.05M
      CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
739
2.05M
                                 ND->isCXXInstanceMember());
740
741
2.05M
      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
742
2.05M
                                                         *this, TemplateArgs);
743
2.05M
      if (NewAttr && 
isRelevantAttr(*this, New, TmplAttr)941k
)
744
941k
        New->addAttr(NewAttr);
745
2.05M
    }
746
2.06M
  }
747
4.32M
}
748
749
/// In the MS ABI, we need to instantiate default arguments of dllexported
750
/// default constructors along with the constructor definition. This allows IR
751
/// gen to emit a constructor closure which calls the default constructor with
752
/// its default arguments.
753
196
void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
754
196
  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
755
196
         Ctor->isDefaultConstructor());
756
196
  unsigned NumParams = Ctor->getNumParams();
757
196
  if (NumParams == 0)
758
181
    return;
759
15
  DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
760
15
  if (!Attr)
761
0
    return;
762
30
  
for (unsigned I = 0; 15
I != NumParams;
++I15
) {
763
15
    (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
764
15
                                   Ctor->getParamDecl(I));
765
15
    DiscardCleanupsInEvaluationContext();
766
15
  }
767
15
}
768
769
/// Get the previous declaration of a declaration for the purposes of template
770
/// instantiation. If this finds a previous declaration, then the previous
771
/// declaration of the instantiation of D should be an instantiation of the
772
/// result of this function.
773
template<typename DeclT>
774
691k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
691k
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
691k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())486
&&
781
25
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
5
    return nullptr;
783
784
691k
  return Result;
785
691k
}
SemaTemplateInstantiateDecl.cpp:clang::TypedefNameDecl* getPreviousDeclForInstantiation<clang::TypedefNameDecl>(clang::TypedefNameDecl*)
Line
Count
Source
774
657k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
657k
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
657k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())435
&&
781
0
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
0
    return nullptr;
783
784
657k
  return Result;
785
657k
}
SemaTemplateInstantiateDecl.cpp:clang::EnumDecl* getPreviousDeclForInstantiation<clang::EnumDecl>(clang::EnumDecl*)
Line
Count
Source
774
2.75k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
2.75k
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
2.75k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())14
&&
781
0
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
0
    return nullptr;
783
784
2.75k
  return Result;
785
2.75k
}
SemaTemplateInstantiateDecl.cpp:clang::CXXRecordDecl* getPreviousDeclForInstantiation<clang::CXXRecordDecl>(clang::CXXRecordDecl*)
Line
Count
Source
774
30.7k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
30.7k
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
30.7k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())37
&&
781
25
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
5
    return nullptr;
783
784
30.7k
  return Result;
785
30.7k
}
SemaTemplateInstantiateDecl.cpp:clang::VarDecl* getPreviousDeclForInstantiation<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
774
191
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
191
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
191
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
781
0
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
0
    return nullptr;
783
784
191
  return Result;
785
191
}
SemaTemplateInstantiateDecl.cpp:clang::FunctionTemplateDecl* getPreviousDeclForInstantiation<clang::FunctionTemplateDecl>(clang::FunctionTemplateDecl*)
Line
Count
Source
774
6
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
6
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
6
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
781
0
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
0
    return nullptr;
783
784
6
  return Result;
785
6
}
SemaTemplateInstantiateDecl.cpp:clang::UsingShadowDecl* getPreviousDeclForInstantiation<clang::UsingShadowDecl>(clang::UsingShadowDecl*)
Line
Count
Source
774
15
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
775
15
  DeclT *Result = D->getPreviousDecl();
776
777
  // If the declaration is within a class, and the previous declaration was
778
  // merged from a different definition of that class, then we don't have a
779
  // previous declaration for the purpose of template instantiation.
780
15
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
781
0
      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
782
0
    return nullptr;
783
784
15
  return Result;
785
15
}
786
787
Decl *
788
0
TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
789
0
  llvm_unreachable("Translation units cannot be instantiated");
790
0
}
791
792
Decl *
793
0
TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
794
0
  llvm_unreachable("pragma comment cannot be instantiated");
795
0
}
796
797
Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
798
0
    PragmaDetectMismatchDecl *D) {
799
0
  llvm_unreachable("pragma comment cannot be instantiated");
800
0
}
801
802
Decl *
803
0
TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
804
0
  llvm_unreachable("extern \"C\" context cannot be instantiated");
805
0
}
806
807
0
Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
808
0
  llvm_unreachable("GUID declaration cannot be instantiated");
809
0
}
810
811
Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
812
0
    TemplateParamObjectDecl *D) {
813
0
  llvm_unreachable("template parameter objects cannot be instantiated");
814
0
}
815
816
Decl *
817
81
TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
818
81
  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
819
81
                                      D->getIdentifier());
820
81
  Owner->addDecl(Inst);
821
81
  return Inst;
822
81
}
823
824
Decl *
825
0
TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
826
0
  llvm_unreachable("Namespaces cannot be instantiated");
827
0
}
828
829
Decl *
830
2
TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
831
2
  NamespaceAliasDecl *Inst
832
2
    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
833
2
                                 D->getNamespaceLoc(),
834
2
                                 D->getAliasLoc(),
835
2
                                 D->getIdentifier(),
836
2
                                 D->getQualifierLoc(),
837
2
                                 D->getTargetNameLoc(),
838
2
                                 D->getNamespace());
839
2
  Owner->addDecl(Inst);
840
2
  return Inst;
841
2
}
842
843
Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
844
630k
                                                           bool IsTypeAlias) {
845
630k
  bool Invalid = false;
846
630k
  TypeSourceInfo *DI = D->getTypeSourceInfo();
847
630k
  if (DI->getType()->isInstantiationDependentType() ||
848
599k
      
DI->getType()->isVariablyModifiedType()30.7k
) {
849
599k
    DI = SemaRef.SubstType(DI, TemplateArgs,
850
599k
                           D->getLocation(), D->getDeclName());
851
599k
    if (!DI) {
852
215
      Invalid = true;
853
215
      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
854
215
    }
855
30.7k
  } else {
856
30.7k
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
857
30.7k
  }
858
859
  // HACK: g++ has a bug where it gets the value kind of ?: wrong.
860
  // libstdc++ relies upon this bug in its implementation of common_type.
861
  // If we happen to be processing that implementation, fake up the g++ ?:
862
  // semantics. See LWG issue 2141 for more information on the bug.
863
630k
  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
864
630k
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
865
630k
  if (DT && 
RD935
&&
isa<ConditionalOperator>(DT->getUnderlyingExpr())303
&&
866
1
      DT->isReferenceType() &&
867
1
      RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
868
1
      RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
869
1
      D->getIdentifier() && D->getIdentifier()->isStr("type") &&
870
1
      SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
871
    // Fold it to the (non-reference) type which g++ would have produced.
872
1
    DI = SemaRef.Context.getTrivialTypeSourceInfo(
873
1
      DI->getType().getNonReferenceType());
874
875
  // Create the new typedef
876
630k
  TypedefNameDecl *Typedef;
877
630k
  if (IsTypeAlias)
878
85.6k
    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
879
85.6k
                                    D->getLocation(), D->getIdentifier(), DI);
880
544k
  else
881
544k
    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
882
544k
                                  D->getLocation(), D->getIdentifier(), DI);
883
630k
  if (Invalid)
884
215
    Typedef->setInvalidDecl();
885
886
  // If the old typedef was the name for linkage purposes of an anonymous
887
  // tag decl, re-establish that relationship for the new typedef.
888
630k
  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
889
8.22k
    TagDecl *oldTag = oldTagType->getDecl();
890
8.22k
    if (oldTag->getTypedefNameForAnonDecl() == D && 
!Invalid20
) {
891
20
      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
892
20
      assert(!newTag->hasNameForLinkage());
893
20
      newTag->setTypedefNameForAnonDecl(Typedef);
894
20
    }
895
8.22k
  }
896
897
630k
  if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
898
435
    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
899
435
                                                       TemplateArgs);
900
435
    if (!InstPrev)
901
0
      return nullptr;
902
903
435
    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
904
905
    // If the typedef types are not identical, reject them.
906
435
    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
907
908
435
    Typedef->setPreviousDecl(InstPrevTypedef);
909
435
  }
910
911
630k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
912
913
630k
  if (D->getUnderlyingType()->getAs<DependentNameType>())
914
234k
    SemaRef.inferGslPointerAttribute(Typedef);
915
916
630k
  Typedef->setAccess(D->getAccess());
917
918
630k
  return Typedef;
919
630k
}
920
921
544k
Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
922
544k
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
923
544k
  if (Typedef)
924
544k
    Owner->addDecl(Typedef);
925
544k
  return Typedef;
926
544k
}
927
928
58.4k
Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
929
58.4k
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
930
58.4k
  if (Typedef)
931
58.4k
    Owner->addDecl(Typedef);
932
58.4k
  return Typedef;
933
58.4k
}
934
935
Decl *
936
27.2k
TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
937
  // Create a local instantiation scope for this type alias template, which
938
  // will contain the instantiations of the template parameters.
939
27.2k
  LocalInstantiationScope Scope(SemaRef);
940
941
27.2k
  TemplateParameterList *TempParams = D->getTemplateParameters();
942
27.2k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
943
27.2k
  if (!InstParams)
944
0
    return nullptr;
945
946
27.2k
  TypeAliasDecl *Pattern = D->getTemplatedDecl();
947
948
27.2k
  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
949
27.2k
  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
950
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
951
0
    if (!Found.empty()) {
952
0
      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
953
0
    }
954
0
  }
955
956
27.2k
  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
957
27.2k
    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
958
27.2k
  if (!AliasInst)
959
0
    return nullptr;
960
961
27.2k
  TypeAliasTemplateDecl *Inst
962
27.2k
    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
963
27.2k
                                    D->getDeclName(), InstParams, AliasInst);
964
27.2k
  AliasInst->setDescribedAliasTemplate(Inst);
965
27.2k
  if (PrevAliasTemplate)
966
0
    Inst->setPreviousDecl(PrevAliasTemplate);
967
968
27.2k
  Inst->setAccess(D->getAccess());
969
970
27.2k
  if (!PrevAliasTemplate)
971
27.2k
    Inst->setInstantiatedFromMemberTemplate(D);
972
973
27.2k
  Owner->addDecl(Inst);
974
975
27.2k
  return Inst;
976
27.2k
}
977
978
44
Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
979
44
  auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
980
44
                                    D->getIdentifier());
981
44
  NewBD->setReferenced(D->isReferenced());
982
44
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
983
44
  return NewBD;
984
44
}
985
986
26
Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
987
  // Transform the bindings first.
988
26
  SmallVector<BindingDecl*, 16> NewBindings;
989
26
  for (auto *OldBD : D->bindings())
990
44
    NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
991
26
  ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
992
993
26
  auto *NewDD = cast_or_null<DecompositionDecl>(
994
26
      VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
995
996
26
  if (!NewDD || NewDD->isInvalidDecl())
997
8
    for (auto *NewBD : NewBindings)
998
15
      NewBD->setInvalidDecl();
999
1000
26
  return NewDD;
1001
26
}
1002
1003
341k
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1004
341k
  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1005
341k
}
1006
1007
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1008
                                             bool InstantiatingVarTemplate,
1009
341k
                                             ArrayRef<BindingDecl*> *Bindings) {
1010
1011
  // Do substitution on the type of the declaration
1012
341k
  TypeSourceInfo *DI = SemaRef.SubstType(
1013
341k
      D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1014
341k
      D->getDeclName(), /*AllowDeducedTST*/true);
1015
341k
  if (!DI)
1016
82
    return nullptr;
1017
1018
341k
  if (DI->getType()->isFunctionType()) {
1019
6
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1020
6
      << D->isStaticDataMember() << DI->getType();
1021
6
    return nullptr;
1022
6
  }
1023
1024
341k
  DeclContext *DC = Owner;
1025
341k
  if (D->isLocalExternDecl())
1026
88
    SemaRef.adjustContextForLocalExternDecl(DC);
1027
1028
  // Build the instantiated declaration.
1029
341k
  VarDecl *Var;
1030
341k
  if (Bindings)
1031
26
    Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1032
26
                                    D->getLocation(), DI->getType(), DI,
1033
26
                                    D->getStorageClass(), *Bindings);
1034
341k
  else
1035
341k
    Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1036
341k
                          D->getLocation(), D->getIdentifier(), DI->getType(),
1037
341k
                          DI, D->getStorageClass());
1038
1039
  // In ARC, infer 'retaining' for variables of retainable type.
1040
341k
  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1041
57
      SemaRef.inferObjCARCLifetime(Var))
1042
0
    Var->setInvalidDecl();
1043
1044
341k
  if (SemaRef.getLangOpts().OpenCL)
1045
7
    SemaRef.deduceOpenCLAddressSpace(Var);
1046
1047
  // Substitute the nested name specifier, if any.
1048
341k
  if (SubstQualifier(D, Var))
1049
1
    return nullptr;
1050
1051
341k
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1052
341k
                                     StartingScope, InstantiatingVarTemplate);
1053
1054
341k
  if (D->isNRVOVariable()) {
1055
3.63k
    QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
1056
3.63k
    if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
1057
482
      Var->setNRVOVariable(true);
1058
3.63k
  }
1059
1060
341k
  Var->setImplicit(D->isImplicit());
1061
1062
341k
  if (Var->isStaticLocal())
1063
714
    SemaRef.CheckStaticLocalForDllExport(Var);
1064
1065
341k
  return Var;
1066
341k
}
1067
1068
165k
Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1069
165k
  AccessSpecDecl* AD
1070
165k
    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1071
165k
                             D->getAccessSpecifierLoc(), D->getColonLoc());
1072
165k
  Owner->addHiddenDecl(AD);
1073
165k
  return AD;
1074
165k
}
1075
1076
63.6k
Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1077
63.6k
  bool Invalid = false;
1078
63.6k
  TypeSourceInfo *DI = D->getTypeSourceInfo();
1079
63.6k
  if (DI->getType()->isInstantiationDependentType() ||
1080
52.6k
      
DI->getType()->isVariablyModifiedType()10.9k
) {
1081
52.6k
    DI = SemaRef.SubstType(DI, TemplateArgs,
1082
52.6k
                           D->getLocation(), D->getDeclName());
1083
52.6k
    if (!DI) {
1084
63
      DI = D->getTypeSourceInfo();
1085
63
      Invalid = true;
1086
52.5k
    } else if (DI->getType()->isFunctionType()) {
1087
      // C++ [temp.arg.type]p3:
1088
      //   If a declaration acquires a function type through a type
1089
      //   dependent on a template-parameter and this causes a
1090
      //   declaration that does not use the syntactic form of a
1091
      //   function declarator to have function type, the program is
1092
      //   ill-formed.
1093
15
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1094
15
        << DI->getType();
1095
15
      Invalid = true;
1096
15
    }
1097
10.9k
  } else {
1098
10.9k
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1099
10.9k
  }
1100
1101
63.6k
  Expr *BitWidth = D->getBitWidth();
1102
63.6k
  if (Invalid)
1103
78
    BitWidth = nullptr;
1104
63.5k
  else if (BitWidth) {
1105
    // The bit-width expression is a constant expression.
1106
101
    EnterExpressionEvaluationContext Unevaluated(
1107
101
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1108
1109
101
    ExprResult InstantiatedBitWidth
1110
101
      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1111
101
    if (InstantiatedBitWidth.isInvalid()) {
1112
0
      Invalid = true;
1113
0
      BitWidth = nullptr;
1114
0
    } else
1115
101
      BitWidth = InstantiatedBitWidth.getAs<Expr>();
1116
101
  }
1117
1118
63.6k
  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1119
63.6k
                                            DI->getType(), DI,
1120
63.6k
                                            cast<RecordDecl>(Owner),
1121
63.6k
                                            D->getLocation(),
1122
63.6k
                                            D->isMutable(),
1123
63.6k
                                            BitWidth,
1124
63.6k
                                            D->getInClassInitStyle(),
1125
63.6k
                                            D->getInnerLocStart(),
1126
63.6k
                                            D->getAccess(),
1127
63.6k
                                            nullptr);
1128
63.6k
  if (!Field) {
1129
0
    cast<Decl>(Owner)->setInvalidDecl();
1130
0
    return nullptr;
1131
0
  }
1132
1133
63.6k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1134
1135
63.6k
  if (Field->hasAttrs())
1136
34
    SemaRef.CheckAlignasUnderalignment(Field);
1137
1138
63.6k
  if (Invalid)
1139
78
    Field->setInvalidDecl();
1140
1141
63.6k
  if (!Field->getDeclName()) {
1142
    // Keep track of where this decl came from.
1143
1.42k
    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1144
1.42k
  }
1145
63.6k
  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1146
63.6k
    if (Parent->isAnonymousStructOrUnion() &&
1147
3.50k
        Parent->getRedeclContext()->isFunctionOrMethod())
1148
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1149
63.6k
  }
1150
1151
63.6k
  Field->setImplicit(D->isImplicit());
1152
63.6k
  Field->setAccess(D->getAccess());
1153
63.6k
  Owner->addDecl(Field);
1154
1155
63.6k
  return Field;
1156
63.6k
}
1157
1158
29
Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1159
29
  bool Invalid = false;
1160
29
  TypeSourceInfo *DI = D->getTypeSourceInfo();
1161
1162
29
  if (DI->getType()->isVariablyModifiedType()) {
1163
0
    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1164
0
      << D;
1165
0
    Invalid = true;
1166
29
  } else if (DI->getType()->isInstantiationDependentType())  {
1167
26
    DI = SemaRef.SubstType(DI, TemplateArgs,
1168
26
                           D->getLocation(), D->getDeclName());
1169
26
    if (!DI) {
1170
0
      DI = D->getTypeSourceInfo();
1171
0
      Invalid = true;
1172
26
    } else if (DI->getType()->isFunctionType()) {
1173
      // C++ [temp.arg.type]p3:
1174
      //   If a declaration acquires a function type through a type
1175
      //   dependent on a template-parameter and this causes a
1176
      //   declaration that does not use the syntactic form of a
1177
      //   function declarator to have function type, the program is
1178
      //   ill-formed.
1179
0
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1180
0
      << DI->getType();
1181
0
      Invalid = true;
1182
0
    }
1183
3
  } else {
1184
3
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1185
3
  }
1186
1187
29
  MSPropertyDecl *Property = MSPropertyDecl::Create(
1188
29
      SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1189
29
      DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1190
1191
29
  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1192
29
                           StartingScope);
1193
1194
29
  if (Invalid)
1195
0
    Property->setInvalidDecl();
1196
1197
29
  Property->setAccess(D->getAccess());
1198
29
  Owner->addDecl(Property);
1199
1200
29
  return Property;
1201
29
}
1202
1203
3.49k
Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1204
3.49k
  NamedDecl **NamedChain =
1205
3.49k
    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1206
1207
3.49k
  int i = 0;
1208
7.01k
  for (auto *PI : D->chain()) {
1209
7.01k
    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1210
7.01k
                                              TemplateArgs);
1211
7.01k
    if (!Next)
1212
0
      return nullptr;
1213
1214
7.01k
    NamedChain[i++] = Next;
1215
7.01k
  }
1216
1217
3.49k
  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1218
3.49k
  IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1219
3.49k
      SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1220
3.49k
      {NamedChain, D->getChainingSize()});
1221
1222
3.49k
  for (const auto *Attr : D->attrs())
1223
0
    IndirectField->addAttr(Attr->clone(SemaRef.Context));
1224
1225
3.49k
  IndirectField->setImplicit(D->isImplicit());
1226
3.49k
  IndirectField->setAccess(D->getAccess());
1227
3.49k
  Owner->addDecl(IndirectField);
1228
3.49k
  return IndirectField;
1229
3.49k
}
1230
1231
25.4k
Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1232
  // Handle friend type expressions by simply substituting template
1233
  // parameters into the pattern type and checking the result.
1234
25.4k
  if (TypeSourceInfo *Ty = D->getFriendType()) {
1235
1.66k
    TypeSourceInfo *InstTy;
1236
    // If this is an unsupported friend, don't bother substituting template
1237
    // arguments into it. The actual type referred to won't be used by any
1238
    // parts of Clang, and may not be valid for instantiating. Just use the
1239
    // same info for the instantiated friend.
1240
1.66k
    if (D->isUnsupportedFriend()) {
1241
3
      InstTy = Ty;
1242
1.66k
    } else {
1243
1.66k
      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1244
1.66k
                                 D->getLocation(), DeclarationName());
1245
1.66k
    }
1246
1.66k
    if (!InstTy)
1247
1
      return nullptr;
1248
1249
1.66k
    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1250
1.66k
                                                 D->getFriendLoc(), InstTy);
1251
1.66k
    if (!FD)
1252
0
      return nullptr;
1253
1254
1.66k
    FD->setAccess(AS_public);
1255
1.66k
    FD->setUnsupportedFriend(D->isUnsupportedFriend());
1256
1.66k
    Owner->addDecl(FD);
1257
1.66k
    return FD;
1258
1.66k
  }
1259
1260
23.7k
  NamedDecl *ND = D->getFriendDecl();
1261
23.7k
  assert(ND && "friend decl must be a decl or a type!");
1262
1263
  // All of the Visit implementations for the various potential friend
1264
  // declarations have to be carefully written to work for friend
1265
  // objects, with the most important detail being that the target
1266
  // decl should almost certainly not be placed in Owner.
1267
23.7k
  Decl *NewND = Visit(ND);
1268
23.7k
  if (!NewND) 
return nullptr5
;
1269
1270
23.7k
  FriendDecl *FD =
1271
23.7k
    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1272
23.7k
                       cast<NamedDecl>(NewND), D->getFriendLoc());
1273
23.7k
  FD->setAccess(AS_public);
1274
23.7k
  FD->setUnsupportedFriend(D->isUnsupportedFriend());
1275
23.7k
  Owner->addDecl(FD);
1276
23.7k
  return FD;
1277
23.7k
}
1278
1279
41.4k
Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1280
41.4k
  Expr *AssertExpr = D->getAssertExpr();
1281
1282
  // The expression in a static assertion is a constant expression.
1283
41.4k
  EnterExpressionEvaluationContext Unevaluated(
1284
41.4k
      SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1285
1286
41.4k
  ExprResult InstantiatedAssertExpr
1287
41.4k
    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1288
41.4k
  if (InstantiatedAssertExpr.isInvalid())
1289
5
    return nullptr;
1290
1291
41.4k
  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1292
41.4k
                                              InstantiatedAssertExpr.get(),
1293
41.4k
                                              D->getMessage(),
1294
41.4k
                                              D->getRParenLoc(),
1295
41.4k
                                              D->isFailed());
1296
41.4k
}
1297
1298
2.75k
Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1299
2.75k
  EnumDecl *PrevDecl = nullptr;
1300
2.75k
  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1301
14
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1302
14
                                                   PatternPrev,
1303
14
                                                   TemplateArgs);
1304
14
    if (!Prev) 
return nullptr0
;
1305
14
    PrevDecl = cast<EnumDecl>(Prev);
1306
14
  }
1307
1308
2.75k
  EnumDecl *Enum =
1309
2.75k
      EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1310
2.75k
                       D->getLocation(), D->getIdentifier(), PrevDecl,
1311
2.75k
                       D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1312
2.75k
  if (D->isFixed()) {
1313
140
    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1314
      // If we have type source information for the underlying type, it means it
1315
      // has been explicitly set by the user. Perform substitution on it before
1316
      // moving on.
1317
77
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1318
77
      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1319
77
                                                DeclarationName());
1320
77
      if (!NewTI || 
SemaRef.CheckEnumUnderlyingType(NewTI)75
)
1321
4
        Enum->setIntegerType(SemaRef.Context.IntTy);
1322
73
      else
1323
73
        Enum->setIntegerTypeSourceInfo(NewTI);
1324
63
    } else {
1325
63
      assert(!D->getIntegerType()->isDependentType()
1326
63
             && "Dependent type without type source info");
1327
63
      Enum->setIntegerType(D->getIntegerType());
1328
63
    }
1329
140
  }
1330
1331
2.75k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1332
1333
2.75k
  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1334
2.75k
  Enum->setAccess(D->getAccess());
1335
  // Forward the mangling number from the template to the instantiated decl.
1336
2.75k
  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1337
  // See if the old tag was defined along with a declarator.
1338
  // If it did, mark the new tag as being associated with that declarator.
1339
2.75k
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1340
3
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1341
  // See if the old tag was defined along with a typedef.
1342
  // If it did, mark the new tag as being associated with that typedef.
1343
2.75k
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1344
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1345
2.75k
  if (SubstQualifier(D, Enum)) 
return nullptr0
;
1346
2.75k
  Owner->addDecl(Enum);
1347
1348
2.75k
  EnumDecl *Def = D->getDefinition();
1349
2.75k
  if (Def && 
Def != D2.69k
) {
1350
    // If this is an out-of-line definition of an enum member template, check
1351
    // that the underlying types match in the instantiation of both
1352
    // declarations.
1353
36
    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1354
21
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1355
21
      QualType DefnUnderlying =
1356
21
        SemaRef.SubstType(TI->getType(), TemplateArgs,
1357
21
                          UnderlyingLoc, DeclarationName());
1358
21
      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1359
21
                                     DefnUnderlying, /*IsFixed=*/true, Enum);
1360
21
    }
1361
36
  }
1362
1363
  // C++11 [temp.inst]p1: The implicit instantiation of a class template
1364
  // specialization causes the implicit instantiation of the declarations, but
1365
  // not the definitions of scoped member enumerations.
1366
  //
1367
  // DR1484 clarifies that enumeration definitions inside of a template
1368
  // declaration aren't considered entities that can be separately instantiated
1369
  // from the rest of the entity they are declared inside of.
1370
2.75k
  if (isDeclWithinFunction(D) ? 
D == Def68
:
Def2.68k
&&
!Enum->isScoped()2.62k
) {
1371
2.63k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1372
2.63k
    InstantiateEnumDefinition(Enum, Def);
1373
2.63k
  }
1374
1375
2.75k
  return Enum;
1376
2.75k
}
1377
1378
void TemplateDeclInstantiator::InstantiateEnumDefinition(
1379
2.66k
    EnumDecl *Enum, EnumDecl *Pattern) {
1380
2.66k
  Enum->startDefinition();
1381
1382
  // Update the location to refer to the definition.
1383
2.66k
  Enum->setLocation(Pattern->getLocation());
1384
1385
2.66k
  SmallVector<Decl*, 4> Enumerators;
1386
1387
2.66k
  EnumConstantDecl *LastEnumConst = nullptr;
1388
2.74k
  for (auto *EC : Pattern->enumerators()) {
1389
    // The specified value for the enumerator.
1390
2.74k
    ExprResult Value((Expr *)nullptr);
1391
2.74k
    if (Expr *UninstValue = EC->getInitExpr()) {
1392
      // The enumerator's value expression is a constant expression.
1393
2.59k
      EnterExpressionEvaluationContext Unevaluated(
1394
2.59k
          SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1395
1396
2.59k
      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1397
2.59k
    }
1398
1399
    // Drop the initial value and continue.
1400
2.74k
    bool isInvalid = false;
1401
2.74k
    if (Value.isInvalid()) {
1402
19
      Value = nullptr;
1403
19
      isInvalid = true;
1404
19
    }
1405
1406
2.74k
    EnumConstantDecl *EnumConst
1407
2.74k
      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1408
2.74k
                                  EC->getLocation(), EC->getIdentifier(),
1409
2.74k
                                  Value.get());
1410
1411
2.74k
    if (isInvalid) {
1412
19
      if (EnumConst)
1413
19
        EnumConst->setInvalidDecl();
1414
19
      Enum->setInvalidDecl();
1415
19
    }
1416
1417
2.74k
    if (EnumConst) {
1418
2.74k
      SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1419
1420
2.74k
      EnumConst->setAccess(Enum->getAccess());
1421
2.74k
      Enum->addDecl(EnumConst);
1422
2.74k
      Enumerators.push_back(EnumConst);
1423
2.74k
      LastEnumConst = EnumConst;
1424
1425
2.74k
      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1426
61
          !Enum->isScoped()) {
1427
        // If the enumeration is within a function or method, record the enum
1428
        // constant as a local.
1429
47
        SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1430
47
      }
1431
2.74k
    }
1432
2.74k
  }
1433
1434
2.66k
  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1435
2.66k
                        Enumerators, nullptr, ParsedAttributesView());
1436
2.66k
}
1437
1438
0
Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1439
0
  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1440
0
}
1441
1442
Decl *
1443
0
TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1444
0
  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1445
0
}
1446
1447
17.4k
Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1448
17.4k
  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1449
1450
  // Create a local instantiation scope for this class template, which
1451
  // will contain the instantiations of the template parameters.
1452
17.4k
  LocalInstantiationScope Scope(SemaRef);
1453
17.4k
  TemplateParameterList *TempParams = D->getTemplateParameters();
1454
17.4k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1455
17.4k
  if (!InstParams)
1456
5
    return nullptr;
1457
1458
17.4k
  CXXRecordDecl *Pattern = D->getTemplatedDecl();
1459
1460
  // Instantiate the qualifier.  We have to do this first in case
1461
  // we're a friend declaration, because if we are then we need to put
1462
  // the new declaration in the appropriate context.
1463
17.4k
  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1464
17.4k
  if (QualifierLoc) {
1465
8
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1466
8
                                                       TemplateArgs);
1467
8
    if (!QualifierLoc)
1468
0
      return nullptr;
1469
17.4k
  }
1470
1471
17.4k
  CXXRecordDecl *PrevDecl = nullptr;
1472
17.4k
  ClassTemplateDecl *PrevClassTemplate = nullptr;
1473
1474
17.4k
  if (!isFriend && 
getPreviousDeclForInstantiation(Pattern)12.3k
) {
1475
4
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1476
4
    if (!Found.empty()) {
1477
4
      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1478
4
      if (PrevClassTemplate)
1479
4
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1480
4
    }
1481
4
  }
1482
1483
  // If this isn't a friend, then it's a member template, in which
1484
  // case we just want to build the instantiation in the
1485
  // specialization.  If it is a friend, we want to build it in
1486
  // the appropriate context.
1487
17.4k
  DeclContext *DC = Owner;
1488
17.4k
  if (isFriend) {
1489
5.04k
    if (QualifierLoc) {
1490
8
      CXXScopeSpec SS;
1491
8
      SS.Adopt(QualifierLoc);
1492
8
      DC = SemaRef.computeDeclContext(SS);
1493
8
      if (!DC) 
return nullptr0
;
1494
5.03k
    } else {
1495
5.03k
      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1496
5.03k
                                           Pattern->getDeclContext(),
1497
5.03k
                                           TemplateArgs);
1498
5.03k
    }
1499
1500
    // Look for a previous declaration of the template in the owning
1501
    // context.
1502
5.04k
    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1503
5.04k
                   Sema::LookupOrdinaryName,
1504
5.04k
                   SemaRef.forRedeclarationInCurContext());
1505
5.04k
    SemaRef.LookupQualifiedName(R, DC);
1506
1507
5.04k
    if (R.isSingleResult()) {
1508
4.86k
      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1509
4.86k
      if (PrevClassTemplate)
1510
4.86k
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1511
4.86k
    }
1512
1513
5.04k
    if (!PrevClassTemplate && 
QualifierLoc187
) {
1514
0
      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1515
0
        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1516
0
        << QualifierLoc.getSourceRange();
1517
0
      return nullptr;
1518
0
    }
1519
1520
5.04k
    bool AdoptedPreviousTemplateParams = false;
1521
5.04k
    if (PrevClassTemplate) {
1522
4.86k
      bool Complain = true;
1523
1524
      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1525
      // template for struct std::tr1::__detail::_Map_base, where the
1526
      // template parameters of the friend declaration don't match the
1527
      // template parameters of the original declaration. In this one
1528
      // case, we don't complain about the ill-formed friend
1529
      // declaration.
1530
4.86k
      if (isFriend && Pattern->getIdentifier() &&
1531
4.86k
          Pattern->getIdentifier()->isStr("_Map_base") &&
1532
1
          DC->isNamespace() &&
1533
1
          cast<NamespaceDecl>(DC)->getIdentifier() &&
1534
1
          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1535
1
        DeclContext *DCParent = DC->getParent();
1536
1
        if (DCParent->isNamespace() &&
1537
1
            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1538
1
            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1539
1
          if (cast<Decl>(DCParent)->isInStdNamespace())
1540
1
            Complain = false;
1541
1
        }
1542
1
      }
1543
1544
4.86k
      TemplateParameterList *PrevParams
1545
4.86k
        = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1546
1547
      // Make sure the parameter lists match.
1548
4.86k
      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1549
4.86k
                                                  Complain,
1550
3
                                                  Sema::TPL_TemplateMatch)) {
1551
3
        if (Complain)
1552
2
          return nullptr;
1553
1554
1
        AdoptedPreviousTemplateParams = true;
1555
1
        InstParams = PrevParams;
1556
1
      }
1557
1558
      // Do some additional validation, then merge default arguments
1559
      // from the existing declarations.
1560
4.85k
      if (!AdoptedPreviousTemplateParams &&
1561
4.85k
          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1562
4.85k
                                             Sema::TPC_ClassTemplate))
1563
0
        return nullptr;
1564
17.4k
    }
1565
5.04k
  }
1566
1567
17.4k
  CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1568
17.4k
      SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1569
17.4k
      Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1570
17.4k
      /*DelayTypeCreation=*/true);
1571
1572
17.4k
  if (QualifierLoc)
1573
7
    RecordInst->setQualifierInfo(QualifierLoc);
1574
1575
17.4k
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1576
17.4k
                                                              StartingScope);
1577
1578
17.4k
  ClassTemplateDecl *Inst
1579
17.4k
    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1580
17.4k
                                D->getIdentifier(), InstParams, RecordInst);
1581
17.4k
  assert(!(isFriend && Owner->isDependentContext()));
1582
17.4k
  Inst->setPreviousDecl(PrevClassTemplate);
1583
1584
17.4k
  RecordInst->setDescribedClassTemplate(Inst);
1585
1586
17.4k
  if (isFriend) {
1587
5.04k
    if (PrevClassTemplate)
1588
4.85k
      Inst->setAccess(PrevClassTemplate->getAccess());
1589
187
    else
1590
187
      Inst->setAccess(D->getAccess());
1591
1592
5.04k
    Inst->setObjectOfFriendDecl();
1593
    // TODO: do we want to track the instantiation progeny of this
1594
    // friend target decl?
1595
12.3k
  } else {
1596
12.3k
    Inst->setAccess(D->getAccess());
1597
12.3k
    if (!PrevClassTemplate)
1598
12.3k
      Inst->setInstantiatedFromMemberTemplate(D);
1599
12.3k
  }
1600
1601
  // Trigger creation of the type for the instantiation.
1602
17.4k
  SemaRef.Context.getInjectedClassNameType(RecordInst,
1603
17.4k
                                    Inst->getInjectedClassNameSpecialization());
1604
1605
  // Finish handling of friends.
1606
17.4k
  if (isFriend) {
1607
5.04k
    DC->makeDeclVisibleInContext(Inst);
1608
5.04k
    Inst->setLexicalDeclContext(Owner);
1609
5.04k
    RecordInst->setLexicalDeclContext(Owner);
1610
5.04k
    return Inst;
1611
5.04k
  }
1612
1613
12.3k
  if (D->isOutOfLine()) {
1614
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1615
0
    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1616
0
  }
1617
1618
12.3k
  Owner->addDecl(Inst);
1619
1620
12.3k
  if (!PrevClassTemplate) {
1621
    // Queue up any out-of-line partial specializations of this member
1622
    // class template; the client will force their instantiation once
1623
    // the enclosing class has been instantiated.
1624
12.3k
    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1625
12.3k
    D->getPartialSpecializations(PartialSpecs);
1626
20.1k
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I7.81k
)
1627
7.81k
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1628
9
        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1629
12.3k
  }
1630
1631
12.3k
  return Inst;
1632
12.3k
}
1633
1634
Decl *
1635
TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1636
7.80k
                                   ClassTemplatePartialSpecializationDecl *D) {
1637
7.80k
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1638
1639
  // Lookup the already-instantiated declaration in the instantiation
1640
  // of the class template and return that.
1641
7.80k
  DeclContext::lookup_result Found
1642
7.80k
    = Owner->lookup(ClassTemplate->getDeclName());
1643
7.80k
  if (Found.empty())
1644
0
    return nullptr;
1645
1646
7.80k
  ClassTemplateDecl *InstClassTemplate
1647
7.80k
    = dyn_cast<ClassTemplateDecl>(Found.front());
1648
7.80k
  if (!InstClassTemplate)
1649
0
    return nullptr;
1650
1651
7.80k
  if (ClassTemplatePartialSpecializationDecl *Result
1652
0
        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1653
0
    return Result;
1654
1655
7.80k
  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1656
7.80k
}
1657
1658
191
Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1659
191
  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1660
191
         "Only static data member templates are allowed.");
1661
1662
  // Create a local instantiation scope for this variable template, which
1663
  // will contain the instantiations of the template parameters.
1664
191
  LocalInstantiationScope Scope(SemaRef);
1665
191
  TemplateParameterList *TempParams = D->getTemplateParameters();
1666
191
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1667
191
  if (!InstParams)
1668
0
    return nullptr;
1669
1670
191
  VarDecl *Pattern = D->getTemplatedDecl();
1671
191
  VarTemplateDecl *PrevVarTemplate = nullptr;
1672
1673
191
  if (getPreviousDeclForInstantiation(Pattern)) {
1674
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1675
0
    if (!Found.empty())
1676
0
      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1677
0
  }
1678
1679
191
  VarDecl *VarInst =
1680
191
      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1681
191
                                         /*InstantiatingVarTemplate=*/true));
1682
191
  if (!VarInst) 
return nullptr3
;
1683
1684
188
  DeclContext *DC = Owner;
1685
1686
188
  VarTemplateDecl *Inst = VarTemplateDecl::Create(
1687
188
      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1688
188
      VarInst);
1689
188
  VarInst->setDescribedVarTemplate(Inst);
1690
188
  Inst->setPreviousDecl(PrevVarTemplate);
1691
1692
188
  Inst->setAccess(D->getAccess());
1693
188
  if (!PrevVarTemplate)
1694
188
    Inst->setInstantiatedFromMemberTemplate(D);
1695
1696
188
  if (D->isOutOfLine()) {
1697
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1698
0
    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1699
0
  }
1700
1701
188
  Owner->addDecl(Inst);
1702
1703
188
  if (!PrevVarTemplate) {
1704
    // Queue up any out-of-line partial specializations of this member
1705
    // variable template; the client will force their instantiation once
1706
    // the enclosing class has been instantiated.
1707
188
    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1708
188
    D->getPartialSpecializations(PartialSpecs);
1709
236
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I48
)
1710
48
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1711
7
        OutOfLineVarPartialSpecs.push_back(
1712
7
            std::make_pair(Inst, PartialSpecs[I]));
1713
188
  }
1714
1715
188
  return Inst;
1716
188
}
1717
1718
Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1719
43
    VarTemplatePartialSpecializationDecl *D) {
1720
43
  assert(D->isStaticDataMember() &&
1721
43
         "Only static data member templates are allowed.");
1722
1723
43
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1724
1725
  // Lookup the already-instantiated declaration and return that.
1726
43
  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1727
43
  assert(!Found.empty() && "Instantiation found nothing?");
1728
1729
43
  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1730
43
  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1731
1732
43
  if (VarTemplatePartialSpecializationDecl *Result =
1733
0
          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1734
0
    return Result;
1735
1736
43
  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1737
43
}
1738
1739
Decl *
1740
194k
TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1741
  // Create a local instantiation scope for this function template, which
1742
  // will contain the instantiations of the template parameters and then get
1743
  // merged with the local instantiation scope for the function template
1744
  // itself.
1745
194k
  LocalInstantiationScope Scope(SemaRef);
1746
1747
194k
  TemplateParameterList *TempParams = D->getTemplateParameters();
1748
194k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1749
194k
  if (!InstParams)
1750
1
    return nullptr;
1751
1752
194k
  FunctionDecl *Instantiated = nullptr;
1753
194k
  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1754
184k
    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1755
184k
                                                                 InstParams));
1756
10.3k
  else
1757
10.3k
    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1758
10.3k
                                                          D->getTemplatedDecl(),
1759
10.3k
                                                                InstParams));
1760
1761
194k
  if (!Instantiated)
1762
4
    return nullptr;
1763
1764
  // Link the instantiated function template declaration to the function
1765
  // template from which it was instantiated.
1766
194k
  FunctionTemplateDecl *InstTemplate
1767
194k
    = Instantiated->getDescribedFunctionTemplate();
1768
194k
  InstTemplate->setAccess(D->getAccess());
1769
194k
  assert(InstTemplate &&
1770
194k
         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1771
1772
194k
  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1773
1774
  // Link the instantiation back to the pattern *unless* this is a
1775
  // non-definition friend declaration.
1776
194k
  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1777
194k
      !(isFriend && 
!D->getTemplatedDecl()->isThisDeclarationADefinition()10.3k
))
1778
184k
    InstTemplate->setInstantiatedFromMemberTemplate(D);
1779
1780
  // Make declarations visible in the appropriate context.
1781
194k
  if (!isFriend) {
1782
184k
    Owner->addDecl(InstTemplate);
1783
10.3k
  } else if (InstTemplate->getDeclContext()->isRecord() &&
1784
6
             !getPreviousDeclForInstantiation(D)) {
1785
6
    SemaRef.CheckFriendAccess(InstTemplate);
1786
6
  }
1787
1788
194k
  return InstTemplate;
1789
194k
}
1790
1791
740k
Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1792
740k
  CXXRecordDecl *PrevDecl = nullptr;
1793
740k
  if (D->isInjectedClassName())
1794
722k
    PrevDecl = cast<CXXRecordDecl>(Owner);
1795
18.3k
  else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1796
28
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1797
28
                                                   PatternPrev,
1798
28
                                                   TemplateArgs);
1799
28
    if (!Prev) 
return nullptr0
;
1800
28
    PrevDecl = cast<CXXRecordDecl>(Prev);
1801
28
  }
1802
1803
740k
  CXXRecordDecl *Record = CXXRecordDecl::Create(
1804
740k
      SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1805
740k
      D->getLocation(), D->getIdentifier(), PrevDecl);
1806
1807
  // Substitute the nested name specifier, if any.
1808
740k
  if (SubstQualifier(D, Record))
1809
0
    return nullptr;
1810
1811
740k
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1812
740k
                                                              StartingScope);
1813
1814
740k
  Record->setImplicit(D->isImplicit());
1815
  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1816
  // the tag decls introduced by friend class declarations don't have an access
1817
  // specifier. Remove once this area of the code gets sorted out.
1818
740k
  if (D->getAccess() != AS_none)
1819
739k
    Record->setAccess(D->getAccess());
1820
740k
  if (!D->isInjectedClassName())
1821
18.3k
    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1822
1823
  // If the original function was part of a friend declaration,
1824
  // inherit its namespace state.
1825
740k
  if (D->getFriendObjectKind())
1826
0
    Record->setObjectOfFriendDecl();
1827
1828
  // Make sure that anonymous structs and unions are recorded.
1829
740k
  if (D->isAnonymousStructOrUnion())
1830
1.42k
    Record->setAnonymousStructOrUnion(true);
1831
1832
740k
  if (D->isLocalClass())
1833
2.35k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1834
1835
  // Forward the mangling number from the template to the instantiated decl.
1836
740k
  SemaRef.Context.setManglingNumber(Record,
1837
740k
                                    SemaRef.Context.getManglingNumber(D));
1838
1839
  // See if the old tag was defined along with a declarator.
1840
  // If it did, mark the new tag as being associated with that declarator.
1841
740k
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1842
3
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1843
1844
  // See if the old tag was defined along with a typedef.
1845
  // If it did, mark the new tag as being associated with that typedef.
1846
740k
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1847
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1848
1849
740k
  Owner->addDecl(Record);
1850
1851
  // DR1484 clarifies that the members of a local class are instantiated as part
1852
  // of the instantiation of their enclosing entity.
1853
740k
  if (D->isCompleteDefinition() && 
D->isLocalClass()17.9k
) {
1854
2.09k
    Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1855
1856
2.09k
    SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1857
2.09k
                             TSK_ImplicitInstantiation,
1858
2.09k
                             /*Complain=*/true);
1859
1860
    // For nested local classes, we will instantiate the members when we
1861
    // reach the end of the outermost (non-nested) local class.
1862
2.09k
    if (!D->isCXXClassMember())
1863
1.67k
      SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1864
1.67k
                                      TSK_ImplicitInstantiation);
1865
1866
    // This class may have local implicit instantiations that need to be
1867
    // performed within this scope.
1868
2.09k
    LocalInstantiations.perform();
1869
2.09k
  }
1870
1871
740k
  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1872
1873
740k
  return Record;
1874
740k
}
1875
1876
/// Adjust the given function type for an instantiation of the
1877
/// given declaration, to cope with modifications to the function's type that
1878
/// aren't reflected in the type-source information.
1879
///
1880
/// \param D The declaration we're instantiating.
1881
/// \param TInfo The already-instantiated type.
1882
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1883
                                                   FunctionDecl *D,
1884
1.06M
                                                   TypeSourceInfo *TInfo) {
1885
1.06M
  const FunctionProtoType *OrigFunc
1886
1.06M
    = D->getType()->castAs<FunctionProtoType>();
1887
1.06M
  const FunctionProtoType *NewFunc
1888
1.06M
    = TInfo->getType()->castAs<FunctionProtoType>();
1889
1.06M
  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1890
1.06M
    return TInfo->getType();
1891
1892
248
  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1893
248
  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1894
248
  return Context.getFunctionType(NewFunc->getReturnType(),
1895
248
                                 NewFunc->getParamTypes(), NewEPI);
1896
248
}
1897
1898
/// Normal class members are of more specific types and therefore
1899
/// don't make it here.  This function serves three purposes:
1900
///   1) instantiating function templates
1901
///   2) substituting friend declarations
1902
///   3) substituting deduction guide declarations for nested class templates
1903
Decl *TemplateDeclInstantiator::VisitFunctionDecl(
1904
    FunctionDecl *D, TemplateParameterList *TemplateParams,
1905
239k
    RewriteKind FunctionRewriteKind) {
1906
  // Check whether there is already a function template specialization for
1907
  // this declaration.
1908
239k
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1909
239k
  if (FunctionTemplate && 
!TemplateParams230k
) {
1910
220k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1911
1912
220k
    void *InsertPos = nullptr;
1913
220k
    FunctionDecl *SpecFunc
1914
220k
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1915
1916
    // If we already have a function template specialization, return it.
1917
220k
    if (SpecFunc)
1918
109k
      return SpecFunc;
1919
130k
  }
1920
1921
130k
  bool isFriend;
1922
130k
  if (FunctionTemplate)
1923
121k
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1924
8.51k
  else
1925
8.51k
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1926
1927
130k
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1928
119k
    Owner->isFunctionOrMethod() ||
1929
119k
    !(isa<Decl>(Owner) &&
1930
119k
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1931
130k
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1932
1933
130k
  ExplicitSpecifier InstantiatedExplicitSpecifier;
1934
130k
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1935
239
    InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1936
239
        SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1937
239
    if (InstantiatedExplicitSpecifier.isInvalid())
1938
10
      return nullptr;
1939
130k
  }
1940
1941
130k
  SmallVector<ParmVarDecl *, 4> Params;
1942
130k
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1943
130k
  if (!TInfo)
1944
9.42k
    return nullptr;
1945
120k
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1946
1947
120k
  if (TemplateParams && 
TemplateParams->size()10.3k
) {
1948
10.3k
    auto *LastParam =
1949
10.3k
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
1950
10.3k
    if (LastParam && 
LastParam->isImplicit()7.10k
&&
1951
0
        LastParam->hasTypeConstraint()) {
1952
      // In abbreviated templates, the type-constraints of invented template
1953
      // type parameters are instantiated with the function type, invalidating
1954
      // the TemplateParameterList which relied on the template type parameter
1955
      // not having a type constraint. Recreate the TemplateParameterList with
1956
      // the updated parameter list.
1957
0
      TemplateParams = TemplateParameterList::Create(
1958
0
          SemaRef.Context, TemplateParams->getTemplateLoc(),
1959
0
          TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
1960
0
          TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
1961
0
    }
1962
10.3k
  }
1963
1964
120k
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1965
120k
  if (QualifierLoc) {
1966
10
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1967
10
                                                       TemplateArgs);
1968
10
    if (!QualifierLoc)
1969
0
      return nullptr;
1970
120k
  }
1971
1972
  // FIXME: Concepts: Do not substitute into constraint expressions
1973
120k
  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
1974
120k
  if (TrailingRequiresClause) {
1975
52
    EnterExpressionEvaluationContext ConstantEvaluated(
1976
52
        SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
1977
52
    ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
1978
52
                                           TemplateArgs);
1979
52
    if (SubstRC.isInvalid())
1980
0
      return nullptr;
1981
52
    TrailingRequiresClause = SubstRC.get();
1982
52
    if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
1983
0
      return nullptr;
1984
120k
  }
1985
1986
  // If we're instantiating a local function declaration, put the result
1987
  // in the enclosing namespace; otherwise we need to find the instantiated
1988
  // context.
1989
120k
  DeclContext *DC;
1990
120k
  if (D->isLocalExternDecl()) {
1991
105
    DC = Owner;
1992
105
    SemaRef.adjustContextForLocalExternDecl(DC);
1993
120k
  } else if (isFriend && 
QualifierLoc18.7k
) {
1994
10
    CXXScopeSpec SS;
1995
10
    SS.Adopt(QualifierLoc);
1996
10
    DC = SemaRef.computeDeclContext(SS);
1997
10
    if (!DC) 
return nullptr0
;
1998
120k
  } else {
1999
120k
    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2000
120k
                                         TemplateArgs);
2001
120k
  }
2002
2003
120k
  DeclarationNameInfo NameInfo
2004
120k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2005
2006
120k
  if (FunctionRewriteKind != RewriteKind::None)
2007
30
    adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2008
2009
120k
  FunctionDecl *Function;
2010
120k
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2011
226
    Function = CXXDeductionGuideDecl::Create(
2012
226
        SemaRef.Context, DC, D->getInnerLocStart(),
2013
226
        InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2014
226
        D->getSourceRange().getEnd());
2015
226
    if (DGuide->isCopyDeductionCandidate())
2016
16
      cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
2017
226
    Function->setAccess(D->getAccess());
2018
120k
  } else {
2019
120k
    Function = FunctionDecl::Create(
2020
120k
        SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2021
120k
        D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
2022
120k
        D->hasWrittenPrototype(), D->getConstexprKind(),
2023
120k
        TrailingRequiresClause);
2024
120k
    Function->setRangeEnd(D->getSourceRange().getEnd());
2025
120k
  }
2026
2027
120k
  if (D->isInlined())
2028
48.3k
    Function->setImplicitlyInline();
2029
2030
120k
  if (QualifierLoc)
2031
10
    Function->setQualifierInfo(QualifierLoc);
2032
2033
120k
  if (D->isLocalExternDecl())
2034
105
    Function->setLocalExternDecl();
2035
2036
120k
  DeclContext *LexicalDC = Owner;
2037
120k
  if (!isFriend && 
D->isOutOfLine()101k
&&
!D->isLocalExternDecl()0
) {
2038
0
    assert(D->getDeclContext()->isFileContext());
2039
0
    LexicalDC = D->getDeclContext();
2040
0
  }
2041
2042
120k
  Function->setLexicalDeclContext(LexicalDC);
2043
2044
  // Attach the parameters
2045
327k
  for (unsigned P = 0; P < Params.size(); 
++P206k
)
2046
206k
    if (Params[P])
2047
206k
      Params[P]->setOwningFunction(Function);
2048
120k
  Function->setParams(Params);
2049
2050
120k
  if (TrailingRequiresClause)
2051
52
    Function->setTrailingRequiresClause(TrailingRequiresClause);
2052
2053
120k
  if (TemplateParams) {
2054
    // Our resulting instantiation is actually a function template, since we
2055
    // are substituting only the outer template parameters. For example, given
2056
    //
2057
    //   template<typename T>
2058
    //   struct X {
2059
    //     template<typename U> friend void f(T, U);
2060
    //   };
2061
    //
2062
    //   X<int> x;
2063
    //
2064
    // We are instantiating the friend function template "f" within X<int>,
2065
    // which means substituting int for T, but leaving "f" as a friend function
2066
    // template.
2067
    // Build the function template itself.
2068
10.3k
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2069
10.3k
                                                    Function->getLocation(),
2070
10.3k
                                                    Function->getDeclName(),
2071
10.3k
                                                    TemplateParams, Function);
2072
10.3k
    Function->setDescribedFunctionTemplate(FunctionTemplate);
2073
2074
10.3k
    FunctionTemplate->setLexicalDeclContext(LexicalDC);
2075
2076
10.3k
    if (isFriend && 
D->isThisDeclarationADefinition()10.3k
) {
2077
16
      FunctionTemplate->setInstantiatedFromMemberTemplate(
2078
16
                                           D->getDescribedFunctionTemplate());
2079
16
    }
2080
110k
  } else if (FunctionTemplate) {
2081
    // Record this function template specialization.
2082
101k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2083
101k
    Function->setFunctionTemplateSpecialization(FunctionTemplate,
2084
101k
                            TemplateArgumentList::CreateCopy(SemaRef.Context,
2085
101k
                                                             Innermost),
2086
101k
                                                /*InsertPos=*/nullptr);
2087
8.51k
  } else if (isFriend && 
D->isThisDeclarationADefinition()8.41k
) {
2088
    // Do not connect the friend to the template unless it's actually a
2089
    // definition. We don't want non-template functions to be marked as being
2090
    // template instantiations.
2091
4.74k
    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2092
4.74k
  }
2093
2094
120k
  if (isFriend) {
2095
18.7k
    Function->setObjectOfFriendDecl();
2096
18.7k
    if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2097
10.3k
      FT->setObjectOfFriendDecl();
2098
18.7k
  }
2099
2100
120k
  if (InitFunctionInstantiation(Function, D))
2101
0
    Function->setInvalidDecl();
2102
2103
120k
  bool IsExplicitSpecialization = false;
2104
2105
120k
  LookupResult Previous(
2106
120k
      SemaRef, Function->getDeclName(), SourceLocation(),
2107
105
      D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2108
120k
                             : Sema::LookupOrdinaryName,
2109
105
      D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2110
120k
                             : SemaRef.forRedeclarationInCurContext());
2111
2112
120k
  if (DependentFunctionTemplateSpecializationInfo *Info
2113
3.40k
        = D->getDependentSpecializationInfo()) {
2114
3.40k
    assert(isFriend && "non-friend has dependent specialization info?");
2115
2116
    // Instantiate the explicit template arguments.
2117
3.40k
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2118
3.40k
                                          Info->getRAngleLoc());
2119
3.40k
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2120
3.40k
                      ExplicitArgs, TemplateArgs))
2121
0
      return nullptr;
2122
2123
    // Map the candidate templates to their instantiations.
2124
30.5k
    
for (unsigned I = 0, E = Info->getNumTemplates(); 3.40k
I != E;
++I27.1k
) {
2125
27.1k
      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2126
27.1k
                                                Info->getTemplate(I),
2127
27.1k
                                                TemplateArgs);
2128
27.1k
      if (!Temp) 
return nullptr0
;
2129
2130
27.1k
      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2131
27.1k
    }
2132
2133
3.40k
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2134
3.40k
                                                    &ExplicitArgs,
2135
3.40k
                                                    Previous))
2136
0
      Function->setInvalidDecl();
2137
2138
3.40k
    IsExplicitSpecialization = true;
2139
117k
  } else if (const ASTTemplateArgumentListInfo *Info =
2140
1
                 D->getTemplateSpecializationArgsAsWritten()) {
2141
    // The name of this function was written as a template-id.
2142
1
    SemaRef.LookupQualifiedName(Previous, DC);
2143
2144
    // Instantiate the explicit template arguments.
2145
1
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2146
1
                                          Info->getRAngleLoc());
2147
1
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2148
1
                      ExplicitArgs, TemplateArgs))
2149
0
      return nullptr;
2150
2151
1
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2152
1
                                                    &ExplicitArgs,
2153
1
                                                    Previous))
2154
0
      Function->setInvalidDecl();
2155
2156
1
    IsExplicitSpecialization = true;
2157
117k
  } else if (TemplateParams || 
!FunctionTemplate106k
) {
2158
    // Look only into the namespace where the friend would be declared to
2159
    // find a previous declaration. This is the innermost enclosing namespace,
2160
    // as described in ActOnFriendFunctionDecl.
2161
15.4k
    SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2162
2163
    // In C++, the previous declaration we find might be a tag type
2164
    // (class or enum). In this case, the new declaration will hide the
2165
    // tag type. Note that this does does not apply if we're declaring a
2166
    // typedef (C++ [dcl.typedef]p4).
2167
15.4k
    if (Previous.isSingleTagDecl())
2168
0
      Previous.clear();
2169
2170
    // Filter out previous declarations that don't match the scope. The only
2171
    // effect this has is to remove declarations found in inline namespaces
2172
    // for friend declarations with unqualified names.
2173
15.4k
    SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
2174
15.4k
                                 /*ConsiderLinkage*/ true,
2175
15.4k
                                 QualifierLoc.hasQualifier());
2176
15.4k
  }
2177
2178
120k
  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2179
120k
                                   IsExplicitSpecialization);
2180
2181
  // Check the template parameter list against the previous declaration. The
2182
  // goal here is to pick up default arguments added since the friend was
2183
  // declared; we know the template parameter lists match, since otherwise
2184
  // we would not have picked this template as the previous declaration.
2185
120k
  if (isFriend && 
TemplateParams18.7k
&&
FunctionTemplate->getPreviousDecl()10.3k
) {
2186
10.2k
    SemaRef.CheckTemplateParameterList(
2187
10.2k
        TemplateParams,
2188
10.2k
        FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2189
10.2k
        Function->isThisDeclarationADefinition()
2190
0
            ? Sema::TPC_FriendFunctionTemplateDefinition
2191
10.2k
            : Sema::TPC_FriendFunctionTemplate);
2192
10.2k
  }
2193
2194
  // If we're introducing a friend definition after the first use, trigger
2195
  // instantiation.
2196
  // FIXME: If this is a friend function template definition, we should check
2197
  // to see if any specializations have been used.
2198
120k
  if (isFriend && 
D->isThisDeclarationADefinition()18.7k
&&
Function->isUsed(false)4.76k
) {
2199
7
    if (MemberSpecializationInfo *MSInfo =
2200
7
            Function->getMemberSpecializationInfo()) {
2201
7
      if (MSInfo->getPointOfInstantiation().isInvalid()) {
2202
7
        SourceLocation Loc = D->getLocation(); // FIXME
2203
7
        MSInfo->setPointOfInstantiation(Loc);
2204
7
        SemaRef.PendingLocalImplicitInstantiations.push_back(
2205
7
            std::make_pair(Function, Loc));
2206
7
      }
2207
7
    }
2208
7
  }
2209
2210
120k
  if (D->isExplicitlyDefaulted()) {
2211
84
    if (SubstDefaultedFunction(Function, D))
2212
0
      return nullptr;
2213
120k
  }
2214
120k
  if (D->isDeleted())
2215
1.41k
    SemaRef.SetDeclDeleted(Function, D->getLocation());
2216
2217
120k
  NamedDecl *PrincipalDecl =
2218
110k
      (TemplateParams ? 
cast<NamedDecl>(FunctionTemplate)10.3k
: Function);
2219
2220
  // If this declaration lives in a different context from its lexical context,
2221
  // add it to the corresponding lookup table.
2222
120k
  if (isFriend ||
2223
101k
      (Function->isLocalExternDecl() && 
!Function->getPreviousDecl()105
))
2224
18.8k
    DC->makeDeclVisibleInContext(PrincipalDecl);
2225
2226
120k
  if (Function->isOverloadedOperator() && 
!DC->isRecord()20.2k
&&
2227
20.2k
      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2228
15.5k
    PrincipalDecl->setNonMemberOperator();
2229
2230
120k
  return Function;
2231
120k
}
2232
2233
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2234
    CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2235
    Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2236
1.04M
    RewriteKind FunctionRewriteKind) {
2237
1.04M
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2238
1.04M
  if (FunctionTemplate && 
!TemplateParams381k
) {
2239
    // We are creating a function template specialization from a function
2240
    // template. Check whether there is already a function template
2241
    // specialization for this particular set of template arguments.
2242
197k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2243
2244
197k
    void *InsertPos = nullptr;
2245
197k
    FunctionDecl *SpecFunc
2246
197k
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2247
2248
    // If we already have a function template specialization, return it.
2249
197k
    if (SpecFunc)
2250
72.2k
      return SpecFunc;
2251
969k
  }
2252
2253
969k
  bool isFriend;
2254
969k
  if (FunctionTemplate)
2255
309k
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2256
659k
  else
2257
659k
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2258
2259
969k
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2260
785k
    !(isa<Decl>(Owner) &&
2261
785k
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2262
969k
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2263
2264
  // Instantiate enclosing template arguments for friends.
2265
969k
  SmallVector<TemplateParameterList *, 4> TempParamLists;
2266
969k
  unsigned NumTempParamLists = 0;
2267
969k
  if (isFriend && 
(NumTempParamLists = D->getNumTemplateParameterLists())40
) {
2268
3
    TempParamLists.resize(NumTempParamLists);
2269
10
    for (unsigned I = 0; I != NumTempParamLists; 
++I7
) {
2270
7
      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2271
7
      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2272
7
      if (!InstParams)
2273
0
        return nullptr;
2274
7
      TempParamLists[I] = InstParams;
2275
7
    }
2276
3
  }
2277
2278
969k
  ExplicitSpecifier InstantiatedExplicitSpecifier =
2279
969k
      instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2280
969k
                                   ExplicitSpecifier::getFromDecl(D), D);
2281
969k
  if (InstantiatedExplicitSpecifier.isInvalid())
2282
134
    return nullptr;
2283
2284
968k
  SmallVector<ParmVarDecl *, 4> Params;
2285
968k
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2286
968k
  if (!TInfo)
2287
24.2k
    return nullptr;
2288
944k
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2289
2290
944k
  if (TemplateParams && 
TemplateParams->size()184k
) {
2291
184k
    auto *LastParam =
2292
184k
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2293
184k
    if (LastParam && 
LastParam->isImplicit()158k
&&
2294
10
        LastParam->hasTypeConstraint()) {
2295
      // In abbreviated templates, the type-constraints of invented template
2296
      // type parameters are instantiated with the function type, invalidating
2297
      // the TemplateParameterList which relied on the template type parameter
2298
      // not having a type constraint. Recreate the TemplateParameterList with
2299
      // the updated parameter list.
2300
5
      TemplateParams = TemplateParameterList::Create(
2301
5
          SemaRef.Context, TemplateParams->getTemplateLoc(),
2302
5
          TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2303
5
          TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2304
5
    }
2305
184k
  }
2306
2307
944k
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2308
944k
  if (QualifierLoc) {
2309
308
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2310
308
                                                 TemplateArgs);
2311
308
    if (!QualifierLoc)
2312
1
      return nullptr;
2313
944k
  }
2314
2315
  // FIXME: Concepts: Do not substitute into constraint expressions
2316
944k
  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2317
944k
  if (TrailingRequiresClause) {
2318
32
    EnterExpressionEvaluationContext ConstantEvaluated(
2319
32
        SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2320
32
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
2321
32
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext,
2322
32
                                     D->getMethodQualifiers(), ThisContext);
2323
32
    ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2324
32
                                           TemplateArgs);
2325
32
    if (SubstRC.isInvalid())
2326
0
      return nullptr;
2327
32
    TrailingRequiresClause = SubstRC.get();
2328
32
    if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2329
0
      return nullptr;
2330
944k
  }
2331
2332
944k
  DeclContext *DC = Owner;
2333
944k
  if (isFriend) {
2334
39
    if (QualifierLoc) {
2335
39
      CXXScopeSpec SS;
2336
39
      SS.Adopt(QualifierLoc);
2337
39
      DC = SemaRef.computeDeclContext(SS);
2338
2339
39
      if (DC && 
SemaRef.RequireCompleteDeclContext(SS, DC)37
)
2340
0
        return nullptr;
2341
0
    } else {
2342
0
      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2343
0
                                           D->getDeclContext(),
2344
0
                                           TemplateArgs);
2345
0
    }
2346
39
    if (!DC) 
return nullptr2
;
2347
944k
  }
2348
2349
944k
  DeclarationNameInfo NameInfo
2350
944k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2351
2352
944k
  if (FunctionRewriteKind != RewriteKind::None)
2353
79
    adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2354
2355
  // Build the instantiated method declaration.
2356
944k
  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2357
944k
  CXXMethodDecl *Method = nullptr;
2358
2359
944k
  SourceLocation StartLoc = D->getInnerLocStart();
2360
944k
  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2361
214k
    Method = CXXConstructorDecl::Create(
2362
214k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2363
214k
        InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2364
214k
        Constructor->getConstexprKind(), InheritedConstructor(),
2365
214k
        TrailingRequiresClause);
2366
214k
    Method->setRangeEnd(Constructor->getEndLoc());
2367
730k
  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2368
13.1k
    Method = CXXDestructorDecl::Create(
2369
13.1k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2370
13.1k
        Destructor->isInlineSpecified(), false, Destructor->getConstexprKind(),
2371
13.1k
        TrailingRequiresClause);
2372
13.1k
    Method->setRangeEnd(Destructor->getEndLoc());
2373
716k
  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2374
12.0k
    Method = CXXConversionDecl::Create(
2375
12.0k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2376
12.0k
        Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2377
12.0k
        Conversion->getConstexprKind(), Conversion->getEndLoc(),
2378
12.0k
        TrailingRequiresClause);
2379
704k
  } else {
2380
534k
    StorageClass SC = D->isStatic() ? 
SC_Static170k
: SC_None;
2381
704k
    Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2382
704k
                                   T, TInfo, SC, D->isInlineSpecified(),
2383
704k
                                   D->getConstexprKind(), D->getEndLoc(),
2384
704k
                                   TrailingRequiresClause);
2385
704k
  }
2386
2387
944k
  if (D->isInlined())
2388
670k
    Method->setImplicitlyInline();
2389
2390
944k
  if (QualifierLoc)
2391
305
    Method->setQualifierInfo(QualifierLoc);
2392
2393
944k
  if (TemplateParams) {
2394
    // Our resulting instantiation is actually a function template, since we
2395
    // are substituting only the outer template parameters. For example, given
2396
    //
2397
    //   template<typename T>
2398
    //   struct X {
2399
    //     template<typename U> void f(T, U);
2400
    //   };
2401
    //
2402
    //   X<int> x;
2403
    //
2404
    // We are instantiating the member template "f" within X<int>, which means
2405
    // substituting int for T, but leaving "f" as a member function template.
2406
    // Build the function template itself.
2407
184k
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2408
184k
                                                    Method->getLocation(),
2409
184k
                                                    Method->getDeclName(),
2410
184k
                                                    TemplateParams, Method);
2411
184k
    if (isFriend) {
2412
6
      FunctionTemplate->setLexicalDeclContext(Owner);
2413
6
      FunctionTemplate->setObjectOfFriendDecl();
2414
184k
    } else if (D->isOutOfLine())
2415
0
      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2416
184k
    Method->setDescribedFunctionTemplate(FunctionTemplate);
2417
760k
  } else if (FunctionTemplate) {
2418
    // Record this function template specialization.
2419
101k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2420
101k
    Method->setFunctionTemplateSpecialization(FunctionTemplate,
2421
101k
                         TemplateArgumentList::CreateCopy(SemaRef.Context,
2422
101k
                                                          Innermost),
2423
101k
                                              /*InsertPos=*/nullptr);
2424
659k
  } else if (!isFriend) {
2425
    // Record that this is an instantiation of a member function.
2426
659k
    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2427
659k
  }
2428
2429
  // If we are instantiating a member function defined
2430
  // out-of-line, the instantiation will have the same lexical
2431
  // context (which will be a namespace scope) as the template.
2432
944k
  if (isFriend) {
2433
37
    if (NumTempParamLists)
2434
0
      Method->setTemplateParameterListsInfo(
2435
0
          SemaRef.Context,
2436
0
          llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2437
2438
37
    Method->setLexicalDeclContext(Owner);
2439
37
    Method->setObjectOfFriendDecl();
2440
944k
  } else if (D->isOutOfLine())
2441
268
    Method->setLexicalDeclContext(D->getLexicalDeclContext());
2442
2443
  // Attach the parameters
2444
2.00M
  for (unsigned P = 0; P < Params.size(); 
++P1.05M
)
2445
1.05M
    Params[P]->setOwningFunction(Method);
2446
944k
  Method->setParams(Params);
2447
2448
944k
  if (InitMethodInstantiation(Method, D))
2449
0
    Method->setInvalidDecl();
2450
2451
944k
  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2452
944k
                        Sema::ForExternalRedeclaration);
2453
2454
944k
  bool IsExplicitSpecialization = false;
2455
2456
  // If the name of this function was written as a template-id, instantiate
2457
  // the explicit template arguments.
2458
944k
  if (DependentFunctionTemplateSpecializationInfo *Info
2459
4
        = D->getDependentSpecializationInfo()) {
2460
4
    assert(isFriend && "non-friend has dependent specialization info?");
2461
2462
    // Instantiate the explicit template arguments.
2463
4
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2464
4
                                          Info->getRAngleLoc());
2465
4
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2466
4
                      ExplicitArgs, TemplateArgs))
2467
0
      return nullptr;
2468
2469
    // Map the candidate templates to their instantiations.
2470
8
    
for (unsigned I = 0, E = Info->getNumTemplates(); 4
I != E;
++I4
) {
2471
4
      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2472
4
                                                Info->getTemplate(I),
2473
4
                                                TemplateArgs);
2474
4
      if (!Temp) 
return nullptr0
;
2475
2476
4
      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2477
4
    }
2478
2479
4
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2480
4
                                                    &ExplicitArgs,
2481
4
                                                    Previous))
2482
0
      Method->setInvalidDecl();
2483
2484
4
    IsExplicitSpecialization = true;
2485
944k
  } else if (const ASTTemplateArgumentListInfo *Info =
2486
80
                 ClassScopeSpecializationArgs.getValueOr(
2487
80
                     D->getTemplateSpecializationArgsAsWritten())) {
2488
80
    SemaRef.LookupQualifiedName(Previous, DC);
2489
2490
80
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2491
80
                                          Info->getRAngleLoc());
2492
80
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2493
80
                      ExplicitArgs, TemplateArgs))
2494
0
      return nullptr;
2495
2496
80
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2497
80
                                                    &ExplicitArgs,
2498
80
                                                    Previous))
2499
0
      Method->setInvalidDecl();
2500
2501
80
    IsExplicitSpecialization = true;
2502
944k
  } else if (ClassScopeSpecializationArgs) {
2503
    // Class-scope explicit specialization written without explicit template
2504
    // arguments.
2505
11
    SemaRef.LookupQualifiedName(Previous, DC);
2506
11
    if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2507
0
      Method->setInvalidDecl();
2508
2509
11
    IsExplicitSpecialization = true;
2510
944k
  } else if (!FunctionTemplate || 
TemplateParams285k
||
isFriend101k
) {
2511
843k
    SemaRef.LookupQualifiedName(Previous, Record);
2512
2513
    // In C++, the previous declaration we find might be a tag type
2514
    // (class or enum). In this case, the new declaration will hide the
2515
    // tag type. Note that this does does not apply if we're declaring a
2516
    // typedef (C++ [dcl.typedef]p4).
2517
843k
    if (Previous.isSingleTagDecl())
2518
0
      Previous.clear();
2519
843k
  }
2520
2521
944k
  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2522
944k
                                   IsExplicitSpecialization);
2523
2524
944k
  if (D->isPure())
2525
229
    SemaRef.CheckPureMethod(Method, SourceRange());
2526
2527
  // Propagate access.  For a non-friend declaration, the access is
2528
  // whatever we're propagating from.  For a friend, it should be the
2529
  // previous declaration we just found.
2530
944k
  if (isFriend && 
Method->getPreviousDecl()37
)
2531
35
    Method->setAccess(Method->getPreviousDecl()->getAccess());
2532
944k
  else
2533
944k
    Method->setAccess(D->getAccess());
2534
944k
  if (FunctionTemplate)
2535
285k
    FunctionTemplate->setAccess(Method->getAccess());
2536
2537
944k
  SemaRef.CheckOverrideControl(Method);
2538
2539
  // If a function is defined as defaulted or deleted, mark it as such now.
2540
944k
  if (D->isExplicitlyDefaulted()) {
2541
14.4k
    if (SubstDefaultedFunction(Method, D))
2542
0
      return nullptr;
2543
944k
  }
2544
944k
  if (D->isDeletedAsWritten())
2545
4.79k
    SemaRef.SetDeclDeleted(Method, Method->getLocation());
2546
2547
  // If this is an explicit specialization, mark the implicitly-instantiated
2548
  // template specialization as being an explicit specialization too.
2549
  // FIXME: Is this necessary?
2550
944k
  if (IsExplicitSpecialization && 
!isFriend95
)
2551
90
    SemaRef.CompleteMemberSpecialization(Method, Previous);
2552
2553
  // If there's a function template, let our caller handle it.
2554
944k
  if (FunctionTemplate) {
2555
    // do nothing
2556
2557
  // Don't hide a (potentially) valid declaration with an invalid one.
2558
659k
  } else if (Method->isInvalidDecl() && 
!Previous.empty()5
) {
2559
    // do nothing
2560
2561
  // Otherwise, check access to friends and make them visible.
2562
659k
  } else if (isFriend) {
2563
    // We only need to re-check access for methods which we didn't
2564
    // manage to match during parsing.
2565
30
    if (!D->getPreviousDecl())
2566
25
      SemaRef.CheckFriendAccess(Method);
2567
2568
30
    Record->makeDeclVisibleInContext(Method);
2569
2570
  // Otherwise, add the declaration.  We don't need to do this for
2571
  // class-scope specializations because we'll have matched them with
2572
  // the appropriate template.
2573
659k
  } else {
2574
659k
    Owner->addDecl(Method);
2575
659k
  }
2576
2577
  // PR17480: Honor the used attribute to instantiate member function
2578
  // definitions
2579
944k
  if (Method->hasAttr<UsedAttr>()) {
2580
4
    if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2581
4
      SourceLocation Loc;
2582
4
      if (const MemberSpecializationInfo *MSInfo =
2583
0
              A->getMemberSpecializationInfo())
2584
0
        Loc = MSInfo->getPointOfInstantiation();
2585
4
      else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2586
4
        Loc = Spec->getPointOfInstantiation();
2587
4
      SemaRef.MarkFunctionReferenced(Loc, Method);
2588
4
    }
2589
4
  }
2590
2591
944k
  return Method;
2592
944k
}
2593
2594
193k
Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2595
193k
  return VisitCXXMethodDecl(D);
2596
193k
}
2597
2598
13.1k
Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2599
13.1k
  return VisitCXXMethodDecl(D);
2600
13.1k
}
2601
2602
14.0k
Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2603
14.0k
  return VisitCXXMethodDecl(D);
2604
14.0k
}
2605
2606
0
Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2607
0
  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2608
0
                                  /*ExpectParameterPack=*/ false);
2609
0
}
2610
2611
Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2612
369k
                                                    TemplateTypeParmDecl *D) {
2613
  // TODO: don't always clone when decls are refcounted.
2614
369k
  assert(D->getTypeForDecl()->isTemplateTypeParmType());
2615
2616
369k
  Optional<unsigned> NumExpanded;
2617
2618
369k
  if (const TypeConstraint *TC = D->getTypeConstraint()) {
2619
30
    if (D->isPackExpansion() && 
!D->isExpandedParameterPack()3
) {
2620
3
      assert(TC->getTemplateArgsAsWritten() &&
2621
3
             "type parameter can only be an expansion when explicit arguments "
2622
3
             "are specified");
2623
      // The template type parameter pack's type is a pack expansion of types.
2624
      // Determine whether we need to expand this parameter pack into separate
2625
      // types.
2626
3
      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2627
3
      for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2628
5
        SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2629
2630
      // Determine whether the set of unexpanded parameter packs can and should
2631
      // be expanded.
2632
3
      bool Expand = true;
2633
3
      bool RetainExpansion = false;
2634
3
      if (SemaRef.CheckParameterPacksForExpansion(
2635
3
              cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2636
3
                  ->getEllipsisLoc(),
2637
3
              SourceRange(TC->getConceptNameLoc(),
2638
3
                          TC->hasExplicitTemplateArgs() ?
2639
3
                          TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2640
0
                          TC->getConceptNameInfo().getEndLoc()),
2641
3
              Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2642
0
        return nullptr;
2643
369k
    }
2644
30
  }
2645
2646
369k
  TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2647
369k
      SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2648
369k
      D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2649
369k
      D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2650
369k
      D->hasTypeConstraint(), NumExpanded);
2651
2652
369k
  Inst->setAccess(AS_public);
2653
369k
  Inst->setImplicit(D->isImplicit());
2654
369k
  if (auto *TC = D->getTypeConstraint()) {
2655
30
    if (!D->isImplicit()) {
2656
      // Invented template parameter type constraints will be instantiated with
2657
      // the corresponding auto-typed parameter as it might reference other
2658
      // parameters.
2659
2660
      // TODO: Concepts: do not instantiate the constraint (delayed constraint
2661
      // substitution)
2662
24
      const ASTTemplateArgumentListInfo *TemplArgInfo
2663
24
        = TC->getTemplateArgsAsWritten();
2664
24
      TemplateArgumentListInfo InstArgs;
2665
2666
24
      if (TemplArgInfo) {
2667
18
        InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2668
18
        InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2669
18
        if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2670
18
                          TemplArgInfo->NumTemplateArgs,
2671
18
                          InstArgs, TemplateArgs))
2672
4
          return nullptr;
2673
20
      }
2674
20
      if (SemaRef.AttachTypeConstraint(
2675
20
              TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2676
20
              TC->getNamedConcept(), &InstArgs, Inst,
2677
20
              D->isParameterPack()
2678
2
                  ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2679
2
                      ->getEllipsisLoc()
2680
18
                  : SourceLocation()))
2681
0
        return nullptr;
2682
369k
    }
2683
30
  }
2684
369k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()93.3k
) {
2685
93.3k
    TypeSourceInfo *InstantiatedDefaultArg =
2686
93.3k
        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2687
93.3k
                          D->getDefaultArgumentLoc(), D->getDeclName());
2688
93.3k
    if (InstantiatedDefaultArg)
2689
93.2k
      Inst->setDefaultArgument(InstantiatedDefaultArg);
2690
93.3k
  }
2691
2692
  // Introduce this template parameter's instantiation into the instantiation
2693
  // scope.
2694
369k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2695
2696
369k
  return Inst;
2697
369k
}
2698
2699
Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2700
114k
                                                 NonTypeTemplateParmDecl *D) {
2701
  // Substitute into the type of the non-type template parameter.
2702
114k
  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2703
114k
  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2704
114k
  SmallVector<QualType, 4> ExpandedParameterPackTypes;
2705
114k
  bool IsExpandedParameterPack = false;
2706
114k
  TypeSourceInfo *DI;
2707
114k
  QualType T;
2708
114k
  bool Invalid = false;
2709
2710
114k
  if (D->isExpandedParameterPack()) {
2711
    // The non-type template parameter pack is an already-expanded pack
2712
    // expansion of types. Substitute into each of the expanded types.
2713
3
    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2714
3
    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2715
12
    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; 
++I9
) {
2716
9
      TypeSourceInfo *NewDI =
2717
9
          SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2718
9
                            D->getLocation(), D->getDeclName());
2719
9
      if (!NewDI)
2720
0
        return nullptr;
2721
2722
9
      QualType NewT =
2723
9
          SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2724
9
      if (NewT.isNull())
2725
0
        return nullptr;
2726
2727
9
      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2728
9
      ExpandedParameterPackTypes.push_back(NewT);
2729
9
    }
2730
2731
3
    IsExpandedParameterPack = true;
2732
3
    DI = D->getTypeSourceInfo();
2733
3
    T = DI->getType();
2734
114k
  } else if (D->isPackExpansion()) {
2735
    // The non-type template parameter pack's type is a pack expansion of types.
2736
    // Determine whether we need to expand this parameter pack into separate
2737
    // types.
2738
53
    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2739
53
    TypeLoc Pattern = Expansion.getPatternLoc();
2740
53
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2741
53
    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2742
2743
    // Determine whether the set of unexpanded parameter packs can and should
2744
    // be expanded.
2745
53
    bool Expand = true;
2746
53
    bool RetainExpansion = false;
2747
53
    Optional<unsigned> OrigNumExpansions
2748
53
      = Expansion.getTypePtr()->getNumExpansions();
2749
53
    Optional<unsigned> NumExpansions = OrigNumExpansions;
2750
53
    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2751
53
                                                Pattern.getSourceRange(),
2752
53
                                                Unexpanded,
2753
53
                                                TemplateArgs,
2754
53
                                                Expand, RetainExpansion,
2755
53
                                                NumExpansions))
2756
0
      return nullptr;
2757
2758
53
    if (Expand) {
2759
128
      for (unsigned I = 0; I != *NumExpansions; 
++I81
) {
2760
82
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2761
82
        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2762
82
                                                  D->getLocation(),
2763
82
                                                  D->getDeclName());
2764
82
        if (!NewDI)
2765
0
          return nullptr;
2766
2767
82
        QualType NewT =
2768
82
            SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2769
82
        if (NewT.isNull())
2770
1
          return nullptr;
2771
2772
81
        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2773
81
        ExpandedParameterPackTypes.push_back(NewT);
2774
81
      }
2775
2776
      // Note that we have an expanded parameter pack. The "type" of this
2777
      // expanded parameter pack is the original expansion type, but callers
2778
      // will end up using the expanded parameter pack types for type-checking.
2779
46
      IsExpandedParameterPack = true;
2780
46
      DI = D->getTypeSourceInfo();
2781
46
      T = DI->getType();
2782
6
    } else {
2783
      // We cannot fully expand the pack expansion now, so substitute into the
2784
      // pattern and create a new pack expansion type.
2785
6
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2786
6
      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2787
6
                                                     D->getLocation(),
2788
6
                                                     D->getDeclName());
2789
6
      if (!NewPattern)
2790
0
        return nullptr;
2791
2792
6
      SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2793
6
      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2794
6
                                      NumExpansions);
2795
6
      if (!DI)
2796
0
        return nullptr;
2797
2798
6
      T = DI->getType();
2799
6
    }
2800
114k
  } else {
2801
    // Simple case: substitution into a parameter that is not a parameter pack.
2802
114k
    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2803
114k
                           D->getLocation(), D->getDeclName());
2804
114k
    if (!DI)
2805
6
      return nullptr;
2806
2807
    // Check that this type is acceptable for a non-type template parameter.
2808
114k
    T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2809
114k
    if (T.isNull()) {
2810
4
      T = SemaRef.Context.IntTy;
2811
4
      Invalid = true;
2812
4
    }
2813
114k
  }
2814
2815
114k
  NonTypeTemplateParmDecl *Param;
2816
114k
  if (IsExpandedParameterPack)
2817
49
    Param = NonTypeTemplateParmDecl::Create(
2818
49
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2819
49
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2820
49
        D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2821
49
        ExpandedParameterPackTypesAsWritten);
2822
114k
  else
2823
114k
    Param = NonTypeTemplateParmDecl::Create(
2824
114k
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2825
114k
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2826
114k
        D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2827
2828
114k
  if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
2829
20
    if (AutoLoc.isConstrained())
2830
0
      if (SemaRef.AttachTypeConstraint(
2831
0
              AutoLoc, Param,
2832
0
              IsExpandedParameterPack
2833
0
                ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
2834
0
                    .getEllipsisLoc()
2835
0
                : SourceLocation()))
2836
0
        Invalid = true;
2837
2838
114k
  Param->setAccess(AS_public);
2839
114k
  Param->setImplicit(D->isImplicit());
2840
114k
  if (Invalid)
2841
4
    Param->setInvalidDecl();
2842
2843
114k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()35.6k
) {
2844
35.6k
    EnterExpressionEvaluationContext ConstantEvaluated(
2845
35.6k
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2846
35.6k
    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2847
35.6k
    if (!Value.isInvalid())
2848
35.6k
      Param->setDefaultArgument(Value.get());
2849
35.6k
  }
2850
2851
  // Introduce this template parameter's instantiation into the instantiation
2852
  // scope.
2853
114k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2854
114k
  return Param;
2855
114k
}
2856
2857
static void collectUnexpandedParameterPacks(
2858
    Sema &S,
2859
    TemplateParameterList *Params,
2860
17
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2861
18
  for (const auto &P : *Params) {
2862
18
    if (P->isTemplateParameterPack())
2863
0
      continue;
2864
18
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2865
17
      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2866
17
                                        Unexpanded);
2867
18
    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2868
0
      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2869
0
                                      Unexpanded);
2870
18
  }
2871
17
}
2872
2873
Decl *
2874
TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2875
1.58k
                                                  TemplateTemplateParmDecl *D) {
2876
  // Instantiate the template parameter list of the template template parameter.
2877
1.58k
  TemplateParameterList *TempParams = D->getTemplateParameters();
2878
1.58k
  TemplateParameterList *InstParams;
2879
1.58k
  SmallVector<TemplateParameterList*, 8> ExpandedParams;
2880
2881
1.58k
  bool IsExpandedParameterPack = false;
2882
2883
1.58k
  if (D->isExpandedParameterPack()) {
2884
    // The template template parameter pack is an already-expanded pack
2885
    // expansion of template parameters. Substitute into each of the expanded
2886
    // parameters.
2887
1
    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2888
1
    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2889
1
         I != N; 
++I0
) {
2890
0
      LocalInstantiationScope Scope(SemaRef);
2891
0
      TemplateParameterList *Expansion =
2892
0
        SubstTemplateParams(D->getExpansionTemplateParameters(I));
2893
0
      if (!Expansion)
2894
0
        return nullptr;
2895
0
      ExpandedParams.push_back(Expansion);
2896
0
    }
2897
2898
1
    IsExpandedParameterPack = true;
2899
1
    InstParams = TempParams;
2900
1.58k
  } else if (D->isPackExpansion()) {
2901
    // The template template parameter pack expands to a pack of template
2902
    // template parameters. Determine whether we need to expand this parameter
2903
    // pack into separate parameters.
2904
17
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2905
17
    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2906
17
                                    Unexpanded);
2907
2908
    // Determine whether the set of unexpanded parameter packs can and should
2909
    // be expanded.
2910
17
    bool Expand = true;
2911
17
    bool RetainExpansion = false;
2912
17
    Optional<unsigned> NumExpansions;
2913
17
    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2914
17
                                                TempParams->getSourceRange(),
2915
17
                                                Unexpanded,
2916
17
                                                TemplateArgs,
2917
17
                                                Expand, RetainExpansion,
2918
17
                                                NumExpansions))
2919
0
      return nullptr;
2920
2921
17
    if (Expand) {
2922
8.24k
      for (unsigned I = 0; I != *NumExpansions; 
++I8.22k
) {
2923
8.22k
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2924
8.22k
        LocalInstantiationScope Scope(SemaRef);
2925
8.22k
        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2926
8.22k
        if (!Expansion)
2927
0
          return nullptr;
2928
8.22k
        ExpandedParams.push_back(Expansion);
2929
8.22k
      }
2930
2931
      // Note that we have an expanded parameter pack. The "type" of this
2932
      // expanded parameter pack is the original expansion type, but callers
2933
      // will end up using the expanded parameter pack types for type-checking.
2934
17
      IsExpandedParameterPack = true;
2935
17
      InstParams = TempParams;
2936
0
    } else {
2937
      // We cannot fully expand the pack expansion now, so just substitute
2938
      // into the pattern.
2939
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2940
2941
0
      LocalInstantiationScope Scope(SemaRef);
2942
0
      InstParams = SubstTemplateParams(TempParams);
2943
0
      if (!InstParams)
2944
0
        return nullptr;
2945
1.56k
    }
2946
1.56k
  } else {
2947
    // Perform the actual substitution of template parameters within a new,
2948
    // local instantiation scope.
2949
1.56k
    LocalInstantiationScope Scope(SemaRef);
2950
1.56k
    InstParams = SubstTemplateParams(TempParams);
2951
1.56k
    if (!InstParams)
2952
5
      return nullptr;
2953
1.57k
  }
2954
2955
  // Build the template template parameter.
2956
1.57k
  TemplateTemplateParmDecl *Param;
2957
1.57k
  if (IsExpandedParameterPack)
2958
18
    Param = TemplateTemplateParmDecl::Create(
2959
18
        SemaRef.Context, Owner, D->getLocation(),
2960
18
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2961
18
        D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2962
1.55k
  else
2963
1.55k
    Param = TemplateTemplateParmDecl::Create(
2964
1.55k
        SemaRef.Context, Owner, D->getLocation(),
2965
1.55k
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2966
1.55k
        D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2967
1.57k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()5
) {
2968
5
    NestedNameSpecifierLoc QualifierLoc =
2969
5
        D->getDefaultArgument().getTemplateQualifierLoc();
2970
5
    QualifierLoc =
2971
5
        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2972
5
    TemplateName TName = SemaRef.SubstTemplateName(
2973
5
        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2974
5
        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2975
5
    if (!TName.isNull())
2976
5
      Param->setDefaultArgument(
2977
5
          SemaRef.Context,
2978
5
          TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
2979
5
                              D->getDefaultArgument().getTemplateQualifierLoc(),
2980
5
                              D->getDefaultArgument().getTemplateNameLoc()));
2981
5
  }
2982
1.57k
  Param->setAccess(AS_public);
2983
1.57k
  Param->setImplicit(D->isImplicit());
2984
2985
  // Introduce this template parameter's instantiation into the instantiation
2986
  // scope.
2987
1.57k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2988
2989
1.57k
  return Param;
2990
1.57k
}
2991
2992
14
Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2993
  // Using directives are never dependent (and never contain any types or
2994
  // expressions), so they require no explicit instantiation work.
2995
2996
14
  UsingDirectiveDecl *Inst
2997
14
    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2998
14
                                 D->getNamespaceKeyLocation(),
2999
14
                                 D->getQualifierLoc(),
3000
14
                                 D->getIdentLocation(),
3001
14
                                 D->getNominatedNamespace(),
3002
14
                                 D->getCommonAncestor());
3003
3004
  // Add the using directive to its declaration context
3005
  // only if this is not a function or method.
3006
14
  if (!Owner->isFunctionOrMethod())
3007
0
    Owner->addDecl(Inst);
3008
3009
14
  return Inst;
3010
14
}
3011
3012
197
Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3013
3014
  // The nested name specifier may be dependent, for example
3015
  //     template <typename T> struct t {
3016
  //       struct s1 { T f1(); };
3017
  //       struct s2 : s1 { using s1::f1; };
3018
  //     };
3019
  //     template struct t<int>;
3020
  // Here, in using s1::f1, s1 refers to t<T>::s1;
3021
  // we need to substitute for t<int>::s1.
3022
197
  NestedNameSpecifierLoc QualifierLoc
3023
197
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3024
197
                                          TemplateArgs);
3025
197
  if (!QualifierLoc)
3026
0
    return nullptr;
3027
3028
  // For an inheriting constructor declaration, the name of the using
3029
  // declaration is the name of a constructor in this class, not in the
3030
  // base class.
3031
197
  DeclarationNameInfo NameInfo = D->getNameInfo();
3032
197
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3033
17
    if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3034
17
      NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3035
17
          SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3036
3037
  // We only need to do redeclaration lookups if we're in a class
3038
  // scope (in fact, it's not really even possible in non-class
3039
  // scopes).
3040
197
  bool CheckRedeclaration = Owner->isRecord();
3041
3042
197
  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3043
197
                    Sema::ForVisibleRedeclaration);
3044
3045
197
  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3046
197
                                       D->getUsingLoc(),
3047
197
                                       QualifierLoc,
3048
197
                                       NameInfo,
3049
197
                                       D->hasTypename());
3050
3051
197
  CXXScopeSpec SS;
3052
197
  SS.Adopt(QualifierLoc);
3053
197
  if (CheckRedeclaration) {
3054
182
    Prev.setHideTags(false);
3055
182
    SemaRef.LookupQualifiedName(Prev, Owner);
3056
3057
    // Check for invalid redeclarations.
3058
182
    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3059
182
                                            D->hasTypename(), SS,
3060
182
                                            D->getLocation(), Prev))
3061
0
      NewUD->setInvalidDecl();
3062
3063
182
  }
3064
3065
197
  if (!NewUD->isInvalidDecl() &&
3066
197
      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
3067
197
                                      SS, NameInfo, D->getLocation()))
3068
2
    NewUD->setInvalidDecl();
3069
3070
197
  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3071
197
  NewUD->setAccess(D->getAccess());
3072
197
  Owner->addDecl(NewUD);
3073
3074
  // Don't process the shadow decls for an invalid decl.
3075
197
  if (NewUD->isInvalidDecl())
3076
2
    return NewUD;
3077
3078
195
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3079
16
    SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3080
3081
195
  bool isFunctionScope = Owner->isFunctionOrMethod();
3082
3083
  // Process the shadow decls.
3084
259
  for (auto *Shadow : D->shadows()) {
3085
    // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3086
    // reconstruct it in the case where it matters.
3087
259
    NamedDecl *OldTarget = Shadow->getTargetDecl();
3088
259
    if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3089
48
      if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3090
4
        OldTarget = BaseShadow;
3091
3092
259
    NamedDecl *InstTarget =
3093
259
        cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3094
259
            Shadow->getLocation(), OldTarget, TemplateArgs));
3095
259
    if (!InstTarget)
3096
0
      return nullptr;
3097
3098
259
    UsingShadowDecl *PrevDecl = nullptr;
3099
259
    if (CheckRedeclaration) {
3100
244
      if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
3101
3
        continue;
3102
15
    } else if (UsingShadowDecl *OldPrev =
3103
0
                   getPreviousDeclForInstantiation(Shadow)) {
3104
0
      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3105
0
          Shadow->getLocation(), OldPrev, TemplateArgs));
3106
0
    }
3107
3108
256
    UsingShadowDecl *InstShadow =
3109
256
        SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
3110
256
                                     PrevDecl);
3111
256
    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3112
3113
256
    if (isFunctionScope)
3114
15
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3115
256
  }
3116
3117
195
  return NewUD;
3118
195
}
3119
3120
197
Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3121
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
3122
197
  return nullptr;
3123
197
}
3124
3125
Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3126
51
    ConstructorUsingShadowDecl *D) {
3127
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
3128
51
  return nullptr;
3129
51
}
3130
3131
template <typename T>
3132
Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3133
1.16k
    T *D, bool InstantiatingPackElement) {
3134
  // If this is a pack expansion, expand it now.
3135
1.16k
  if (D->isPackExpansion() && 
!InstantiatingPackElement123
) {
3136
48
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3137
48
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3138
48
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3139
3140
    // Determine whether the set of unexpanded parameter packs can and should
3141
    // be expanded.
3142
48
    bool Expand = true;
3143
48
    bool RetainExpansion = false;
3144
48
    Optional<unsigned> NumExpansions;
3145
48
    if (SemaRef.CheckParameterPacksForExpansion(
3146
48
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3147
48
            Expand, RetainExpansion, NumExpansions))
3148
0
      return nullptr;
3149
3150
    // This declaration cannot appear within a function template signature,
3151
    // so we can't have a partial argument list for a parameter pack.
3152
48
    assert(!RetainExpansion &&
3153
48
           "should never need to retain an expansion for UsingPackDecl");
3154
3155
48
    if (!Expand) {
3156
      // We cannot fully expand the pack expansion now, so substitute into the
3157
      // pattern and create a new pack expansion.
3158
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3159
0
      return instantiateUnresolvedUsingDecl(D, true);
3160
0
    }
3161
3162
    // Within a function, we don't have any normal way to check for conflicts
3163
    // between shadow declarations from different using declarations in the
3164
    // same pack expansion, but this is always ill-formed because all expansions
3165
    // must produce (conflicting) enumerators.
3166
    //
3167
    // Sadly we can't just reject this in the template definition because it
3168
    // could be valid if the pack is empty or has exactly one expansion.
3169
48
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 16
) {
3170
2
      SemaRef.Diag(D->getEllipsisLoc(),
3171
2
                   diag::err_using_decl_redeclaration_expansion);
3172
2
      return nullptr;
3173
2
    }
3174
3175
    // Instantiate the slices of this pack and build a UsingPackDecl.
3176
46
    SmallVector<NamedDecl*, 8> Expansions;
3177
119
    for (unsigned I = 0; I != *NumExpansions; 
++I73
) {
3178
75
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3179
75
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3180
75
      if (!Slice)
3181
2
        return nullptr;
3182
      // Note that we can still get unresolved using declarations here, if we
3183
      // had arguments for all packs but the pattern also contained other
3184
      // template arguments (this only happens during partial substitution, eg
3185
      // into the body of a generic lambda in a function template).
3186
73
      Expansions.push_back(cast<NamedDecl>(Slice));
3187
73
    }
3188
3189
44
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3190
44
    if (isDeclWithinFunction(D))
3191
16
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3192
44
    return NewD;
3193
1.11k
  }
3194
3195
1.11k
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3196
670
  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : 
SourceLocation()445
;
3197
3198
1.11k
  NestedNameSpecifierLoc QualifierLoc
3199
1.11k
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3200
1.11k
                                          TemplateArgs);
3201
1.11k
  if (!QualifierLoc)
3202
7
    return nullptr;
3203
3204
1.10k
  CXXScopeSpec SS;
3205
1.10k
  SS.Adopt(QualifierLoc);
3206
3207
1.10k
  DeclarationNameInfo NameInfo
3208
1.10k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3209
3210
  // Produce a pack expansion only if we're not instantiating a particular
3211
  // slice of a pack expansion.
3212
1.10k
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3213
75
                            SemaRef.ArgumentPackSubstitutionIndex != -1;
3214
1.10k
  SourceLocation EllipsisLoc =
3215
1.03k
      InstantiatingSlice ? 
SourceLocation()75
: D->getEllipsisLoc();
3216
3217
1.10k
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3218
1.10k
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3219
1.10k
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3220
1.10k
      ParsedAttributesView(),
3221
1.10k
      /*IsInstantiation*/ true);
3222
1.10k
  if (UD)
3223
1.08k
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3224
3225
1.10k
  return UD;
3226
1.10k
}
clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingTypenameDecl>(clang::UnresolvedUsingTypenameDecl*, bool)
Line
Count
Source
3133
680
    T *D, bool InstantiatingPackElement) {
3134
  // If this is a pack expansion, expand it now.
3135
680
  if (D->isPackExpansion() && 
!InstantiatingPackElement23
) {
3136
10
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3137
10
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3138
10
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3139
3140
    // Determine whether the set of unexpanded parameter packs can and should
3141
    // be expanded.
3142
10
    bool Expand = true;
3143
10
    bool RetainExpansion = false;
3144
10
    Optional<unsigned> NumExpansions;
3145
10
    if (SemaRef.CheckParameterPacksForExpansion(
3146
10
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3147
10
            Expand, RetainExpansion, NumExpansions))
3148
0
      return nullptr;
3149
3150
    // This declaration cannot appear within a function template signature,
3151
    // so we can't have a partial argument list for a parameter pack.
3152
10
    assert(!RetainExpansion &&
3153
10
           "should never need to retain an expansion for UsingPackDecl");
3154
3155
10
    if (!Expand) {
3156
      // We cannot fully expand the pack expansion now, so substitute into the
3157
      // pattern and create a new pack expansion.
3158
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3159
0
      return instantiateUnresolvedUsingDecl(D, true);
3160
0
    }
3161
3162
    // Within a function, we don't have any normal way to check for conflicts
3163
    // between shadow declarations from different using declarations in the
3164
    // same pack expansion, but this is always ill-formed because all expansions
3165
    // must produce (conflicting) enumerators.
3166
    //
3167
    // Sadly we can't just reject this in the template definition because it
3168
    // could be valid if the pack is empty or has exactly one expansion.
3169
10
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 10
) {
3170
0
      SemaRef.Diag(D->getEllipsisLoc(),
3171
0
                   diag::err_using_decl_redeclaration_expansion);
3172
0
      return nullptr;
3173
0
    }
3174
3175
    // Instantiate the slices of this pack and build a UsingPackDecl.
3176
10
    SmallVector<NamedDecl*, 8> Expansions;
3177
23
    for (unsigned I = 0; I != *NumExpansions; 
++I13
) {
3178
13
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3179
13
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3180
13
      if (!Slice)
3181
0
        return nullptr;
3182
      // Note that we can still get unresolved using declarations here, if we
3183
      // had arguments for all packs but the pattern also contained other
3184
      // template arguments (this only happens during partial substitution, eg
3185
      // into the body of a generic lambda in a function template).
3186
13
      Expansions.push_back(cast<NamedDecl>(Slice));
3187
13
    }
3188
3189
10
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3190
10
    if (isDeclWithinFunction(D))
3191
7
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3192
10
    return NewD;
3193
670
  }
3194
3195
670
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3196
670
  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : 
SourceLocation()0
;
3197
3198
670
  NestedNameSpecifierLoc QualifierLoc
3199
670
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3200
670
                                          TemplateArgs);
3201
670
  if (!QualifierLoc)
3202
0
    return nullptr;
3203
3204
670
  CXXScopeSpec SS;
3205
670
  SS.Adopt(QualifierLoc);
3206
3207
670
  DeclarationNameInfo NameInfo
3208
670
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3209
3210
  // Produce a pack expansion only if we're not instantiating a particular
3211
  // slice of a pack expansion.
3212
670
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3213
13
                            SemaRef.ArgumentPackSubstitutionIndex != -1;
3214
670
  SourceLocation EllipsisLoc =
3215
657
      InstantiatingSlice ? 
SourceLocation()13
: D->getEllipsisLoc();
3216
3217
670
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3218
670
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3219
670
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3220
670
      ParsedAttributesView(),
3221
670
      /*IsInstantiation*/ true);
3222
670
  if (UD)
3223
670
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3224
3225
670
  return UD;
3226
670
}
clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingValueDecl>(clang::UnresolvedUsingValueDecl*, bool)
Line
Count
Source
3133
483
    T *D, bool InstantiatingPackElement) {
3134
  // If this is a pack expansion, expand it now.
3135
483
  if (D->isPackExpansion() && 
!InstantiatingPackElement100
) {
3136
38
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3137
38
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3138
38
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3139
3140
    // Determine whether the set of unexpanded parameter packs can and should
3141
    // be expanded.
3142
38
    bool Expand = true;
3143
38
    bool RetainExpansion = false;
3144
38
    Optional<unsigned> NumExpansions;
3145
38
    if (SemaRef.CheckParameterPacksForExpansion(
3146
38
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3147
38
            Expand, RetainExpansion, NumExpansions))
3148
0
      return nullptr;
3149
3150
    // This declaration cannot appear within a function template signature,
3151
    // so we can't have a partial argument list for a parameter pack.
3152
38
    assert(!RetainExpansion &&
3153
38
           "should never need to retain an expansion for UsingPackDecl");
3154
3155
38
    if (!Expand) {
3156
      // We cannot fully expand the pack expansion now, so substitute into the
3157
      // pattern and create a new pack expansion.
3158
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3159
0
      return instantiateUnresolvedUsingDecl(D, true);
3160
0
    }
3161
3162
    // Within a function, we don't have any normal way to check for conflicts
3163
    // between shadow declarations from different using declarations in the
3164
    // same pack expansion, but this is always ill-formed because all expansions
3165
    // must produce (conflicting) enumerators.
3166
    //
3167
    // Sadly we can't just reject this in the template definition because it
3168
    // could be valid if the pack is empty or has exactly one expansion.
3169
38
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 16
) {
3170
2
      SemaRef.Diag(D->getEllipsisLoc(),
3171
2
                   diag::err_using_decl_redeclaration_expansion);
3172
2
      return nullptr;
3173
2
    }
3174
3175
    // Instantiate the slices of this pack and build a UsingPackDecl.
3176
36
    SmallVector<NamedDecl*, 8> Expansions;
3177
96
    for (unsigned I = 0; I != *NumExpansions; 
++I60
) {
3178
62
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3179
62
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3180
62
      if (!Slice)
3181
2
        return nullptr;
3182
      // Note that we can still get unresolved using declarations here, if we
3183
      // had arguments for all packs but the pattern also contained other
3184
      // template arguments (this only happens during partial substitution, eg
3185
      // into the body of a generic lambda in a function template).
3186
60
      Expansions.push_back(cast<NamedDecl>(Slice));
3187
60
    }
3188
3189
34
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3190
34
    if (isDeclWithinFunction(D))
3191
9
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3192
34
    return NewD;
3193
445
  }
3194
3195
445
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3196
445
  SourceLocation TypenameLoc = TD ? 
TD->getTypenameLoc()0
: SourceLocation();
3197
3198
445
  NestedNameSpecifierLoc QualifierLoc
3199
445
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3200
445
                                          TemplateArgs);
3201
445
  if (!QualifierLoc)
3202
7
    return nullptr;
3203
3204
438
  CXXScopeSpec SS;
3205
438
  SS.Adopt(QualifierLoc);
3206
3207
438
  DeclarationNameInfo NameInfo
3208
438
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3209
3210
  // Produce a pack expansion only if we're not instantiating a particular
3211
  // slice of a pack expansion.
3212
438
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3213
62
                            SemaRef.ArgumentPackSubstitutionIndex != -1;
3214
438
  SourceLocation EllipsisLoc =
3215
376
      InstantiatingSlice ? 
SourceLocation()62
: D->getEllipsisLoc();
3216
3217
438
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3218
438
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3219
438
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3220
438
      ParsedAttributesView(),
3221
438
      /*IsInstantiation*/ true);
3222
438
  if (UD)
3223
414
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3224
3225
438
  return UD;
3226
438
}
3227
3228
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3229
667
    UnresolvedUsingTypenameDecl *D) {
3230
667
  return instantiateUnresolvedUsingDecl(D);
3231
667
}
3232
3233
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3234
421
    UnresolvedUsingValueDecl *D) {
3235
421
  return instantiateUnresolvedUsingDecl(D);
3236
421
}
3237
3238
8
Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3239
8
  SmallVector<NamedDecl*, 8> Expansions;
3240
10
  for (auto *UD : D->expansions()) {
3241
10
    if (NamedDecl *NewUD =
3242
10
            SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3243
10
      Expansions.push_back(NewUD);
3244
0
    else
3245
0
      return nullptr;
3246
10
  }
3247
3248
8
  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3249
8
  if (isDeclWithinFunction(D))
3250
8
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3251
8
  return NewD;
3252
8
}
3253
3254
Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3255
92
    ClassScopeFunctionSpecializationDecl *Decl) {
3256
92
  CXXMethodDecl *OldFD = Decl->getSpecialization();
3257
92
  return cast_or_null<CXXMethodDecl>(
3258
92
      VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3259
92
}
3260
3261
Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3262
216
                                     OMPThreadPrivateDecl *D) {
3263
216
  SmallVector<Expr *, 5> Vars;
3264
240
  for (auto *I : D->varlists()) {
3265
240
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3266
240
    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3267
240
    Vars.push_back(Var);
3268
240
  }
3269
3270
216
  OMPThreadPrivateDecl *TD =
3271
216
    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3272
3273
216
  TD->setAccess(AS_public);
3274
216
  Owner->addDecl(TD);
3275
3276
216
  return TD;
3277
216
}
3278
3279
58
Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3280
58
  SmallVector<Expr *, 5> Vars;
3281
58
  for (auto *I : D->varlists()) {
3282
58
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3283
58
    assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3284
58
    Vars.push_back(Var);
3285
58
  }
3286
58
  SmallVector<OMPClause *, 4> Clauses;
3287
  // Copy map clauses from the original mapper.
3288
42
  for (OMPClause *C : D->clauselists()) {
3289
42
    auto *AC = cast<OMPAllocatorClause>(C);
3290
42
    ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3291
42
    if (!NewE.isUsable())
3292
0
      continue;
3293
42
    OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
3294
42
        NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3295
42
    Clauses.push_back(IC);
3296
42
  }
3297
3298
58
  Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3299
58
      D->getLocation(), Vars, Clauses, Owner);
3300
58
  if (Res.get().isNull())
3301
0
    return nullptr;
3302
58
  return Res.get().getSingleDecl();
3303
58
}
3304
3305
0
Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3306
0
  llvm_unreachable(
3307
0
      "Requires directive cannot be instantiated within a dependent context");
3308
0
}
3309
3310
Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3311
156
    OMPDeclareReductionDecl *D) {
3312
  // Instantiate type and check if it is allowed.
3313
156
  const bool RequiresInstantiation =
3314
156
      D->getType()->isDependentType() ||
3315
26
      D->getType()->isInstantiationDependentType() ||
3316
26
      D->getType()->containsUnexpandedParameterPack();
3317
156
  QualType SubstReductionType;
3318
156
  if (RequiresInstantiation) {
3319
130
    SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3320
130
        D->getLocation(),
3321
130
        ParsedType::make(SemaRef.SubstType(
3322
130
            D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3323
26
  } else {
3324
26
    SubstReductionType = D->getType();
3325
26
  }
3326
156
  if (SubstReductionType.isNull())
3327
12
    return nullptr;
3328
144
  Expr *Combiner = D->getCombiner();
3329
144
  Expr *Init = D->getInitializer();
3330
144
  bool IsCorrect = true;
3331
  // Create instantiated copy.
3332
144
  std::pair<QualType, SourceLocation> ReductionTypes[] = {
3333
144
      std::make_pair(SubstReductionType, D->getLocation())};
3334
144
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3335
144
  if (PrevDeclInScope && 
!PrevDeclInScope->isInvalidDecl()20
) {
3336
20
    PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3337
20
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3338
20
            ->get<Decl *>());
3339
20
  }
3340
144
  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3341
144
      /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3342
144
      PrevDeclInScope);
3343
144
  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3344
144
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3345
144
  Expr *SubstCombiner = nullptr;
3346
144
  Expr *SubstInitializer = nullptr;
3347
  // Combiners instantiation sequence.
3348
144
  if (Combiner) {
3349
144
    SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3350
144
        /*S=*/nullptr, NewDRD);
3351
144
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3352
144
        cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3353
144
        cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3354
144
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3355
144
        cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3356
144
        cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3357
144
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3358
144
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3359
144
                                     ThisContext);
3360
144
    SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3361
144
    SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3362
144
  }
3363
  // Initializers instantiation sequence.
3364
144
  if (Init) {
3365
52
    VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3366
52
        /*S=*/nullptr, NewDRD);
3367
52
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3368
52
        cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3369
52
        cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3370
52
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3371
52
        cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3372
52
        cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3373
52
    if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3374
4
      SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3375
48
    } else {
3376
48
      auto *OldPrivParm =
3377
48
          cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3378
48
      IsCorrect = IsCorrect && OldPrivParm->hasInit();
3379
48
      if (IsCorrect)
3380
48
        SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3381
48
                                               TemplateArgs);
3382
48
    }
3383
52
    SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3384
52
                                                      OmpPrivParm);
3385
52
  }
3386
144
  IsCorrect = IsCorrect && SubstCombiner &&
3387
142
              (!Init ||
3388
52
               (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3389
4
                SubstInitializer) ||
3390
48
               (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3391
48
                !SubstInitializer));
3392
3393
144
  (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3394
144
      /*S=*/nullptr, DRD, IsCorrect && 
!D->isInvalidDecl()142
);
3395
3396
144
  return NewDRD;
3397
144
}
3398
3399
Decl *
3400
30
TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3401
  // Instantiate type and check if it is allowed.
3402
30
  const bool RequiresInstantiation =
3403
30
      D->getType()->isDependentType() ||
3404
18
      D->getType()->isInstantiationDependentType() ||
3405
18
      D->getType()->containsUnexpandedParameterPack();
3406
30
  QualType SubstMapperTy;
3407
30
  DeclarationName VN = D->getVarName();
3408
30
  if (RequiresInstantiation) {
3409
12
    SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3410
12
        D->getLocation(),
3411
12
        ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3412
12
                                           D->getLocation(), VN)));
3413
18
  } else {
3414
18
    SubstMapperTy = D->getType();
3415
18
  }
3416
30
  if (SubstMapperTy.isNull())
3417
0
    return nullptr;
3418
  // Create an instantiated copy of mapper.
3419
30
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3420
30
  if (PrevDeclInScope && 
!PrevDeclInScope->isInvalidDecl()4
) {
3421
4
    PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3422
4
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3423
4
            ->get<Decl *>());
3424
4
  }
3425
30
  bool IsCorrect = true;
3426
30
  SmallVector<OMPClause *, 6> Clauses;
3427
  // Instantiate the mapper variable.
3428
30
  DeclarationNameInfo DirName;
3429
30
  SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3430
30
                              /*S=*/nullptr,
3431
30
                              (*D->clauselist_begin())->getBeginLoc());
3432
30
  ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3433
30
      /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3434
30
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3435
30
      cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3436
30
      cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3437
30
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3438
30
  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3439
30
                                   ThisContext);
3440
  // Instantiate map clauses.
3441
30
  for (OMPClause *C : D->clauselists()) {
3442
30
    auto *OldC = cast<OMPMapClause>(C);
3443
30
    SmallVector<Expr *, 4> NewVars;
3444
30
    for (Expr *OE : OldC->varlists()) {
3445
30
      Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3446
30
      if (!NE) {
3447
0
        IsCorrect = false;
3448
0
        break;
3449
0
      }
3450
30
      NewVars.push_back(NE);
3451
30
    }
3452
30
    if (!IsCorrect)
3453
0
      break;
3454
30
    NestedNameSpecifierLoc NewQualifierLoc =
3455
30
        SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3456
30
                                            TemplateArgs);
3457
30
    CXXScopeSpec SS;
3458
30
    SS.Adopt(NewQualifierLoc);
3459
30
    DeclarationNameInfo NewNameInfo =
3460
30
        SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3461
30
    OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3462
30
                         OldC->getEndLoc());
3463
30
    OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3464
30
        OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3465
30
        NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3466
30
        OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3467
30
    Clauses.push_back(NewC);
3468
30
  }
3469
30
  SemaRef.EndOpenMPDSABlock(nullptr);
3470
30
  if (!IsCorrect)
3471
0
    return nullptr;
3472
30
  Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3473
30
      /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3474
30
      VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3475
30
  Decl *NewDMD = DG.get().getSingleDecl();
3476
30
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3477
30
  return NewDMD;
3478
30
}
3479
3480
Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3481
0
    OMPCapturedExprDecl * /*D*/) {
3482
0
  llvm_unreachable("Should not be met in templates");
3483
0
}
3484
3485
228k
Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3486
228k
  return VisitFunctionDecl(D, nullptr);
3487
228k
}
3488
3489
Decl *
3490
460
TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3491
460
  Decl *Inst = VisitFunctionDecl(D, nullptr);
3492
460
  if (Inst && 
!D->getDescribedFunctionTemplate()447
)
3493
1
    Owner->addDecl(Inst);
3494
460
  return Inst;
3495
460
}
3496
3497
857k
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3498
857k
  return VisitCXXMethodDecl(D, nullptr);
3499
857k
}
3500
3501
0
Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3502
0
  llvm_unreachable("There are only CXXRecordDecls in C++");
3503
0
}
3504
3505
Decl *
3506
TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3507
39
    ClassTemplateSpecializationDecl *D) {
3508
  // As a MS extension, we permit class-scope explicit specialization
3509
  // of member class templates.
3510
39
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3511
39
  assert(ClassTemplate->getDeclContext()->isRecord() &&
3512
39
         D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3513
39
         "can only instantiate an explicit specialization "
3514
39
         "for a member class template");
3515
3516
  // Lookup the already-instantiated declaration in the instantiation
3517
  // of the class template.
3518
39
  ClassTemplateDecl *InstClassTemplate =
3519
39
      cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3520
39
          D->getLocation(), ClassTemplate, TemplateArgs));
3521
39
  if (!InstClassTemplate)
3522
0
    return nullptr;
3523
3524
  // Substitute into the template arguments of the class template explicit
3525
  // specialization.
3526
39
  TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3527
39
                                        castAs<TemplateSpecializationTypeLoc>();
3528
39
  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3529
39
                                            Loc.getRAngleLoc());
3530
39
  SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3531
77
  for (unsigned I = 0; I != Loc.getNumArgs(); 
++I38
)
3532
38
    ArgLocs.push_back(Loc.getArgLoc(I));
3533
39
  if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3534
39
                    InstTemplateArgs, TemplateArgs))
3535
0
    return nullptr;
3536
3537
  // Check that the template argument list is well-formed for this
3538
  // class template.
3539
39
  SmallVector<TemplateArgument, 4> Converted;
3540
39
  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3541
39
                                        D->getLocation(),
3542
39
                                        InstTemplateArgs,
3543
39
                                        false,
3544
39
                                        Converted,
3545
39
                                        /*UpdateArgsWithConversion=*/true))
3546
0
    return nullptr;
3547
3548
  // Figure out where to insert this class template explicit specialization
3549
  // in the member template's set of class template explicit specializations.
3550
39
  void *InsertPos = nullptr;
3551
39
  ClassTemplateSpecializationDecl *PrevDecl =
3552
39
      InstClassTemplate->findSpecialization(Converted, InsertPos);
3553
3554
  // Check whether we've already seen a conflicting instantiation of this
3555
  // declaration (for instance, if there was a prior implicit instantiation).
3556
39
  bool Ignored;
3557
39
  if (PrevDecl &&
3558
14
      SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3559
14
                                                     D->getSpecializationKind(),
3560
14
                                                     PrevDecl,
3561
14
                                                     PrevDecl->getSpecializationKind(),
3562
14
                                                     PrevDecl->getPointOfInstantiation(),
3563
14
                                                     Ignored))
3564
2
    return nullptr;
3565
3566
  // If PrevDecl was a definition and D is also a definition, diagnose.
3567
  // This happens in cases like:
3568
  //
3569
  //   template<typename T, typename U>
3570
  //   struct Outer {
3571
  //     template<typename X> struct Inner;
3572
  //     template<> struct Inner<T> {};
3573
  //     template<> struct Inner<U> {};
3574
  //   };
3575
  //
3576
  //   Outer<int, int> outer; // error: the explicit specializations of Inner
3577
  //                          // have the same signature.
3578
37
  if (PrevDecl && 
PrevDecl->getDefinition()12
&&
3579
7
      D->isThisDeclarationADefinition()) {
3580
7
    SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3581
7
    SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3582
7
                 diag::note_previous_definition);
3583
7
    return nullptr;
3584
7
  }
3585
3586
  // Create the class template partial specialization declaration.
3587
30
  ClassTemplateSpecializationDecl *InstD =
3588
30
      ClassTemplateSpecializationDecl::Create(
3589
30
          SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3590
30
          D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3591
3592
  // Add this partial specialization to the set of class template partial
3593
  // specializations.
3594
30
  if (!PrevDecl)
3595
25
    InstClassTemplate->AddSpecialization(InstD, InsertPos);
3596
3597
  // Substitute the nested name specifier, if any.
3598
30
  if (SubstQualifier(D, InstD))
3599
0
    return nullptr;
3600
3601
  // Build the canonical type that describes the converted template
3602
  // arguments of the class template explicit specialization.
3603
30
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3604
30
      TemplateName(InstClassTemplate), Converted,
3605
30
      SemaRef.Context.getRecordType(InstD));
3606
3607
  // Build the fully-sugared type for this class template
3608
  // specialization as the user wrote in the specialization
3609
  // itself. This means that we'll pretty-print the type retrieved
3610
  // from the specialization's declaration the way that the user
3611
  // actually wrote the specialization, rather than formatting the
3612
  // name based on the "canonical" representation used to store the
3613
  // template arguments in the specialization.
3614
30
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3615
30
      TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3616
30
      CanonType);
3617
3618
30
  InstD->setAccess(D->getAccess());
3619
30
  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3620
30
  InstD->setSpecializationKind(D->getSpecializationKind());
3621
30
  InstD->setTypeAsWritten(WrittenTy);
3622
30
  InstD->setExternLoc(D->getExternLoc());
3623
30
  InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3624
3625
30
  Owner->addDecl(InstD);
3626
3627
  // Instantiate the members of the class-scope explicit specialization eagerly.
3628
  // We don't have support for lazy instantiation of an explicit specialization
3629
  // yet, and MSVC eagerly instantiates in this case.
3630
  // FIXME: This is wrong in standard C++.
3631
30
  if (D->isThisDeclarationADefinition() &&
3632
18
      SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3633
18
                               TSK_ImplicitInstantiation,
3634
18
                               /*Complain=*/true))
3635
0
    return nullptr;
3636
3637
30
  return InstD;
3638
30
}
3639
3640
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3641
57
    VarTemplateSpecializationDecl *D) {
3642
3643
57
  TemplateArgumentListInfo VarTemplateArgsInfo;
3644
57
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3645
57
  assert(VarTemplate &&
3646
57
         "A template specialization without specialized template?");
3647
3648
57
  VarTemplateDecl *InstVarTemplate =
3649
57
      cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3650
57
          D->getLocation(), VarTemplate, TemplateArgs));
3651
57
  if (!InstVarTemplate)
3652
0
    return nullptr;
3653
3654
  // Substitute the current template arguments.
3655
57
  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3656
57
  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3657
57
  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3658
3659
57
  if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3660
57
                    TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
3661
0
    return nullptr;
3662
3663
  // Check that the template argument list is well-formed for this template.
3664
57
  SmallVector<TemplateArgument, 4> Converted;
3665
57
  if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3666
57
                                        VarTemplateArgsInfo, false, Converted,
3667
57
                                        /*UpdateArgsWithConversion=*/true))
3668
0
    return nullptr;
3669
3670
  // Check whether we've already seen a declaration of this specialization.
3671
57
  void *InsertPos = nullptr;
3672
57
  VarTemplateSpecializationDecl *PrevDecl =
3673
57
      InstVarTemplate->findSpecialization(Converted, InsertPos);
3674
3675
  // Check whether we've already seen a conflicting instantiation of this
3676
  // declaration (for instance, if there was a prior implicit instantiation).
3677
57
  bool Ignored;
3678
57
  if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3679
10
                      D->getLocation(), D->getSpecializationKind(), PrevDecl,
3680
10
                      PrevDecl->getSpecializationKind(),
3681
10
                      PrevDecl->getPointOfInstantiation(), Ignored))
3682
0
    return nullptr;
3683
3684
57
  return VisitVarTemplateSpecializationDecl(
3685
57
      InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl);
3686
57
}
3687
3688
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3689
    VarTemplateDecl *VarTemplate, VarDecl *D,
3690
    const TemplateArgumentListInfo &TemplateArgsInfo,
3691
    ArrayRef<TemplateArgument> Converted,
3692
2.16k
    VarTemplateSpecializationDecl *PrevDecl) {
3693
3694
  // Do substitution on the type of the declaration
3695
2.16k
  TypeSourceInfo *DI =
3696
2.16k
      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3697
2.16k
                        D->getTypeSpecStartLoc(), D->getDeclName());
3698
2.16k
  if (!DI)
3699
0
    return nullptr;
3700
3701
2.16k
  if (DI->getType()->isFunctionType()) {
3702
0
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3703
0
        << D->isStaticDataMember() << DI->getType();
3704
0
    return nullptr;
3705
0
  }
3706
3707
  // Build the instantiated declaration
3708
2.16k
  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3709
2.16k
      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3710
2.16k
      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3711
2.16k
  Var->setTemplateArgsInfo(TemplateArgsInfo);
3712
2.16k
  if (!PrevDecl) {
3713
2.01k
    void *InsertPos = nullptr;
3714
2.01k
    VarTemplate->findSpecialization(Converted, InsertPos);
3715
2.01k
    VarTemplate->AddSpecialization(Var, InsertPos);
3716
2.01k
  }
3717
3718
2.16k
  if (SemaRef.getLangOpts().OpenCL)
3719
1
    SemaRef.deduceOpenCLAddressSpace(Var);
3720
3721
  // Substitute the nested name specifier, if any.
3722
2.16k
  if (SubstQualifier(D, Var))
3723
0
    return nullptr;
3724
3725
2.16k
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3726
2.16k
                                     StartingScope, false, PrevDecl);
3727
3728
2.16k
  return Var;
3729
2.16k
}
3730
3731
0
Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3732
0
  llvm_unreachable("@defs is not supported in Objective-C++");
3733
0
}
3734
3735
0
Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3736
  // FIXME: We need to be able to instantiate FriendTemplateDecls.
3737
0
  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3738
0
                                               DiagnosticsEngine::Error,
3739
0
                                               "cannot instantiate %0 yet");
3740
0
  SemaRef.Diag(D->getLocation(), DiagID)
3741
0
    << D->getDeclKindName();
3742
3743
0
  return nullptr;
3744
0
}
3745
3746
0
Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3747
0
  llvm_unreachable("Concept definitions cannot reside inside a template");
3748
0
}
3749
3750
Decl *
3751
0
TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
3752
0
  return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
3753
0
                                      D->getBeginLoc());
3754
0
}
3755
3756
0
Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3757
0
  llvm_unreachable("Unexpected decl");
3758
0
}
3759
3760
Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3761
567k
                      const MultiLevelTemplateArgumentList &TemplateArgs) {
3762
567k
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3763
567k
  if (D->isInvalidDecl())
3764
21
    return nullptr;
3765
3766
567k
  Decl *SubstD;
3767
567k
  runWithSufficientStackSpace(D->getLocation(), [&] {
3768
567k
    SubstD = Instantiator.Visit(D);
3769
567k
  });
3770
567k
  return SubstD;
3771
567k
}
3772
3773
void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
3774
                                                FunctionDecl *Orig, QualType &T,
3775
                                                TypeSourceInfo *&TInfo,
3776
109
                                                DeclarationNameInfo &NameInfo) {
3777
109
  assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
3778
3779
  // C++2a [class.compare.default]p3:
3780
  //   the return type is replaced with bool
3781
109
  auto *FPT = T->castAs<FunctionProtoType>();
3782
109
  T = SemaRef.Context.getFunctionType(
3783
109
      SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
3784
3785
  // Update the return type in the source info too. The most straightforward
3786
  // way is to create new TypeSourceInfo for the new type. Use the location of
3787
  // the '= default' as the location of the new type.
3788
  //
3789
  // FIXME: Set the correct return type when we initially transform the type,
3790
  // rather than delaying it to now.
3791
109
  TypeSourceInfo *NewTInfo =
3792
109
      SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
3793
109
  auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
3794
109
  assert(OldLoc && "type of function is not a function type?");
3795
109
  auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
3796
248
  for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; 
++I139
)
3797
139
    NewLoc.setParam(I, OldLoc.getParam(I));
3798
109
  TInfo = NewTInfo;
3799
3800
  //   and the declarator-id is replaced with operator==
3801
109
  NameInfo.setName(
3802
109
      SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
3803
109
}
3804
3805
FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
3806
109
                                               FunctionDecl *Spaceship) {
3807
109
  if (Spaceship->isInvalidDecl())
3808
0
    return nullptr;
3809
3810
  // C++2a [class.compare.default]p3:
3811
  //   an == operator function is declared implicitly [...] with the same
3812
  //   access and function-definition and in the same class scope as the
3813
  //   three-way comparison operator function
3814
109
  MultiLevelTemplateArgumentList NoTemplateArgs;
3815
109
  NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
3816
109
  NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
3817
109
  TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
3818
109
  Decl *R;
3819
109
  if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
3820
79
    R = Instantiator.VisitCXXMethodDecl(
3821
79
        MD, nullptr, None,
3822
79
        TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3823
30
  } else {
3824
30
    assert(Spaceship->getFriendObjectKind() &&
3825
30
           "defaulted spaceship is neither a member nor a friend");
3826
3827
30
    R = Instantiator.VisitFunctionDecl(
3828
30
        Spaceship, nullptr,
3829
30
        TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3830
30
    if (!R)
3831
0
      return nullptr;
3832
3833
30
    FriendDecl *FD =
3834
30
        FriendDecl::Create(Context, RD, Spaceship->getLocation(),
3835
30
                           cast<NamedDecl>(R), Spaceship->getBeginLoc());
3836
30
    FD->setAccess(AS_public);
3837
30
    RD->addDecl(FD);
3838
30
  }
3839
109
  return cast_or_null<FunctionDecl>(R);
3840
109
}
3841
3842
/// Instantiates a nested template parameter list in the current
3843
/// instantiation context.
3844
///
3845
/// \param L The parameter list to instantiate
3846
///
3847
/// \returns NULL if there was an error
3848
TemplateParameterList *
3849
290k
TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3850
  // Get errors for all the parameters before bailing out.
3851
290k
  bool Invalid = false;
3852
3853
290k
  unsigned N = L->size();
3854
290k
  typedef SmallVector<NamedDecl *, 8> ParamVector;
3855
290k
  ParamVector Params;
3856
290k
  Params.reserve(N);
3857
485k
  for (auto &P : *L) {
3858
485k
    NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3859
485k
    Params.push_back(D);
3860
485k
    Invalid = Invalid || !D || 
D->isInvalidDecl()485k
;
3861
485k
  }
3862
3863
  // Clean up if we had an error.
3864
290k
  if (Invalid)
3865
16
    return nullptr;
3866
3867
  // FIXME: Concepts: Substitution into requires clause should only happen when
3868
  // checking satisfaction.
3869
290k
  Expr *InstRequiresClause = nullptr;
3870
290k
  if (Expr *E = L->getRequiresClause()) {
3871
12
    EnterExpressionEvaluationContext ConstantEvaluated(
3872
12
        SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
3873
12
    ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
3874
12
    if (Res.isInvalid() || !Res.isUsable()) {
3875
0
      return nullptr;
3876
0
    }
3877
12
    InstRequiresClause = Res.get();
3878
12
  }
3879
3880
290k
  TemplateParameterList *InstL
3881
290k
    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3882
290k
                                    L->getLAngleLoc(), Params,
3883
290k
                                    L->getRAngleLoc(), InstRequiresClause);
3884
290k
  return InstL;
3885
290k
}
3886
3887
TemplateParameterList *
3888
Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3889
32.2k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3890
32.2k
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3891
32.2k
  return Instantiator.SubstTemplateParams(Params);
3892
32.2k
}
3893
3894
/// Instantiate the declaration of a class template partial
3895
/// specialization.
3896
///
3897
/// \param ClassTemplate the (instantiated) class template that is partially
3898
// specialized by the instantiation of \p PartialSpec.
3899
///
3900
/// \param PartialSpec the (uninstantiated) class template partial
3901
/// specialization that we are instantiating.
3902
///
3903
/// \returns The instantiated partial specialization, if successful; otherwise,
3904
/// NULL to indicate an error.
3905
ClassTemplatePartialSpecializationDecl *
3906
TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3907
                                            ClassTemplateDecl *ClassTemplate,
3908
7.81k
                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
3909
  // Create a local instantiation scope for this class template partial
3910
  // specialization, which will contain the instantiations of the template
3911
  // parameters.
3912
7.81k
  LocalInstantiationScope Scope(SemaRef);
3913
3914
  // Substitute into the template parameters of the class template partial
3915
  // specialization.
3916
7.81k
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3917
7.81k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3918
7.81k
  if (!InstParams)
3919
0
    return nullptr;
3920
3921
  // Substitute into the template arguments of the class template partial
3922
  // specialization.
3923
7.81k
  const ASTTemplateArgumentListInfo *TemplArgInfo
3924
7.81k
    = PartialSpec->getTemplateArgsAsWritten();
3925
7.81k
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3926
7.81k
                                            TemplArgInfo->RAngleLoc);
3927
7.81k
  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3928
7.81k
                    TemplArgInfo->NumTemplateArgs,
3929
7.81k
                    InstTemplateArgs, TemplateArgs))
3930
0
    return nullptr;
3931
3932
  // Check that the template argument list is well-formed for this
3933
  // class template.
3934
7.81k
  SmallVector<TemplateArgument, 4> Converted;
3935
7.81k
  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3936
7.81k
                                        PartialSpec->getLocation(),
3937
7.81k
                                        InstTemplateArgs,
3938
7.81k
                                        false,
3939
7.81k
                                        Converted))
3940
0
    return nullptr;
3941
3942
  // Check these arguments are valid for a template partial specialization.
3943
7.81k
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
3944
7.81k
          PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3945
7.81k
          Converted))
3946
5
    return nullptr;
3947
3948
  // Figure out where to insert this class template partial specialization
3949
  // in the member template's set of class template partial specializations.
3950
7.80k
  void *InsertPos = nullptr;
3951
7.80k
  ClassTemplateSpecializationDecl *PrevDecl
3952
7.80k
    = ClassTemplate->findPartialSpecialization(Converted, InstParams,
3953
7.80k
                                               InsertPos);
3954
3955
  // Build the canonical type that describes the converted template
3956
  // arguments of the class template partial specialization.
3957
7.80k
  QualType CanonType
3958
7.80k
    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3959
7.80k
                                                    Converted);
3960
3961
  // Build the fully-sugared type for this class template
3962
  // specialization as the user wrote in the specialization
3963
  // itself. This means that we'll pretty-print the type retrieved
3964
  // from the specialization's declaration the way that the user
3965
  // actually wrote the specialization, rather than formatting the
3966
  // name based on the "canonical" representation used to store the
3967
  // template arguments in the specialization.
3968
7.80k
  TypeSourceInfo *WrittenTy
3969
7.80k
    = SemaRef.Context.getTemplateSpecializationTypeInfo(
3970
7.80k
                                                    TemplateName(ClassTemplate),
3971
7.80k
                                                    PartialSpec->getLocation(),
3972
7.80k
                                                    InstTemplateArgs,
3973
7.80k
                                                    CanonType);
3974
3975
7.80k
  if (PrevDecl) {
3976
    // We've already seen a partial specialization with the same template
3977
    // parameters and template arguments. This can happen, for example, when
3978
    // substituting the outer template arguments ends up causing two
3979
    // class template partial specializations of a member class template
3980
    // to have identical forms, e.g.,
3981
    //
3982
    //   template<typename T, typename U>
3983
    //   struct Outer {
3984
    //     template<typename X, typename Y> struct Inner;
3985
    //     template<typename Y> struct Inner<T, Y>;
3986
    //     template<typename Y> struct Inner<U, Y>;
3987
    //   };
3988
    //
3989
    //   Outer<int, int> outer; // error: the partial specializations of Inner
3990
    //                          // have the same signature.
3991
1
    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3992
1
      << WrittenTy->getType();
3993
1
    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3994
1
      << SemaRef.Context.getTypeDeclType(PrevDecl);
3995
1
    return nullptr;
3996
1
  }
3997
3998
3999
  // Create the class template partial specialization declaration.
4000
7.80k
  ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4001
7.80k
      ClassTemplatePartialSpecializationDecl::Create(
4002
7.80k
          SemaRef.Context, PartialSpec->getTagKind(), Owner,
4003
7.80k
          PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4004
7.80k
          ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
4005
  // Substitute the nested name specifier, if any.
4006
7.80k
  if (SubstQualifier(PartialSpec, InstPartialSpec))
4007
0
    return nullptr;
4008
4009
7.80k
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4010
7.80k
  InstPartialSpec->setTypeAsWritten(WrittenTy);
4011
4012
  // Check the completed partial specialization.
4013
7.80k
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4014
4015
  // Add this partial specialization to the set of class template partial
4016
  // specializations.
4017
7.80k
  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4018
7.80k
                                          /*InsertPos=*/nullptr);
4019
7.80k
  return InstPartialSpec;
4020
7.80k
}
4021
4022
/// Instantiate the declaration of a variable template partial
4023
/// specialization.
4024
///
4025
/// \param VarTemplate the (instantiated) variable template that is partially
4026
/// specialized by the instantiation of \p PartialSpec.
4027
///
4028
/// \param PartialSpec the (uninstantiated) variable template partial
4029
/// specialization that we are instantiating.
4030
///
4031
/// \returns The instantiated partial specialization, if successful; otherwise,
4032
/// NULL to indicate an error.
4033
VarTemplatePartialSpecializationDecl *
4034
TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4035
    VarTemplateDecl *VarTemplate,
4036
50
    VarTemplatePartialSpecializationDecl *PartialSpec) {
4037
  // Create a local instantiation scope for this variable template partial
4038
  // specialization, which will contain the instantiations of the template
4039
  // parameters.
4040
50
  LocalInstantiationScope Scope(SemaRef);
4041
4042
  // Substitute into the template parameters of the variable template partial
4043
  // specialization.
4044
50
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4045
50
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4046
50
  if (!InstParams)
4047
0
    return nullptr;
4048
4049
  // Substitute into the template arguments of the variable template partial
4050
  // specialization.
4051
50
  const ASTTemplateArgumentListInfo *TemplArgInfo
4052
50
    = PartialSpec->getTemplateArgsAsWritten();
4053
50
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4054
50
                                            TemplArgInfo->RAngleLoc);
4055
50
  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
4056
50
                    TemplArgInfo->NumTemplateArgs,
4057
50
                    InstTemplateArgs, TemplateArgs))
4058
0
    return nullptr;
4059
4060
  // Check that the template argument list is well-formed for this
4061
  // class template.
4062
50
  SmallVector<TemplateArgument, 4> Converted;
4063
50
  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4064
50
                                        InstTemplateArgs, false, Converted))
4065
1
    return nullptr;
4066
4067
  // Check these arguments are valid for a template partial specialization.
4068
49
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
4069
49
          PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4070
49
          Converted))
4071
0
    return nullptr;
4072
4073
  // Figure out where to insert this variable template partial specialization
4074
  // in the member template's set of variable template partial specializations.
4075
49
  void *InsertPos = nullptr;
4076
49
  VarTemplateSpecializationDecl *PrevDecl =
4077
49
      VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos);
4078
4079
  // Build the canonical type that describes the converted template
4080
  // arguments of the variable template partial specialization.
4081
49
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4082
49
      TemplateName(VarTemplate), Converted);
4083
4084
  // Build the fully-sugared type for this variable template
4085
  // specialization as the user wrote in the specialization
4086
  // itself. This means that we'll pretty-print the type retrieved
4087
  // from the specialization's declaration the way that the user
4088
  // actually wrote the specialization, rather than formatting the
4089
  // name based on the "canonical" representation used to store the
4090
  // template arguments in the specialization.
4091
49
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4092
49
      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4093
49
      CanonType);
4094
4095
49
  if (PrevDecl) {
4096
    // We've already seen a partial specialization with the same template
4097
    // parameters and template arguments. This can happen, for example, when
4098
    // substituting the outer template arguments ends up causing two
4099
    // variable template partial specializations of a member variable template
4100
    // to have identical forms, e.g.,
4101
    //
4102
    //   template<typename T, typename U>
4103
    //   struct Outer {
4104
    //     template<typename X, typename Y> pair<X,Y> p;
4105
    //     template<typename Y> pair<T, Y> p;
4106
    //     template<typename Y> pair<U, Y> p;
4107
    //   };
4108
    //
4109
    //   Outer<int, int> outer; // error: the partial specializations of Inner
4110
    //                          // have the same signature.
4111
0
    SemaRef.Diag(PartialSpec->getLocation(),
4112
0
                 diag::err_var_partial_spec_redeclared)
4113
0
        << WrittenTy->getType();
4114
0
    SemaRef.Diag(PrevDecl->getLocation(),
4115
0
                 diag::note_var_prev_partial_spec_here);
4116
0
    return nullptr;
4117
0
  }
4118
4119
  // Do substitution on the type of the declaration
4120
49
  TypeSourceInfo *DI = SemaRef.SubstType(
4121
49
      PartialSpec->getTypeSourceInfo(), TemplateArgs,
4122
49
      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4123
49
  if (!DI)
4124
0
    return nullptr;
4125
4126
49
  if (DI->getType()->isFunctionType()) {
4127
0
    SemaRef.Diag(PartialSpec->getLocation(),
4128
0
                 diag::err_variable_instantiates_to_function)
4129
0
        << PartialSpec->isStaticDataMember() << DI->getType();
4130
0
    return nullptr;
4131
0
  }
4132
4133
  // Create the variable template partial specialization declaration.
4134
49
  VarTemplatePartialSpecializationDecl *InstPartialSpec =
4135
49
      VarTemplatePartialSpecializationDecl::Create(
4136
49
          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4137
49
          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4138
49
          DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
4139
4140
  // Substitute the nested name specifier, if any.
4141
49
  if (SubstQualifier(PartialSpec, InstPartialSpec))
4142
0
    return nullptr;
4143
4144
49
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4145
49
  InstPartialSpec->setTypeAsWritten(WrittenTy);
4146
4147
  // Check the completed partial specialization.
4148
49
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4149
4150
  // Add this partial specialization to the set of variable template partial
4151
  // specializations. The instantiation of the initializer is not necessary.
4152
49
  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4153
4154
49
  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4155
49
                                     LateAttrs, Owner, StartingScope);
4156
4157
49
  return InstPartialSpec;
4158
49
}
4159
4160
TypeSourceInfo*
4161
TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4162
1.09M
                              SmallVectorImpl<ParmVarDecl *> &Params) {
4163
1.09M
  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4164
1.09M
  assert(OldTInfo && "substituting function without type source info");
4165
1.09M
  assert(Params.empty() && "parameter vector is non-empty at start");
4166
4167
1.09M
  CXXRecordDecl *ThisContext = nullptr;
4168
1.09M
  Qualifiers ThisTypeQuals;
4169
1.09M
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4170
968k
    ThisContext = cast<CXXRecordDecl>(Owner);
4171
968k
    ThisTypeQuals = Method->getMethodQualifiers();
4172
968k
  }
4173
4174
1.09M
  TypeSourceInfo *NewTInfo
4175
1.09M
    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
4176
1.09M
                                    D->getTypeSpecStartLoc(),
4177
1.09M
                                    D->getDeclName(),
4178
1.09M
                                    ThisContext, ThisTypeQuals);
4179
1.09M
  if (!NewTInfo)
4180
33.7k
    return nullptr;
4181
4182
1.06M
  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4183
1.06M
  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4184
1.06M
    if (NewTInfo != OldTInfo) {
4185
      // Get parameters from the new type info.
4186
932k
      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4187
932k
      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4188
932k
      unsigned NewIdx = 0;
4189
932k
      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4190
2.19M
           OldIdx != NumOldParams; 
++OldIdx1.26M
) {
4191
1.26M
        ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4192
1.26M
        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4193
4194
1.26M
        Optional<unsigned> NumArgumentsInExpansion;
4195
1.26M
        if (OldParam->isParameterPack())
4196
22.6k
          NumArgumentsInExpansion =
4197
22.6k
              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4198
22.6k
                                                 TemplateArgs);
4199
1.26M
        if (!NumArgumentsInExpansion) {
4200
          // Simple case: normal parameter, or a parameter pack that's
4201
          // instantiated to a (still-dependent) parameter pack.
4202
1.25M
          ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4203
1.25M
          Params.push_back(NewParam);
4204
1.25M
          Scope->InstantiatedLocal(OldParam, NewParam);
4205
8.87k
        } else {
4206
          // Parameter pack expansion: make the instantiation an argument pack.
4207
8.87k
          Scope->MakeInstantiatedLocalArgPack(OldParam);
4208
21.8k
          for (unsigned I = 0; I != *NumArgumentsInExpansion; 
++I12.9k
) {
4209
12.9k
            ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4210
12.9k
            Params.push_back(NewParam);
4211
12.9k
            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4212
12.9k
          }
4213
8.87k
        }
4214
1.26M
      }
4215
133k
    } else {
4216
      // The function type itself was not dependent and therefore no
4217
      // substitution occurred. However, we still need to instantiate
4218
      // the function parameters themselves.
4219
133k
      const FunctionProtoType *OldProto =
4220
133k
          cast<FunctionProtoType>(OldProtoLoc.getType());
4221
133k
      for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4222
2
           ++i) {
4223
2
        ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4224
2
        if (!OldParam) {
4225
2
          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4226
2
              D, D->getLocation(), OldProto->getParamType(i)));
4227
2
          continue;
4228
2
        }
4229
4230
0
        ParmVarDecl *Parm =
4231
0
            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4232
0
        if (!Parm)
4233
0
          return nullptr;
4234
0
        Params.push_back(Parm);
4235
0
      }
4236
133k
    }
4237
87
  } else {
4238
    // If the type of this function, after ignoring parentheses, is not
4239
    // *directly* a function type, then we're instantiating a function that
4240
    // was declared via a typedef or with attributes, e.g.,
4241
    //
4242
    //   typedef int functype(int, int);
4243
    //   functype func;
4244
    //   int __cdecl meth(int, int);
4245
    //
4246
    // In this case, we'll just go instantiate the ParmVarDecls that we
4247
    // synthesized in the method declaration.
4248
87
    SmallVector<QualType, 4> ParamTypes;
4249
87
    Sema::ExtParameterInfoBuilder ExtParamInfos;
4250
87
    if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4251
87
                               TemplateArgs, ParamTypes, &Params,
4252
87
                               ExtParamInfos))
4253
0
      return nullptr;
4254
1.06M
  }
4255
4256
1.06M
  return NewTInfo;
4257
1.06M
}
4258
4259
/// Introduce the instantiated function parameters into the local
4260
/// instantiation scope, and set the parameter names to those used
4261
/// in the template.
4262
static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
4263
                                             const FunctionDecl *PatternDecl,
4264
                                             LocalInstantiationScope &Scope,
4265
190k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4266
190k
  unsigned FParamIdx = 0;
4267
397k
  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; 
++I206k
) {
4268
206k
    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4269
206k
    if (!PatternParam->isParameterPack()) {
4270
      // Simple case: not a parameter pack.
4271
199k
      assert(FParamIdx < Function->getNumParams());
4272
199k
      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4273
199k
      FunctionParam->setDeclName(PatternParam->getDeclName());
4274
      // If the parameter's type is not dependent, update it to match the type
4275
      // in the pattern. They can differ in top-level cv-qualifiers, and we want
4276
      // the pattern's type here. If the type is dependent, they can't differ,
4277
      // per core issue 1668. Substitute into the type from the pattern, in case
4278
      // it's instantiation-dependent.
4279
      // FIXME: Updating the type to work around this is at best fragile.
4280
199k
      if (!PatternDecl->getType()->isDependentType()) {
4281
5.55k
        QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
4282
5.55k
                                 FunctionParam->getLocation(),
4283
5.55k
                                 FunctionParam->getDeclName());
4284
5.55k
        if (T.isNull())
4285
0
          return true;
4286
5.55k
        FunctionParam->setType(T);
4287
5.55k
      }
4288
4289
199k
      Scope.InstantiatedLocal(PatternParam, FunctionParam);
4290
199k
      ++FParamIdx;
4291
199k
      continue;
4292
6.91k
    }
4293
4294
    // Expand the parameter pack.
4295
6.91k
    Scope.MakeInstantiatedLocalArgPack(PatternParam);
4296
6.91k
    Optional<unsigned> NumArgumentsInExpansion
4297
6.91k
      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4298
6.91k
    if (NumArgumentsInExpansion) {
4299
6.91k
      QualType PatternType =
4300
6.91k
          PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4301
16.9k
      for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; 
++Arg10.0k
) {
4302
10.0k
        ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4303
10.0k
        FunctionParam->setDeclName(PatternParam->getDeclName());
4304
10.0k
        if (!PatternDecl->getType()->isDependentType()) {
4305
0
          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
4306
0
          QualType T = S.SubstType(PatternType, TemplateArgs,
4307
0
                                   FunctionParam->getLocation(),
4308
0
                                   FunctionParam->getDeclName());
4309
0
          if (T.isNull())
4310
0
            return true;
4311
0
          FunctionParam->setType(T);
4312
0
        }
4313
4314
10.0k
        Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4315
10.0k
        ++FParamIdx;
4316
10.0k
      }
4317
6.91k
    }
4318
6.91k
  }
4319
4320
190k
  return false;
4321
190k
}
4322
4323
bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4324
9.44k
                                      ParmVarDecl *Param) {
4325
9.44k
  assert(Param->hasUninstantiatedDefaultArg());
4326
9.44k
  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4327
4328
9.44k
  EnterExpressionEvaluationContext EvalContext(
4329
9.44k
      *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4330
4331
  // Instantiate the expression.
4332
  //
4333
  // FIXME: Pass in a correct Pattern argument, otherwise
4334
  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4335
  //
4336
  // template<typename T>
4337
  // struct A {
4338
  //   static int FooImpl();
4339
  //
4340
  //   template<typename Tp>
4341
  //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4342
  //   // template argument list [[T], [Tp]], should be [[Tp]].
4343
  //   friend A<Tp> Foo(int a);
4344
  // };
4345
  //
4346
  // template<typename T>
4347
  // A<T> Foo(int a = A<T>::FooImpl());
4348
9.44k
  MultiLevelTemplateArgumentList TemplateArgs
4349
9.44k
    = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4350
4351
9.44k
  InstantiatingTemplate Inst(*this, CallLoc, Param,
4352
9.44k
                             TemplateArgs.getInnermost());
4353
9.44k
  if (Inst.isInvalid())
4354
1
    return true;
4355
9.44k
  if (Inst.isAlreadyInstantiating()) {
4356
1
    Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4357
1
    Param->setInvalidDecl();
4358
1
    return true;
4359
1
  }
4360
4361
9.44k
  ExprResult Result;
4362
9.44k
  {
4363
    // C++ [dcl.fct.default]p5:
4364
    //   The names in the [default argument] expression are bound, and
4365
    //   the semantic constraints are checked, at the point where the
4366
    //   default argument expression appears.
4367
9.44k
    ContextRAII SavedContext(*this, FD);
4368
9.44k
    LocalInstantiationScope Local(*this);
4369
4370
9.44k
    FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
4371
9.44k
        /*ForDefinition*/ false);
4372
9.44k
    if (addInstantiatedParametersToScope(*this, FD, Pattern, Local,
4373
9.44k
                                         TemplateArgs))
4374
0
      return true;
4375
4376
9.44k
    runWithSufficientStackSpace(CallLoc, [&] {
4377
9.44k
      Result = SubstInitializer(UninstExpr, TemplateArgs,
4378
9.44k
                                /*DirectInit*/false);
4379
9.44k
    });
4380
9.44k
  }
4381
9.44k
  if (Result.isInvalid())
4382
156
    return true;
4383
4384
  // Check the expression as an initializer for the parameter.
4385
9.28k
  InitializedEntity Entity
4386
9.28k
    = InitializedEntity::InitializeParameter(Context, Param);
4387
9.28k
  InitializationKind Kind = InitializationKind::CreateCopy(
4388
9.28k
      Param->getLocation(),
4389
9.28k
      /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4390
9.28k
  Expr *ResultE = Result.getAs<Expr>();
4391
4392
9.28k
  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4393
9.28k
  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4394
9.28k
  if (Result.isInvalid())
4395
25
    return true;
4396
4397
9.26k
  Result =
4398
9.26k
      ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4399
9.26k
                          /*DiscardedValue*/ false);
4400
9.26k
  if (Result.isInvalid())
4401
0
    return true;
4402
4403
  // Remember the instantiated default argument.
4404
9.26k
  Param->setDefaultArg(Result.getAs<Expr>());
4405
9.26k
  if (ASTMutationListener *L = getASTMutationListener())
4406
496
    L->DefaultArgumentInstantiated(Param);
4407
4408
9.26k
  return false;
4409
9.26k
}
4410
4411
void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4412
5.45k
                                    FunctionDecl *Decl) {
4413
5.45k
  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4414
5.45k
  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4415
0
    return;
4416
4417
5.45k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4418
5.45k
                             InstantiatingTemplate::ExceptionSpecification());
4419
5.45k
  if (Inst.isInvalid()) {
4420
    // We hit the instantiation depth limit. Clear the exception specification
4421
    // so that our callers don't have to cope with EST_Uninstantiated.
4422
0
    UpdateExceptionSpec(Decl, EST_None);
4423
0
    return;
4424
0
  }
4425
5.45k
  if (Inst.isAlreadyInstantiating()) {
4426
    // This exception specification indirectly depends on itself. Reject.
4427
    // FIXME: Corresponding rule in the standard?
4428
10
    Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4429
10
    UpdateExceptionSpec(Decl, EST_None);
4430
10
    return;
4431
10
  }
4432
4433
  // Enter the scope of this instantiation. We don't use
4434
  // PushDeclContext because we don't have a scope.
4435
5.44k
  Sema::ContextRAII savedContext(*this, Decl);
4436
5.44k
  LocalInstantiationScope Scope(*this);
4437
4438
5.44k
  MultiLevelTemplateArgumentList TemplateArgs =
4439
5.44k
    getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
4440
4441
  // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4442
  // here, because for a non-defining friend declaration in a class template,
4443
  // we don't store enough information to map back to the friend declaration in
4444
  // the template.
4445
5.44k
  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4446
5.44k
  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
4447
0
                                       TemplateArgs)) {
4448
0
    UpdateExceptionSpec(Decl, EST_None);
4449
0
    return;
4450
0
  }
4451
4452
5.44k
  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4453
5.44k
                     TemplateArgs);
4454
5.44k
}
4455
4456
bool Sema::CheckInstantiatedFunctionTemplateConstraints(
4457
    SourceLocation PointOfInstantiation, FunctionDecl *Decl,
4458
    ArrayRef<TemplateArgument> TemplateArgs,
4459
382k
    ConstraintSatisfaction &Satisfaction) {
4460
  // In most cases we're not going to have constraints, so check for that first.
4461
382k
  FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
4462
  // Note - code synthesis context for the constraints check is created
4463
  // inside CheckConstraintsSatisfaction.
4464
382k
  SmallVector<const Expr *, 3> TemplateAC;
4465
382k
  Template->getAssociatedConstraints(TemplateAC);
4466
382k
  if (TemplateAC.empty()) {
4467
382k
    Satisfaction.IsSatisfied = true;
4468
382k
    return false;
4469
382k
  }
4470
4471
  // Enter the scope of this instantiation. We don't use
4472
  // PushDeclContext because we don't have a scope.
4473
217
  Sema::ContextRAII savedContext(*this, Decl);
4474
217
  LocalInstantiationScope Scope(*this);
4475
4476
  // If this is not an explicit specialization - we need to get the instantiated
4477
  // version of the template arguments and add them to scope for the
4478
  // substitution.
4479
217
  if (Decl->isTemplateInstantiation()) {
4480
217
    InstantiatingTemplate Inst(*this, Decl->getPointOfInstantiation(),
4481
217
        InstantiatingTemplate::ConstraintsCheck{}, Decl->getPrimaryTemplate(),
4482
217
        TemplateArgs, SourceRange());
4483
217
    if (Inst.isInvalid())
4484
0
      return true;
4485
217
    MultiLevelTemplateArgumentList MLTAL(
4486
217
        *Decl->getTemplateSpecializationArgs());
4487
217
    if (addInstantiatedParametersToScope(
4488
217
            *this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
4489
217
            Scope, MLTAL))
4490
0
      return true;
4491
217
  }
4492
217
  Qualifiers ThisQuals;
4493
217
  CXXRecordDecl *Record = nullptr;
4494
217
  if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
4495
48
    ThisQuals = Method->getMethodQualifiers();
4496
48
    Record = Method->getParent();
4497
48
  }
4498
217
  CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
4499
217
  return CheckConstraintSatisfaction(Template, TemplateAC, TemplateArgs,
4500
217
                                     PointOfInstantiation, Satisfaction);
4501
217
}
4502
4503
/// Initializes the common fields of an instantiation function
4504
/// declaration (New) from the corresponding fields of its template (Tmpl).
4505
///
4506
/// \returns true if there was an error
4507
bool
4508
TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4509
1.06M
                                                    FunctionDecl *Tmpl) {
4510
1.06M
  New->setImplicit(Tmpl->isImplicit());
4511
4512
  // Forward the mangling number from the template to the instantiated decl.
4513
1.06M
  SemaRef.Context.setManglingNumber(New,
4514
1.06M
                                    SemaRef.Context.getManglingNumber(Tmpl));
4515
4516
  // If we are performing substituting explicitly-specified template arguments
4517
  // or deduced template arguments into a function template and we reach this
4518
  // point, we are now past the point where SFINAE applies and have committed
4519
  // to keeping the new function template specialization. We therefore
4520
  // convert the active template instantiation for the function template
4521
  // into a template instantiation for this specific function template
4522
  // specialization, which is not a SFINAE context, so that we diagnose any
4523
  // further errors in the declaration itself.
4524
  //
4525
  // FIXME: This is a hack.
4526
1.06M
  typedef Sema::CodeSynthesisContext ActiveInstType;
4527
1.06M
  ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4528
1.06M
  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4529
1.06M
      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4530
203k
    if (FunctionTemplateDecl *FunTmpl
4531
203k
          = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4532
203k
      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4533
203k
             "Deduction from the wrong function template?");
4534
203k
      (void) FunTmpl;
4535
203k
      SemaRef.InstantiatingSpecializations.erase(
4536
203k
          {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4537
203k
      atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4538
203k
      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4539
203k
      ActiveInst.Entity = New;
4540
203k
      atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4541
203k
    }
4542
203k
  }
4543
4544
1.06M
  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4545
1.06M
  assert(Proto && "Function template without prototype?");
4546
4547
1.06M
  if (Proto->hasExceptionSpec() || 
Proto->getNoReturnAttr()653k
) {
4548
411k
    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4549
4550
    // DR1330: In C++11, defer instantiation of a non-trivial
4551
    // exception specification.
4552
    // DR1484: Local classes and their members are instantiated along with the
4553
    // containing function.
4554
411k
    if (SemaRef.getLangOpts().CPlusPlus11 &&
4555
411k
        EPI.ExceptionSpec.Type != EST_None &&
4556
411k
        EPI.ExceptionSpec.Type != EST_DynamicNone &&
4557
411k
        EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4558
45.3k
        !Tmpl->isInLocalScopeForInstantiation()) {
4559
45.3k
      FunctionDecl *ExceptionSpecTemplate = Tmpl;
4560
45.3k
      if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4561
3.68k
        ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4562
45.3k
      ExceptionSpecificationType NewEST = EST_Uninstantiated;
4563
45.3k
      if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4564
0
        NewEST = EST_Unevaluated;
4565
4566
      // Mark the function has having an uninstantiated exception specification.
4567
45.3k
      const FunctionProtoType *NewProto
4568
45.3k
        = New->getType()->getAs<FunctionProtoType>();
4569
45.3k
      assert(NewProto && "Template instantiation without function prototype?");
4570
45.3k
      EPI = NewProto->getExtProtoInfo();
4571
45.3k
      EPI.ExceptionSpec.Type = NewEST;
4572
45.3k
      EPI.ExceptionSpec.SourceDecl = New;
4573
45.3k
      EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4574
45.3k
      New->setType(SemaRef.Context.getFunctionType(
4575
45.3k
          NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4576
366k
    } else {
4577
366k
      Sema::ContextRAII SwitchContext(SemaRef, New);
4578
366k
      SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4579
366k
    }
4580
411k
  }
4581
4582
  // Get the definition. Leaves the variable unchanged if undefined.
4583
1.06M
  const FunctionDecl *Definition = Tmpl;
4584
1.06M
  Tmpl->isDefined(Definition);
4585
4586
1.06M
  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4587
1.06M
                           LateAttrs, StartingScope);
4588
4589
1.06M
  return false;
4590
1.06M
}
4591
4592
/// Initializes common fields of an instantiated method
4593
/// declaration (New) from the corresponding fields of its template
4594
/// (Tmpl).
4595
///
4596
/// \returns true if there was an error
4597
bool
4598
TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4599
944k
                                                  CXXMethodDecl *Tmpl) {
4600
944k
  if (InitFunctionInstantiation(New, Tmpl))
4601
0
    return true;
4602
4603
944k
  if (isa<CXXDestructorDecl>(New) && 
SemaRef.getLangOpts().CPlusPlus1113.1k
)
4604
13.0k
    SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4605
4606
944k
  New->setAccess(Tmpl->getAccess());
4607
944k
  if (Tmpl->isVirtualAsWritten())
4608
18.9k
    New->setVirtualAsWritten(true);
4609
4610
  // FIXME: New needs a pointer to Tmpl
4611
944k
  return false;
4612
944k
}
4613
4614
bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4615
14.5k
                                                      FunctionDecl *Tmpl) {
4616
  // Transfer across any unqualified lookups.
4617
14.5k
  if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4618
129
    SmallVector<DeclAccessPair, 32> Lookups;
4619
129
    Lookups.reserve(DFI->getUnqualifiedLookups().size());
4620
129
    bool AnyChanged = false;
4621
23
    for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4622
23
      NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4623
23
                                                  DA.getDecl(), TemplateArgs);
4624
23
      if (!D)
4625
0
        return true;
4626
23
      AnyChanged |= (D != DA.getDecl());
4627
23
      Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4628
23
    }
4629
4630
    // It's unlikely that substitution will change any declarations. Don't
4631
    // store an unnecessary copy in that case.
4632
129
    New->setDefaultedFunctionInfo(
4633
8
        AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4634
8
                         SemaRef.Context, Lookups)
4635
121
                   : DFI);
4636
129
  }
4637
4638
14.5k
  SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4639
14.5k
  return false;
4640
14.5k
}
4641
4642
/// Instantiate (or find existing instantiation of) a function template with a
4643
/// given set of template arguments.
4644
///
4645
/// Usually this should not be used, and template argument deduction should be
4646
/// used in its place.
4647
FunctionDecl *
4648
Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4649
                                     const TemplateArgumentList *Args,
4650
1.43k
                                     SourceLocation Loc) {
4651
1.43k
  FunctionDecl *FD = FTD->getTemplatedDecl();
4652
4653
1.43k
  sema::TemplateDeductionInfo Info(Loc);
4654
1.43k
  InstantiatingTemplate Inst(
4655
1.43k
      *this, Loc, FTD, Args->asArray(),
4656
1.43k
      CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4657
1.43k
  if (Inst.isInvalid())
4658
0
    return nullptr;
4659
4660
1.43k
  ContextRAII SavedContext(*this, FD);
4661
1.43k
  MultiLevelTemplateArgumentList MArgs(*Args);
4662
4663
1.43k
  return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4664
1.43k
}
4665
4666
/// Instantiate the definition of the given function from its
4667
/// template.
4668
///
4669
/// \param PointOfInstantiation the point at which the instantiation was
4670
/// required. Note that this is not precisely a "point of instantiation"
4671
/// for the function, but it's close.
4672
///
4673
/// \param Function the already-instantiated declaration of a
4674
/// function template specialization or member function of a class template
4675
/// specialization.
4676
///
4677
/// \param Recursive if true, recursively instantiates any functions that
4678
/// are required by this instantiation.
4679
///
4680
/// \param DefinitionRequired if true, then we are performing an explicit
4681
/// instantiation where the body of the function is required. Complain if
4682
/// there is no such body.
4683
void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4684
                                         FunctionDecl *Function,
4685
                                         bool Recursive,
4686
                                         bool DefinitionRequired,
4687
189k
                                         bool AtEndOfTU) {
4688
189k
  if (Function->isInvalidDecl() || 
isa<CXXDeductionGuideDecl>(Function)189k
)
4689
176
    return;
4690
4691
  // Never instantiate an explicit specialization except if it is a class scope
4692
  // explicit specialization.
4693
188k
  TemplateSpecializationKind TSK =
4694
188k
      Function->getTemplateSpecializationKindForInstantiation();
4695
188k
  if (TSK == TSK_ExplicitSpecialization)
4696
1
    return;
4697
4698
  // Don't instantiate a definition if we already have one.
4699
188k
  const FunctionDecl *ExistingDefn = nullptr;
4700
188k
  if (Function->isDefined(ExistingDefn,
4701
3.64k
                          /*CheckForPendingFriendDefinition=*/true)) {
4702
3.64k
    if (ExistingDefn->isThisDeclarationADefinition())
4703
3.36k
      return;
4704
4705
    // If we're asked to instantiate a function whose body comes from an
4706
    // instantiated friend declaration, attach the instantiated body to the
4707
    // corresponding declaration of the function.
4708
286
    assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4709
286
    Function = const_cast<FunctionDecl*>(ExistingDefn);
4710
286
  }
4711
4712
  // Find the function body that we'll be substituting.
4713
185k
  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4714
185k
  assert(PatternDecl && "instantiating a non-template");
4715
4716
185k
  const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4717
185k
  Stmt *Pattern = nullptr;
4718
185k
  if (PatternDef) {
4719
175k
    Pattern = PatternDef->getBody(PatternDef);
4720
175k
    PatternDecl = PatternDef;
4721
175k
    if (PatternDef->willHaveBody())
4722
15
      PatternDef = nullptr;
4723
175k
  }
4724
4725
  // FIXME: We need to track the instantiation stack in order to know which
4726
  // definitions should be visible within this instantiation.
4727
185k
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4728
185k
                                Function->getInstantiatedFromMemberFunction(),
4729
185k
                                     PatternDecl, PatternDef, TSK,
4730
10.2k
                                     /*Complain*/DefinitionRequired)) {
4731
10.2k
    if (DefinitionRequired)
4732
7
      Function->setInvalidDecl();
4733
10.1k
    else if (TSK == TSK_ExplicitInstantiationDefinition) {
4734
      // Try again at the end of the translation unit (at which point a
4735
      // definition will be required).
4736
20
      assert(!Recursive);
4737
20
      Function->setInstantiationIsPending(true);
4738
20
      PendingInstantiations.push_back(
4739
20
        std::make_pair(Function, PointOfInstantiation));
4740
10.1k
    } else if (TSK == TSK_ImplicitInstantiation) {
4741
10.1k
      if (AtEndOfTU && 
!getDiagnostics().hasErrorOccurred()10.1k
&&
4742
3.29k
          !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4743
2.65k
        Diag(PointOfInstantiation, diag::warn_func_template_missing)
4744
2.65k
          << Function;
4745
2.65k
        Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4746
2.65k
        if (getLangOpts().CPlusPlus11)
4747
2.57k
          Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4748
2.57k
            << Function;
4749
2.65k
      }
4750
10.1k
    }
4751
4752
10.2k
    return;
4753
10.2k
  }
4754
4755
  // Postpone late parsed template instantiations.
4756
175k
  if (PatternDecl->isLateTemplateParsed() &&
4757
475
      !LateTemplateParser) {
4758
93
    Function->setInstantiationIsPending(true);
4759
93
    LateParsedInstantiations.push_back(
4760
93
        std::make_pair(Function, PointOfInstantiation));
4761
93
    return;
4762
93
  }
4763
4764
175k
  llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4765
1
    std::string Name;
4766
1
    llvm::raw_string_ostream OS(Name);
4767
1
    Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4768
1
                                   /*Qualified=*/true);
4769
1
    return Name;
4770
1
  });
4771
4772
  // If we're performing recursive template instantiation, create our own
4773
  // queue of pending implicit instantiations that we will instantiate later,
4774
  // while we're still within our own instantiation context.
4775
  // This has to happen before LateTemplateParser below is called, so that
4776
  // it marks vtables used in late parsed templates as used.
4777
175k
  GlobalEagerInstantiationScope GlobalInstantiations(*this,
4778
175k
                                                     /*Enabled=*/Recursive);
4779
175k
  LocalEagerInstantiationScope LocalInstantiations(*this);
4780
4781
  // Call the LateTemplateParser callback if there is a need to late parse
4782
  // a templated function definition.
4783
175k
  if (!Pattern && 
PatternDecl->isLateTemplateParsed()396
&&
4784
382
      Lat