Coverage Report

Created: 2021-08-24 07:12

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