Coverage Report

Created: 2022-05-17 06:19

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