Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
9
//
10
//===----------------------------------------------------------------------===/
11
12
#include "TreeTransform.h"
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/DeclTemplate.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/PrettyDeclStackTrace.h"
20
#include "clang/AST/TypeVisitor.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/Stack.h"
23
#include "clang/Basic/TargetInfo.h"
24
#include "clang/Sema/DeclSpec.h"
25
#include "clang/Sema/Initialization.h"
26
#include "clang/Sema/Lookup.h"
27
#include "clang/Sema/SemaConcept.h"
28
#include "clang/Sema/SemaInternal.h"
29
#include "clang/Sema/Template.h"
30
#include "clang/Sema/TemplateDeduction.h"
31
#include "clang/Sema/TemplateInstCallback.h"
32
#include "llvm/Support/TimeProfiler.h"
33
34
using namespace clang;
35
using namespace sema;
36
37
//===----------------------------------------------------------------------===/
38
// Template Instantiation Support
39
//===----------------------------------------------------------------------===/
40
41
/// Retrieve the template argument list(s) that should be used to
42
/// instantiate the definition of the given declaration.
43
///
44
/// \param D the declaration for which we are computing template instantiation
45
/// arguments.
46
///
47
/// \param Innermost if non-NULL, the innermost template argument list.
48
///
49
/// \param RelativeToPrimary true if we should get the template
50
/// arguments relative to the primary template, even when we're
51
/// dealing with a specialization. This is only relevant for function
52
/// template specializations.
53
///
54
/// \param Pattern If non-NULL, indicates the pattern from which we will be
55
/// instantiating the definition of the given declaration, \p D. This is
56
/// used to determine the proper set of template instantiation arguments for
57
/// friend function template specializations.
58
MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
59
    const NamedDecl *D, const TemplateArgumentList *Innermost,
60
1.89M
    bool RelativeToPrimary, const FunctionDecl *Pattern) {
61
  // Accumulate the set of template argument lists in this structure.
62
1.89M
  MultiLevelTemplateArgumentList Result;
63
64
1.89M
  if (Innermost)
65
0
    Result.addOuterTemplateArguments(Innermost);
66
67
1.89M
  const auto *Ctx = dyn_cast<DeclContext>(D);
68
1.89M
  if (!Ctx) {
69
866k
    Ctx = D->getDeclContext();
70
71
    // Add template arguments from a variable template instantiation. For a
72
    // class-scope explicit specialization, there are no template arguments
73
    // at this level, but there may be enclosing template arguments.
74
866k
    const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(D);
75
866k
    if (Spec && 
!Spec->isClassScopeExplicitSpecialization()2.53k
) {
76
      // We're done when we hit an explicit specialization.
77
2.52k
      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
78
2.52k
          
!isa<VarTemplatePartialSpecializationDecl>(Spec)0
)
79
0
        return Result;
80
81
2.52k
      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
82
83
      // If this variable template specialization was instantiated from a
84
      // specialized member that is a variable template, we're done.
85
2.52k
      assert(Spec->getSpecializedTemplate() && "No variable template?");
86
0
      llvm::PointerUnion<VarTemplateDecl*,
87
2.52k
                         VarTemplatePartialSpecializationDecl*> Specialized
88
2.52k
                             = Spec->getSpecializedTemplateOrPartial();
89
2.52k
      if (VarTemplatePartialSpecializationDecl *Partial =
90
2.52k
              Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
91
552
        if (Partial->isMemberSpecialization())
92
3
          return Result;
93
1.96k
      } else {
94
1.96k
        VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
95
1.96k
        if (Tmpl->isMemberSpecialization())
96
11
          return Result;
97
1.96k
      }
98
2.52k
    }
99
100
    // If we have a template template parameter with translation unit context,
101
    // then we're performing substitution into a default template argument of
102
    // this template template parameter before we've constructed the template
103
    // that will own this template template parameter. In this case, we
104
    // use empty template parameter lists for all of the outer templates
105
    // to avoid performing any substitutions.
106
866k
    if (Ctx->isTranslationUnit()) {
107
748
      if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
108
0
        for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
109
0
          Result.addOuterTemplateArguments(None);
110
0
        return Result;
111
0
      }
112
748
    }
113
866k
  }
114
115
4.01M
  
while (1.89M
!Ctx->isFileContext()) {
116
    // Add template arguments from a class template instantiation.
117
2.11M
    const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
118
2.11M
    if (Spec && 
!Spec->isClassScopeExplicitSpecialization()1.89M
) {
119
      // We're done when we hit an explicit specialization.
120
1.89M
      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
121
1.89M
          
!isa<ClassTemplatePartialSpecializationDecl>(Spec)182
)
122
182
        break;
123
124
1.89M
      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
125
126
      // If this class template specialization was instantiated from a
127
      // specialized member that is a class template, we're done.
128
1.89M
      assert(Spec->getSpecializedTemplate() && "No class template?");
129
1.89M
      if (Spec->getSpecializedTemplate()->isMemberSpecialization())
130
48
        break;
131
1.89M
    }
132
    // Add template arguments from a function template specialization.
133
227k
    else if (const auto *Function = dyn_cast<FunctionDecl>(Ctx)) {
134
206k
      if (!RelativeToPrimary &&
135
206k
          Function->getTemplateSpecializationKindForInstantiation() ==
136
191k
              TSK_ExplicitSpecialization)
137
0
        break;
138
139
206k
      if (!RelativeToPrimary && Function->getTemplateSpecializationKind() ==
140
191k
                                    TSK_ExplicitSpecialization) {
141
        // This is an implicit instantiation of an explicit specialization. We
142
        // don't get any template arguments from this function but might get
143
        // some from an enclosing template.
144
206k
      } else if (const TemplateArgumentList *TemplateArgs
145
206k
            = Function->getTemplateSpecializationArgs()) {
146
        // Add the template arguments for this specialization.
147
103k
        Result.addOuterTemplateArguments(TemplateArgs);
148
149
        // If this function was instantiated from a specialized member that is
150
        // a function template, we're done.
151
103k
        assert(Function->getPrimaryTemplate() && "No function template?");
152
103k
        if (Function->getPrimaryTemplate()->isMemberSpecialization())
153
36
          break;
154
155
        // If this function is a generic lambda specialization, we are done.
156
103k
        if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
157
2.57k
          break;
158
159
103k
      } else 
if (102k
Function->getDescribedFunctionTemplate()102k
) {
160
13
        assert(Result.getNumSubstitutedLevels() == 0 &&
161
13
               "Outer template not instantiated?");
162
13
      }
163
164
      // If this is a friend declaration and it declares an entity at
165
      // namespace scope, take arguments from its lexical parent
166
      // instead of its semantic parent, unless of course the pattern we're
167
      // instantiating actually comes from the file's context!
168
203k
      if (Function->getFriendObjectKind() &&
169
203k
          
Function->getDeclContext()->isFileContext()389
&&
170
203k
          
(372
!Pattern372
||
!Pattern->getLexicalDeclContext()->isFileContext()370
)) {
171
343
        Ctx = Function->getLexicalDeclContext();
172
343
        RelativeToPrimary = false;
173
343
        continue;
174
343
      }
175
203k
    } else 
if (const auto *21.3k
Rec21.3k
= dyn_cast<CXXRecordDecl>(Ctx)) {
176
18.4k
      if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
177
0
        assert(Result.getNumSubstitutedLevels() == 0 &&
178
0
               "Outer template not instantiated?");
179
0
        if (ClassTemplate->isMemberSpecialization())
180
0
          break;
181
0
      }
182
18.4k
    }
183
184
2.11M
    Ctx = Ctx->getParent();
185
2.11M
    RelativeToPrimary = false;
186
2.11M
  }
187
188
1.89M
  return Result;
189
1.89M
}
190
191
14.4M
bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
192
14.4M
  switch (Kind) {
193
6.68M
  case TemplateInstantiation:
194
6.70M
  case ExceptionSpecInstantiation:
195
7.90M
  case DefaultTemplateArgumentInstantiation:
196
7.91M
  case DefaultFunctionArgumentInstantiation:
197
8.43M
  case ExplicitTemplateArgumentSubstitution:
198
10.1M
  case DeducedTemplateArgumentSubstitution:
199
11.1M
  case PriorTemplateArgumentSubstitution:
200
11.1M
  case ConstraintsCheck:
201
11.1M
  case NestedRequirementConstraintsCheck:
202
11.1M
    return true;
203
204
364
  case RequirementInstantiation:
205
1.91M
  case DefaultTemplateArgumentChecking:
206
2.78M
  case DeclaringSpecialMember:
207
2.78M
  case DeclaringImplicitEqualityComparison:
208
2.95M
  case DefiningSynthesizedFunction:
209
3.33M
  case ExceptionSpecEvaluation:
210
3.33M
  case ConstraintSubstitution:
211
3.33M
  case ParameterMappingSubstitution:
212
3.33M
  case ConstraintNormalization:
213
3.33M
  case RewritingOperatorAsSpaceship:
214
3.33M
  case InitializingStructuredBinding:
215
3.33M
  case MarkingClassDllexported:
216
3.33M
  case BuildingBuiltinDumpStructCall:
217
3.33M
    return false;
218
219
  // This function should never be called when Kind's value is Memoization.
220
0
  case Memoization:
221
0
    break;
222
14.4M
  }
223
224
0
  llvm_unreachable("Invalid SynthesisKind!");
225
0
}
226
227
Sema::InstantiatingTemplate::InstantiatingTemplate(
228
    Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
229
    SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
230
    Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
231
    sema::TemplateDeductionInfo *DeductionInfo)
232
6.53M
    : SemaRef(SemaRef) {
233
  // Don't allow further instantiation if a fatal error and an uncompilable
234
  // error have occurred. Any diagnostics we might have raised will not be
235
  // visible, and we do not need to construct a correct AST.
236
6.53M
  if (SemaRef.Diags.hasFatalErrorOccurred() &&
237
6.53M
      
SemaRef.hasUncompilableErrorOccurred()3.85k
) {
238
3.84k
    Invalid = true;
239
3.84k
    return;
240
3.84k
  }
241
6.53M
  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
242
6.53M
  if (!Invalid) {
243
6.53M
    CodeSynthesisContext Inst;
244
6.53M
    Inst.Kind = Kind;
245
6.53M
    Inst.PointOfInstantiation = PointOfInstantiation;
246
6.53M
    Inst.Entity = Entity;
247
6.53M
    Inst.Template = Template;
248
6.53M
    Inst.TemplateArgs = TemplateArgs.data();
249
6.53M
    Inst.NumTemplateArgs = TemplateArgs.size();
250
6.53M
    Inst.DeductionInfo = DeductionInfo;
251
6.53M
    Inst.InstantiationRange = InstantiationRange;
252
6.53M
    SemaRef.pushCodeSynthesisContext(Inst);
253
254
6.53M
    AlreadyInstantiating = !Inst.Entity ? 
false364
:
255
6.53M
        !SemaRef.InstantiatingSpecializations
256
6.53M
             .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
257
6.53M
             .second;
258
6.53M
    atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
259
6.53M
  }
260
6.53M
}
261
262
Sema::InstantiatingTemplate::InstantiatingTemplate(
263
    Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
264
    SourceRange InstantiationRange)
265
    : InstantiatingTemplate(SemaRef,
266
                            CodeSynthesisContext::TemplateInstantiation,
267
3.23M
                            PointOfInstantiation, InstantiationRange, Entity) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Decl*, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Decl*, clang::SourceRange)
Line
Count
Source
267
3.23M
                            PointOfInstantiation, InstantiationRange, Entity) {}
268
269
Sema::InstantiatingTemplate::InstantiatingTemplate(
270
    Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
271
    ExceptionSpecification, SourceRange InstantiationRange)
272
    : InstantiatingTemplate(
273
          SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
274
6.39k
          PointOfInstantiation, InstantiationRange, Entity) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionDecl*, clang::Sema::InstantiatingTemplate::ExceptionSpecification, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionDecl*, clang::Sema::InstantiatingTemplate::ExceptionSpecification, clang::SourceRange)
Line
Count
Source
274
6.39k
          PointOfInstantiation, InstantiationRange, Entity) {}
275
276
Sema::InstantiatingTemplate::InstantiatingTemplate(
277
    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
278
    TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
279
    SourceRange InstantiationRange)
280
    : InstantiatingTemplate(
281
          SemaRef,
282
          CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
283
          PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
284
601k
          Template, TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, llvm::PointerUnion<clang::TemplateTypeParmDecl*, clang::NonTypeTemplateParmDecl*, clang::TemplateTemplateParmDecl*>, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, llvm::PointerUnion<clang::TemplateTypeParmDecl*, clang::NonTypeTemplateParmDecl*, clang::TemplateTemplateParmDecl*>, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
284
601k
          Template, TemplateArgs) {}
285
286
Sema::InstantiatingTemplate::InstantiatingTemplate(
287
    Sema &SemaRef, SourceLocation PointOfInstantiation,
288
    FunctionTemplateDecl *FunctionTemplate,
289
    ArrayRef<TemplateArgument> TemplateArgs,
290
    CodeSynthesisContext::SynthesisKind Kind,
291
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
292
    : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
293
                            InstantiationRange, FunctionTemplate, nullptr,
294
813k
                            TemplateArgs, &DeductionInfo) {
295
813k
  assert(
296
813k
    Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
297
813k
    Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
298
813k
}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionTemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::Sema::CodeSynthesisContext::SynthesisKind, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionTemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::Sema::CodeSynthesisContext::SynthesisKind, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
294
813k
                            TemplateArgs, &DeductionInfo) {
295
813k
  assert(
296
813k
    Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
297
813k
    Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
298
813k
}
299
300
Sema::InstantiatingTemplate::InstantiatingTemplate(
301
    Sema &SemaRef, SourceLocation PointOfInstantiation,
302
    TemplateDecl *Template,
303
    ArrayRef<TemplateArgument> TemplateArgs,
304
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
305
    : InstantiatingTemplate(
306
          SemaRef,
307
          CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
308
          PointOfInstantiation, InstantiationRange, Template, nullptr,
309
153k
          TemplateArgs, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
309
153k
          TemplateArgs, &DeductionInfo) {}
310
311
Sema::InstantiatingTemplate::InstantiatingTemplate(
312
    Sema &SemaRef, SourceLocation PointOfInstantiation,
313
    ClassTemplatePartialSpecializationDecl *PartialSpec,
314
    ArrayRef<TemplateArgument> TemplateArgs,
315
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
316
    : InstantiatingTemplate(
317
          SemaRef,
318
          CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
319
          PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
320
238k
          TemplateArgs, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ClassTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ClassTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
320
238k
          TemplateArgs, &DeductionInfo) {}
321
322
Sema::InstantiatingTemplate::InstantiatingTemplate(
323
    Sema &SemaRef, SourceLocation PointOfInstantiation,
324
    VarTemplatePartialSpecializationDecl *PartialSpec,
325
    ArrayRef<TemplateArgument> TemplateArgs,
326
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
327
    : InstantiatingTemplate(
328
          SemaRef,
329
          CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
330
          PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
331
895
          TemplateArgs, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::VarTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::VarTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
331
895
          TemplateArgs, &DeductionInfo) {}
332
333
Sema::InstantiatingTemplate::InstantiatingTemplate(
334
    Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
335
    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
336
    : InstantiatingTemplate(
337
          SemaRef,
338
          CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
339
          PointOfInstantiation, InstantiationRange, Param, nullptr,
340
8.20k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ParmVarDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ParmVarDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
340
8.20k
          TemplateArgs) {}
341
342
Sema::InstantiatingTemplate::InstantiatingTemplate(
343
    Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
344
    NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
345
    SourceRange InstantiationRange)
346
    : InstantiatingTemplate(
347
          SemaRef,
348
          CodeSynthesisContext::PriorTemplateArgumentSubstitution,
349
          PointOfInstantiation, InstantiationRange, Param, Template,
350
474k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::NonTypeTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::NonTypeTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
350
474k
          TemplateArgs) {}
351
352
Sema::InstantiatingTemplate::InstantiatingTemplate(
353
    Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
354
    TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
355
    SourceRange InstantiationRange)
356
    : InstantiatingTemplate(
357
          SemaRef,
358
          CodeSynthesisContext::PriorTemplateArgumentSubstitution,
359
          PointOfInstantiation, InstantiationRange, Param, Template,
360
42.8k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::TemplateTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::TemplateTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
360
42.8k
          TemplateArgs) {}
361
362
Sema::InstantiatingTemplate::InstantiatingTemplate(
363
    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
364
    NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
365
    SourceRange InstantiationRange)
366
    : InstantiatingTemplate(
367
          SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
368
          PointOfInstantiation, InstantiationRange, Param, Template,
369
958k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
369
958k
          TemplateArgs) {}
370
371
Sema::InstantiatingTemplate::InstantiatingTemplate(
372
    Sema &SemaRef, SourceLocation PointOfInstantiation,
373
    concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
374
    SourceRange InstantiationRange)
375
    : InstantiatingTemplate(
376
          SemaRef, CodeSynthesisContext::RequirementInstantiation,
377
          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
378
182
          /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::Requirement*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::Requirement*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
378
182
          /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
379
380
381
Sema::InstantiatingTemplate::InstantiatingTemplate(
382
    Sema &SemaRef, SourceLocation PointOfInstantiation,
383
    concepts::NestedRequirement *Req, ConstraintsCheck,
384
    SourceRange InstantiationRange)
385
    : InstantiatingTemplate(
386
          SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
387
          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
388
24
          /*Template=*/nullptr, /*TemplateArgs=*/None) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::NestedRequirement*, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::NestedRequirement*, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::SourceRange)
Line
Count
Source
388
24
          /*Template=*/nullptr, /*TemplateArgs=*/None) {}
389
390
391
Sema::InstantiatingTemplate::InstantiatingTemplate(
392
    Sema &SemaRef, SourceLocation PointOfInstantiation,
393
    ConstraintsCheck, NamedDecl *Template,
394
    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
395
    : InstantiatingTemplate(
396
          SemaRef, CodeSynthesisContext::ConstraintsCheck,
397
          PointOfInstantiation, InstantiationRange, Template, nullptr,
398
1.17k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
398
1.17k
          TemplateArgs) {}
399
400
Sema::InstantiatingTemplate::InstantiatingTemplate(
401
    Sema &SemaRef, SourceLocation PointOfInstantiation,
402
    ConstraintSubstitution, NamedDecl *Template,
403
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
404
    : InstantiatingTemplate(
405
          SemaRef, CodeSynthesisContext::ConstraintSubstitution,
406
          PointOfInstantiation, InstantiationRange, Template, nullptr,
407
1.05k
          {}, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintSubstitution, clang::NamedDecl*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintSubstitution, clang::NamedDecl*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
407
1.05k
          {}, &DeductionInfo) {}
408
409
Sema::InstantiatingTemplate::InstantiatingTemplate(
410
    Sema &SemaRef, SourceLocation PointOfInstantiation,
411
    ConstraintNormalization, NamedDecl *Template,
412
    SourceRange InstantiationRange)
413
    : InstantiatingTemplate(
414
          SemaRef, CodeSynthesisContext::ConstraintNormalization,
415
133
          PointOfInstantiation, InstantiationRange, Template) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintNormalization, clang::NamedDecl*, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintNormalization, clang::NamedDecl*, clang::SourceRange)
Line
Count
Source
415
133
          PointOfInstantiation, InstantiationRange, Template) {}
416
417
Sema::InstantiatingTemplate::InstantiatingTemplate(
418
    Sema &SemaRef, SourceLocation PointOfInstantiation,
419
    ParameterMappingSubstitution, NamedDecl *Template,
420
    SourceRange InstantiationRange)
421
    : InstantiatingTemplate(
422
          SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
423
146
          PointOfInstantiation, InstantiationRange, Template) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ParameterMappingSubstitution, clang::NamedDecl*, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ParameterMappingSubstitution, clang::NamedDecl*, clang::SourceRange)
Line
Count
Source
423
146
          PointOfInstantiation, InstantiationRange, Template) {}
424
425
7.24M
void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
426
7.24M
  Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
427
7.24M
  InNonInstantiationSFINAEContext = false;
428
429
7.24M
  CodeSynthesisContexts.push_back(Ctx);
430
431
7.24M
  if (!Ctx.isInstantiationRecord())
432
1.66M
    ++NonInstantiationEntries;
433
434
  // Check to see if we're low on stack space. We can't do anything about this
435
  // from here, but we can at least warn the user.
436
7.24M
  if (isStackNearlyExhausted())
437
0
    warnStackExhausted(Ctx.PointOfInstantiation);
438
7.24M
}
439
440
7.24M
void Sema::popCodeSynthesisContext() {
441
7.24M
  auto &Active = CodeSynthesisContexts.back();
442
7.24M
  if (!Active.isInstantiationRecord()) {
443
1.66M
    assert(NonInstantiationEntries > 0);
444
0
    --NonInstantiationEntries;
445
1.66M
  }
446
447
0
  InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
448
449
  // Name lookup no longer looks in this template's defining module.
450
7.24M
  assert(CodeSynthesisContexts.size() >=
451
7.24M
             CodeSynthesisContextLookupModules.size() &&
452
7.24M
         "forgot to remove a lookup module for a template instantiation");
453
7.24M
  if (CodeSynthesisContexts.size() ==
454
7.24M
      CodeSynthesisContextLookupModules.size()) {
455
1.21k
    if (Module *M = CodeSynthesisContextLookupModules.back())
456
720
      LookupModulesCache.erase(M);
457
1.21k
    CodeSynthesisContextLookupModules.pop_back();
458
1.21k
  }
459
460
  // If we've left the code synthesis context for the current context stack,
461
  // stop remembering that we've emitted that stack.
462
7.24M
  if (CodeSynthesisContexts.size() ==
463
7.24M
      LastEmittedCodeSynthesisContextDepth)
464
6.01k
    LastEmittedCodeSynthesisContextDepth = 0;
465
466
7.24M
  CodeSynthesisContexts.pop_back();
467
7.24M
}
468
469
6.53M
void Sema::InstantiatingTemplate::Clear() {
470
6.53M
  if (!Invalid) {
471
6.53M
    if (!AlreadyInstantiating) {
472
6.52M
      auto &Active = SemaRef.CodeSynthesisContexts.back();
473
6.52M
      if (Active.Entity)
474
6.52M
        SemaRef.InstantiatingSpecializations.erase(
475
6.52M
            {Active.Entity->getCanonicalDecl(), Active.Kind});
476
6.52M
    }
477
478
6.53M
    atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
479
6.53M
                  SemaRef.CodeSynthesisContexts.back());
480
481
6.53M
    SemaRef.popCodeSynthesisContext();
482
6.53M
    Invalid = true;
483
6.53M
  }
484
6.53M
}
485
486
static std::string convertCallArgsToString(Sema &S,
487
6
                                           llvm::ArrayRef<const Expr *> Args) {
488
6
  std::string Result;
489
6
  llvm::raw_string_ostream OS(Result);
490
6
  llvm::ListSeparator Comma;
491
11
  for (const Expr *Arg : Args) {
492
11
    OS << Comma;
493
11
    Arg->IgnoreParens()->printPretty(OS, nullptr,
494
11
                                     S.Context.getPrintingPolicy());
495
11
  }
496
6
  return Result;
497
6
}
498
499
bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
500
                                        SourceLocation PointOfInstantiation,
501
6.53M
                                           SourceRange InstantiationRange) {
502
6.53M
  assert(SemaRef.NonInstantiationEntries <=
503
6.53M
         SemaRef.CodeSynthesisContexts.size());
504
6.53M
  if ((SemaRef.CodeSynthesisContexts.size() -
505
6.53M
          SemaRef.NonInstantiationEntries)
506
6.53M
        <= SemaRef.getLangOpts().InstantiationDepth)
507
6.53M
    return false;
508
509
12
  SemaRef.Diag(PointOfInstantiation,
510
12
               diag::err_template_recursion_depth_exceeded)
511
12
    << SemaRef.getLangOpts().InstantiationDepth
512
12
    << InstantiationRange;
513
12
  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
514
12
    << SemaRef.getLangOpts().InstantiationDepth;
515
12
  return true;
516
6.53M
}
517
518
/// Prints the current instantiation stack through a series of
519
/// notes.
520
6.04k
void Sema::PrintInstantiationStack() {
521
  // Determine which template instantiations to skip, if any.
522
6.04k
  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
523
6.04k
  unsigned Limit = Diags.getTemplateBacktraceLimit();
524
6.04k
  if (Limit && Limit < CodeSynthesisContexts.size()) {
525
12
    SkipStart = Limit / 2 + Limit % 2;
526
12
    SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
527
12
  }
528
529
  // FIXME: In all of these cases, we need to show the template arguments
530
6.04k
  unsigned InstantiationIdx = 0;
531
6.04k
  for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
532
6.04k
         Active = CodeSynthesisContexts.rbegin(),
533
6.04k
         ActiveEnd = CodeSynthesisContexts.rend();
534
18.8k
       Active != ActiveEnd;
535
12.7k
       ++Active, ++InstantiationIdx) {
536
    // Skip this instantiation?
537
12.7k
    if (InstantiationIdx >= SkipStart && 
InstantiationIdx < SkipEnd6.22k
) {
538
6.18k
      if (InstantiationIdx == SkipStart) {
539
        // Note that we're skipping instantiations.
540
12
        Diags.Report(Active->PointOfInstantiation,
541
12
                     diag::note_instantiation_contexts_suppressed)
542
12
          << unsigned(CodeSynthesisContexts.size() - Limit);
543
12
      }
544
6.18k
      continue;
545
6.18k
    }
546
547
6.57k
    switch (Active->Kind) {
548
5.95k
    case CodeSynthesisContext::TemplateInstantiation: {
549
5.95k
      Decl *D = Active->Entity;
550
5.95k
      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
551
761
        unsigned DiagID = diag::note_template_member_class_here;
552
761
        if (isa<ClassTemplateSpecializationDecl>(Record))
553
706
          DiagID = diag::note_template_class_instantiation_here;
554
761
        Diags.Report(Active->PointOfInstantiation, DiagID)
555
761
          << Record << Active->InstantiationRange;
556
5.19k
      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
557
5.04k
        unsigned DiagID;
558
5.04k
        if (Function->getPrimaryTemplate())
559
4.08k
          DiagID = diag::note_function_template_spec_here;
560
961
        else
561
961
          DiagID = diag::note_template_member_function_here;
562
5.04k
        Diags.Report(Active->PointOfInstantiation, DiagID)
563
5.04k
          << Function
564
5.04k
          << Active->InstantiationRange;
565
5.04k
      } else 
if (VarDecl *149
VD149
= dyn_cast<VarDecl>(D)) {
566
94
        Diags.Report(Active->PointOfInstantiation,
567
94
                     VD->isStaticDataMember()?
568
73
                       diag::note_template_static_data_member_def_here
569
94
                     : 
diag::note_template_variable_def_here21
)
570
94
          << VD
571
94
          << Active->InstantiationRange;
572
94
      } else 
if (EnumDecl *55
ED55
= dyn_cast<EnumDecl>(D)) {
573
6
        Diags.Report(Active->PointOfInstantiation,
574
6
                     diag::note_template_enum_def_here)
575
6
          << ED
576
6
          << Active->InstantiationRange;
577
49
      } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
578
35
        Diags.Report(Active->PointOfInstantiation,
579
35
                     diag::note_template_nsdmi_here)
580
35
            << FD << Active->InstantiationRange;
581
35
      } else {
582
14
        Diags.Report(Active->PointOfInstantiation,
583
14
                     diag::note_template_type_alias_instantiation_here)
584
14
          << cast<TypeAliasTemplateDecl>(D)
585
14
          << Active->InstantiationRange;
586
14
      }
587
5.95k
      break;
588
0
    }
589
590
55
    case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
591
55
      TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
592
55
      SmallString<128> TemplateArgsStr;
593
55
      llvm::raw_svector_ostream OS(TemplateArgsStr);
594
55
      Template->printName(OS);
595
55
      printTemplateArgumentList(OS, Active->template_arguments(),
596
55
                                getPrintingPolicy());
597
55
      Diags.Report(Active->PointOfInstantiation,
598
55
                   diag::note_default_arg_instantiation_here)
599
55
        << OS.str()
600
55
        << Active->InstantiationRange;
601
55
      break;
602
0
    }
603
604
5
    case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
605
5
      FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
606
5
      Diags.Report(Active->PointOfInstantiation,
607
5
                   diag::note_explicit_template_arg_substitution_here)
608
5
        << FnTmpl
609
5
        << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
610
5
                                           Active->TemplateArgs,
611
5
                                           Active->NumTemplateArgs)
612
5
        << Active->InstantiationRange;
613
5
      break;
614
0
    }
615
616
90
    case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
617
90
      if (FunctionTemplateDecl *FnTmpl =
618
90
              dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
619
78
        Diags.Report(Active->PointOfInstantiation,
620
78
                     diag::note_function_template_deduction_instantiation_here)
621
78
          << FnTmpl
622
78
          << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
623
78
                                             Active->TemplateArgs,
624
78
                                             Active->NumTemplateArgs)
625
78
          << Active->InstantiationRange;
626
78
      } else {
627
12
        bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
628
12
                     isa<VarTemplateSpecializationDecl>(Active->Entity);
629
12
        bool IsTemplate = false;
630
12
        TemplateParameterList *Params;
631
12
        if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
632
0
          IsTemplate = true;
633
0
          Params = D->getTemplateParameters();
634
12
        } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
635
12
                       Active->Entity)) {
636
4
          Params = D->getTemplateParameters();
637
8
        } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
638
8
                       Active->Entity)) {
639
8
          Params = D->getTemplateParameters();
640
8
        } else {
641
0
          llvm_unreachable("unexpected template kind");
642
0
        }
643
644
12
        Diags.Report(Active->PointOfInstantiation,
645
12
                     diag::note_deduced_template_arg_substitution_here)
646
12
          << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
647
12
          << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
648
12
                                             Active->NumTemplateArgs)
649
12
          << Active->InstantiationRange;
650
12
      }
651
90
      break;
652
0
    }
653
654
75
    case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
655
75
      ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
656
75
      FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
657
658
75
      SmallString<128> TemplateArgsStr;
659
75
      llvm::raw_svector_ostream OS(TemplateArgsStr);
660
75
      FD->printName(OS);
661
75
      printTemplateArgumentList(OS, Active->template_arguments(),
662
75
                                getPrintingPolicy());
663
75
      Diags.Report(Active->PointOfInstantiation,
664
75
                   diag::note_default_function_arg_instantiation_here)
665
75
        << OS.str()
666
75
        << Active->InstantiationRange;
667
75
      break;
668
0
    }
669
670
13
    case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
671
13
      NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
672
13
      std::string Name;
673
13
      if (!Parm->getName().empty())
674
2
        Name = std::string(" '") + Parm->getName().str() + "'";
675
676
13
      TemplateParameterList *TemplateParams = nullptr;
677
13
      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
678
13
        TemplateParams = Template->getTemplateParameters();
679
0
      else
680
0
        TemplateParams =
681
0
          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
682
0
                                                      ->getTemplateParameters();
683
13
      Diags.Report(Active->PointOfInstantiation,
684
13
                   diag::note_prior_template_arg_substitution)
685
13
        << isa<TemplateTemplateParmDecl>(Parm)
686
13
        << Name
687
13
        << getTemplateArgumentBindingsText(TemplateParams,
688
13
                                           Active->TemplateArgs,
689
13
                                           Active->NumTemplateArgs)
690
13
        << Active->InstantiationRange;
691
13
      break;
692
0
    }
693
694
5
    case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
695
5
      TemplateParameterList *TemplateParams = nullptr;
696
5
      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
697
5
        TemplateParams = Template->getTemplateParameters();
698
0
      else
699
0
        TemplateParams =
700
0
          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
701
0
                                                      ->getTemplateParameters();
702
703
5
      Diags.Report(Active->PointOfInstantiation,
704
5
                   diag::note_template_default_arg_checking)
705
5
        << getTemplateArgumentBindingsText(TemplateParams,
706
5
                                           Active->TemplateArgs,
707
5
                                           Active->NumTemplateArgs)
708
5
        << Active->InstantiationRange;
709
5
      break;
710
0
    }
711
712
34
    case CodeSynthesisContext::ExceptionSpecEvaluation:
713
34
      Diags.Report(Active->PointOfInstantiation,
714
34
                   diag::note_evaluating_exception_spec_here)
715
34
          << cast<FunctionDecl>(Active->Entity);
716
34
      break;
717
718
80
    case CodeSynthesisContext::ExceptionSpecInstantiation:
719
80
      Diags.Report(Active->PointOfInstantiation,
720
80
                   diag::note_template_exception_spec_instantiation_here)
721
80
        << cast<FunctionDecl>(Active->Entity)
722
80
        << Active->InstantiationRange;
723
80
      break;
724
725
1
    case CodeSynthesisContext::RequirementInstantiation:
726
1
      Diags.Report(Active->PointOfInstantiation,
727
1
                   diag::note_template_requirement_instantiation_here)
728
1
        << Active->InstantiationRange;
729
1
      break;
730
731
0
    case CodeSynthesisContext::NestedRequirementConstraintsCheck:
732
0
      Diags.Report(Active->PointOfInstantiation,
733
0
                   diag::note_nested_requirement_here)
734
0
        << Active->InstantiationRange;
735
0
      break;
736
737
11
    case CodeSynthesisContext::DeclaringSpecialMember:
738
11
      Diags.Report(Active->PointOfInstantiation,
739
11
                   diag::note_in_declaration_of_implicit_special_member)
740
11
        << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
741
11
      break;
742
743
1
    case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
744
1
      Diags.Report(Active->Entity->getLocation(),
745
1
                   diag::note_in_declaration_of_implicit_equality_comparison);
746
1
      break;
747
748
184
    case CodeSynthesisContext::DefiningSynthesizedFunction: {
749
      // FIXME: For synthesized functions that are not defaulted,
750
      // produce a note.
751
184
      auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
752
184
      DefaultedFunctionKind DFK =
753
184
          FD ? getDefaultedFunctionKind(FD) : 
DefaultedFunctionKind()0
;
754
184
      if (DFK.isSpecialMember()) {
755
163
        auto *MD = cast<CXXMethodDecl>(FD);
756
163
        Diags.Report(Active->PointOfInstantiation,
757
163
                     diag::note_member_synthesized_at)
758
163
            << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
759
163
            << Context.getTagDeclType(MD->getParent());
760
163
      } else 
if (21
DFK.isComparison()21
) {
761
21
        Diags.Report(Active->PointOfInstantiation,
762
21
                     diag::note_comparison_synthesized_at)
763
21
            << (int)DFK.asComparison()
764
21
            << Context.getTagDeclType(
765
21
                   cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
766
21
      }
767
184
      break;
768
0
    }
769
770
3
    case CodeSynthesisContext::RewritingOperatorAsSpaceship:
771
3
      Diags.Report(Active->Entity->getLocation(),
772
3
                   diag::note_rewriting_operator_as_spaceship);
773
3
      break;
774
775
10
    case CodeSynthesisContext::InitializingStructuredBinding:
776
10
      Diags.Report(Active->PointOfInstantiation,
777
10
                   diag::note_in_binding_decl_init)
778
10
          << cast<BindingDecl>(Active->Entity);
779
10
      break;
780
781
2
    case CodeSynthesisContext::MarkingClassDllexported:
782
2
      Diags.Report(Active->PointOfInstantiation,
783
2
                   diag::note_due_to_dllexported_class)
784
2
          << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
785
2
      break;
786
787
6
    case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
788
6
      Diags.Report(Active->PointOfInstantiation,
789
6
                   diag::note_building_builtin_dump_struct_call)
790
6
          << convertCallArgsToString(
791
6
                 *this,
792
6
                 llvm::makeArrayRef(Active->CallArgs, Active->NumCallArgs));
793
6
      break;
794
795
0
    case CodeSynthesisContext::Memoization:
796
0
      break;
797
798
24
    case CodeSynthesisContext::ConstraintsCheck: {
799
24
      unsigned DiagID = 0;
800
24
      if (!Active->Entity) {
801
2
        Diags.Report(Active->PointOfInstantiation,
802
2
                     diag::note_nested_requirement_here)
803
2
          << Active->InstantiationRange;
804
2
        break;
805
2
      }
806
22
      if (isa<ConceptDecl>(Active->Entity))
807
5
        DiagID = diag::note_concept_specialization_here;
808
17
      else if (isa<TemplateDecl>(Active->Entity))
809
7
        DiagID = diag::note_checking_constraints_for_template_id_here;
810
10
      else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
811
6
        DiagID = diag::note_checking_constraints_for_var_spec_id_here;
812
4
      else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
813
2
        DiagID = diag::note_checking_constraints_for_class_spec_id_here;
814
2
      else {
815
2
        assert(isa<FunctionDecl>(Active->Entity));
816
0
        DiagID = diag::note_checking_constraints_for_function_here;
817
2
      }
818
0
      SmallString<128> TemplateArgsStr;
819
22
      llvm::raw_svector_ostream OS(TemplateArgsStr);
820
22
      cast<NamedDecl>(Active->Entity)->printName(OS);
821
22
      if (!isa<FunctionDecl>(Active->Entity)) {
822
20
        printTemplateArgumentList(OS, Active->template_arguments(),
823
20
                                  getPrintingPolicy());
824
20
      }
825
22
      Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
826
22
        << Active->InstantiationRange;
827
22
      break;
828
24
    }
829
12
    case CodeSynthesisContext::ConstraintSubstitution:
830
12
      Diags.Report(Active->PointOfInstantiation,
831
12
                   diag::note_constraint_substitution_here)
832
12
          << Active->InstantiationRange;
833
12
      break;
834
1
    case CodeSynthesisContext::ConstraintNormalization:
835
1
      Diags.Report(Active->PointOfInstantiation,
836
1
                   diag::note_constraint_normalization_here)
837
1
          << cast<NamedDecl>(Active->Entity)->getName()
838
1
          << Active->InstantiationRange;
839
1
      break;
840
1
    case CodeSynthesisContext::ParameterMappingSubstitution:
841
1
      Diags.Report(Active->PointOfInstantiation,
842
1
                   diag::note_parameter_mapping_substitution_here)
843
1
          << Active->InstantiationRange;
844
1
      break;
845
6.57k
    }
846
6.57k
  }
847
6.04k
}
848
849
5.44M
Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
850
5.44M
  if (InNonInstantiationSFINAEContext)
851
74.1k
    return Optional<TemplateDeductionInfo *>(nullptr);
852
853
5.37M
  for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
854
5.37M
         Active = CodeSynthesisContexts.rbegin(),
855
5.37M
         ActiveEnd = CodeSynthesisContexts.rend();
856
5.64M
       Active != ActiveEnd;
857
5.37M
       
++Active272k
)
858
2.37M
  {
859
2.37M
    switch (Active->Kind) {
860
1.40M
    case CodeSynthesisContext::TemplateInstantiation:
861
      // An instantiation of an alias template may or may not be a SFINAE
862
      // context, depending on what else is on the stack.
863
1.40M
      if (isa<TypeAliasTemplateDecl>(Active->Entity))
864
114k
        break;
865
1.40M
      
LLVM_FALLTHROUGH1.28M
;1.28M
866
1.28M
    case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
867
1.28M
    case CodeSynthesisContext::ExceptionSpecInstantiation:
868
1.28M
    case CodeSynthesisContext::ConstraintsCheck:
869
1.28M
    case CodeSynthesisContext::ParameterMappingSubstitution:
870
1.28M
    case CodeSynthesisContext::ConstraintNormalization:
871
1.28M
    case CodeSynthesisContext::NestedRequirementConstraintsCheck:
872
      // This is a template instantiation, so there is no SFINAE.
873
1.28M
      return None;
874
875
72.3k
    case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
876
157k
    case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
877
157k
    case CodeSynthesisContext::DefaultTemplateArgumentChecking:
878
157k
    case CodeSynthesisContext::RewritingOperatorAsSpaceship:
879
      // A default template argument instantiation and substitution into
880
      // template parameters with arguments for prior parameters may or may
881
      // not be a SFINAE context; look further up the stack.
882
157k
      break;
883
884
81.3k
    case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
885
778k
    case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
886
779k
    case CodeSynthesisContext::ConstraintSubstitution:
887
780k
    case CodeSynthesisContext::RequirementInstantiation:
888
      // We're either substituting explicitly-specified template arguments,
889
      // deduced template arguments, a constraint expression or a requirement
890
      // in a requires expression, so SFINAE applies.
891
780k
      assert(Active->DeductionInfo && "Missing deduction info pointer");
892
0
      return Active->DeductionInfo;
893
894
19.7k
    case CodeSynthesisContext::DeclaringSpecialMember:
895
19.8k
    case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
896
29.2k
    case CodeSynthesisContext::DefiningSynthesizedFunction:
897
30.0k
    case CodeSynthesisContext::InitializingStructuredBinding:
898
30.0k
    case CodeSynthesisContext::MarkingClassDllexported:
899
30.1k
    case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
900
      // This happens in a context unrelated to template instantiation, so
901
      // there is no SFINAE.
902
30.1k
      return None;
903
904
69
    case CodeSynthesisContext::ExceptionSpecEvaluation:
905
      // FIXME: This should not be treated as a SFINAE context, because
906
      // we will cache an incorrect exception specification. However, clang
907
      // bootstrap relies this! See PR31692.
908
69
      break;
909
910
0
    case CodeSynthesisContext::Memoization:
911
0
      break;
912
2.37M
    }
913
914
    // The inner context was transparent for SFINAE. If it occurred within a
915
    // non-instantiation SFINAE context, then SFINAE applies.
916
272k
    if (Active->SavedInNonInstantiationSFINAEContext)
917
3
      return Optional<TemplateDeductionInfo *>(nullptr);
918
272k
  }
919
920
3.27M
  return None;
921
5.37M
}
922
923
//===----------------------------------------------------------------------===/
924
// Template Instantiation for Types
925
//===----------------------------------------------------------------------===/
926
namespace {
927
  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
928
    const MultiLevelTemplateArgumentList &TemplateArgs;
929
    SourceLocation Loc;
930
    DeclarationName Entity;
931
932
  public:
933
    typedef TreeTransform<TemplateInstantiator> inherited;
934
935
    TemplateInstantiator(Sema &SemaRef,
936
                         const MultiLevelTemplateArgumentList &TemplateArgs,
937
                         SourceLocation Loc,
938
                         DeclarationName Entity)
939
      : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
940
9.48M
        Entity(Entity) { }
941
942
    /// Determine whether the given type \p T has already been
943
    /// transformed.
944
    ///
945
    /// For the purposes of template instantiation, a type has already been
946
    /// transformed if it is NULL or if it is not dependent.
947
    bool AlreadyTransformed(QualType T);
948
949
    /// Returns the location of the entity being instantiated, if known.
950
12.3M
    SourceLocation getBaseLocation() { return Loc; }
951
952
    /// Returns the name of the entity being instantiated, if any.
953
21.3M
    DeclarationName getBaseEntity() { return Entity; }
954
955
    /// Sets the "base" location and entity when that
956
    /// information is known based on another transformation.
957
19.3M
    void setBase(SourceLocation Loc, DeclarationName Entity) {
958
19.3M
      this->Loc = Loc;
959
19.3M
      this->Entity = Entity;
960
19.3M
    }
961
962
25
    unsigned TransformTemplateDepth(unsigned Depth) {
963
25
      return TemplateArgs.getNewDepth(Depth);
964
25
    }
965
966
    bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
967
                                 SourceRange PatternRange,
968
                                 ArrayRef<UnexpandedParameterPack> Unexpanded,
969
                                 bool &ShouldExpand, bool &RetainExpansion,
970
320k
                                 Optional<unsigned> &NumExpansions) {
971
320k
      return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
972
320k
                                                       PatternRange, Unexpanded,
973
320k
                                                       TemplateArgs,
974
320k
                                                       ShouldExpand,
975
320k
                                                       RetainExpansion,
976
320k
                                                       NumExpansions);
977
320k
    }
978
979
9.92k
    void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
980
9.92k
      SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
981
9.92k
    }
982
983
3.96k
    TemplateArgument ForgetPartiallySubstitutedPack() {
984
3.96k
      TemplateArgument Result;
985
3.96k
      if (NamedDecl *PartialPack
986
3.96k
            = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
987
3.96k
        MultiLevelTemplateArgumentList &TemplateArgs
988
3.96k
          = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
989
3.96k
        unsigned Depth, Index;
990
3.96k
        std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
991
3.96k
        if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
992
3.96k
          Result = TemplateArgs(Depth, Index);
993
3.96k
          TemplateArgs.setArgument(Depth, Index, TemplateArgument());
994
3.96k
        }
995
3.96k
      }
996
997
3.96k
      return Result;
998
3.96k
    }
999
1000
3.96k
    void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1001
3.96k
      if (Arg.isNull())
1002
0
        return;
1003
1004
3.96k
      if (NamedDecl *PartialPack
1005
3.96k
            = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1006
3.96k
        MultiLevelTemplateArgumentList &TemplateArgs
1007
3.96k
        = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1008
3.96k
        unsigned Depth, Index;
1009
3.96k
        std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1010
3.96k
        TemplateArgs.setArgument(Depth, Index, Arg);
1011
3.96k
      }
1012
3.96k
    }
1013
1014
    /// Transform the given declaration by instantiating a reference to
1015
    /// this declaration.
1016
    Decl *TransformDecl(SourceLocation Loc, Decl *D);
1017
1018
2.57k
    void transformAttrs(Decl *Old, Decl *New) {
1019
2.57k
      SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1020
2.57k
    }
1021
1022
5.53k
    void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1023
5.53k
      if (Old->isParameterPack()) {
1024
8
        SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
1025
8
        for (auto *New : NewDecls)
1026
13
          SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1027
13
              Old, cast<VarDecl>(New));
1028
8
        return;
1029
8
      }
1030
1031
5.52k
      assert(NewDecls.size() == 1 &&
1032
5.52k
             "should only have multiple expansions for a pack");
1033
0
      Decl *New = NewDecls.front();
1034
1035
      // If we've instantiated the call operator of a lambda or the call
1036
      // operator template of a generic lambda, update the "instantiation of"
1037
      // information.
1038
5.52k
      auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1039
5.52k
      if (NewMD && 
isLambdaCallOperator(NewMD)2.57k
) {
1040
2.57k
        auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1041
2.57k
        if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1042
1.40k
          NewTD->setInstantiatedFromMemberTemplate(
1043
1.40k
              OldMD->getDescribedFunctionTemplate());
1044
1.17k
        else
1045
1.17k
          NewMD->setInstantiationOfMemberFunction(OldMD,
1046
1.17k
                                                  TSK_ImplicitInstantiation);
1047
2.57k
      }
1048
1049
5.52k
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1050
1051
      // We recreated a local declaration, but not by instantiating it. There
1052
      // may be pending dependent diagnostics to produce.
1053
5.52k
      if (auto *DC = dyn_cast<DeclContext>(Old))
1054
5.15k
        SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1055
5.52k
    }
1056
1057
    /// Transform the definition of the given declaration by
1058
    /// instantiating it.
1059
    Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1060
1061
    /// Transform the first qualifier within a scope by instantiating the
1062
    /// declaration.
1063
    NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1064
1065
    /// Rebuild the exception declaration and register the declaration
1066
    /// as an instantiated local.
1067
    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1068
                                  TypeSourceInfo *Declarator,
1069
                                  SourceLocation StartLoc,
1070
                                  SourceLocation NameLoc,
1071
                                  IdentifierInfo *Name);
1072
1073
    /// Rebuild the Objective-C exception declaration and register the
1074
    /// declaration as an instantiated local.
1075
    VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1076
                                      TypeSourceInfo *TSInfo, QualType T);
1077
1078
    /// Check for tag mismatches when instantiating an
1079
    /// elaborated type.
1080
    QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1081
                                   ElaboratedTypeKeyword Keyword,
1082
                                   NestedNameSpecifierLoc QualifierLoc,
1083
                                   QualType T);
1084
1085
    TemplateName
1086
    TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1087
                          SourceLocation NameLoc,
1088
                          QualType ObjectType = QualType(),
1089
                          NamedDecl *FirstQualifierInScope = nullptr,
1090
                          bool AllowInjectedClassName = false);
1091
1092
    const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1093
1094
    ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1095
    ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1096
    ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1097
1098
    ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1099
                                            NonTypeTemplateParmDecl *D);
1100
    ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1101
                                           SubstNonTypeTemplateParmPackExpr *E);
1102
    ExprResult TransformSubstNonTypeTemplateParmExpr(
1103
                                           SubstNonTypeTemplateParmExpr *E);
1104
1105
    /// Rebuild a DeclRefExpr for a VarDecl reference.
1106
    ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1107
1108
    /// Transform a reference to a function or init-capture parameter pack.
1109
    ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1110
1111
    /// Transform a FunctionParmPackExpr which was built when we couldn't
1112
    /// expand a function parameter pack reference which refers to an expanded
1113
    /// pack.
1114
    ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1115
1116
    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1117
7.08k
                                        FunctionProtoTypeLoc TL) {
1118
      // Call the base version; it will forward to our overridden version below.
1119
7.08k
      return inherited::TransformFunctionProtoType(TLB, TL);
1120
7.08k
    }
1121
1122
    template<typename Fn>
1123
    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1124
                                        FunctionProtoTypeLoc TL,
1125
                                        CXXRecordDecl *ThisContext,
1126
                                        Qualifiers ThisTypeQuals,
1127
                                        Fn TransformExceptionSpec);
1128
1129
    ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1130
                                            int indexAdjustment,
1131
                                            Optional<unsigned> NumExpansions,
1132
                                            bool ExpectParameterPack);
1133
1134
    /// Transforms a template type parameter type by performing
1135
    /// substitution of the corresponding template type argument.
1136
    QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1137
                                           TemplateTypeParmTypeLoc TL);
1138
1139
    /// Transforms an already-substituted template type parameter pack
1140
    /// into either itself (if we aren't substituting into its pack expansion)
1141
    /// or the appropriate substituted argument.
1142
    QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1143
                                           SubstTemplateTypeParmPackTypeLoc TL);
1144
1145
2.58k
    ExprResult TransformLambdaExpr(LambdaExpr *E) {
1146
2.58k
      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1147
2.58k
      return inherited::TransformLambdaExpr(E);
1148
2.58k
    }
1149
1150
177
    ExprResult TransformRequiresExpr(RequiresExpr *E) {
1151
177
      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1152
177
      return inherited::TransformRequiresExpr(E);
1153
177
    }
1154
1155
    bool TransformRequiresExprRequirements(
1156
        ArrayRef<concepts::Requirement *> Reqs,
1157
174
        SmallVectorImpl<concepts::Requirement *> &Transformed) {
1158
174
      bool SatisfactionDetermined = false;
1159
202
      for (concepts::Requirement *Req : Reqs) {
1160
202
        concepts::Requirement *TransReq = nullptr;
1161
202
        if (!SatisfactionDetermined) {
1162
194
          if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1163
35
            TransReq = TransformTypeRequirement(TypeReq);
1164
159
          else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1165
121
            TransReq = TransformExprRequirement(ExprReq);
1166
38
          else
1167
38
            TransReq = TransformNestedRequirement(
1168
38
                cast<concepts::NestedRequirement>(Req));
1169
194
          if (!TransReq)
1170
0
            return true;
1171
194
          if (!TransReq->isDependent() && !TransReq->isSatisfied())
1172
            // [expr.prim.req]p6
1173
            //   [...]  The substitution and semantic constraint checking
1174
            //   proceeds in lexical order and stops when a condition that
1175
            //   determines the result of the requires-expression is
1176
            //   encountered. [..]
1177
102
            SatisfactionDetermined = true;
1178
194
        } else
1179
8
          TransReq = Req;
1180
202
        Transformed.push_back(TransReq);
1181
202
      }
1182
174
      return false;
1183
174
    }
1184
1185
    TemplateParameterList *TransformTemplateParameterList(
1186
2.61k
                              TemplateParameterList *OrigTPL)  {
1187
2.61k
      if (!OrigTPL || 
!OrigTPL->size()1.43k
)
return OrigTPL1.18k
;
1188
1189
1.43k
      DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1190
1.43k
      TemplateDeclInstantiator  DeclInstantiator(getSema(),
1191
1.43k
                        /* DeclContext *Owner */ Owner, TemplateArgs);
1192
1.43k
      return DeclInstantiator.SubstTemplateParams(OrigTPL);
1193
2.61k
    }
1194
1195
    concepts::TypeRequirement *
1196
    TransformTypeRequirement(concepts::TypeRequirement *Req);
1197
    concepts::ExprRequirement *
1198
    TransformExprRequirement(concepts::ExprRequirement *Req);
1199
    concepts::NestedRequirement *
1200
    TransformNestedRequirement(concepts::NestedRequirement *Req);
1201
1202
  private:
1203
    ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1204
                                               SourceLocation loc,
1205
                                               TemplateArgument arg);
1206
  };
1207
}
1208
1209
16.5M
bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1210
16.5M
  if (T.isNull())
1211
0
    return true;
1212
1213
16.5M
  if (T->isInstantiationDependentType() || 
T->isVariablyModifiedType()831k
)
1214
15.7M
    return false;
1215
1216
831k
  getSema().MarkDeclarationsReferencedInType(Loc, T);
1217
831k
  return true;
1218
16.5M
}
1219
1220
static TemplateArgument
1221
554k
getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1222
554k
  assert(S.ArgumentPackSubstitutionIndex >= 0);
1223
0
  assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1224
0
  Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1225
554k
  if (Arg.isPackExpansion())
1226
56.6k
    Arg = Arg.getPackExpansionPattern();
1227
554k
  return Arg;
1228
554k
}
1229
1230
8.41M
Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1231
8.41M
  if (!D)
1232
129k
    return nullptr;
1233
1234
8.28M
  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1235
9.84k
    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1236
      // If the corresponding template argument is NULL or non-existent, it's
1237
      // because we are performing instantiation from explicitly-specified
1238
      // template arguments in a function template, but there were some
1239
      // arguments left unspecified.
1240
0
      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1241
0
                                            TTP->getPosition()))
1242
0
        return D;
1243
1244
0
      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1245
1246
0
      if (TTP->isParameterPack()) {
1247
0
        assert(Arg.getKind() == TemplateArgument::Pack &&
1248
0
               "Missing argument pack");
1249
0
        Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1250
0
      }
1251
1252
0
      TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1253
0
      assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1254
0
             "Wrong kind of template template argument");
1255
0
      return Template.getAsTemplateDecl();
1256
0
    }
1257
1258
    // Fall through to find the instantiated declaration for this template
1259
    // template parameter.
1260
9.84k
  }
1261
1262
8.28M
  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1263
8.28M
}
1264
1265
147k
Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1266
147k
  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1267
147k
  if (!Inst)
1268
158
    return nullptr;
1269
1270
147k
  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1271
147k
  return Inst;
1272
147k
}
1273
1274
NamedDecl *
1275
TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1276
129k
                                                     SourceLocation Loc) {
1277
  // If the first part of the nested-name-specifier was a template type
1278
  // parameter, instantiate that type parameter down to a tag type.
1279
129k
  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1280
13
    const TemplateTypeParmType *TTP
1281
13
      = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1282
1283
13
    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1284
      // FIXME: This needs testing w/ member access expressions.
1285
12
      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1286
1287
12
      if (TTP->isParameterPack()) {
1288
0
        assert(Arg.getKind() == TemplateArgument::Pack &&
1289
0
               "Missing argument pack");
1290
1291
0
        if (getSema().ArgumentPackSubstitutionIndex == -1)
1292
0
          return nullptr;
1293
1294
0
        Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1295
0
      }
1296
1297
12
      QualType T = Arg.getAsType();
1298
12
      if (T.isNull())
1299
0
        return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1300
1301
12
      if (const TagType *Tag = T->getAs<TagType>())
1302
12
        return Tag->getDecl();
1303
1304
      // The resulting type is not a tag; complain.
1305
0
      getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1306
0
      return nullptr;
1307
12
    }
1308
13
  }
1309
1310
129k
  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1311
129k
}
1312
1313
VarDecl *
1314
TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1315
                                           TypeSourceInfo *Declarator,
1316
                                           SourceLocation StartLoc,
1317
                                           SourceLocation NameLoc,
1318
12
                                           IdentifierInfo *Name) {
1319
12
  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1320
12
                                                 StartLoc, NameLoc, Name);
1321
12
  if (Var)
1322
12
    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1323
12
  return Var;
1324
12
}
1325
1326
VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1327
                                                        TypeSourceInfo *TSInfo,
1328
2
                                                        QualType T) {
1329
2
  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1330
2
  if (Var)
1331
2
    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1332
2
  return Var;
1333
2
}
1334
1335
QualType
1336
TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1337
                                            ElaboratedTypeKeyword Keyword,
1338
                                            NestedNameSpecifierLoc QualifierLoc,
1339
34.8k
                                            QualType T) {
1340
34.8k
  if (const TagType *TT = T->getAs<TagType>()) {
1341
25.0k
    TagDecl* TD = TT->getDecl();
1342
1343
25.0k
    SourceLocation TagLocation = KeywordLoc;
1344
1345
25.0k
    IdentifierInfo *Id = TD->getIdentifier();
1346
1347
    // TODO: should we even warn on struct/class mismatches for this?  Seems
1348
    // like it's likely to produce a lot of spurious errors.
1349
25.0k
    if (Id && 
Keyword != ETK_None22.2k
&&
Keyword != ETK_Typename2.10k
) {
1350
1.44k
      TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1351
1.44k
      if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1352
1.44k
                                                TagLocation, Id)) {
1353
0
        SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1354
0
          << Id
1355
0
          << FixItHint::CreateReplacement(SourceRange(TagLocation),
1356
0
                                          TD->getKindName());
1357
0
        SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1358
0
      }
1359
1.44k
    }
1360
25.0k
  }
1361
1362
34.8k
  return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1363
34.8k
}
1364
1365
TemplateName TemplateInstantiator::TransformTemplateName(
1366
    CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1367
    QualType ObjectType, NamedDecl *FirstQualifierInScope,
1368
3.78M
    bool AllowInjectedClassName) {
1369
3.78M
  if (TemplateTemplateParmDecl *TTP
1370
3.78M
       = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1371
36.9k
    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1372
      // If the corresponding template argument is NULL or non-existent, it's
1373
      // because we are performing instantiation from explicitly-specified
1374
      // template arguments in a function template, but there were some
1375
      // arguments left unspecified.
1376
27.0k
      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1377
27.0k
                                            TTP->getPosition()))
1378
7
        return Name;
1379
1380
27.0k
      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1381
1382
27.0k
      if (TemplateArgs.isRewrite()) {
1383
        // We're rewriting the template parameter as a reference to another
1384
        // template parameter.
1385
202
        if (Arg.getKind() == TemplateArgument::Pack) {
1386
1
          assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1387
1
                 "unexpected pack arguments in template rewrite");
1388
0
          Arg = Arg.pack_begin()->getPackExpansionPattern();
1389
1
        }
1390
0
        assert(Arg.getKind() == TemplateArgument::Template &&
1391
202
               "unexpected nontype template argument kind in template rewrite");
1392
0
        return Arg.getAsTemplate();
1393
202
      }
1394
1395
26.8k
      if (TTP->isParameterPack()) {
1396
16.4k
        assert(Arg.getKind() == TemplateArgument::Pack &&
1397
16.4k
               "Missing argument pack");
1398
1399
16.4k
        if (getSema().ArgumentPackSubstitutionIndex == -1) {
1400
          // We have the template argument pack to substitute, but we're not
1401
          // actually expanding the enclosing pack expansion yet. So, just
1402
          // keep the entire argument pack.
1403
6
          return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1404
6
        }
1405
1406
16.4k
        Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1407
16.4k
      }
1408
1409
26.8k
      TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1410
26.8k
      assert(!Template.isNull() && "Null template template argument");
1411
0
      assert(!Template.getAsQualifiedTemplateName() &&
1412
26.8k
             "template decl to substitute is qualified?");
1413
1414
0
      Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1415
26.8k
      return Template;
1416
26.8k
    }
1417
36.9k
  }
1418
1419
3.75M
  if (SubstTemplateTemplateParmPackStorage *SubstPack
1420
3.75M
      = Name.getAsSubstTemplateTemplateParmPack()) {
1421
3
    if (getSema().ArgumentPackSubstitutionIndex == -1)
1422
0
      return Name;
1423
1424
3
    TemplateArgument Arg = SubstPack->getArgumentPack();
1425
3
    Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1426
3
    return Arg.getAsTemplate().getNameToSubstitute();
1427
3
  }
1428
1429
3.75M
  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1430
3.75M
                                          FirstQualifierInScope,
1431
3.75M
                                          AllowInjectedClassName);
1432
3.75M
}
1433
1434
ExprResult
1435
75
TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1436
75
  if (!E->isTypeDependent())
1437
0
    return E;
1438
1439
75
  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1440
75
}
1441
1442
ExprResult
1443
TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1444
822k
                                               NonTypeTemplateParmDecl *NTTP) {
1445
  // If the corresponding template argument is NULL or non-existent, it's
1446
  // because we are performing instantiation from explicitly-specified
1447
  // template arguments in a function template, but there were some
1448
  // arguments left unspecified.
1449
822k
  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1450
822k
                                        NTTP->getPosition()))
1451
2.51k
    return E;
1452
1453
819k
  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1454
1455
819k
  if (TemplateArgs.isRewrite()) {
1456
    // We're rewriting the template parameter as a reference to another
1457
    // template parameter.
1458
67
    if (Arg.getKind() == TemplateArgument::Pack) {
1459
25
      assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1460
25
             "unexpected pack arguments in template rewrite");
1461
0
      Arg = Arg.pack_begin()->getPackExpansionPattern();
1462
25
    }
1463
0
    assert(Arg.getKind() == TemplateArgument::Expression &&
1464
67
           "unexpected nontype template argument kind in template rewrite");
1465
    // FIXME: This can lead to the same subexpression appearing multiple times
1466
    // in a complete expression.
1467
0
    return Arg.getAsExpr();
1468
67
  }
1469
1470
819k
  if (NTTP->isParameterPack()) {
1471
24.5k
    assert(Arg.getKind() == TemplateArgument::Pack &&
1472
24.5k
           "Missing argument pack");
1473
1474
24.5k
    if (getSema().ArgumentPackSubstitutionIndex == -1) {
1475
      // We have an argument pack, but we can't select a particular argument
1476
      // out of it yet. Therefore, we'll build an expression to hold on to that
1477
      // argument pack.
1478
53
      QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1479
53
                                              E->getLocation(),
1480
53
                                              NTTP->getDeclName());
1481
53
      if (TargetType.isNull())
1482
0
        return ExprError();
1483
1484
53
      QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1485
53
      if (TargetType->isRecordType())
1486
0
        ExprType.addConst();
1487
1488
53
      return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1489
53
          ExprType, TargetType->isReferenceType() ? 
VK_LValue2
:
VK_PRValue51
,
1490
53
          NTTP, E->getLocation(), Arg);
1491
53
    }
1492
1493
24.4k
    Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1494
24.4k
  }
1495
1496
819k
  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1497
819k
}
1498
1499
const LoopHintAttr *
1500
46
TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1501
46
  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1502
1503
46
  if (TransformedExpr == LH->getValue())
1504
11
    return LH;
1505
1506
  // Generate error if there is a problem with the value.
1507
35
  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1508
8
    return LH;
1509
1510
  // Create new LoopHintValueAttr with integral expression in place of the
1511
  // non-type template parameter.
1512
27
  return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1513
27
                                      LH->getState(), TransformedExpr, *LH);
1514
35
}
1515
1516
ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1517
                                                 NonTypeTemplateParmDecl *parm,
1518
                                                 SourceLocation loc,
1519
821k
                                                 TemplateArgument arg) {
1520
821k
  ExprResult result;
1521
1522
  // Determine the substituted parameter type. We can usually infer this from
1523
  // the template argument, but not always.
1524
821k
  auto SubstParamType = [&] {
1525
2
    QualType T;
1526
2
    if (parm->isExpandedParameterPack())
1527
0
      T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1528
2
    else
1529
2
      T = parm->getType();
1530
2
    if (parm->isParameterPack() && 
isa<PackExpansionType>(T)0
)
1531
0
      T = cast<PackExpansionType>(T)->getPattern();
1532
2
    return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1533
2
  };
1534
1535
821k
  bool refParam = false;
1536
1537
  // The template argument itself might be an expression, in which case we just
1538
  // return that expression. This happens when substituting into an alias
1539
  // template.
1540
821k
  if (arg.getKind() == TemplateArgument::Expression) {
1541
315k
    Expr *argExpr = arg.getAsExpr();
1542
315k
    result = argExpr;
1543
315k
    if (argExpr->isLValue()) {
1544
6
      if (argExpr->getType()->isRecordType()) {
1545
        // Check whether the parameter was actually a reference.
1546
2
        QualType paramType = SubstParamType();
1547
2
        if (paramType.isNull())
1548
0
          return ExprError();
1549
2
        refParam = paramType->isReferenceType();
1550
4
      } else {
1551
4
        refParam = true;
1552
4
      }
1553
6
    }
1554
505k
  } else if (arg.getKind() == TemplateArgument::Declaration ||
1555
505k
             
arg.getKind() == TemplateArgument::NullPtr504k
) {
1556
1.51k
    ValueDecl *VD;
1557
1.51k
    if (arg.getKind() == TemplateArgument::Declaration) {
1558
1.44k
      VD = arg.getAsDecl();
1559
1560
      // Find the instantiation of the template argument.  This is
1561
      // required for nested templates.
1562
1.44k
      VD = cast_or_null<ValueDecl>(
1563
1.44k
             getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1564
1.44k
      if (!VD)
1565
0
        return ExprError();
1566
1.44k
    } else {
1567
      // Propagate NULL template argument.
1568
70
      VD = nullptr;
1569
70
    }
1570
1571
1.51k
    QualType paramType = VD ? 
arg.getParamTypeForDecl()1.44k
:
arg.getNullPtrType()70
;
1572
1.51k
    assert(!paramType.isNull() && "type substitution failed for param type");
1573
0
    assert(!paramType->isDependentType() && "param type still dependent");
1574
0
    result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
1575
1.51k
    refParam = paramType->isReferenceType();
1576
503k
  } else {
1577
503k
    result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1578
503k
    assert(result.isInvalid() ||
1579
503k
           SemaRef.Context.hasSameType(result.get()->getType(),
1580
503k
                                       arg.getIntegralType()));
1581
503k
  }
1582
1583
821k
  if (result.isInvalid())
1584
2
    return ExprError();
1585
1586
821k
  Expr *resultExpr = result.get();
1587
821k
  return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1588
821k
      resultExpr->getType(), resultExpr->getValueKind(), loc, parm, refParam,
1589
821k
      resultExpr);
1590
821k
}
1591
1592
ExprResult
1593
TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1594
145
                                          SubstNonTypeTemplateParmPackExpr *E) {
1595
145
  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1596
    // We aren't expanding the parameter pack, so just return ourselves.
1597
0
    return E;
1598
0
  }
1599
1600
145
  TemplateArgument Arg = E->getArgumentPack();
1601
145
  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1602
145
  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1603
145
                                         E->getParameterPackLocation(),
1604
145
                                         Arg);
1605
145
}
1606
1607
ExprResult
1608
TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1609
1.09k
                                          SubstNonTypeTemplateParmExpr *E) {
1610
1.09k
  ExprResult SubstReplacement = E->getReplacement();
1611
1.09k
  if (!isa<ConstantExpr>(SubstReplacement.get()))
1612
1.09k
    SubstReplacement = TransformExpr(E->getReplacement());
1613
1.09k
  if (SubstReplacement.isInvalid())
1614
0
    return true;
1615
1.09k
  QualType SubstType = TransformType(E->getParameterType(getSema().Context));
1616
1.09k
  if (SubstType.isNull())
1617
0
    return true;
1618
  // The type may have been previously dependent and not now, which means we
1619
  // might have to implicit cast the argument to the new type, for example:
1620
  // template<auto T, decltype(T) U>
1621
  // concept C = sizeof(U) == 4;
1622
  // void foo() requires C<2, 'a'> { }
1623
  // When normalizing foo(), we first form the normalized constraints of C:
1624
  // AtomicExpr(sizeof(U) == 4,
1625
  //            U=SubstNonTypeTemplateParmExpr(Param=U,
1626
  //                                           Expr=DeclRef(U),
1627
  //                                           Type=decltype(T)))
1628
  // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1629
  // produce:
1630
  // AtomicExpr(sizeof(U) == 4,
1631
  //            U=SubstNonTypeTemplateParmExpr(Param=U,
1632
  //                                           Expr=ImpCast(
1633
  //                                               decltype(2),
1634
  //                                               SubstNTTPE(Param=U, Expr='a',
1635
  //                                                          Type=char)),
1636
  //                                           Type=decltype(2)))
1637
  // The call to CheckTemplateArgument here produces the ImpCast.
1638
1.09k
  TemplateArgument Converted;
1639
1.09k
  if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType,
1640
1.09k
                                    SubstReplacement.get(),
1641
1.09k
                                    Converted).isInvalid())
1642
0
    return true;
1643
1.09k
  return transformNonTypeTemplateParmRef(E->getParameter(),
1644
1.09k
                                         E->getExprLoc(), Converted);
1645
1.09k
}
1646
1647
ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1648
11.0k
                                                       SourceLocation Loc) {
1649
11.0k
  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1650
11.0k
  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1651
11.0k
}
1652
1653
ExprResult
1654
55
TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1655
55
  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1656
    // We can expand this parameter pack now.
1657
54
    VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1658
54
    VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1659
54
    if (!VD)
1660
0
      return ExprError();
1661
54
    return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1662
54
  }
1663
1664
1
  QualType T = TransformType(E->getType());
1665
1
  if (T.isNull())
1666
0
    return ExprError();
1667
1668
  // Transform each of the parameter expansions into the corresponding
1669
  // parameters in the instantiation of the function decl.
1670
1
  SmallVector<VarDecl *, 8> Vars;
1671
1
  Vars.reserve(E->getNumExpansions());
1672
1
  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1673
3
       I != End; 
++I2
) {
1674
2
    VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1675
2
    if (!D)
1676
0
      return ExprError();
1677
2
    Vars.push_back(D);
1678
2
  }
1679
1680
1
  auto *PackExpr =
1681
1
      FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1682
1
                                   E->getParameterPackLocation(), Vars);
1683
1
  getSema().MarkFunctionParmPackReferenced(PackExpr);
1684
1
  return PackExpr;
1685
1
}
1686
1687
ExprResult
1688
TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1689
11.2k
                                                       VarDecl *PD) {
1690
11.2k
  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1691
11.2k
  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1692
11.2k
    = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1693
11.2k
  assert(Found && "no instantiation for parameter pack");
1694
1695
0
  Decl *TransformedDecl;
1696
11.2k
  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1697
    // If this is a reference to a function parameter pack which we can
1698
    // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1699
10.8k
    if (getSema().ArgumentPackSubstitutionIndex == -1) {
1700
228
      QualType T = TransformType(E->getType());
1701
228
      if (T.isNull())
1702
0
        return ExprError();
1703
228
      auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1704
228
                                                    E->getExprLoc(), *Pack);
1705
228
      getSema().MarkFunctionParmPackReferenced(PackExpr);
1706
228
      return PackExpr;
1707
228
    }
1708
1709
10.6k
    TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1710
10.6k
  } else {
1711
367
    TransformedDecl = Found->get<Decl*>();
1712
367
  }
1713
1714
  // We have either an unexpanded pack or a specific expansion.
1715
11.0k
  return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1716
11.2k
}
1717
1718
ExprResult
1719
1.84M
TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1720
1.84M
  NamedDecl *D = E->getDecl();
1721
1722
  // Handle references to non-type template parameters and non-type template
1723
  // parameter packs.
1724
1.84M
  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1725
892k
    if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1726
822k
      return TransformTemplateParmRefExpr(E, NTTP);
1727
1728
    // We have a non-type template parameter that isn't fully substituted;
1729
    // FindInstantiatedDecl will find it in the local instantiation scope.
1730
892k
  }
1731
1732
  // Handle references to function parameter packs.
1733
1.01M
  if (VarDecl *PD = dyn_cast<VarDecl>(D))
1734
838k
    if (PD->isParameterPack())
1735
11.2k
      return TransformFunctionParmPackRefExpr(E, PD);
1736
1737
1.00M
  return inherited::TransformDeclRefExpr(E);
1738
1.01M
}
1739
1740
ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1741
0
    CXXDefaultArgExpr *E) {
1742
0
  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1743
0
             getDescribedFunctionTemplate() &&
1744
0
         "Default arg expressions are never formed in dependent cases.");
1745
0
  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1746
0
                           cast<FunctionDecl>(E->getParam()->getDeclContext()),
1747
0
                                        E->getParam());
1748
0
}
1749
1750
template<typename Fn>
1751
QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1752
                                 FunctionProtoTypeLoc TL,
1753
                                 CXXRecordDecl *ThisContext,
1754
                                 Qualifiers ThisTypeQuals,
1755
1.02M
                                 Fn TransformExceptionSpec) {
1756
  // We need a local instantiation scope for this function prototype.
1757
1.02M
  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1758
1.02M
  return inherited::TransformFunctionProtoType(
1759
1.02M
      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1760
1.02M
}
SemaTemplateInstantiate.cpp:clang::QualType (anonymous namespace)::TemplateInstantiator::TransformFunctionProtoType<clang::TreeTransform<(anonymous namespace)::TemplateInstantiator>::TransformFunctionProtoType(clang::TypeLocBuilder&, clang::FunctionProtoTypeLoc)::'lambda'(clang::FunctionProtoType::ExceptionSpecInfo&, bool&)>(clang::TypeLocBuilder&, clang::FunctionProtoTypeLoc, clang::CXXRecordDecl*, clang::Qualifiers, (anonymous namespace)::TemplateInstantiator)
Line
Count
Source
1755
7.08k
                                 Fn TransformExceptionSpec) {
1756
  // We need a local instantiation scope for this function prototype.
1757
7.08k
  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1758
7.08k
  return inherited::TransformFunctionProtoType(
1759
7.08k
      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1760
7.08k
}
SemaTemplateInstantiate.cpp:clang::QualType (anonymous namespace)::TemplateInstantiator::TransformFunctionProtoType<clang::Sema::SubstFunctionDeclType(clang::TypeSourceInfo*, clang::MultiLevelTemplateArgumentList const&, clang::SourceLocation, clang::DeclarationName, clang::CXXRecordDecl*, clang::Qualifiers)::$_0>(clang::TypeLocBuilder&, clang::FunctionProtoTypeLoc, clang::CXXRecordDecl*, clang::Qualifiers, clang::Sema::SubstFunctionDeclType(clang::TypeSourceInfo*, clang::MultiLevelTemplateArgumentList const&, clang::SourceLocation, clang::DeclarationName, clang::CXXRecordDecl*, clang::Qualifiers)::$_0)
Line
Count
Source
1755
1.01M
                                 Fn TransformExceptionSpec) {
1756
  // We need a local instantiation scope for this function prototype.
1757
1.01M
  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1758
1.01M
  return inherited::TransformFunctionProtoType(
1759
1.01M
      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1760
1.01M
}
1761
1762
ParmVarDecl *
1763
TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1764
                                                 int indexAdjustment,
1765
                                               Optional<unsigned> NumExpansions,
1766
1.53M
                                                 bool ExpectParameterPack) {
1767
1.53M
  auto NewParm =
1768
1.53M
      SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1769
1.53M
                               NumExpansions, ExpectParameterPack);
1770
1.53M
  if (NewParm && 
SemaRef.getLangOpts().OpenCL1.50M
)
1771
23
    SemaRef.deduceOpenCLAddressSpace(NewParm);
1772
1.53M
  return NewParm;
1773
1.53M
}
1774
1775
QualType
1776
TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1777
5.30M
                                                TemplateTypeParmTypeLoc TL) {
1778
5.30M
  const TemplateTypeParmType *T = TL.getTypePtr();
1779
5.30M
  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1780
    // Replace the template type parameter with its corresponding
1781
    // template argument.
1782
1783
    // If the corresponding template argument is NULL or doesn't exist, it's
1784
    // because we are performing instantiation from explicitly-specified
1785
    // template arguments in a function template class, but there were some
1786
    // arguments left unspecified.
1787
4.81M
    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1788
45.1k
      TemplateTypeParmTypeLoc NewTL
1789
45.1k
        = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1790
45.1k
      NewTL.setNameLoc(TL.getNameLoc());
1791
45.1k
      return TL.getType();
1792
45.1k
    }
1793
1794
4.76M
    TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1795
1796
4.76M
    if (TemplateArgs.isRewrite()) {
1797
      // We're rewriting the template parameter as a reference to another
1798
      // template parameter.
1799
2.44k
      if (Arg.getKind() == TemplateArgument::Pack) {
1800
601
        assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1801
601
               "unexpected pack arguments in template rewrite");
1802
0
        Arg = Arg.pack_begin()->getPackExpansionPattern();
1803
601
      }
1804
0
      assert(Arg.getKind() == TemplateArgument::Type &&
1805
2.44k
             "unexpected nontype template argument kind in template rewrite");
1806
0
      QualType NewT = Arg.getAsType();
1807
2.44k
      assert(isa<TemplateTypeParmType>(NewT) &&
1808
2.44k
             "type parm not rewritten to type parm");
1809
0
      auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
1810
2.44k
      NewTL.setNameLoc(TL.getNameLoc());
1811
2.44k
      return NewT;
1812
2.44k
    }
1813
1814
4.76M
    if (T->isParameterPack()) {
1815
551k
      assert(Arg.getKind() == TemplateArgument::Pack &&
1816
551k
             "Missing argument pack");
1817
1818
551k
      if (getSema().ArgumentPackSubstitutionIndex == -1) {
1819
        // We have the template argument pack, but we're not expanding the
1820
        // enclosing pack expansion yet. Just save the template argument
1821
        // pack for later substitution.
1822
41.6k
        QualType Result
1823
41.6k
          = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1824
41.6k
        SubstTemplateTypeParmPackTypeLoc NewTL
1825
41.6k
          = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1826
41.6k
        NewTL.setNameLoc(TL.getNameLoc());
1827
41.6k
        return Result;
1828
41.6k
      }
1829
1830
509k
      Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1831
509k
    }
1832
1833
4.72M
    assert(Arg.getKind() == TemplateArgument::Type &&
1834
4.72M
           "Template argument kind mismatch");
1835
1836
0
    QualType Replacement = Arg.getAsType();
1837
1838
    // TODO: only do this uniquing once, at the start of instantiation.
1839
4.72M
    QualType Result
1840
4.72M
      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1841
4.72M
    SubstTemplateTypeParmTypeLoc NewTL
1842
4.72M
      = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1843
4.72M
    NewTL.setNameLoc(TL.getNameLoc());
1844
4.72M
    return Result;
1845
4.76M
  }
1846
1847
  // The template type parameter comes from an inner template (e.g.,
1848
  // the template parameter list of a member template inside the
1849
  // template we are instantiating). Create a new template type
1850
  // parameter with the template "level" reduced by one.
1851
488k
  TemplateTypeParmDecl *NewTTPDecl = nullptr;
1852
488k
  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1853
488k
    NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1854
488k
                                  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1855
1856
488k
  QualType Result = getSema().Context.getTemplateTypeParmType(
1857
488k
      T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1858
488k
      T->isParameterPack(), NewTTPDecl);
1859
488k
  TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1860
488k
  NewTL.setNameLoc(TL.getNameLoc());
1861
488k
  return Result;
1862
5.30M
}
1863
1864
QualType
1865
TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1866
                                                            TypeLocBuilder &TLB,
1867
3.36k
                                         SubstTemplateTypeParmPackTypeLoc TL) {
1868
3.36k
  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1869
    // We aren't expanding the parameter pack, so just return ourselves.
1870
7
    SubstTemplateTypeParmPackTypeLoc NewTL
1871
7
      = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1872
7
    NewTL.setNameLoc(TL.getNameLoc());
1873
7
    return TL.getType();
1874
7
  }
1875
1876
3.35k
  TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1877
3.35k
  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1878
3.35k
  QualType Result = Arg.getAsType();
1879
1880
3.35k
  Result = getSema().Context.getSubstTemplateTypeParmType(
1881
3.35k
                                      TL.getTypePtr()->getReplacedParameter(),
1882
3.35k
                                                          Result);
1883
3.35k
  SubstTemplateTypeParmTypeLoc NewTL
1884
3.35k
    = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1885
3.35k
  NewTL.setNameLoc(TL.getNameLoc());
1886
3.35k
  return Result;
1887
3.36k
}
1888
1889
template<typename EntityPrinter>
1890
static concepts::Requirement::SubstitutionDiagnostic *
1891
68
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1892
68
  SmallString<128> Message;
1893
68
  SourceLocation ErrorLoc;
1894
68
  if (Info.hasSFINAEDiagnostic()) {
1895
67
    PartialDiagnosticAt PDA(SourceLocation(),
1896
67
                            PartialDiagnostic::NullDiagnostic{});
1897
67
    Info.takeSFINAEDiagnostic(PDA);
1898
67
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1899
67
    ErrorLoc = PDA.first;
1900
67
  } else {
1901
1
    ErrorLoc = Info.getLocation();
1902
1
  }
1903
68
  char *MessageBuf = new (S.Context) char[Message.size()];
1904
68
  std::copy(Message.begin(), Message.end(), MessageBuf);
1905
68
  SmallString<128> Entity;
1906
68
  llvm::raw_svector_ostream OS(Entity);
1907
68
  Printer(OS);
1908
68
  char *EntityBuf = new (S.Context) char[Entity.size()];
1909
68
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1910
68
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1911
68
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1912
68
      StringRef(MessageBuf, Message.size())};
1913
68
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformTypeRequirement(clang::concepts::TypeRequirement*)::$_2>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformTypeRequirement(clang::concepts::TypeRequirement*)::$_2)
Line
Count
Source
1891
19
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1892
19
  SmallString<128> Message;
1893
19
  SourceLocation ErrorLoc;
1894
19
  if (Info.hasSFINAEDiagnostic()) {
1895
18
    PartialDiagnosticAt PDA(SourceLocation(),
1896
18
                            PartialDiagnostic::NullDiagnostic{});
1897
18
    Info.takeSFINAEDiagnostic(PDA);
1898
18
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1899
18
    ErrorLoc = PDA.first;
1900
18
  } else {
1901
1
    ErrorLoc = Info.getLocation();
1902
1
  }
1903
19
  char *MessageBuf = new (S.Context) char[Message.size()];
1904
19
  std::copy(Message.begin(), Message.end(), MessageBuf);
1905
19
  SmallString<128> Entity;
1906
19
  llvm::raw_svector_ostream OS(Entity);
1907
19
  Printer(OS);
1908
19
  char *EntityBuf = new (S.Context) char[Entity.size()];
1909
19
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1910
19
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1911
19
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1912
19
      StringRef(MessageBuf, Message.size())};
1913
19
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_3>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_3)
Line
Count
Source
1891
42
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1892
42
  SmallString<128> Message;
1893
42
  SourceLocation ErrorLoc;
1894
42
  if (Info.hasSFINAEDiagnostic()) {
1895
42
    PartialDiagnosticAt PDA(SourceLocation(),
1896
42
                            PartialDiagnostic::NullDiagnostic{});
1897
42
    Info.takeSFINAEDiagnostic(PDA);
1898
42
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1899
42
    ErrorLoc = PDA.first;
1900
42
  } else {
1901
0
    ErrorLoc = Info.getLocation();
1902
0
  }
1903
42
  char *MessageBuf = new (S.Context) char[Message.size()];
1904
42
  std::copy(Message.begin(), Message.end(), MessageBuf);
1905
42
  SmallString<128> Entity;
1906
42
  llvm::raw_svector_ostream OS(Entity);
1907
42
  Printer(OS);
1908
42
  char *EntityBuf = new (S.Context) char[Entity.size()];
1909
42
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1910
42
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1911
42
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1912
42
      StringRef(MessageBuf, Message.size())};
1913
42
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_4>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_4)
Line
Count
Source
1891
4
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1892
4
  SmallString<128> Message;
1893
4
  SourceLocation ErrorLoc;
1894
4
  if (Info.hasSFINAEDiagnostic()) {
1895
4
    PartialDiagnosticAt PDA(SourceLocation(),
1896
4
                            PartialDiagnostic::NullDiagnostic{});
1897
4
    Info.takeSFINAEDiagnostic(PDA);
1898
4
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1899
4
    ErrorLoc = PDA.first;
1900
4
  } else {
1901
0
    ErrorLoc = Info.getLocation();
1902
0
  }
1903
4
  char *MessageBuf = new (S.Context) char[Message.size()];
1904
4
  std::copy(Message.begin(), Message.end(), MessageBuf);
1905
4
  SmallString<128> Entity;
1906
4
  llvm::raw_svector_ostream OS(Entity);
1907
4
  Printer(OS);
1908
4
  char *EntityBuf = new (S.Context) char[Entity.size()];
1909
4
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1910
4
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1911
4
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1912
4
      StringRef(MessageBuf, Message.size())};
1913
4
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformNestedRequirement(clang::concepts::NestedRequirement*)::$_5>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformNestedRequirement(clang::concepts::NestedRequirement*)::$_5)
Line
Count
Source
1891
3
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1892
3
  SmallString<128> Message;
1893
3
  SourceLocation ErrorLoc;
1894
3
  if (Info.hasSFINAEDiagnostic()) {
1895
3
    PartialDiagnosticAt PDA(SourceLocation(),
1896
3
                            PartialDiagnostic::NullDiagnostic{});
1897
3
    Info.takeSFINAEDiagnostic(PDA);
1898
3
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1899
3
    ErrorLoc = PDA.first;
1900
3
  } else {
1901
0
    ErrorLoc = Info.getLocation();
1902
0
  }
1903
3
  char *MessageBuf = new (S.Context) char[Message.size()];
1904
3
  std::copy(Message.begin(), Message.end(), MessageBuf);
1905
3
  SmallString<128> Entity;
1906
3
  llvm::raw_svector_ostream OS(Entity);
1907
3
  Printer(OS);
1908
3
  char *EntityBuf = new (S.Context) char[Entity.size()];
1909
3
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1910
3
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1911
3
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1912
3
      StringRef(MessageBuf, Message.size())};
1913
3
}
1914
1915
concepts::TypeRequirement *
1916
35
TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
1917
35
  if (!Req->isDependent() && 
!AlwaysRebuild()1
)
1918
1
    return Req;
1919
34
  if (Req->isSubstitutionFailure()) {
1920
0
    if (AlwaysRebuild())
1921
0
      return RebuildTypeRequirement(
1922
0
              Req->getSubstitutionDiagnostic());
1923
0
    return Req;
1924
0
  }
1925
1926
34
  Sema::SFINAETrap Trap(SemaRef);
1927
34
  TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
1928
34
  Sema::InstantiatingTemplate TypeInst(SemaRef,
1929
34
      Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
1930
34
      Req->getType()->getTypeLoc().getSourceRange());
1931
34
  if (TypeInst.isInvalid())
1932
0
    return nullptr;
1933
34
  TypeSourceInfo *TransType = TransformType(Req->getType());
1934
34
  if (!TransType || 
Trap.hasErrorOccurred()15
)
1935
19
    return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
1936
19
        [&] (llvm::raw_ostream& OS) {
1937
19
            Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
1938
19
        }));
1939
15
  return RebuildTypeRequirement(TransType);
1940
34
}
1941
1942
concepts::ExprRequirement *
1943
121
TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
1944
121
  if (!Req->isDependent() && 
!AlwaysRebuild()26
)
1945
22
    return Req;
1946
1947
99
  Sema::SFINAETrap Trap(SemaRef);
1948
1949
99
  llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
1950
99
      TransExpr;
1951
99
  if (Req->isExprSubstitutionFailure())
1952
3
    TransExpr = Req->getExprSubstitutionDiagnostic();
1953
96
  else {
1954
96
    Expr *E = Req->getExpr();
1955
96
    TemplateDeductionInfo Info(E->getBeginLoc());
1956
96
    Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
1957
96
                                         E->getSourceRange());
1958
96
    if (ExprInst.isInvalid())
1959
0
      return nullptr;
1960
96
    ExprResult TransExprRes = TransformExpr(E);
1961
96
    if (!TransExprRes.isInvalid() && 
!Trap.hasErrorOccurred()65
&&
1962
96
        
TransExprRes.get()->hasPlaceholderType()64
)
1963
10
      TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
1964
96
    if (TransExprRes.isInvalid() || 
Trap.hasErrorOccurred()55
)
1965
42
      TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
1966
42
        E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1967
42
      });
1968
54
    else
1969
54
      TransExpr = TransExprRes.get();
1970
96
  }
1971
1972
99
  llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
1973
99
  const auto &RetReq = Req->getReturnTypeRequirement();
1974
99
  if (RetReq.isEmpty())
1975
71
    TransRetReq.emplace();
1976
28
  else if (RetReq.isSubstitutionFailure())
1977
0
    TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
1978
28
  else if (RetReq.isTypeConstraint()) {
1979
28
    TemplateParameterList *OrigTPL =
1980
28
        RetReq.getTypeConstraintTemplateParameterList();
1981
28
    TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
1982
28
    Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
1983
28
                                        Req, Info, OrigTPL->getSourceRange());
1984
28
    if (TPLInst.isInvalid())
1985
0
      return nullptr;
1986
28
    TemplateParameterList *TPL =
1987
28
        TransformTemplateParameterList(OrigTPL);
1988
28
    if (!TPL)
1989
4
      TransRetReq.emplace(createSubstDiag(SemaRef, Info,
1990
4
          [&] (llvm::raw_ostream& OS) {
1991
4
              RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
1992
4
                  ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1993
4
          }));
1994
24
    else {
1995
24
      TPLInst.Clear();
1996
24
      TransRetReq.emplace(TPL);
1997
24
    }
1998
28
  }
1999
99
  assert(TransRetReq.hasValue() &&
2000
99
         "All code paths leading here must set TransRetReq");
2001
99
  if (Expr *E = TransExpr.dyn_cast<Expr *>())
2002
54
    return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2003
54
                                  std::move(*TransRetReq));
2004
45
  return RebuildExprRequirement(
2005
45
      TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
2006
45
      Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2007
99
}
2008
2009
concepts::NestedRequirement *
2010
TemplateInstantiator::TransformNestedRequirement(
2011
38
    concepts::NestedRequirement *Req) {
2012
38
  if (!Req->isDependent() && 
!AlwaysRebuild()14
)
2013
14
    return Req;
2014
24
  if (Req->isSubstitutionFailure()) {
2015
0
    if (AlwaysRebuild())
2016
0
      return RebuildNestedRequirement(
2017
0
          Req->getSubstitutionDiagnostic());
2018
0
    return Req;
2019
0
  }
2020
24
  Sema::InstantiatingTemplate ReqInst(SemaRef,
2021
24
      Req->getConstraintExpr()->getBeginLoc(), Req,
2022
24
      Sema::InstantiatingTemplate::ConstraintsCheck{},
2023
24
      Req->getConstraintExpr()->getSourceRange());
2024
2025
24
  ExprResult TransConstraint;
2026
24
  TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2027
24
  {
2028
24
    EnterExpressionEvaluationContext ContextRAII(
2029
24
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2030
24
    Sema::SFINAETrap Trap(SemaRef);
2031
24
    Sema::InstantiatingTemplate ConstrInst(SemaRef,
2032
24
        Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2033
24
        Req->getConstraintExpr()->getSourceRange());
2034
24
    if (ConstrInst.isInvalid())
2035
0
      return nullptr;
2036
24
    TransConstraint = TransformExpr(Req->getConstraintExpr());
2037
24
    if (TransConstraint.isInvalid() || 
Trap.hasErrorOccurred()21
)
2038
3
      return RebuildNestedRequirement(createSubstDiag(SemaRef, Info,
2039
3
          [&] (llvm::raw_ostream& OS) {
2040
3
              Req->getConstraintExpr()->printPretty(OS, nullptr,
2041
3
                                                    SemaRef.getPrintingPolicy());
2042
3
          }));
2043
24
  }
2044
21
  return RebuildNestedRequirement(TransConstraint.get());
2045
24
}
2046
2047
2048
/// Perform substitution on the type T with a given set of template
2049
/// arguments.
2050
///
2051
/// This routine substitutes the given template arguments into the
2052
/// type T and produces the instantiated type.
2053
///
2054
/// \param T the type into which the template arguments will be
2055
/// substituted. If this type is not dependent, it will be returned
2056
/// immediately.
2057
///
2058
/// \param Args the template arguments that will be
2059
/// substituted for the top-level template parameters within T.
2060
///
2061
/// \param Loc the location in the source code where this substitution
2062
/// is being performed. It will typically be the location of the
2063
/// declarator (if we're instantiating the type of some declaration)
2064
/// or the location of the type in the source code (if, e.g., we're
2065
/// instantiating the type of a cast expression).
2066
///
2067
/// \param Entity the name of the entity associated with a declaration
2068
/// being instantiated (if any). May be empty to indicate that there
2069
/// is no such entity (if, e.g., this is a type that occurs as part of
2070
/// a cast expression) or that the entity has no name (e.g., an
2071
/// unnamed function parameter).
2072
///
2073
/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2074
/// acceptable as the top level type of the result.
2075
///
2076
/// \returns If the instantiation succeeds, the instantiated
2077
/// type. Otherwise, produces diagnostics and returns a NULL type.
2078
TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2079
                                const MultiLevelTemplateArgumentList &Args,
2080
                                SourceLocation Loc,
2081
                                DeclarationName Entity,
2082
3.23M
                                bool AllowDeducedTST) {
2083
3.23M
  assert(!CodeSynthesisContexts.empty() &&
2084
3.23M
         "Cannot perform an instantiation without some context on the "
2085
3.23M
         "instantiation stack");
2086
2087
3.23M
  if (!T->getType()->isInstantiationDependentType() &&
2088
3.23M
      
!T->getType()->isVariablyModifiedType()701k
)
2089
701k
    return T;
2090
2091
2.53M
  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2092
2.53M
  return AllowDeducedTST ? 
Instantiator.TransformTypeWithDeducedTST(T)70.2k
2093
2.53M
                         : 
Instantiator.TransformType(T)2.46M
;
2094
3.23M
}
2095
2096
TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2097
                                const MultiLevelTemplateArgumentList &Args,
2098
                                SourceLocation Loc,
2099
33.1k
                                DeclarationName Entity) {
2100
33.1k
  assert(!CodeSynthesisContexts.empty() &&
2101
33.1k
         "Cannot perform an instantiation without some context on the "
2102
33.1k
         "instantiation stack");
2103
2104
33.1k
  if (TL.getType().isNull())
2105
0
    return nullptr;
2106
2107
33.1k
  if (!TL.getType()->isInstantiationDependentType() &&
2108
33.1k
      
!TL.getType()->isVariablyModifiedType()0
) {
2109
    // FIXME: Make a copy of the TypeLoc data here, so that we can
2110
    // return a new TypeSourceInfo. Inefficient!
2111
0
    TypeLocBuilder TLB;
2112
0
    TLB.pushFullCopy(TL);
2113
0
    return TLB.getTypeSourceInfo(Context, TL.getType());
2114
0
  }
2115
2116
33.1k
  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2117
33.1k
  TypeLocBuilder TLB;
2118
33.1k
  TLB.reserve(TL.getFullDataSize());
2119
33.1k
  QualType Result = Instantiator.TransformType(TLB, TL);
2120
33.1k
  if (Result.isNull())
2121
0
    return nullptr;
2122
2123
33.1k
  return TLB.getTypeSourceInfo(Context, Result);
2124
33.1k
}
2125
2126
/// Deprecated form of the above.
2127
QualType Sema::SubstType(QualType T,
2128
                         const MultiLevelTemplateArgumentList &TemplateArgs,
2129
1.62M
                         SourceLocation Loc, DeclarationName Entity) {
2130
1.62M
  assert(!CodeSynthesisContexts.empty() &&
2131
1.62M
         "Cannot perform an instantiation without some context on the "
2132
1.62M
         "instantiation stack");
2133
2134
  // If T is not a dependent type or a variably-modified type, there
2135
  // is nothing to do.
2136
1.62M
  if (!T->isInstantiationDependentType() && 
!T->isVariablyModifiedType()129k
)
2137
129k
    return T;
2138
2139
1.49M
  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2140
1.49M
  return Instantiator.TransformType(T);
2141
1.62M
}
2142
2143
1.16M
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2144
1.16M
  if (T->getType()->isInstantiationDependentType() ||
2145
1.16M
      
T->getType()->isVariablyModifiedType()197k
)
2146
969k
    return true;
2147
2148
197k
  TypeLoc TL = T->getTypeLoc().IgnoreParens();
2149
197k
  if (!TL.getAs<FunctionProtoTypeLoc>())
2150
23
    return false;
2151
2152
197k
  FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2153
197k
  for (ParmVarDecl *P : FP.getParams()) {
2154
    // This must be synthesized from a typedef.
2155
46.4k
    if (!P) 
continue2
;
2156
2157
    // If there are any parameters, a new TypeSourceInfo that refers to the
2158
    // instantiated parameters must be built.
2159
46.4k
    return true;
2160
46.4k
  }
2161
2162
151k
  return false;
2163
197k
}
2164
2165
/// A form of SubstType intended specifically for instantiating the
2166
/// type of a FunctionDecl.  Its purpose is solely to force the
2167
/// instantiation of default-argument expressions and to avoid
2168
/// instantiating an exception-specification.
2169
TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2170
                                const MultiLevelTemplateArgumentList &Args,
2171
                                SourceLocation Loc,
2172
                                DeclarationName Entity,
2173
                                CXXRecordDecl *ThisContext,
2174
1.16M
                                Qualifiers ThisTypeQuals) {
2175
1.16M
  assert(!CodeSynthesisContexts.empty() &&
2176
1.16M
         "Cannot perform an instantiation without some context on the "
2177
1.16M
         "instantiation stack");
2178
2179
1.16M
  if (!NeedsInstantiationAsFunctionType(T))
2180
151k
    return T;
2181
2182
1.01M
  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2183
2184
1.01M
  TypeLocBuilder TLB;
2185
2186
1.01M
  TypeLoc TL = T->getTypeLoc();
2187
1.01M
  TLB.reserve(TL.getFullDataSize());
2188
2189
1.01M
  QualType Result;
2190
2191
1.01M
  if (FunctionProtoTypeLoc Proto =
2192
1.01M
          TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2193
    // Instantiate the type, other than its exception specification. The
2194
    // exception specification is instantiated in InitFunctionInstantiation
2195
    // once we've built the FunctionDecl.
2196
    // FIXME: Set the exception specification to EST_Uninstantiated here,
2197
    // instead of rebuilding the function type again later.
2198
1.01M
    Result = Instantiator.TransformFunctionProtoType(
2199
1.01M
        TLB, Proto, ThisContext, ThisTypeQuals,
2200
1.01M
        [](FunctionProtoType::ExceptionSpecInfo &ESI,
2201
1.01M
           bool &Changed) 
{ return false; }963k
);
2202
1.01M
  } else {
2203
65
    Result = Instantiator.TransformType(TLB, TL);
2204
65
  }
2205
1.01M
  if (Result.isNull())
2206
52.6k
    return nullptr;
2207
2208
963k
  return TLB.getTypeSourceInfo(Context, Result);
2209
1.01M
}
2210
2211
bool Sema::SubstExceptionSpec(SourceLocation Loc,
2212
                              FunctionProtoType::ExceptionSpecInfo &ESI,
2213
                              SmallVectorImpl<QualType> &ExceptionStorage,
2214
394k
                              const MultiLevelTemplateArgumentList &Args) {
2215
394k
  assert(ESI.Type != EST_Uninstantiated);
2216
2217
0
  bool Changed = false;
2218
394k
  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2219
394k
  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2220
394k
                                             Changed);
2221
394k
}
2222
2223
void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2224
392k
                              const MultiLevelTemplateArgumentList &Args) {
2225
392k
  FunctionProtoType::ExceptionSpecInfo ESI =
2226
392k
      Proto->getExtProtoInfo().ExceptionSpec;
2227
2228
392k
  SmallVector<QualType, 4> ExceptionStorage;
2229
392k
  if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2230
392k
                         ESI, ExceptionStorage, Args))
2231
    // On error, recover by dropping the exception specification.
2232
38
    ESI.Type = EST_None;
2233
2234
392k
  UpdateExceptionSpec(New, ESI);
2235
392k
}
2236
2237
namespace {
2238
2239
  struct GetContainedInventedTypeParmVisitor :
2240
    public TypeVisitor<GetContainedInventedTypeParmVisitor,
2241
                       TemplateTypeParmDecl *> {
2242
    using TypeVisitor<GetContainedInventedTypeParmVisitor,
2243
                      TemplateTypeParmDecl *>::Visit;
2244
2245
2.27M
    TemplateTypeParmDecl *Visit(QualType T) {
2246
2.27M
      if (T.isNull())
2247
0
        return nullptr;
2248
2.27M
      return Visit(T.getTypePtr());
2249
2.27M
    }
2250
    // The deduced type itself.
2251
    TemplateTypeParmDecl *VisitTemplateTypeParmType(
2252
384k
        const TemplateTypeParmType *T) {
2253
384k
      if (!T->getDecl() || 
!T->getDecl()->isImplicit()384k
)
2254
375k
        return nullptr;
2255
9.05k
      return T->getDecl();
2256
384k
    }
2257
2258
    // Only these types can contain 'auto' types, and subsequently be replaced
2259
    // by references to invented parameters.
2260
2261
17.4k
    TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2262
17.4k
      return Visit(T->getNamedType());
2263
17.4k
    }
2264
2265
181k
    TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2266
181k
      return Visit(T->getPointeeType());
2267
181k
    }
2268
2269
1
    TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2270
1
      return Visit(T->getPointeeType());
2271
1
    }
2272
2273
531k
    TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2274
531k
      return Visit(T->getPointeeTypeAsWritten());
2275
531k
    }
2276
2277
154
    TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2278
154
      return Visit(T->getPointeeType());
2279
154
    }
2280
2281
824
    TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2282
824
      return Visit(T->getElementType());
2283
824
    }
2284
2285
    TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2286
0
      const DependentSizedExtVectorType *T) {
2287
0
      return Visit(T->getElementType());
2288
0
    }
2289
2290
0
    TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2291
0
      return Visit(T->getElementType());
2292
0
    }
2293
2294
1.57k
    TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2295
1.57k
      return VisitFunctionType(T);
2296
1.57k
    }
2297
2298
1.57k
    TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2299
1.57k
      return Visit(T->getReturnType());
2300
1.57k
    }
2301
2302
2.19k
    TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2303
2.19k
      return Visit(T->getInnerType());
2304
2.19k
    }
2305
2306
37
    TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2307
37
      return Visit(T->getModifiedType());
2308
37
    }
2309
2310
2
    TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2311
2
      return Visit(T->getUnderlyingType());
2312
2
    }
2313
2314
0
    TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2315
0
      return Visit(T->getOriginalType());
2316
0
    }
2317
2318
32.9k
    TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2319
32.9k
      return Visit(T->getPattern());
2320
32.9k
    }
2321
  };
2322
2323
} // namespace
2324
2325
bool Sema::SubstTypeConstraint(
2326
    TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2327
54
    const MultiLevelTemplateArgumentList &TemplateArgs) {
2328
54
  const ASTTemplateArgumentListInfo *TemplArgInfo =
2329
54
      TC->getTemplateArgsAsWritten();
2330
54
  TemplateArgumentListInfo InstArgs;
2331
2332
54
  if (TemplArgInfo) {
2333
36
    InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2334
36
    InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2335
36
    if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2336
36
                               InstArgs))
2337
4
      return true;
2338
36
  }
2339
50
  return AttachTypeConstraint(
2340
50
      TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2341
50
      TC->getNamedConcept(), &InstArgs, Inst,
2342
50
      Inst->isParameterPack()
2343
50
          ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2344
4
                ->getEllipsisLoc()
2345
50
          : 
SourceLocation()46
);
2346
54
}
2347
2348
ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
2349
                            const MultiLevelTemplateArgumentList &TemplateArgs,
2350
                                    int indexAdjustment,
2351
                                    Optional<unsigned> NumExpansions,
2352
1.53M
                                    bool ExpectParameterPack) {
2353
1.53M
  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2354
1.53M
  TypeSourceInfo *NewDI = nullptr;
2355
2356
1.53M
  TypeLoc OldTL = OldDI->getTypeLoc();
2357
1.53M
  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2358
2359
    // We have a function parameter pack. Substitute into the pattern of the
2360
    // expansion.
2361
32.9k
    NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2362
32.9k
                      OldParm->getLocation(), OldParm->getDeclName());
2363
32.9k
    if (!NewDI)
2364
0
      return nullptr;
2365
2366
32.9k
    if (NewDI->getType()->containsUnexpandedParameterPack()) {
2367
      // We still have unexpanded parameter packs, which means that
2368
      // our function parameter is still a function parameter pack.
2369
      // Therefore, make its type a pack expansion type.
2370
15.9k
      NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2371
15.9k
                                 NumExpansions);
2372
16.9k
    } else if (ExpectParameterPack) {
2373
      // We expected to get a parameter pack but didn't (because the type
2374
      // itself is not a pack expansion type), so complain. This can occur when
2375
      // the substitution goes through an alias template that "loses" the
2376
      // pack expansion.
2377
0
      Diag(OldParm->getLocation(),
2378
0
           diag::err_function_parameter_pack_without_parameter_packs)
2379
0
        << NewDI->getType();
2380
0
      return nullptr;
2381
0
    }
2382
1.49M
  } else {
2383
1.49M
    NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2384
1.49M
                      OldParm->getDeclName());
2385
1.49M
  }
2386
2387
1.53M
  if (!NewDI)
2388
23.9k
    return nullptr;
2389
2390
1.50M
  if (NewDI->getType()->isVoidType()) {
2391
13
    Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2392
13
    return nullptr;
2393
13
  }
2394
2395
  // In abbreviated templates, TemplateTypeParmDecls with possible
2396
  // TypeConstraints are created when the parameter list is originally parsed.
2397
  // The TypeConstraints can therefore reference other functions parameters in
2398
  // the abbreviated function template, which is why we must instantiate them
2399
  // here, when the instantiated versions of those referenced parameters are in
2400
  // scope.
2401
1.50M
  if (TemplateTypeParmDecl *TTP =
2402
1.50M
          GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2403
9.05k
    if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2404
111
      auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2405
111
          FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2406
      // We will first get here when instantiating the abbreviated function
2407
      // template's described function, but we might also get here later.
2408
      // Make sure we do not instantiate the TypeConstraint more than once.
2409
111
      if (Inst && !Inst->getTypeConstraint()) {
2410
        // TODO: Concepts: do not instantiate the constraint (delayed constraint
2411
        // substitution)
2412
12
        if (SubstTypeConstraint(Inst, TC, TemplateArgs))
2413
0
          return nullptr;
2414
12
      }
2415
111
    }
2416
9.05k
  }
2417
2418
1.50M
  ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
2419
1.50M
                                        OldParm->getInnerLocStart(),
2420
1.50M
                                        OldParm->getLocation(),
2421
1.50M
                                        OldParm->getIdentifier(),
2422
1.50M
                                        NewDI->getType(), NewDI,
2423
1.50M
                                        OldParm->getStorageClass());
2424
1.50M
  if (!NewParm)
2425
0
    return nullptr;
2426
2427
  // Mark the (new) default argument as uninstantiated (if any).
2428
1.50M
  if (OldParm->hasUninstantiatedDefaultArg()) {
2429
11.3k
    Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2430
11.3k
    NewParm->setUninstantiatedDefaultArg(Arg);
2431
1.49M
  } else if (OldParm->hasUnparsedDefaultArg()) {
2432
13
    NewParm->setUnparsedDefaultArg();
2433
13
    UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2434
1.49M
  } else if (Expr *Arg = OldParm->getDefaultArg()) {
2435
80.0k
    FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
2436
80.0k
    if (OwningFunc->isInLocalScopeForInstantiation()) {
2437
      // Instantiate default arguments for methods of local classes (DR1484)
2438
      // and non-defining declarations.
2439
46
      Sema::ContextRAII SavedContext(*this, OwningFunc);
2440
46
      LocalInstantiationScope Local(*this, true);
2441
46
      ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
2442
46
      if (NewArg.isUsable()) {
2443
        // It would be nice if we still had this.
2444
35
        SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
2445
35
        ExprResult Result =
2446
35
            ConvertParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
2447
35
        if (Result.isInvalid())
2448
7
          return nullptr;
2449
2450
28
        SetParamDefaultArgument(NewParm, Result.getAs<Expr>(), EqualLoc);
2451
28
      }
2452
79.9k
    } else {
2453
      // FIXME: if we non-lazily instantiated non-dependent default args for
2454
      // non-dependent parameter types we could remove a bunch of duplicate
2455
      // conversion warnings for such arguments.
2456
79.9k
      NewParm->setUninstantiatedDefaultArg(Arg);
2457
79.9k
    }
2458
80.0k
  }
2459
2460
1.50M
  NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
2461
2462
1.50M
  if (OldParm->isParameterPack() && 
!NewParm->isParameterPack()32.9k
) {
2463
    // Add the new parameter to the instantiated parameter pack.
2464
16.9k
    CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
2465
1.48M
  } else {
2466
    // Introduce an Old -> New mapping
2467
1.48M
    CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2468
1.48M
  }
2469
2470
  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2471
  // can be anything, is this right ?
2472
1.50M
  NewParm->setDeclContext(CurContext);
2473
2474
1.50M
  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2475
1.50M
                        OldParm->getFunctionScopeIndex() + indexAdjustment);
2476
2477
1.50M
  InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2478
2479
1.50M
  return NewParm;
2480
1.50M
}
2481
2482
/// Substitute the given template arguments into the given set of
2483
/// parameters, producing the set of parameter types that would be generated
2484
/// from such a substitution.
2485
bool Sema::SubstParmTypes(
2486
    SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2487
    const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2488
    const MultiLevelTemplateArgumentList &TemplateArgs,
2489
    SmallVectorImpl<QualType> &ParamTypes,
2490
    SmallVectorImpl<ParmVarDecl *> *OutParams,
2491
248k
    ExtParameterInfoBuilder &ParamInfos) {
2492
248k
  assert(!CodeSynthesisContexts.empty() &&
2493
248k
         "Cannot perform an instantiation without some context on the "
2494
248k
         "instantiation stack");
2495
2496
0
  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2497
248k
                                    DeclarationName());
2498
248k
  return Instantiator.TransformFunctionTypeParams(
2499
248k
      Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2500
248k
}
2501
2502
/// Perform substitution on the base class specifiers of the
2503
/// given class template specialization.
2504
///
2505
/// Produces a diagnostic and returns true on error, returns false and
2506
/// attaches the instantiated base classes to the class template
2507
/// specialization if successful.
2508
bool
2509
Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
2510
                          CXXRecordDecl *Pattern,
2511
779k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2512
779k
  bool Invalid = false;
2513
779k
  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2514
779k
  for (const auto &Base : Pattern->bases()) {
2515
310k
    if (!Base.getType()->isDependentType()) {
2516
82.5k
      if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2517
82.5k
        if (RD->isInvalidDecl())
2518
4
          Instantiation->setInvalidDecl();
2519
82.5k
      }
2520
82.5k
      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2521
82.5k
      continue;
2522
82.5k
    }
2523
2524
227k
    SourceLocation EllipsisLoc;
2525
227k
    TypeSourceInfo *BaseTypeLoc;
2526
227k
    if (Base.isPackExpansion()) {
2527
      // This is a pack expansion. See whether we should expand it now, or
2528
      // wait until later.
2529
416
      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2530
416
      collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2531
416
                                      Unexpanded);
2532
416
      bool ShouldExpand = false;
2533
416
      bool RetainExpansion = false;
2534
416
      Optional<unsigned> NumExpansions;
2535
416
      if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2536
416
                                          Base.getSourceRange(),
2537
416
                                          Unexpanded,
2538
416
                                          TemplateArgs, ShouldExpand,
2539
416
                                          RetainExpansion,
2540
416
                                          NumExpansions)) {
2541
0
        Invalid = true;
2542
0
        continue;
2543
0
      }
2544
2545
      // If we should expand this pack expansion now, do so.
2546
416
      if (ShouldExpand) {
2547
1.20k
        for (unsigned I = 0; I != *NumExpansions; 
++I785
) {
2548
785
            Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2549
2550
785
          TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2551
785
                                                  TemplateArgs,
2552
785
                                              Base.getSourceRange().getBegin(),
2553
785
                                                  DeclarationName());
2554
785
          if (!BaseTypeLoc) {
2555
0
            Invalid = true;
2556
0
            continue;
2557
0
          }
2558
2559
785
          if (CXXBaseSpecifier *InstantiatedBase
2560
785
                = CheckBaseSpecifier(Instantiation,
2561
785
                                     Base.getSourceRange(),
2562
785
                                     Base.isVirtual(),
2563
785
                                     Base.getAccessSpecifierAsWritten(),
2564
785
                                     BaseTypeLoc,
2565
785
                                     SourceLocation()))
2566
785
            InstantiatedBases.push_back(InstantiatedBase);
2567
0
          else
2568
0
            Invalid = true;
2569
785
        }
2570
2571
416
        continue;
2572
416
      }
2573
2574
      // The resulting base specifier will (still) be a pack expansion.
2575
0
      EllipsisLoc = Base.getEllipsisLoc();
2576
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2577
0
      BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2578
0
                              TemplateArgs,
2579
0
                              Base.getSourceRange().getBegin(),
2580
0
                              DeclarationName());
2581
227k
    } else {
2582
227k
      BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2583
227k
                              TemplateArgs,
2584
227k
                              Base.getSourceRange().getBegin(),
2585
227k
                              DeclarationName());
2586
227k
    }
2587
2588
227k
    if (!BaseTypeLoc) {
2589
10
      Invalid = true;
2590
10
      continue;
2591
10
    }
2592
2593
227k
    if (CXXBaseSpecifier *InstantiatedBase
2594
227k
          = CheckBaseSpecifier(Instantiation,
2595
227k
                               Base.getSourceRange(),
2596
227k
                               Base.isVirtual(),
2597
227k
                               Base.getAccessSpecifierAsWritten(),
2598
227k
                               BaseTypeLoc,
2599
227k
                               EllipsisLoc))
2600
226k
      InstantiatedBases.push_back(InstantiatedBase);
2601
1.07k
    else
2602
1.07k
      Invalid = true;
2603
227k
  }
2604
2605
779k
  if (!Invalid && 
AttachBaseSpecifiers(Instantiation, InstantiatedBases)778k
)
2606
2
    Invalid = true;
2607
2608
779k
  return Invalid;
2609
779k
}
2610
2611
// Defined via #include from SemaTemplateInstantiateDecl.cpp
2612
namespace clang {
2613
  namespace sema {
2614
    Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2615
                            const MultiLevelTemplateArgumentList &TemplateArgs);
2616
    Attr *instantiateTemplateAttributeForDecl(
2617
        const Attr *At, ASTContext &C, Sema &S,
2618
        const MultiLevelTemplateArgumentList &TemplateArgs);
2619
  }
2620
}
2621
2622
/// Instantiate the definition of a class from a given pattern.
2623
///
2624
/// \param PointOfInstantiation The point of instantiation within the
2625
/// source code.
2626
///
2627
/// \param Instantiation is the declaration whose definition is being
2628
/// instantiated. This will be either a class template specialization
2629
/// or a member class of a class template specialization.
2630
///
2631
/// \param Pattern is the pattern from which the instantiation
2632
/// occurs. This will be either the declaration of a class template or
2633
/// the declaration of a member class of a class template.
2634
///
2635
/// \param TemplateArgs The template arguments to be substituted into
2636
/// the pattern.
2637
///
2638
/// \param TSK the kind of implicit or explicit instantiation to perform.
2639
///
2640
/// \param Complain whether to complain if the class cannot be instantiated due
2641
/// to the lack of a definition.
2642
///
2643
/// \returns true if an error occurred, false otherwise.
2644
bool
2645
Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2646
                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2647
                       const MultiLevelTemplateArgumentList &TemplateArgs,
2648
                       TemplateSpecializationKind TSK,
2649
816k
                       bool Complain) {
2650
816k
  CXXRecordDecl *PatternDef
2651
816k
    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2652
816k
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2653
816k
                                Instantiation->getInstantiatedFromMemberClass(),
2654
816k
                                     Pattern, PatternDef, TSK, Complain))
2655
36.3k
    return true;
2656
2657
779k
  llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2658
1
    std::string Name;
2659
1
    llvm::raw_string_ostream OS(Name);
2660
1
    Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2661
1
                                        /*Qualified=*/true);
2662
1
    return Name;
2663
1
  });
2664
2665
779k
  Pattern = PatternDef;
2666
2667
  // Record the point of instantiation.
2668
779k
  if (MemberSpecializationInfo *MSInfo
2669
779k
        = Instantiation->getMemberSpecializationInfo()) {
2670
9.82k
    MSInfo->setTemplateSpecializationKind(TSK);
2671
9.82k
    MSInfo->setPointOfInstantiation(PointOfInstantiation);
2672
770k
  } else if (ClassTemplateSpecializationDecl *Spec
2673
770k
        = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2674
770k
    Spec->setTemplateSpecializationKind(TSK);
2675
770k
    Spec->setPointOfInstantiation(PointOfInstantiation);
2676
770k
  }
2677
2678
779k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2679
779k
  if (Inst.isInvalid())
2680
1
    return true;
2681
779k
  assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2682
0
  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2683
779k
                                      "instantiating class definition");
2684
2685
  // Enter the scope of this instantiation. We don't use
2686
  // PushDeclContext because we don't have a scope.
2687
779k
  ContextRAII SavedContext(*this, Instantiation);
2688
779k
  EnterExpressionEvaluationContext EvalContext(
2689
779k
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2690
2691
  // If this is an instantiation of a local class, merge this local
2692
  // instantiation scope with the enclosing scope. Otherwise, every
2693
  // instantiation of a class has its own local instantiation scope.
2694
779k
  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2695
779k
  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2696
2697
  // Some class state isn't processed immediately but delayed till class
2698
  // instantiation completes. We may not be ready to handle any delayed state
2699
  // already on the stack as it might correspond to a different class, so save
2700
  // it now and put it back later.
2701
779k
  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2702
2703
  // Pull attributes from the pattern onto the instantiation.
2704
779k
  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2705
2706
  // Start the definition of this instantiation.
2707
779k
  Instantiation->startDefinition();
2708
2709
  // The instantiation is visible here, even if it was first declared in an
2710
  // unimported module.
2711
779k
  Instantiation->setVisibleDespiteOwningModule();
2712
2713
  // FIXME: This loses the as-written tag kind for an explicit instantiation.
2714
779k
  Instantiation->setTagKind(Pattern->getTagKind());
2715
2716
  // Do substitution on the base class specifiers.
2717
779k
  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2718
1.08k
    Instantiation->setInvalidDecl();
2719
2720
779k
  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2721
779k
  SmallVector<Decl*, 4> Fields;
2722
  // Delay instantiation of late parsed attributes.
2723
779k
  LateInstantiatedAttrVec LateAttrs;
2724
779k
  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2725
2726
779k
  bool MightHaveConstexprVirtualFunctions = false;
2727
2.80M
  for (auto *Member : Pattern->decls()) {
2728
    // Don't instantiate members not belonging in this semantic context.
2729
    // e.g. for:
2730
    // @code
2731
    //    template <int i> class A {
2732
    //      class B *g;
2733
    //    };
2734
    // @endcode
2735
    // 'class B' has the template as lexical context but semantically it is
2736
    // introduced in namespace scope.
2737
2.80M
    if (Member->getDeclContext() != Pattern)
2738
222
      continue;
2739
2740
    // BlockDecls can appear in a default-member-initializer. They must be the
2741
    // child of a BlockExpr, so we only know how to instantiate them from there.
2742
    // Similarly, lambda closure types are recreated when instantiating the
2743
    // corresponding LambdaExpr.
2744
2.80M
    if (isa<BlockDecl>(Member) ||
2745
2.80M
        
(2.80M
isa<CXXRecordDecl>(Member)2.80M
&&
cast<CXXRecordDecl>(Member)->isLambda()799k
))
2746
207
      continue;
2747
2748
2.80M
    if (Member->isInvalidDecl()) {
2749
121
      Instantiation->setInvalidDecl();
2750
121
      continue;
2751
121
    }
2752
2753
2.80M
    Decl *NewMember = Instantiator.Visit(Member);
2754
2.80M
    if (NewMember) {
2755
2.80M
      if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2756
66.5k
        Fields.push_back(Field);
2757
2.73M
      } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2758
        // C++11 [temp.inst]p1: The implicit instantiation of a class template
2759
        // specialization causes the implicit instantiation of the definitions
2760
        // of unscoped member enumerations.
2761
        // Record a point of instantiation for this implicit instantiation.
2762
2.86k
        if (TSK == TSK_ImplicitInstantiation && 
!Enum->isScoped()2.83k
&&
2763
2.86k
            
Enum->isCompleteDefinition()2.74k
) {
2764
2.73k
          MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2765
2.73k
          assert(MSInfo && "no spec info for member enum specialization");
2766
0
          MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2767
2.73k
          MSInfo->setPointOfInstantiation(PointOfInstantiation);
2768
2.73k
        }
2769
2.73M
      } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2770
40.5k
        if (SA->isFailed()) {
2771
          // A static_assert failed. Bail out; instantiating this
2772
          // class is probably not meaningful.
2773
12
          Instantiation->setInvalidDecl();
2774
12
          break;
2775
12
        }
2776
2.69M
      } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2777
671k
        if (MD->isConstexpr() && 
!MD->getFriendObjectKind()120k
&&
2778
671k
            
(120k
MD->isVirtualAsWritten()120k
||
Instantiation->getNumBases()120k
))
2779
42.6k
          MightHaveConstexprVirtualFunctions = true;
2780
671k
      }
2781
2782
2.80M
      if (NewMember->isInvalidDecl())
2783
462
        Instantiation->setInvalidDecl();
2784
2.80M
    } else {
2785
      // FIXME: Eventually, a NULL return will mean that one of the
2786
      // instantiations was a semantic disaster, and we'll want to mark the
2787
      // declaration invalid.
2788
      // For now, we expect to skip some members that we can't yet handle.
2789
482
    }
2790
2.80M
  }
2791
2792
  // Finish checking fields.
2793
779k
  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2794
779k
              SourceLocation(), SourceLocation(), ParsedAttributesView());
2795
779k
  CheckCompletedCXXClass(nullptr, Instantiation);
2796
2797
  // Default arguments are parsed, if not instantiated. We can go instantiate
2798
  // default arg exprs for default constructors if necessary now. Unless we're
2799
  // parsing a class, in which case wait until that's finished.
2800
779k
  if (ParsingClassDepth == 0)
2801
607k
    ActOnFinishCXXNonNestedClass();
2802
2803
  // Instantiate late parsed attributes, and attach them to their decls.
2804
  // See Sema::InstantiateAttrs
2805
779k
  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2806
779k
       E = LateAttrs.end(); I != E; 
++I82
) {
2807
82
    assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2808
0
    CurrentInstantiationScope = I->Scope;
2809
2810
    // Allow 'this' within late-parsed attributes.
2811
82
    auto *ND = cast<NamedDecl>(I->NewDecl);
2812
82
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2813
82
    CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2814
82
                               ND->isCXXInstanceMember());
2815
2816
82
    Attr *NewAttr =
2817
82
      instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2818
82
    if (NewAttr)
2819
82
      I->NewDecl->addAttr(NewAttr);
2820
82
    LocalInstantiationScope::deleteScopes(I->Scope,
2821
82
                                          Instantiator.getStartingScope());
2822
82
  }
2823
779k
  Instantiator.disableLateAttributeInstantiation();
2824
779k
  LateAttrs.clear();
2825
2826
779k
  ActOnFinishDelayedMemberInitializers(Instantiation);
2827
2828
  // FIXME: We should do something similar for explicit instantiations so they
2829
  // end up in the right module.
2830
779k
  if (TSK == TSK_ImplicitInstantiation) {
2831
773k
    Instantiation->setLocation(Pattern->getLocation());
2832
773k
    Instantiation->setLocStart(Pattern->getInnerLocStart());
2833
773k
    Instantiation->setBraceRange(Pattern->getBraceRange());
2834
773k
  }
2835
2836
779k
  if (!Instantiation->isInvalidDecl()) {
2837
    // Perform any dependent diagnostics from the pattern.
2838
778k
    if (Pattern->isDependentContext())
2839
778k
      PerformDependentDiagnostics(Pattern, TemplateArgs);
2840
2841
    // Instantiate any out-of-line class template partial
2842
    // specializations now.
2843
778k
    for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2844
778k
              P = Instantiator.delayed_partial_spec_begin(),
2845
778k
           PEnd = Instantiator.delayed_partial_spec_end();
2846
778k
         P != PEnd; 
++P9
) {
2847
9
      if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2848
9
              P->first, P->second)) {
2849
0
        Instantiation->setInvalidDecl();
2850
0
        break;
2851
0
      }
2852
9
    }
2853
2854
    // Instantiate any out-of-line variable template partial
2855
    // specializations now.
2856
778k
    for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2857
778k
              P = Instantiator.delayed_var_partial_spec_begin(),
2858
778k
           PEnd = Instantiator.delayed_var_partial_spec_end();
2859
778k
         P != PEnd; 
++P7
) {
2860
7
      if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2861
7
              P->first, P->second)) {
2862
0
        Instantiation->setInvalidDecl();
2863
0
        break;
2864
0
      }
2865
7
    }
2866
778k
  }
2867
2868
  // Exit the scope of this instantiation.
2869
779k
  SavedContext.pop();
2870
2871
779k
  if (!Instantiation->isInvalidDecl()) {
2872
    // Always emit the vtable for an explicit instantiation definition
2873
    // of a polymorphic class template specialization. Otherwise, eagerly
2874
    // instantiate only constexpr virtual functions in preparation for their use
2875
    // in constant evaluation.
2876
778k
    if (TSK == TSK_ExplicitInstantiationDefinition)
2877
1.55k
      MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2878
776k
    else if (MightHaveConstexprVirtualFunctions)
2879
9.83k
      MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2880
9.83k
                                   /*ConstexprOnly*/ true);
2881
778k
  }
2882
2883
779k
  Consumer.HandleTagDeclDefinition(Instantiation);
2884
2885
779k
  return Instantiation->isInvalidDecl();
2886
779k
}
2887
2888
/// Instantiate the definition of an enum from a given pattern.
2889
///
2890
/// \param PointOfInstantiation The point of instantiation within the
2891
///        source code.
2892
/// \param Instantiation is the declaration whose definition is being
2893
///        instantiated. This will be a member enumeration of a class
2894
///        temploid specialization, or a local enumeration within a
2895
///        function temploid specialization.
2896
/// \param Pattern The templated declaration from which the instantiation
2897
///        occurs.
2898
/// \param TemplateArgs The template arguments to be substituted into
2899
///        the pattern.
2900
/// \param TSK The kind of implicit or explicit instantiation to perform.
2901
///
2902
/// \return \c true if an error occurred, \c false otherwise.
2903
bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2904
                           EnumDecl *Instantiation, EnumDecl *Pattern,
2905
                           const MultiLevelTemplateArgumentList &TemplateArgs,
2906
48
                           TemplateSpecializationKind TSK) {
2907
48
  EnumDecl *PatternDef = Pattern->getDefinition();
2908
48
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2909
48
                                 Instantiation->getInstantiatedFromMemberEnum(),
2910
48
                                     Pattern, PatternDef, TSK,/*Complain*/true))
2911
6
    return true;
2912
42
  Pattern = PatternDef;
2913
2914
  // Record the point of instantiation.
2915
42
  if (MemberSpecializationInfo *MSInfo
2916
42
        = Instantiation->getMemberSpecializationInfo()) {
2917
42
    MSInfo->setTemplateSpecializationKind(TSK);
2918
42
    MSInfo->setPointOfInstantiation(PointOfInstantiation);
2919
42
  }
2920
2921
42
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2922
42
  if (Inst.isInvalid())
2923
0
    return true;
2924
42
  if (Inst.isAlreadyInstantiating())
2925
0
    return false;
2926
42
  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2927
42
                                      "instantiating enum definition");
2928
2929
  // The instantiation is visible here, even if it was first declared in an
2930
  // unimported module.
2931
42
  Instantiation->setVisibleDespiteOwningModule();
2932
2933
  // Enter the scope of this instantiation. We don't use
2934
  // PushDeclContext because we don't have a scope.
2935
42
  ContextRAII SavedContext(*this, Instantiation);
2936
42
  EnterExpressionEvaluationContext EvalContext(
2937
42
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2938
2939
42
  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2940
2941
  // Pull attributes from the pattern onto the instantiation.
2942
42
  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2943
2944
42
  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2945
42
  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2946
2947
  // Exit the scope of this instantiation.
2948
42
  SavedContext.pop();
2949
2950
42
  return Instantiation->isInvalidDecl();
2951
42
}
2952
2953
2954
/// Instantiate the definition of a field from the given pattern.
2955
///
2956
/// \param PointOfInstantiation The point of instantiation within the
2957
///        source code.
2958
/// \param Instantiation is the declaration whose definition is being
2959
///        instantiated. This will be a class of a class temploid
2960
///        specialization, or a local enumeration within a function temploid
2961
///        specialization.
2962
/// \param Pattern The templated declaration from which the instantiation
2963
///        occurs.
2964
/// \param TemplateArgs The template arguments to be substituted into
2965
///        the pattern.
2966
///
2967
/// \return \c true if an error occurred, \c false otherwise.
2968
bool Sema::InstantiateInClassInitializer(
2969
    SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2970
1.01k
    FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2971
  // If there is no initializer, we don't need to do anything.
2972
1.01k
  if (!Pattern->hasInClassInitializer())
2973
0
    return false;
2974
2975
1.01k
  assert(Instantiation->getInClassInitStyle() ==
2976
1.01k
             Pattern->getInClassInitStyle() &&
2977
1.01k
         "pattern and instantiation disagree about init style");
2978
2979
  // Error out if we haven't parsed the initializer of the pattern yet because
2980
  // we are waiting for the closing brace of the outer class.
2981
0
  Expr *OldInit = Pattern->getInClassInitializer();
2982
1.01k
  if (!OldInit) {
2983
3
    RecordDecl *PatternRD = Pattern->getParent();
2984
3
    RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2985
3
    Diag(PointOfInstantiation,
2986
3
         diag::err_default_member_initializer_not_yet_parsed)
2987
3
        << OutermostClass << Pattern;
2988
3
    Diag(Pattern->getEndLoc(),
2989
3
         diag::note_default_member_initializer_not_yet_parsed);
2990
3
    Instantiation->setInvalidDecl();
2991
3
    return true;
2992
3
  }
2993
2994
1.01k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2995
1.01k
  if (Inst.isInvalid())
2996
0
    return true;
2997
1.01k
  if (Inst.isAlreadyInstantiating()) {
2998
    // Error out if we hit an instantiation cycle for this initializer.
2999
1
    Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3000
1
      << Instantiation;
3001
1
    return true;
3002
1
  }
3003
1.01k
  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3004
1.01k
                                      "instantiating default member init");
3005
3006
  // Enter the scope of this instantiation. We don't use PushDeclContext because
3007
  // we don't have a scope.
3008
1.01k
  ContextRAII SavedContext(*this, Instantiation->getParent());
3009
1.01k
  EnterExpressionEvaluationContext EvalContext(
3010
1.01k
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3011
3012
1.01k
  LocalInstantiationScope Scope(*this, true);
3013
3014
  // Instantiate the initializer.
3015
1.01k
  ActOnStartCXXInClassMemberInitializer();
3016
1.01k
  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3017
3018
1.01k
  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3019
1.01k
                                        /*CXXDirectInit=*/false);
3020
1.01k
  Expr *Init = NewInit.get();
3021
1.01k
  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3022
0
  ActOnFinishCXXInClassMemberInitializer(
3023
1.01k
      Instantiation, Init ? 
Init->getBeginLoc()1.00k
:
SourceLocation()6
, Init);
3024
3025
1.01k
  if (auto *L = getASTMutationListener())
3026
36
    L->DefaultMemberInitializerInstantiated(Instantiation);
3027
3028
  // Return true if the in-class initializer is still missing.
3029
1.01k
  return !Instantiation->getInClassInitializer();
3030
1.01k
}
3031
3032
namespace {
3033
  /// A partial specialization whose template arguments have matched
3034
  /// a given template-id.
3035
  struct PartialSpecMatchResult {
3036
    ClassTemplatePartialSpecializationDecl *Partial;
3037
    TemplateArgumentList *Args;
3038
  };
3039
}
3040
3041
bool Sema::usesPartialOrExplicitSpecialization(
3042
2
    SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3043
2
  if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3044
2
      TSK_ExplicitSpecialization)
3045
0
    return true;
3046
3047
2
  SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3048
2
  ClassTemplateSpec->getSpecializedTemplate()
3049
2
                   ->getPartialSpecializations(PartialSpecs);
3050
2
  for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I0
) {
3051
0
    TemplateDeductionInfo Info(Loc);
3052
0
    if (!DeduceTemplateArguments(PartialSpecs[I],
3053
0
                                 ClassTemplateSpec->getTemplateArgs(), Info))
3054
0
      return true;
3055
0
  }
3056
3057
2
  return false;
3058
2
}
3059
3060
/// Get the instantiation pattern to use to instantiate the definition of a
3061
/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3062
/// template or of a partial specialization).
3063
static ActionResult<CXXRecordDecl *>
3064
getPatternForClassTemplateSpecialization(
3065
    Sema &S, SourceLocation PointOfInstantiation,
3066
    ClassTemplateSpecializationDecl *ClassTemplateSpec,
3067
806k
    TemplateSpecializationKind TSK) {
3068
806k
  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3069
806k
  if (Inst.isInvalid())
3070
478
    return {/*Invalid=*/true};
3071
806k
  if (Inst.isAlreadyInstantiating())
3072
0
    return {/*Invalid=*/false};
3073
3074
806k
  llvm::PointerUnion<ClassTemplateDecl *,
3075
806k
                     ClassTemplatePartialSpecializationDecl *>
3076
806k
      Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3077
806k
  if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3078
    // Find best matching specialization.
3079
806k
    ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3080
3081
    // C++ [temp.class.spec.match]p1:
3082
    //   When a class template is used in a context that requires an
3083
    //   instantiation of the class, it is necessary to determine
3084
    //   whether the instantiation is to be generated using the primary
3085
    //   template or one of the partial specializations. This is done by
3086
    //   matching the template arguments of the class template
3087
    //   specialization with the template argument lists of the partial
3088
    //   specializations.
3089
806k
    typedef PartialSpecMatchResult MatchResult;
3090
806k
    SmallVector<MatchResult, 4> Matched;
3091
806k
    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3092
806k
    Template->getPartialSpecializations(PartialSpecs);
3093
806k
    TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3094
1.38M
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I577k
) {
3095
577k
      ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3096
577k
      TemplateDeductionInfo Info(FailedCandidates.getLocation());
3097
577k
      if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
3098
577k
              Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
3099
        // Store the failed-deduction information for use in diagnostics, later.
3100
        // TODO: Actually use the failed-deduction info?
3101
395k
        FailedCandidates.addCandidate().set(
3102
395k
            DeclAccessPair::make(Template, AS_public), Partial,
3103
395k
            MakeDeductionFailureInfo(S.Context, Result, Info));
3104
395k
        (void)Result;
3105
395k
      } else {
3106
182k
        Matched.push_back(PartialSpecMatchResult());
3107
182k
        Matched.back().Partial = Partial;
3108
182k
        Matched.back().Args = Info.take();
3109
182k
      }
3110
577k
    }
3111
3112
    // If we're dealing with a member template where the template parameters
3113
    // have been instantiated, this provides the original template parameters
3114
    // from which the member template's parameters were instantiated.
3115
3116
806k
    if (Matched.size() >= 1) {
3117
175k
      SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3118
175k
      if (Matched.size() == 1) {
3119
        //   -- If exactly one matching specialization is found, the
3120
        //      instantiation is generated from that specialization.
3121
        // We don't need to do anything for this.
3122
169k
      } else {
3123
        //   -- If more than one matching specialization is found, the
3124
        //      partial order rules (14.5.4.2) are used to determine
3125
        //      whether one of the specializations is more specialized
3126
        //      than the others. If none of the specializations is more
3127
        //      specialized than all of the other matching
3128
        //      specializations, then the use of the class template is
3129
        //      ambiguous and the program is ill-formed.
3130
5.84k
        for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3131
5.84k
                                                 PEnd = Matched.end();
3132
12.6k
             P != PEnd; 
++P6.78k
) {
3133
6.78k
          if (S.getMoreSpecializedPartialSpecialization(
3134
6.78k
                  P->Partial, Best->Partial, PointOfInstantiation) ==
3135
6.78k
              P->Partial)
3136
6.53k
            Best = P;
3137
6.78k
        }
3138
3139
        // Determine if the best partial specialization is more specialized than
3140
        // the others.
3141
5.84k
        bool Ambiguous = false;
3142
5.84k
        for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3143
5.84k
                                                 PEnd = Matched.end();
3144
18.4k
             P != PEnd; 
++P12.6k
) {
3145
12.6k
          if (P != Best && S.getMoreSpecializedPartialSpecialization(
3146
6.78k
                               P->Partial, Best->Partial,
3147
6.78k
                               PointOfInstantiation) != Best->Partial) {
3148
23
            Ambiguous = true;
3149
23
            break;
3150
23
          }
3151
12.6k
        }
3152
3153
5.84k
        if (Ambiguous) {
3154
          // Partial ordering did not produce a clear winner. Complain.
3155
23
          Inst.Clear();
3156
23
          ClassTemplateSpec->setInvalidDecl();
3157
23
          S.Diag(PointOfInstantiation,
3158
23
                 diag::err_partial_spec_ordering_ambiguous)
3159
23
              << ClassTemplateSpec;
3160
3161
          // Print the matching partial specializations.
3162
23
          for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3163
23
                                                   PEnd = Matched.end();
3164
73
               P != PEnd; 
++P50
)
3165
50
            S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3166
50
                << S.getTemplateArgumentBindingsText(
3167
50
                       P->Partial->getTemplateParameters(), *P->Args);
3168
3169
23
          return {/*Invalid=*/true};
3170
23
        }
3171
5.84k
      }
3172
3173
175k
      ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3174
631k
    } else {
3175
      //   -- If no matches are found, the instantiation is generated
3176
      //      from the primary template.
3177
631k
    }
3178
806k
  }
3179
3180
806k
  CXXRecordDecl *Pattern = nullptr;
3181
806k
  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3182
806k
  if (auto *PartialSpec =
3183
806k
          Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3184
    // Instantiate using the best class template partial specialization.
3185
175k
    while (PartialSpec->getInstantiatedFromMember()) {
3186
      // If we've found an explicit specialization of this class template,
3187
      // stop here and use that as the pattern.
3188
453
      if (PartialSpec->isMemberSpecialization())
3189
1
        break;
3190
3191
452
      PartialSpec = PartialSpec->getInstantiatedFromMember();
3192
452
    }
3193
175k
    Pattern = PartialSpec;
3194
631k
  } else {
3195
631k
    ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3196
640k
    while (Template->getInstantiatedFromMemberTemplate()) {
3197
      // If we've found an explicit specialization of this class template,
3198
      // stop here and use that as the pattern.
3199
9.33k
      if (Template->isMemberSpecialization())
3200
41
        break;
3201
3202
9.29k
      Template = Template->getInstantiatedFromMemberTemplate();
3203
9.29k
    }
3204
631k
    Pattern = Template->getTemplatedDecl();
3205
631k
  }
3206
3207
806k
  return Pattern;
3208
806k
}
3209
3210
bool Sema::InstantiateClassTemplateSpecialization(
3211
    SourceLocation PointOfInstantiation,
3212
    ClassTemplateSpecializationDecl *ClassTemplateSpec,
3213
806k
    TemplateSpecializationKind TSK, bool Complain) {
3214
  // Perform the actual instantiation on the canonical declaration.
3215
806k
  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3216
806k
      ClassTemplateSpec->getCanonicalDecl());
3217
806k
  if (ClassTemplateSpec->isInvalidDecl())
3218
2
    return true;
3219
3220
806k
  ActionResult<CXXRecordDecl *> Pattern =
3221
806k
      getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3222
806k
                                               ClassTemplateSpec, TSK);
3223
806k
  if (!Pattern.isUsable())
3224
501
    return Pattern.isInvalid();
3225
3226
806k
  return InstantiateClass(
3227
806k
      PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3228
806k
      getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3229
806k
}
3230
3231
/// Instantiates the definitions of all of the member
3232
/// of the given class, which is an instantiation of a class template
3233
/// or a member class of a template.
3234
void
3235
Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
3236
                              CXXRecordDecl *Instantiation,
3237
                        const MultiLevelTemplateArgumentList &TemplateArgs,
3238
9.15k
                              TemplateSpecializationKind TSK) {
3239
  // FIXME: We need to notify the ASTMutationListener that we did all of these
3240
  // things, in case we have an explicit instantiation definition in a PCM, a
3241
  // module, or preamble, and the declaration is in an imported AST.
3242
9.15k
  assert(
3243
9.15k
      (TSK == TSK_ExplicitInstantiationDefinition ||
3244
9.15k
       TSK == TSK_ExplicitInstantiationDeclaration ||
3245
9.15k
       (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3246
9.15k
      "Unexpected template specialization kind!");
3247
114k
  for (auto *D : Instantiation->decls()) {
3248
114k
    bool SuppressNew = false;
3249
114k
    if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3250
72.8k
      if (FunctionDecl *Pattern =
3251
72.8k
              Function->getInstantiatedFromMemberFunction()) {
3252
3253
64.2k
        if (Function->getTrailingRequiresClause()) {
3254
7
          ConstraintSatisfaction Satisfaction;
3255
7
          if (CheckFunctionConstraints(Function, Satisfaction) ||
3256
7
              !Satisfaction.IsSatisfied) {
3257
4
            continue;
3258
4
          }
3259
7
        }
3260
3261
64.2k
        if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3262
31.2k
          continue;
3263
3264
33.0k
        MemberSpecializationInfo *MSInfo =
3265
33.0k
            Function->getMemberSpecializationInfo();
3266
33.0k
        assert(MSInfo && "No member specialization information?");
3267
33.0k
        if (MSInfo->getTemplateSpecializationKind()
3268
33.0k
                                                 == TSK_ExplicitSpecialization)
3269
393
          continue;
3270
3271
32.6k
        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3272
32.6k
                                                   Function,
3273
32.6k
                                        MSInfo->getTemplateSpecializationKind(),
3274
32.6k
                                              MSInfo->getPointOfInstantiation(),
3275
32.6k
                                                   SuppressNew) ||
3276
32.6k
            SuppressNew)
3277
10
          continue;
3278
3279
        // C++11 [temp.explicit]p8:
3280
        //   An explicit instantiation definition that names a class template
3281
        //   specialization explicitly instantiates the class template
3282
        //   specialization and is only an explicit instantiation definition
3283
        //   of members whose definition is visible at the point of
3284
        //   instantiation.
3285
32.6k
        if (TSK == TSK_ExplicitInstantiationDefinition && 
!Pattern->isDefined()1.72k
)
3286
129
          continue;
3287
3288
32.4k
        Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3289
3290
32.4k
        if (Function->isDefined()) {
3291
          // Let the ASTConsumer know that this function has been explicitly
3292
          // instantiated now, and its linkage might have changed.
3293
1.45k
          Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
3294
31.0k
        } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3295
1.51k
          InstantiateFunctionDefinition(PointOfInstantiation, Function);
3296
29.5k
        } else if (TSK == TSK_ImplicitInstantiation) {
3297
150
          PendingLocalImplicitInstantiations.push_back(
3298
150
              std::make_pair(Function, PointOfInstantiation));
3299
150
        }
3300
32.4k
      }
3301
72.8k
    } else 
if (auto *41.8k
Var41.8k
= dyn_cast<VarDecl>(D)) {
3302
2.30k
      if (isa<VarTemplateSpecializationDecl>(Var))
3303
1
        continue;
3304
3305
2.30k
      if (Var->isStaticDataMember()) {
3306
2.30k
        if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3307
4
          continue;
3308
3309
2.30k
        MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3310
2.30k
        assert(MSInfo && "No member specialization information?");
3311
2.30k
        if (MSInfo->getTemplateSpecializationKind()
3312
2.30k
                                                 == TSK_ExplicitSpecialization)
3313
7
          continue;
3314
3315
2.29k
        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3316
2.29k
                                                   Var,
3317
2.29k
                                        MSInfo->getTemplateSpecializationKind(),
3318
2.29k
                                              MSInfo->getPointOfInstantiation(),
3319
2.29k
                                                   SuppressNew) ||
3320
2.29k
            SuppressNew)
3321
0
          continue;
3322
3323
2.29k
        if (TSK == TSK_ExplicitInstantiationDefinition) {
3324
          // C++0x [temp.explicit]p8:
3325
          //   An explicit instantiation definition that names a class template
3326
          //   specialization explicitly instantiates the class template
3327
          //   specialization and is only an explicit instantiation definition
3328
          //   of members whose definition is visible at the point of
3329
          //   instantiation.
3330
235
          if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3331
141
            continue;
3332
3333
94
          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3334
94
          InstantiateVariableDefinition(PointOfInstantiation, Var);
3335
2.06k
        } else {
3336
2.06k
          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3337
2.06k
        }
3338
2.29k
      }
3339
39.5k
    } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3340
8.12k
      if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3341
4
        continue;
3342
3343
      // Always skip the injected-class-name, along with any
3344
      // redeclarations of nested classes, since both would cause us
3345
      // to try to instantiate the members of a class twice.
3346
      // Skip closure types; they'll get instantiated when we instantiate
3347
      // the corresponding lambda-expression.
3348
8.12k
      if (Record->isInjectedClassName() || 
Record->getPreviousDecl()912
||
3349
8.12k
          
Record->isLambda()903
)
3350
7.22k
        continue;
3351
3352
897
      MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3353
897
      assert(MSInfo && "No member specialization information?");
3354
3355
897
      if (MSInfo->getTemplateSpecializationKind()
3356
897
                                                == TSK_ExplicitSpecialization)
3357
1
        continue;
3358
3359
896
      if (Context.getTargetInfo().getTriple().isOSWindows() &&
3360
896
          
TSK == TSK_ExplicitInstantiationDeclaration19
) {
3361
        // On Windows, explicit instantiation decl of the outer class doesn't
3362
        // affect the inner class. Typically extern template declarations are
3363
        // used in combination with dll import/export annotations, but those
3364
        // are not propagated from the outer class templates to inner classes.
3365
        // Therefore, do not instantiate inner classes on this platform, so
3366
        // that users don't end up with undefined symbols during linking.
3367
11
        continue;
3368
11
      }
3369
3370
885
      if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3371
885
                                                 Record,
3372
885
                                        MSInfo->getTemplateSpecializationKind(),
3373
885
                                              MSInfo->getPointOfInstantiation(),
3374
885
                                                 SuppressNew) ||
3375
885
          SuppressNew)
3376
0
        continue;
3377
3378
885
      CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3379
885
      assert(Pattern && "Missing instantiated-from-template information");
3380
3381
885
      if (!Record->getDefinition()) {
3382
435
        if (!Pattern->getDefinition()) {
3383
          // C++0x [temp.explicit]p8:
3384
          //   An explicit instantiation definition that names a class template
3385
          //   specialization explicitly instantiates the class template
3386
          //   specialization and is only an explicit instantiation definition
3387
          //   of members whose definition is visible at the point of
3388
          //   instantiation.
3389
1
          if (TSK == TSK_ExplicitInstantiationDeclaration) {
3390
0
            MSInfo->setTemplateSpecializationKind(TSK);
3391
0
            MSInfo->setPointOfInstantiation(PointOfInstantiation);
3392
0
          }
3393
3394
1
          continue;
3395
1
        }
3396
3397
434
        InstantiateClass(PointOfInstantiation, Record, Pattern,
3398
434
                         TemplateArgs,
3399
434
                         TSK);
3400
450
      } else {
3401
450
        if (TSK == TSK_ExplicitInstantiationDefinition &&
3402
450
            Record->getTemplateSpecializationKind() ==
3403
10
                TSK_ExplicitInstantiationDeclaration) {
3404
4
          Record->setTemplateSpecializationKind(TSK);
3405
4
          MarkVTableUsed(PointOfInstantiation, Record, true);
3406
4
        }
3407
450
      }
3408
3409
884
      Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3410
884
      if (Pattern)
3411
884
        InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3412
884
                                TSK);
3413
31.4k
    } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3414
34
      MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3415
34
      assert(MSInfo && "No member specialization information?");
3416
3417
34
      if (MSInfo->getTemplateSpecializationKind()
3418
34
            == TSK_ExplicitSpecialization)
3419
0
        continue;
3420
3421
34
      if (CheckSpecializationInstantiationRedecl(
3422
34
            PointOfInstantiation, TSK, Enum,
3423
34
            MSInfo->getTemplateSpecializationKind(),
3424
34
            MSInfo->getPointOfInstantiation(), SuppressNew) ||
3425
34
          SuppressNew)
3426
0
        continue;
3427
3428
34
      if (Enum->getDefinition())
3429
22
        continue;
3430
3431
12
      EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3432
12
      assert(Pattern && "Missing instantiated-from-template information");
3433
3434
12
      if (TSK == TSK_ExplicitInstantiationDefinition) {
3435
11
        if (!Pattern->getDefinition())
3436
1
          continue;
3437
3438
10
        InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3439
10
      } else {
3440
1
        MSInfo->setTemplateSpecializationKind(TSK);
3441
1
        MSInfo->setPointOfInstantiation(PointOfInstantiation);
3442
1
      }
3443
31.4k
    } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3444
      // No need to instantiate in-class initializers during explicit
3445
      // instantiation.
3446
9.55k
      if (Field->hasInClassInitializer() && 
TSK == TSK_ImplicitInstantiation49
) {
3447
44
        CXXRecordDecl *ClassPattern =
3448
44
            Instantiation->getTemplateInstantiationPattern();
3449
44
        DeclContext::lookup_result Lookup =
3450
44
            ClassPattern->lookup(Field->getDeclName());
3451
44
        FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
3452
44
        assert(Pattern);
3453
0
        InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3454
44
                                      TemplateArgs);
3455
44
      }
3456
9.55k
    }
3457
114k
  }
3458
9.15k
}
3459
3460
/// Instantiate the definitions of all of the members of the
3461
/// given class template specialization, which was named as part of an
3462
/// explicit instantiation.
3463
void
3464
Sema::InstantiateClassTemplateSpecializationMembers(
3465
                                           SourceLocation PointOfInstantiation,
3466
                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
3467
6.47k
                                               TemplateSpecializationKind TSK) {
3468
  // C++0x [temp.explicit]p7:
3469
  //   An explicit instantiation that names a class template
3470
  //   specialization is an explicit instantion of the same kind
3471
  //   (declaration or definition) of each of its members (not
3472
  //   including members inherited from base classes) that has not
3473
  //   been previously explicitly specialized in the translation unit
3474
  //   containing the explicit instantiation, except as described
3475
  //   below.
3476
6.47k
  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3477
6.47k
                          getTemplateInstantiationArgs(ClassTemplateSpec),
3478
6.47k
                          TSK);
3479
6.47k
}
3480
3481
StmtResult
3482
191k
Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
3483
191k
  if (!S)
3484
0
    return S;
3485
3486
191k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3487
191k
                                    SourceLocation(),
3488
191k
                                    DeclarationName());
3489
191k
  return Instantiator.TransformStmt(S);
3490
191k
}
3491
3492
bool Sema::SubstTemplateArguments(
3493
    ArrayRef<TemplateArgumentLoc> Args,
3494
    const MultiLevelTemplateArgumentList &TemplateArgs,
3495
237k
    TemplateArgumentListInfo &Out) {
3496
237k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3497
237k
                                    SourceLocation(),
3498
237k
                                    DeclarationName());
3499
237k
  return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(),
3500
237k
                                                 Out);
3501
237k
}
3502
3503
ExprResult
3504
438k
Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
3505
438k
  if (!E)
3506
0
    return E;
3507
3508
438k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3509
438k
                                    SourceLocation(),
3510
438k
                                    DeclarationName());
3511
438k
  return Instantiator.TransformExpr(E);
3512
438k
}
3513
3514
ExprResult Sema::SubstInitializer(Expr *Init,
3515
                          const MultiLevelTemplateArgumentList &TemplateArgs,
3516
309k
                          bool CXXDirectInit) {
3517
309k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3518
309k
                                    SourceLocation(),
3519
309k
                                    DeclarationName());
3520
309k
  return Instantiator.TransformInitializer(Init, CXXDirectInit);
3521
309k
}
3522
3523
bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3524
                      const MultiLevelTemplateArgumentList &TemplateArgs,
3525
53
                      SmallVectorImpl<Expr *> &Outputs) {
3526
53
  if (Exprs.empty())
3527
4
    return false;
3528
3529
49
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3530
49
                                    SourceLocation(),
3531
49
                                    DeclarationName());
3532
49
  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3533
49
                                     IsCall, Outputs);
3534
53
}
3535
3536
NestedNameSpecifierLoc
3537
Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3538
27.2k
                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3539
27.2k
  if (!NNS)
3540
6.81k
    return NestedNameSpecifierLoc();
3541
3542
20.4k
  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3543
20.4k
                                    DeclarationName());
3544
20.4k
  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3545
27.2k
}
3546
3547
/// Do template substitution on declaration name info.
3548
DeclarationNameInfo
3549
Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3550
2.55M
                         const MultiLevelTemplateArgumentList &TemplateArgs) {
3551
2.55M
  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
3552
2.55M
                                    NameInfo.getName());
3553
2.55M
  return Instantiator.TransformDeclarationNameInfo(NameInfo);
3554
2.55M
}
3555
3556
TemplateName
3557
Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
3558
                        TemplateName Name, SourceLocation Loc,
3559
8.85k
                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3560
8.85k
  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3561
8.85k
                                    DeclarationName());
3562
8.85k
  CXXScopeSpec SS;
3563
8.85k
  SS.Adopt(QualifierLoc);
3564
8.85k
  return Instantiator.TransformTemplateName(SS, Name, Loc);
3565
8.85k
}
3566
3567
5.19M
static const Decl *getCanonicalParmVarDecl(const Decl *D) {
3568
  // When storing ParmVarDecls in the local instantiation scope, we always
3569
  // want to use the ParmVarDecl from the canonical function declaration,
3570
  // since the map is then valid for any redeclaration or definition of that
3571
  // function.
3572
5.19M
  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3573
3.40M
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3574
3.39M
      unsigned i = PV->getFunctionScopeIndex();
3575
      // This parameter might be from a freestanding function type within the
3576
      // function and isn't necessarily referring to one of FD's parameters.
3577
3.39M
      if (i < FD->getNumParams() && 
FD->getParamDecl(i) == PV3.39M
)
3578
3.39M
        return FD->getCanonicalDecl()->getParamDecl(i);
3579
3.39M
    }
3580
3.40M
  }
3581
1.80M
  return D;
3582
5.19M
}
3583
3584
3585
llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3586
1.28M
LocalInstantiationScope::findInstantiationOf(const Decl *D) {
3587
1.28M
  D = getCanonicalParmVarDecl(D);
3588
1.99M
  for (LocalInstantiationScope *Current = this; Current;
3589
1.99M
       
Current = Current->Outer704k
) {
3590
3591
    // Check if we found something within this scope.
3592
1.99M
    const Decl *CheckD = D;
3593
1.99M
    do {
3594
1.99M
      LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3595
1.99M
      if (Found != Current->LocalDecls.end())
3596
1.28M
        return &Found->second;
3597
3598
      // If this is a tag declaration, it's possible that we need to look for
3599
      // a previous declaration.
3600
704k
      if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3601
840
        CheckD = Tag->getPreviousDecl();
3602
703k
      else
3603
703k
        CheckD = nullptr;
3604
704k
    } while (CheckD);
3605
3606
    // If we aren't combined with our outer scope, we're done.
3607
704k
    if (!Current->CombineWithOuterScope)
3608
673
      break;
3609
704k
  }
3610
3611
  // If we're performing a partial substitution during template argument
3612
  // deduction, we may not have values for template parameters yet.
3613
673
  if (isa<NonTypeTemplateParmDecl>(D) || 
isa<TemplateTypeParmDecl>(D)650
||
3614
673
      
isa<TemplateTemplateParmDecl>(D)132
)
3615
541
    return nullptr;
3616
3617
  // Local types referenced prior to definition may require instantiation.
3618
132
  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3619
30
    if (RD->isLocalClass())
3620
30
      return nullptr;
3621
3622
  // Enumeration types referenced prior to definition may appear as a result of
3623
  // error recovery.
3624
102
  if (isa<EnumDecl>(D))
3625
8
    return nullptr;
3626
3627
  // Materialized typedefs/type alias for implicit deduction guides may require
3628
  // instantiation.
3629
94
  if (isa<TypedefNameDecl>(D) &&
3630
94
      
isa<CXXDeductionGuideDecl>(D->getDeclContext())9
)
3631
9
    return nullptr;
3632
3633
  // If we didn't find the decl, then we either have a sema bug, or we have a
3634
  // forward reference to a label declaration.  Return null to indicate that
3635
  // we have an uninstantiated label.
3636
85
  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
3637
0
  return nullptr;
3638
94
}
3639
3640
3.84M
void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
3641
3.84M
  D = getCanonicalParmVarDecl(D);
3642
3.84M
  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3643
3.84M
  if (Stored.isNull()) {
3644
3.71M
#ifndef NDEBUG
3645
    // It should not be present in any surrounding scope either.
3646
3.71M
    LocalInstantiationScope *Current = this;
3647
5.99M
    while (Current->CombineWithOuterScope && 
Current->Outer2.28M
) {
3648
2.27M
      Current = Current->Outer;
3649
2.27M
      assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3650
2.27M
             "Instantiated local in inner and outer scopes");
3651
2.27M
    }
3652
3.71M
#endif
3653
3.71M
    Stored = Inst;
3654
3.71M
  } else 
if (DeclArgumentPack *127k
Pack127k
= Stored.dyn_cast<DeclArgumentPack *>()) {
3655
353
    Pack->push_back(cast<VarDecl>(Inst));
3656
127k
  } else {
3657
127k
    assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3658
127k
  }
3659
3.84M
}
3660
3661
void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
3662
40.1k
                                                       VarDecl *Inst) {
3663
40.1k
  D = getCanonicalParmVarDecl(D);
3664
40.1k
  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3665
40.1k
  Pack->push_back(Inst);
3666
40.1k
}
3667
3668
25.0k
void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
3669
25.0k
#ifndef NDEBUG
3670
  // This should be the first time we've been told about this decl.
3671
25.0k
  for (LocalInstantiationScope *Current = this;
3672
38.9k
       Current && 
Current->CombineWithOuterScope38.8k
;
Current = Current->Outer13.9k
)
3673
13.9k
    assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3674
25.0k
           "Creating local pack after instantiation of local");
3675
25.0k
#endif
3676
3677
25.0k
  D = getCanonicalParmVarDecl(D);
3678
25.0k
  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3679
25.0k
  DeclArgumentPack *Pack = new DeclArgumentPack;
3680
25.0k
  Stored = Pack;
3681
25.0k
  ArgumentPacks.push_back(Pack);
3682
25.0k
}
3683
3684
55
bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
3685
55
  for (DeclArgumentPack *Pack : ArgumentPacks)
3686
61
    if (llvm::is_contained(*Pack, D))
3687
55
      return true;
3688
0
  return false;
3689
55
}
3690
3691
void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
3692
                                          const TemplateArgument *ExplicitArgs,
3693
24.9k
                                                    unsigned NumExplicitArgs) {
3694
24.9k
  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3695
24.9k
         "Already have a partially-substituted pack");
3696
0
  assert((!PartiallySubstitutedPack
3697
24.9k
          || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3698
24.9k
         "Wrong number of arguments in partially-substituted pack");
3699
0
  PartiallySubstitutedPack = Pack;
3700
24.9k
  ArgsInPartiallySubstitutedPack = ExplicitArgs;
3701
24.9k
  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3702
24.9k
}
3703
3704
NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3705
                                         const TemplateArgument **ExplicitArgs,
3706
328k
                                              unsigned *NumExplicitArgs) const {
3707
328k
  if (ExplicitArgs)
3708
51.4k
    *ExplicitArgs = nullptr;
3709
328k
  if (NumExplicitArgs)
3710
51.4k
    *NumExplicitArgs = 0;
3711
3712
372k
  for (const LocalInstantiationScope *Current = this; Current;
3713
372k
       
Current = Current->Outer43.9k
) {
3714
372k
    if (Current->PartiallySubstitutedPack) {
3715
56.3k
      if (ExplicitArgs)
3716
19.4k
        *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3717
56.3k
      if (NumExplicitArgs)
3718
19.4k
        *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3719
3720
56.3k
      return Current->PartiallySubstitutedPack;
3721
56.3k
    }
3722
3723
315k
    if (!Current->CombineWithOuterScope)
3724
271k
      break;
3725
315k
  }
3726
3727
272k
  return nullptr;
3728
328k
}