1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 //  This file implements C++ template instantiation.
10 //
11 //===----------------------------------------------------------------------===/
12 
13 #include "Sema.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Parse/DeclSpec.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "llvm/Support/Compiler.h"
21 
22 using namespace clang;
23 
24 //===----------------------------------------------------------------------===/
25 // Template Instantiation Support
26 //===----------------------------------------------------------------------===/
27 
28 /// \brief Retrieve the template argument list that should be used to
29 /// instantiate the given declaration.
30 const TemplateArgumentList &
31 Sema::getTemplateInstantiationArgs(NamedDecl *D) {
32   // Template arguments for a class template specialization.
33   if (ClassTemplateSpecializationDecl *Spec
34         = dyn_cast<ClassTemplateSpecializationDecl>(D))
35     return Spec->getTemplateInstantiationArgs();
36 
37   // Template arguments for a function template specialization.
38   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
39     if (const TemplateArgumentList *TemplateArgs
40           = Function->getTemplateSpecializationArgs())
41       return *TemplateArgs;
42 
43   // Template arguments for a member of a class template specialization.
44   DeclContext *EnclosingTemplateCtx = D->getDeclContext();
45   while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) {
46     assert(!EnclosingTemplateCtx->isFileContext() &&
47            "Tried to get the instantiation arguments of a non-template");
48     EnclosingTemplateCtx = EnclosingTemplateCtx->getParent();
49   }
50 
51   ClassTemplateSpecializationDecl *EnclosingTemplate
52     = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx);
53   return EnclosingTemplate->getTemplateInstantiationArgs();
54 }
55 
56 Sema::InstantiatingTemplate::
57 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
58                       Decl *Entity,
59                       SourceRange InstantiationRange)
60   :  SemaRef(SemaRef) {
61 
62   Invalid = CheckInstantiationDepth(PointOfInstantiation,
63                                     InstantiationRange);
64   if (!Invalid) {
65     ActiveTemplateInstantiation Inst;
66     Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
67     Inst.PointOfInstantiation = PointOfInstantiation;
68     Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
69     Inst.TemplateArgs = 0;
70     Inst.NumTemplateArgs = 0;
71     Inst.InstantiationRange = InstantiationRange;
72     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
73     Invalid = false;
74   }
75 }
76 
77 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
78                                          SourceLocation PointOfInstantiation,
79                                          TemplateDecl *Template,
80                                          const TemplateArgument *TemplateArgs,
81                                          unsigned NumTemplateArgs,
82                                          SourceRange InstantiationRange)
83   : SemaRef(SemaRef) {
84 
85   Invalid = CheckInstantiationDepth(PointOfInstantiation,
86                                     InstantiationRange);
87   if (!Invalid) {
88     ActiveTemplateInstantiation Inst;
89     Inst.Kind
90       = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
91     Inst.PointOfInstantiation = PointOfInstantiation;
92     Inst.Entity = reinterpret_cast<uintptr_t>(Template);
93     Inst.TemplateArgs = TemplateArgs;
94     Inst.NumTemplateArgs = NumTemplateArgs;
95     Inst.InstantiationRange = InstantiationRange;
96     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
97     Invalid = false;
98   }
99 }
100 
101 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
102                                          SourceLocation PointOfInstantiation,
103                                       FunctionTemplateDecl *FunctionTemplate,
104                                         const TemplateArgument *TemplateArgs,
105                                                    unsigned NumTemplateArgs,
106                          ActiveTemplateInstantiation::InstantiationKind Kind,
107                                               SourceRange InstantiationRange)
108 : SemaRef(SemaRef) {
109 
110   Invalid = CheckInstantiationDepth(PointOfInstantiation,
111                                     InstantiationRange);
112   if (!Invalid) {
113     ActiveTemplateInstantiation Inst;
114     Inst.Kind = Kind;
115     Inst.PointOfInstantiation = PointOfInstantiation;
116     Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
117     Inst.TemplateArgs = TemplateArgs;
118     Inst.NumTemplateArgs = NumTemplateArgs;
119     Inst.InstantiationRange = InstantiationRange;
120     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
121     Invalid = false;
122   }
123 }
124 
125 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
126                                          SourceLocation PointOfInstantiation,
127                           ClassTemplatePartialSpecializationDecl *PartialSpec,
128                                          const TemplateArgument *TemplateArgs,
129                                          unsigned NumTemplateArgs,
130                                          SourceRange InstantiationRange)
131   : SemaRef(SemaRef) {
132 
133   Invalid = CheckInstantiationDepth(PointOfInstantiation,
134                                     InstantiationRange);
135   if (!Invalid) {
136     ActiveTemplateInstantiation Inst;
137     Inst.Kind
138       = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
139     Inst.PointOfInstantiation = PointOfInstantiation;
140     Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
141     Inst.TemplateArgs = TemplateArgs;
142     Inst.NumTemplateArgs = NumTemplateArgs;
143     Inst.InstantiationRange = InstantiationRange;
144     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
145     Invalid = false;
146   }
147 }
148 
149 void Sema::InstantiatingTemplate::Clear() {
150   if (!Invalid) {
151     SemaRef.ActiveTemplateInstantiations.pop_back();
152     Invalid = true;
153   }
154 }
155 
156 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
157                                         SourceLocation PointOfInstantiation,
158                                            SourceRange InstantiationRange) {
159   if (SemaRef.ActiveTemplateInstantiations.size()
160        <= SemaRef.getLangOptions().InstantiationDepth)
161     return false;
162 
163   SemaRef.Diag(PointOfInstantiation,
164                diag::err_template_recursion_depth_exceeded)
165     << SemaRef.getLangOptions().InstantiationDepth
166     << InstantiationRange;
167   SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
168     << SemaRef.getLangOptions().InstantiationDepth;
169   return true;
170 }
171 
172 /// \brief Prints the current instantiation stack through a series of
173 /// notes.
174 void Sema::PrintInstantiationStack() {
175   // FIXME: In all of these cases, we need to show the template arguments
176   for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
177          Active = ActiveTemplateInstantiations.rbegin(),
178          ActiveEnd = ActiveTemplateInstantiations.rend();
179        Active != ActiveEnd;
180        ++Active) {
181     switch (Active->Kind) {
182     case ActiveTemplateInstantiation::TemplateInstantiation: {
183       Decl *D = reinterpret_cast<Decl *>(Active->Entity);
184       if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
185         unsigned DiagID = diag::note_template_member_class_here;
186         if (isa<ClassTemplateSpecializationDecl>(Record))
187           DiagID = diag::note_template_class_instantiation_here;
188         Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
189                      DiagID)
190           << Context.getTypeDeclType(Record)
191           << Active->InstantiationRange;
192       } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
193         unsigned DiagID;
194         if (Function->getPrimaryTemplate())
195           DiagID = diag::note_function_template_spec_here;
196         else
197           DiagID = diag::note_template_member_function_here;
198         Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
199                      DiagID)
200           << Function
201           << Active->InstantiationRange;
202       } else {
203         Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
204                      diag::note_template_static_data_member_def_here)
205           << cast<VarDecl>(D)
206           << Active->InstantiationRange;
207       }
208       break;
209     }
210 
211     case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
212       TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
213       std::string TemplateArgsStr
214         = TemplateSpecializationType::PrintTemplateArgumentList(
215                                                          Active->TemplateArgs,
216                                                       Active->NumTemplateArgs,
217                                                       Context.PrintingPolicy);
218       Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
219                    diag::note_default_arg_instantiation_here)
220         << (Template->getNameAsString() + TemplateArgsStr)
221         << Active->InstantiationRange;
222       break;
223     }
224 
225     case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
226       FunctionTemplateDecl *FnTmpl
227         = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
228       Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
229                    diag::note_explicit_template_arg_substitution_here)
230         << FnTmpl << Active->InstantiationRange;
231       break;
232     }
233 
234     case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
235       if (ClassTemplatePartialSpecializationDecl *PartialSpec
236             = dyn_cast<ClassTemplatePartialSpecializationDecl>(
237                                                     (Decl *)Active->Entity)) {
238         Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
239                      diag::note_partial_spec_deduct_instantiation_here)
240           << Context.getTypeDeclType(PartialSpec)
241           << Active->InstantiationRange;
242       } else {
243         FunctionTemplateDecl *FnTmpl
244           = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
245         Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
246                      diag::note_function_template_deduction_instantiation_here)
247           << FnTmpl << Active->InstantiationRange;
248       }
249       break;
250 
251     }
252   }
253 }
254 
255 bool Sema::isSFINAEContext() const {
256   using llvm::SmallVector;
257   for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
258          Active = ActiveTemplateInstantiations.rbegin(),
259          ActiveEnd = ActiveTemplateInstantiations.rend();
260        Active != ActiveEnd;
261        ++Active) {
262 
263     switch(Active->Kind) {
264     case ActiveTemplateInstantiation::TemplateInstantiation:
265       // This is a template instantiation, so there is no SFINAE.
266       return false;
267 
268     case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
269       // A default template argument instantiation may or may not be a
270       // SFINAE context; look further up the stack.
271       break;
272 
273     case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
274     case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
275       // We're either substitution explicitly-specified template arguments
276       // or deduced template arguments, so SFINAE applies.
277       return true;
278     }
279   }
280 
281   return false;
282 }
283 
284 //===----------------------------------------------------------------------===/
285 // Template Instantiation for Types
286 //===----------------------------------------------------------------------===/
287 namespace {
288   class VISIBILITY_HIDDEN TemplateTypeInstantiator {
289     Sema &SemaRef;
290     const TemplateArgumentList &TemplateArgs;
291     SourceLocation Loc;
292     DeclarationName Entity;
293 
294   public:
295     TemplateTypeInstantiator(Sema &SemaRef,
296                              const TemplateArgumentList &TemplateArgs,
297                              SourceLocation Loc,
298                              DeclarationName Entity)
299       : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
300         Loc(Loc), Entity(Entity) { }
301 
302     QualType operator()(QualType T) const { return Instantiate(T); }
303 
304     QualType Instantiate(QualType T) const;
305 
306     // Declare instantiate functions for each type.
307 #define TYPE(Class, Base)                                       \
308     QualType Instantiate##Class##Type(const Class##Type *T) const;
309 #define ABSTRACT_TYPE(Class, Base)
310 #include "clang/AST/TypeNodes.def"
311   };
312 }
313 
314 QualType
315 TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T) const {
316   // FIXME: Implement this
317   assert(false && "Cannot instantiate ExtQualType yet");
318   return QualType();
319 }
320 
321 QualType
322 TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T) const {
323   assert(false && "Builtin types are not dependent and cannot be instantiated");
324   return QualType(T, 0);
325 }
326 
327 QualType
328 TemplateTypeInstantiator::
329 InstantiateFixedWidthIntType(const FixedWidthIntType *T) const {
330   // FIXME: Implement this
331   assert(false && "Cannot instantiate FixedWidthIntType yet");
332   return QualType();
333 }
334 
335 QualType
336 TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T) const {
337   // FIXME: Implement this
338   assert(false && "Cannot instantiate ComplexType yet");
339   return QualType();
340 }
341 
342 QualType
343 TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T) const {
344   QualType PointeeType = Instantiate(T->getPointeeType());
345   if (PointeeType.isNull())
346     return QualType();
347 
348   return SemaRef.BuildPointerType(PointeeType, 0, Loc, Entity);
349 }
350 
351 QualType
352 TemplateTypeInstantiator::InstantiateBlockPointerType(
353                                             const BlockPointerType *T) const {
354   QualType PointeeType = Instantiate(T->getPointeeType());
355   if (PointeeType.isNull())
356     return QualType();
357 
358   return SemaRef.BuildBlockPointerType(PointeeType, 0, Loc, Entity);
359 }
360 
361 QualType
362 TemplateTypeInstantiator::InstantiateLValueReferenceType(
363                                         const LValueReferenceType *T) const {
364   QualType ReferentType = Instantiate(T->getPointeeType());
365   if (ReferentType.isNull())
366     return QualType();
367 
368   return SemaRef.BuildReferenceType(ReferentType, true, 0, Loc, Entity);
369 }
370 
371 QualType
372 TemplateTypeInstantiator::InstantiateRValueReferenceType(
373                                         const RValueReferenceType *T) const {
374   QualType ReferentType = Instantiate(T->getPointeeType());
375   if (ReferentType.isNull())
376     return QualType();
377 
378   return SemaRef.BuildReferenceType(ReferentType, false, 0, Loc, Entity);
379 }
380 
381 QualType
382 TemplateTypeInstantiator::
383 InstantiateMemberPointerType(const MemberPointerType *T) const {
384   QualType PointeeType = Instantiate(T->getPointeeType());
385   if (PointeeType.isNull())
386     return QualType();
387 
388   QualType ClassType = Instantiate(QualType(T->getClass(), 0));
389   if (ClassType.isNull())
390     return QualType();
391 
392   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, 0, Loc,
393                                         Entity);
394 }
395 
396 QualType
397 TemplateTypeInstantiator::
398 InstantiateConstantArrayType(const ConstantArrayType *T) const {
399   QualType ElementType = Instantiate(T->getElementType());
400   if (ElementType.isNull())
401     return ElementType;
402 
403   // Build a temporary integer literal to specify the size for
404   // BuildArrayType. Since we have already checked the size as part of
405   // creating the dependent array type in the first place, we know
406   // there aren't any errors. However, we do need to determine what
407   // C++ type to give the size expression.
408   llvm::APInt Size = T->getSize();
409   QualType Types[] = {
410     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
411     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
412     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
413   };
414   const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
415   QualType SizeType;
416   for (unsigned I = 0; I != NumTypes; ++I)
417     if (Size.getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
418       SizeType = Types[I];
419       break;
420     }
421 
422   if (SizeType.isNull())
423     SizeType = SemaRef.Context.getFixedWidthIntType(Size.getBitWidth(), false);
424 
425   IntegerLiteral ArraySize(Size, SizeType, Loc);
426   return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
427                                 &ArraySize, T->getIndexTypeQualifier(),
428                                 SourceRange(), // FIXME: provide proper range?
429                                 Entity);
430 }
431 
432 QualType
433 TemplateTypeInstantiator::InstantiateConstantArrayWithExprType
434 (const ConstantArrayWithExprType *T) const {
435   return InstantiateConstantArrayType(T);
436 }
437 
438 QualType
439 TemplateTypeInstantiator::InstantiateConstantArrayWithoutExprType
440 (const ConstantArrayWithoutExprType *T) const {
441   return InstantiateConstantArrayType(T);
442 }
443 
444 QualType
445 TemplateTypeInstantiator::
446 InstantiateIncompleteArrayType(const IncompleteArrayType *T) const {
447   QualType ElementType = Instantiate(T->getElementType());
448   if (ElementType.isNull())
449     return ElementType;
450 
451   return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
452                                 0, T->getIndexTypeQualifier(),
453                                 SourceRange(), // FIXME: provide proper range?
454                                 Entity);
455 }
456 
457 QualType
458 TemplateTypeInstantiator::
459 InstantiateVariableArrayType(const VariableArrayType *T) const {
460   // FIXME: Implement this
461   assert(false && "Cannot instantiate VariableArrayType yet");
462   return QualType();
463 }
464 
465 QualType
466 TemplateTypeInstantiator::
467 InstantiateDependentSizedArrayType(const DependentSizedArrayType *T) const {
468   Expr *ArraySize = T->getSizeExpr();
469   assert(ArraySize->isValueDependent() &&
470          "dependent sized array types must have value dependent size expr");
471 
472   // Instantiate the element type if needed
473   QualType ElementType = T->getElementType();
474   if (ElementType->isDependentType()) {
475     ElementType = Instantiate(ElementType);
476     if (ElementType.isNull())
477       return QualType();
478   }
479 
480   // Instantiate the size expression
481   EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
482   Sema::OwningExprResult InstantiatedArraySize =
483     SemaRef.InstantiateExpr(ArraySize, TemplateArgs);
484   if (InstantiatedArraySize.isInvalid())
485     return QualType();
486 
487   return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
488                                 InstantiatedArraySize.takeAs<Expr>(),
489                                 T->getIndexTypeQualifier(),
490                                 SourceRange(), // FIXME: provide proper range?
491                                 Entity);
492 }
493 
494 QualType
495 TemplateTypeInstantiator::
496 InstantiateDependentSizedExtVectorType(
497                                 const DependentSizedExtVectorType *T) const {
498 
499   // Instantiate the element type if needed.
500   QualType ElementType = T->getElementType();
501   if (ElementType->isDependentType()) {
502     ElementType = Instantiate(ElementType);
503     if (ElementType.isNull())
504       return QualType();
505   }
506 
507   // The expression in a dependent-sized extended vector type is not
508   // potentially evaluated.
509   EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
510 
511   // Instantiate the size expression.
512   const Expr *SizeExpr = T->getSizeExpr();
513   Sema::OwningExprResult InstantiatedArraySize =
514     SemaRef.InstantiateExpr(const_cast<Expr *>(SizeExpr), TemplateArgs);
515   if (InstantiatedArraySize.isInvalid())
516     return QualType();
517 
518   return SemaRef.BuildExtVectorType(ElementType,
519                                     SemaRef.Owned(
520                                       InstantiatedArraySize.takeAs<Expr>()),
521                                     T->getAttributeLoc());
522 }
523 
524 QualType
525 TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T) const {
526   // FIXME: Implement this
527   assert(false && "Cannot instantiate VectorType yet");
528   return QualType();
529 }
530 
531 QualType
532 TemplateTypeInstantiator::InstantiateExtVectorType(
533                                               const ExtVectorType *T) const {
534   // FIXME: Implement this
535   assert(false && "Cannot instantiate ExtVectorType yet");
536   return QualType();
537 }
538 
539 QualType
540 TemplateTypeInstantiator::
541 InstantiateFunctionProtoType(const FunctionProtoType *T) const {
542   QualType ResultType = Instantiate(T->getResultType());
543   if (ResultType.isNull())
544     return ResultType;
545 
546   llvm::SmallVector<QualType, 4> ParamTypes;
547   for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
548                                          ParamEnd = T->arg_type_end();
549        Param != ParamEnd; ++Param) {
550     QualType P = Instantiate(*Param);
551     if (P.isNull())
552       return P;
553 
554     ParamTypes.push_back(P);
555   }
556 
557   return SemaRef.BuildFunctionType(ResultType, ParamTypes.data(),
558                                    ParamTypes.size(),
559                                    T->isVariadic(), T->getTypeQuals(),
560                                    Loc, Entity);
561 }
562 
563 QualType
564 TemplateTypeInstantiator::
565 InstantiateFunctionNoProtoType(const FunctionNoProtoType *T) const {
566   assert(false && "Functions without prototypes cannot be dependent.");
567   return QualType();
568 }
569 
570 QualType
571 TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T) const {
572   TypedefDecl *Typedef
573     = cast_or_null<TypedefDecl>(
574                            SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
575   if (!Typedef)
576     return QualType();
577 
578   return SemaRef.Context.getTypeDeclType(Typedef);
579 }
580 
581 QualType
582 TemplateTypeInstantiator::InstantiateTypeOfExprType(
583                                               const TypeOfExprType *T) const {
584   // The expression in a typeof is not potentially evaluated.
585   EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
586 
587   Sema::OwningExprResult E
588     = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
589   if (E.isInvalid())
590     return QualType();
591 
592   return SemaRef.BuildTypeofExprType(E.takeAs<Expr>());
593 }
594 
595 QualType
596 TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T) const {
597   QualType Underlying = Instantiate(T->getUnderlyingType());
598   if (Underlying.isNull())
599     return QualType();
600 
601   return SemaRef.Context.getTypeOfType(Underlying);
602 }
603 
604 QualType
605 TemplateTypeInstantiator::InstantiateDecltypeType(const DecltypeType *T) const {
606   // C++0x [dcl.type.simple]p4:
607   //   The operand of the decltype specifier is an unevaluated operand.
608   EnterExpressionEvaluationContext Unevaluated(SemaRef,
609                                                Action::Unevaluated);
610 
611   Sema::OwningExprResult E
612     = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
613 
614   if (E.isInvalid())
615     return QualType();
616 
617   return SemaRef.BuildDecltypeType(E.takeAs<Expr>());
618 }
619 
620 QualType
621 TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T) const {
622   RecordDecl *Record
623     = cast_or_null<RecordDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
624   if (!Record)
625     return QualType();
626 
627   return SemaRef.Context.getTypeDeclType(Record);
628 }
629 
630 QualType
631 TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T) const {
632   EnumDecl *Enum
633     = cast_or_null<EnumDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
634   if (!Enum)
635     return QualType();
636 
637   return SemaRef.Context.getTypeDeclType(Enum);
638 }
639 
640 QualType
641 TemplateTypeInstantiator::
642 InstantiateTemplateTypeParmType(const TemplateTypeParmType *T) const {
643   if (T->getDepth() == 0) {
644     // Replace the template type parameter with its corresponding
645     // template argument.
646 
647     // If the corresponding template argument is NULL or doesn't exist, it's
648     // because we are performing instantiation from explicitly-specified
649     // template arguments in a function template class, but there were some
650     // arguments left unspecified.
651     if (T->getIndex() >= TemplateArgs.size() ||
652         TemplateArgs[T->getIndex()].isNull())
653       return QualType(T, 0); // Would be nice to keep the original type here
654 
655     assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
656            "Template argument kind mismatch");
657     return TemplateArgs[T->getIndex()].getAsType();
658   }
659 
660   // The template type parameter comes from an inner template (e.g.,
661   // the template parameter list of a member template inside the
662   // template we are instantiating). Create a new template type
663   // parameter with the template "level" reduced by one.
664   return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
665                                                  T->getIndex(),
666                                                  T->isParameterPack(),
667                                                  T->getName());
668 }
669 
670 QualType
671 TemplateTypeInstantiator::
672 InstantiateTemplateSpecializationType(
673                                   const TemplateSpecializationType *T) const {
674   llvm::SmallVector<TemplateArgument, 4> InstantiatedTemplateArgs;
675   InstantiatedTemplateArgs.reserve(T->getNumArgs());
676   for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
677        Arg != ArgEnd; ++Arg) {
678     TemplateArgument InstArg = SemaRef.Instantiate(*Arg, TemplateArgs);
679     if (InstArg.isNull())
680       return QualType();
681 
682     InstantiatedTemplateArgs.push_back(InstArg);
683   }
684 
685   // FIXME: We're missing the locations of the template name, '<', and '>'.
686 
687   TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
688                                                       Loc,
689                                                       TemplateArgs);
690 
691   return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
692                                      InstantiatedTemplateArgs.data(),
693                                      InstantiatedTemplateArgs.size(),
694                                      SourceLocation());
695 }
696 
697 QualType
698 TemplateTypeInstantiator::
699 InstantiateQualifiedNameType(const QualifiedNameType *T) const {
700   // When we instantiated a qualified name type, there's no point in
701   // keeping the qualification around in the instantiated result. So,
702   // just instantiate the named type.
703   return (*this)(T->getNamedType());
704 }
705 
706 QualType
707 TemplateTypeInstantiator::
708 InstantiateTypenameType(const TypenameType *T) const {
709   if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
710     // When the typename type refers to a template-id, the template-id
711     // is dependent and has enough information to instantiate the
712     // result of the typename type. Since we don't care about keeping
713     // the spelling of the typename type in template instantiations,
714     // we just instantiate the template-id.
715     return InstantiateTemplateSpecializationType(TemplateId);
716   }
717 
718   NestedNameSpecifier *NNS
719     = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
720                                              SourceRange(Loc),
721                                              TemplateArgs);
722   if (!NNS)
723     return QualType();
724 
725   return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc));
726 }
727 
728 QualType
729 TemplateTypeInstantiator::
730 InstantiateObjCObjectPointerType(const ObjCObjectPointerType *T) const {
731   assert(false && "Objective-C types cannot be dependent");
732   return QualType();
733 }
734 
735 QualType
736 TemplateTypeInstantiator::
737 InstantiateObjCInterfaceType(const ObjCInterfaceType *T) const {
738   assert(false && "Objective-C types cannot be dependent");
739   return QualType();
740 }
741 
742 /// \brief The actual implementation of Sema::InstantiateType().
743 QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
744   // If T is not a dependent type, there is nothing to do.
745   if (!T->isDependentType())
746     return T;
747 
748   QualType Result;
749   switch (T->getTypeClass()) {
750 #define TYPE(Class, Base)                                               \
751   case Type::Class:                                                     \
752     Result = Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()));  \
753     break;
754 #define ABSTRACT_TYPE(Class, Base)
755 #include "clang/AST/TypeNodes.def"
756   }
757 
758   // C++ [dcl.ref]p1:
759   //   [...] Cv-qualified references are ill-formed except when
760   //   the cv-qualifiers are introduced through the use of a
761   //   typedef (7.1.3) or of a template type argument (14.3), in
762   //   which case the cv-qualifiers are ignored.
763   //
764   // The same rule applies to function types.
765   // FIXME: what about address-space and Objective-C GC qualifiers?
766   if (!Result.isNull() && T.getCVRQualifiers() &&
767       !Result->isFunctionType() && !Result->isReferenceType())
768     Result = Result.getWithAdditionalQualifiers(T.getCVRQualifiers());
769   return Result;
770 }
771 
772 /// \brief Instantiate the type T with a given set of template arguments.
773 ///
774 /// This routine substitutes the given template arguments into the
775 /// type T and produces the instantiated type.
776 ///
777 /// \param T the type into which the template arguments will be
778 /// substituted. If this type is not dependent, it will be returned
779 /// immediately.
780 ///
781 /// \param TemplateArgs the template arguments that will be
782 /// substituted for the top-level template parameters within T.
783 ///
784 /// \param Loc the location in the source code where this substitution
785 /// is being performed. It will typically be the location of the
786 /// declarator (if we're instantiating the type of some declaration)
787 /// or the location of the type in the source code (if, e.g., we're
788 /// instantiating the type of a cast expression).
789 ///
790 /// \param Entity the name of the entity associated with a declaration
791 /// being instantiated (if any). May be empty to indicate that there
792 /// is no such entity (if, e.g., this is a type that occurs as part of
793 /// a cast expression) or that the entity has no name (e.g., an
794 /// unnamed function parameter).
795 ///
796 /// \returns If the instantiation succeeds, the instantiated
797 /// type. Otherwise, produces diagnostics and returns a NULL type.
798 QualType Sema::InstantiateType(QualType T,
799                                const TemplateArgumentList &TemplateArgs,
800                                SourceLocation Loc, DeclarationName Entity) {
801   assert(!ActiveTemplateInstantiations.empty() &&
802          "Cannot perform an instantiation without some context on the "
803          "instantiation stack");
804 
805   // If T is not a dependent type, there is nothing to do.
806   if (!T->isDependentType())
807     return T;
808 
809   TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
810   return Instantiator(T);
811 }
812 
813 /// \brief Instantiate the base class specifiers of the given class
814 /// template specialization.
815 ///
816 /// Produces a diagnostic and returns true on error, returns false and
817 /// attaches the instantiated base classes to the class template
818 /// specialization if successful.
819 bool
820 Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
821                                 CXXRecordDecl *Pattern,
822                                 const TemplateArgumentList &TemplateArgs) {
823   bool Invalid = false;
824   llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
825   for (ClassTemplateSpecializationDecl::base_class_iterator
826          Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
827        Base != BaseEnd; ++Base) {
828     if (!Base->getType()->isDependentType()) {
829       InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
830       continue;
831     }
832 
833     QualType BaseType = InstantiateType(Base->getType(),
834                                         TemplateArgs,
835                                         Base->getSourceRange().getBegin(),
836                                         DeclarationName());
837     if (BaseType.isNull()) {
838       Invalid = true;
839       continue;
840     }
841 
842     if (CXXBaseSpecifier *InstantiatedBase
843           = CheckBaseSpecifier(Instantiation,
844                                Base->getSourceRange(),
845                                Base->isVirtual(),
846                                Base->getAccessSpecifierAsWritten(),
847                                BaseType,
848                                /*FIXME: Not totally accurate */
849                                Base->getSourceRange().getBegin()))
850       InstantiatedBases.push_back(InstantiatedBase);
851     else
852       Invalid = true;
853   }
854 
855   if (!Invalid &&
856       AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
857                            InstantiatedBases.size()))
858     Invalid = true;
859 
860   return Invalid;
861 }
862 
863 /// \brief Instantiate the definition of a class from a given pattern.
864 ///
865 /// \param PointOfInstantiation The point of instantiation within the
866 /// source code.
867 ///
868 /// \param Instantiation is the declaration whose definition is being
869 /// instantiated. This will be either a class template specialization
870 /// or a member class of a class template specialization.
871 ///
872 /// \param Pattern is the pattern from which the instantiation
873 /// occurs. This will be either the declaration of a class template or
874 /// the declaration of a member class of a class template.
875 ///
876 /// \param TemplateArgs The template arguments to be substituted into
877 /// the pattern.
878 ///
879 /// \returns true if an error occurred, false otherwise.
880 bool
881 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
882                        CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
883                        const TemplateArgumentList &TemplateArgs,
884                        bool ExplicitInstantiation) {
885   bool Invalid = false;
886 
887   CXXRecordDecl *PatternDef
888     = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
889   if (!PatternDef) {
890     if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
891       Diag(PointOfInstantiation,
892            diag::err_implicit_instantiate_member_undefined)
893         << Context.getTypeDeclType(Instantiation);
894       Diag(Pattern->getLocation(), diag::note_member_of_template_here);
895     } else {
896       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
897         << ExplicitInstantiation
898         << Context.getTypeDeclType(Instantiation);
899       Diag(Pattern->getLocation(), diag::note_template_decl_here);
900     }
901     return true;
902   }
903   Pattern = PatternDef;
904 
905   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
906   if (Inst)
907     return true;
908 
909   // Enter the scope of this instantiation. We don't use
910   // PushDeclContext because we don't have a scope.
911   DeclContext *PreviousContext = CurContext;
912   CurContext = Instantiation;
913 
914   // Start the definition of this instantiation.
915   Instantiation->startDefinition();
916 
917   // Instantiate the base class specifiers.
918   if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
919     Invalid = true;
920 
921   llvm::SmallVector<DeclPtrTy, 4> Fields;
922   for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
923          MemberEnd = Pattern->decls_end();
924        Member != MemberEnd; ++Member) {
925     Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
926     if (NewMember) {
927       if (NewMember->isInvalidDecl())
928         Invalid = true;
929       else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
930         Fields.push_back(DeclPtrTy::make(Field));
931     } else {
932       // FIXME: Eventually, a NULL return will mean that one of the
933       // instantiations was a semantic disaster, and we'll want to set Invalid =
934       // true. For now, we expect to skip some members that we can't yet handle.
935     }
936   }
937 
938   // Finish checking fields.
939   ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
940               Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
941               0);
942 
943   // Add any implicitly-declared members that we might need.
944   AddImplicitlyDeclaredMembersToClass(Instantiation);
945 
946   // Exit the scope of this instantiation.
947   CurContext = PreviousContext;
948 
949   if (!Invalid)
950     Consumer.HandleTagDeclDefinition(Instantiation);
951 
952   // If this is an explicit instantiation, instantiate our members, too.
953   if (!Invalid && ExplicitInstantiation) {
954     Inst.Clear();
955     InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
956   }
957 
958   return Invalid;
959 }
960 
961 bool
962 Sema::InstantiateClassTemplateSpecialization(
963                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
964                            bool ExplicitInstantiation) {
965   // Perform the actual instantiation on the canonical declaration.
966   ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
967                                          ClassTemplateSpec->getCanonicalDecl());
968 
969   // We can only instantiate something that hasn't already been
970   // instantiated or specialized. Fail without any diagnostics: our
971   // caller will provide an error message.
972   if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
973     return true;
974 
975   ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
976   CXXRecordDecl *Pattern = Template->getTemplatedDecl();
977   const TemplateArgumentList *TemplateArgs
978     = &ClassTemplateSpec->getTemplateArgs();
979 
980   // C++ [temp.class.spec.match]p1:
981   //   When a class template is used in a context that requires an
982   //   instantiation of the class, it is necessary to determine
983   //   whether the instantiation is to be generated using the primary
984   //   template or one of the partial specializations. This is done by
985   //   matching the template arguments of the class template
986   //   specialization with the template argument lists of the partial
987   //   specializations.
988   typedef std::pair<ClassTemplatePartialSpecializationDecl *,
989                     TemplateArgumentList *> MatchResult;
990   llvm::SmallVector<MatchResult, 4> Matched;
991   for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
992          Partial = Template->getPartialSpecializations().begin(),
993          PartialEnd = Template->getPartialSpecializations().end();
994        Partial != PartialEnd;
995        ++Partial) {
996     TemplateDeductionInfo Info(Context);
997     if (TemplateDeductionResult Result
998           = DeduceTemplateArguments(&*Partial,
999                                     ClassTemplateSpec->getTemplateArgs(),
1000                                     Info)) {
1001       // FIXME: Store the failed-deduction information for use in
1002       // diagnostics, later.
1003       (void)Result;
1004     } else {
1005       Matched.push_back(std::make_pair(&*Partial, Info.take()));
1006     }
1007   }
1008 
1009   if (Matched.size() == 1) {
1010     //   -- If exactly one matching specialization is found, the
1011     //      instantiation is generated from that specialization.
1012     Pattern = Matched[0].first;
1013     TemplateArgs = Matched[0].second;
1014     ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second);
1015   } else if (Matched.size() > 1) {
1016     //   -- If more than one matching specialization is found, the
1017     //      partial order rules (14.5.4.2) are used to determine
1018     //      whether one of the specializations is more specialized
1019     //      than the others. If none of the specializations is more
1020     //      specialized than all of the other matching
1021     //      specializations, then the use of the class template is
1022     //      ambiguous and the program is ill-formed.
1023     // FIXME: Implement partial ordering of class template partial
1024     // specializations.
1025     Diag(ClassTemplateSpec->getLocation(),
1026          diag::unsup_template_partial_spec_ordering);
1027   } else {
1028     //   -- If no matches are found, the instantiation is generated
1029     //      from the primary template.
1030 
1031     // Since we initialized the pattern and template arguments from
1032     // the primary template, there is nothing more we need to do here.
1033   }
1034 
1035   // Note that this is an instantiation.
1036   ClassTemplateSpec->setSpecializationKind(
1037                         ExplicitInstantiation? TSK_ExplicitInstantiation
1038                                              : TSK_ImplicitInstantiation);
1039 
1040   bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
1041                                  ClassTemplateSpec, Pattern, *TemplateArgs,
1042                                  ExplicitInstantiation);
1043 
1044   for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1045     // FIXME: Implement TemplateArgumentList::Destroy!
1046     //    if (Matched[I].first != Pattern)
1047     //      Matched[I].second->Destroy(Context);
1048   }
1049 
1050   return Result;
1051 }
1052 
1053 /// \brief Instantiate the definitions of all of the member of the
1054 /// given class, which is an instantiation of a class template or a
1055 /// member class of a template.
1056 void
1057 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1058                               CXXRecordDecl *Instantiation,
1059                               const TemplateArgumentList &TemplateArgs) {
1060   for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1061                                DEnd = Instantiation->decls_end();
1062        D != DEnd; ++D) {
1063     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1064       if (!Function->getBody())
1065         InstantiateFunctionDefinition(PointOfInstantiation, Function);
1066     } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1067       if (Var->isStaticDataMember())
1068         InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
1069     } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1070       if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
1071         assert(Record->getInstantiatedFromMemberClass() &&
1072                "Missing instantiated-from-template information");
1073         InstantiateClass(PointOfInstantiation, Record,
1074                          Record->getInstantiatedFromMemberClass(),
1075                          TemplateArgs, true);
1076       }
1077     }
1078   }
1079 }
1080 
1081 /// \brief Instantiate the definitions of all of the members of the
1082 /// given class template specialization, which was named as part of an
1083 /// explicit instantiation.
1084 void Sema::InstantiateClassTemplateSpecializationMembers(
1085                                            SourceLocation PointOfInstantiation,
1086                           ClassTemplateSpecializationDecl *ClassTemplateSpec) {
1087   // C++0x [temp.explicit]p7:
1088   //   An explicit instantiation that names a class template
1089   //   specialization is an explicit instantion of the same kind
1090   //   (declaration or definition) of each of its members (not
1091   //   including members inherited from base classes) that has not
1092   //   been previously explicitly specialized in the translation unit
1093   //   containing the explicit instantiation, except as described
1094   //   below.
1095   InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1096                           ClassTemplateSpec->getTemplateArgs());
1097 }
1098 
1099 /// \brief Instantiate a nested-name-specifier.
1100 NestedNameSpecifier *
1101 Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
1102                                      SourceRange Range,
1103                                      const TemplateArgumentList &TemplateArgs) {
1104   // Instantiate the prefix of this nested name specifier.
1105   NestedNameSpecifier *Prefix = NNS->getPrefix();
1106   if (Prefix) {
1107     Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs);
1108     if (!Prefix)
1109       return 0;
1110   }
1111 
1112   switch (NNS->getKind()) {
1113   case NestedNameSpecifier::Identifier: {
1114     assert(Prefix &&
1115            "Can't have an identifier nested-name-specifier with no prefix");
1116     CXXScopeSpec SS;
1117     // FIXME: The source location information is all wrong.
1118     SS.setRange(Range);
1119     SS.setScopeRep(Prefix);
1120     return static_cast<NestedNameSpecifier *>(
1121                                  ActOnCXXNestedNameSpecifier(0, SS,
1122                                                              Range.getEnd(),
1123                                                              Range.getEnd(),
1124                                                     *NNS->getAsIdentifier()));
1125     break;
1126   }
1127 
1128   case NestedNameSpecifier::Namespace:
1129   case NestedNameSpecifier::Global:
1130     return NNS;
1131 
1132   case NestedNameSpecifier::TypeSpecWithTemplate:
1133   case NestedNameSpecifier::TypeSpec: {
1134     QualType T = QualType(NNS->getAsType(), 0);
1135     if (!T->isDependentType())
1136       return NNS;
1137 
1138     T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName());
1139     if (T.isNull())
1140       return 0;
1141 
1142     if (T->isDependentType() || T->isRecordType() ||
1143         (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
1144       assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here");
1145       return NestedNameSpecifier::Create(Context, Prefix,
1146                  NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1147                                          T.getTypePtr());
1148     }
1149 
1150     Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
1151     return 0;
1152   }
1153   }
1154 
1155   // Required to silence a GCC warning
1156   return 0;
1157 }
1158 
1159 TemplateName
1160 Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
1161                               const TemplateArgumentList &TemplateArgs) {
1162   if (TemplateTemplateParmDecl *TTP
1163         = dyn_cast_or_null<TemplateTemplateParmDecl>(
1164                                                  Name.getAsTemplateDecl())) {
1165     assert(TTP->getDepth() == 0 &&
1166            "Cannot reduce depth of a template template parameter");
1167     assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
1168            "Wrong kind of template template argument");
1169     ClassTemplateDecl *ClassTemplate
1170       = dyn_cast<ClassTemplateDecl>(
1171                                TemplateArgs[TTP->getPosition()].getAsDecl());
1172     assert(ClassTemplate && "Expected a class template");
1173     if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
1174       NestedNameSpecifier *NNS
1175         = InstantiateNestedNameSpecifier(QTN->getQualifier(),
1176                                          /*FIXME=*/SourceRange(Loc),
1177                                          TemplateArgs);
1178       if (NNS)
1179         return Context.getQualifiedTemplateName(NNS,
1180                                                 QTN->hasTemplateKeyword(),
1181                                                 ClassTemplate);
1182     }
1183 
1184     return TemplateName(ClassTemplate);
1185   } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
1186     NestedNameSpecifier *NNS
1187       = InstantiateNestedNameSpecifier(DTN->getQualifier(),
1188                                        /*FIXME=*/SourceRange(Loc),
1189                                        TemplateArgs);
1190 
1191     if (!NNS) // FIXME: Not the best recovery strategy.
1192       return Name;
1193 
1194     if (NNS->isDependent())
1195       return Context.getDependentTemplateName(NNS, DTN->getName());
1196 
1197     // Somewhat redundant with ActOnDependentTemplateName.
1198     CXXScopeSpec SS;
1199     SS.setRange(SourceRange(Loc));
1200     SS.setScopeRep(NNS);
1201     TemplateTy Template;
1202     TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
1203     if (TNK == TNK_Non_template) {
1204       Diag(Loc, diag::err_template_kw_refers_to_non_template)
1205         << DTN->getName();
1206       return Name;
1207     } else if (TNK == TNK_Function_template) {
1208       Diag(Loc, diag::err_template_kw_refers_to_non_template)
1209         << DTN->getName();
1210       return Name;
1211     }
1212 
1213     return Template.getAsVal<TemplateName>();
1214   }
1215 
1216 
1217 
1218   // FIXME: Even if we're referring to a Decl that isn't a template template
1219   // parameter, we may need to instantiate the outer contexts of that
1220   // Decl. However, this won't be needed until we implement member templates.
1221   return Name;
1222 }
1223 
1224 TemplateArgument Sema::Instantiate(TemplateArgument Arg,
1225                                    const TemplateArgumentList &TemplateArgs) {
1226   switch (Arg.getKind()) {
1227   case TemplateArgument::Null:
1228     assert(false && "Should never have a NULL template argument");
1229     break;
1230 
1231   case TemplateArgument::Type: {
1232     QualType T = InstantiateType(Arg.getAsType(), TemplateArgs,
1233                                  Arg.getLocation(), DeclarationName());
1234     if (T.isNull())
1235       return TemplateArgument();
1236 
1237     return TemplateArgument(Arg.getLocation(), T);
1238   }
1239 
1240   case TemplateArgument::Declaration:
1241     // FIXME: Template instantiation for template template parameters.
1242     return Arg;
1243 
1244   case TemplateArgument::Integral:
1245     return Arg;
1246 
1247   case TemplateArgument::Expression: {
1248     // Template argument expressions are not potentially evaluated.
1249     EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
1250 
1251     Sema::OwningExprResult E = InstantiateExpr(Arg.getAsExpr(), TemplateArgs);
1252     if (E.isInvalid())
1253       return TemplateArgument();
1254     return TemplateArgument(E.takeAs<Expr>());
1255   }
1256 
1257   case TemplateArgument::Pack:
1258     assert(0 && "FIXME: Implement!");
1259     break;
1260   }
1261 
1262   assert(false && "Unhandled template argument kind");
1263   return TemplateArgument();
1264 }
1265