1 //===------- SemaTemplate.h - C++ Templates ---------------------*- C++ -*-===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file provides types used in the semantic analysis of C++ templates.
11 //===----------------------------------------------------------------------===/
12 #ifndef LLVM_CLANG_SEMA_TEMPLATE_H
13 #define LLVM_CLANG_SEMA_TEMPLATE_H
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "llvm/ADT/SmallVector.h"
22 /// \brief Data structure that captures multiple levels of template argument
23 /// lists for use in template instantiation.
25 /// Multiple levels of template arguments occur when instantiating the
26 /// definitions of member templates. For example:
29 /// template<typename T>
38 /// When instantiating X<int>::Y<17>::f, the multi-level template argument
39 /// list will contain a template argument list (int) at depth 0 and a
40 /// template argument list (17) at depth 1.
41 class MultiLevelTemplateArgumentList {
43 typedef std::pair<const TemplateArgument *, unsigned> ArgList;
46 /// \brief The template argument lists, stored from the innermost template
47 /// argument list (first) to the outermost template argument list (last).
48 SmallVector<ArgList, 4> TemplateArgumentLists;
51 /// \brief Construct an empty set of template argument lists.
52 MultiLevelTemplateArgumentList() { }
54 /// \brief Construct a single-level template argument list.
56 MultiLevelTemplateArgumentList(const TemplateArgumentList &TemplateArgs) {
57 addOuterTemplateArguments(&TemplateArgs);
60 /// \brief Determine the number of levels in this template argument
62 unsigned getNumLevels() const { return TemplateArgumentLists.size(); }
64 /// \brief Retrieve the template argument at a given depth and index.
65 const TemplateArgument &operator()(unsigned Depth, unsigned Index) const {
66 assert(Depth < TemplateArgumentLists.size());
67 assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].second);
68 return TemplateArgumentLists[getNumLevels() - Depth - 1].first[Index];
71 /// \brief Determine whether there is a non-NULL template argument at the
72 /// given depth and index.
74 /// There must exist a template argument list at the given depth.
75 bool hasTemplateArgument(unsigned Depth, unsigned Index) const {
76 assert(Depth < TemplateArgumentLists.size());
78 if (Index >= TemplateArgumentLists[getNumLevels() - Depth - 1].second)
81 return !(*this)(Depth, Index).isNull();
84 /// \brief Clear out a specific template argument.
85 void setArgument(unsigned Depth, unsigned Index,
86 TemplateArgument Arg) {
87 assert(Depth < TemplateArgumentLists.size());
88 assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].second);
89 const_cast<TemplateArgument&>(
90 TemplateArgumentLists[getNumLevels() - Depth - 1].first[Index])
94 /// \brief Add a new outermost level to the multi-level template argument
96 void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs) {
97 TemplateArgumentLists.push_back(ArgList(TemplateArgs->data(),
98 TemplateArgs->size()));
101 /// \brief Add a new outmost level to the multi-level template argument
103 void addOuterTemplateArguments(const TemplateArgument *Args,
105 TemplateArgumentLists.push_back(ArgList(Args, NumArgs));
108 /// \brief Retrieve the innermost template argument list.
109 const ArgList &getInnermost() const {
110 return TemplateArgumentLists.front();
114 /// \brief The context in which partial ordering of function templates occurs.
116 /// \brief Partial ordering of function templates for a function call.
118 /// \brief Partial ordering of function templates for a call to a
119 /// conversion function.
121 /// \brief Partial ordering of function templates in other contexts, e.g.,
122 /// taking the address of a function template or matching a function
123 /// template specialization to a function template.
127 // This is lame but unavoidable in a world without forward
128 // declarations of enums. The alternatives are to either pollute
129 // Sema.h (by including this file) or sacrifice type safety (by
130 // making Sema.h declare things as enums).
131 class TemplatePartialOrderingContext {
134 TemplatePartialOrderingContext(TPOC Value) : Value(Value) {}
135 operator TPOC() const { return Value; }
138 /// \brief Captures a template argument whose value has been deduced
139 /// via c++ template argument deduction.
140 class DeducedTemplateArgument : public TemplateArgument {
141 /// \brief For a non-type template argument, whether the value was
142 /// deduced from an array bound.
143 bool DeducedFromArrayBound;
146 DeducedTemplateArgument()
147 : TemplateArgument(), DeducedFromArrayBound(false) { }
149 DeducedTemplateArgument(const TemplateArgument &Arg,
150 bool DeducedFromArrayBound = false)
151 : TemplateArgument(Arg), DeducedFromArrayBound(DeducedFromArrayBound) { }
153 /// \brief Construct an integral non-type template argument that
154 /// has been deduced, possibly from an array bound.
155 DeducedTemplateArgument(ASTContext &Ctx,
156 const llvm::APSInt &Value,
158 bool DeducedFromArrayBound)
159 : TemplateArgument(Ctx, Value, ValueType),
160 DeducedFromArrayBound(DeducedFromArrayBound) { }
162 /// \brief For a non-type template argument, determine whether the
163 /// template argument was deduced from an array bound.
164 bool wasDeducedFromArrayBound() const { return DeducedFromArrayBound; }
166 /// \brief Specify whether the given non-type template argument
167 /// was deduced from an array bound.
168 void setDeducedFromArrayBound(bool Deduced) {
169 DeducedFromArrayBound = Deduced;
173 /// \brief A stack-allocated class that identifies which local
174 /// variable declaration instantiations are present in this scope.
176 /// A new instance of this class type will be created whenever we
177 /// instantiate a new function declaration, which will have its own
178 /// set of parameter declarations.
179 class LocalInstantiationScope {
181 /// \brief A set of declarations.
182 typedef SmallVector<Decl *, 4> DeclArgumentPack;
185 /// \brief Reference to the semantic analysis that is performing
186 /// this template instantiation.
189 typedef llvm::DenseMap<const Decl *,
190 llvm::PointerUnion<Decl *, DeclArgumentPack *> >
193 /// \brief A mapping from local declarations that occur
194 /// within a template to their instantiations.
196 /// This mapping is used during instantiation to keep track of,
197 /// e.g., function parameter and variable declarations. For example,
201 /// template<typename T> T add(T x, T y) { return x + y; }
204 /// when we instantiate add<int>, we will introduce a mapping from
205 /// the ParmVarDecl for 'x' that occurs in the template to the
206 /// instantiated ParmVarDecl for 'x'.
208 /// For a parameter pack, the local instantiation scope may contain a
209 /// set of instantiated parameters. This is stored as a DeclArgumentPack
211 LocalDeclsMap LocalDecls;
213 /// \brief The set of argument packs we've allocated.
214 SmallVector<DeclArgumentPack *, 1> ArgumentPacks;
216 /// \brief The outer scope, which contains local variable
217 /// definitions from some other instantiation (that may not be
218 /// relevant to this particular scope).
219 LocalInstantiationScope *Outer;
221 /// \brief Whether we have already exited this scope.
224 /// \brief Whether to combine this scope with the outer scope, such that
225 /// lookup will search our outer scope.
226 bool CombineWithOuterScope;
228 /// \brief If non-NULL, the template parameter pack that has been
229 /// partially substituted per C++0x [temp.arg.explicit]p9.
230 NamedDecl *PartiallySubstitutedPack;
232 /// \brief If \c PartiallySubstitutedPack is non-null, the set of
233 /// explicitly-specified template arguments in that pack.
234 const TemplateArgument *ArgsInPartiallySubstitutedPack;
236 /// \brief If \c PartiallySubstitutedPack, the number of
237 /// explicitly-specified template arguments in
238 /// ArgsInPartiallySubstitutedPack.
239 unsigned NumArgsInPartiallySubstitutedPack;
241 // This class is non-copyable
242 LocalInstantiationScope(
243 const LocalInstantiationScope &) LLVM_DELETED_FUNCTION;
244 void operator=(const LocalInstantiationScope &) LLVM_DELETED_FUNCTION;
247 LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope = false)
248 : SemaRef(SemaRef), Outer(SemaRef.CurrentInstantiationScope),
249 Exited(false), CombineWithOuterScope(CombineWithOuterScope),
250 PartiallySubstitutedPack(0)
252 SemaRef.CurrentInstantiationScope = this;
255 ~LocalInstantiationScope() {
259 const Sema &getSema() const { return SemaRef; }
261 /// \brief Exit this local instantiation scope early.
266 for (unsigned I = 0, N = ArgumentPacks.size(); I != N; ++I)
267 delete ArgumentPacks[I];
269 SemaRef.CurrentInstantiationScope = Outer;
273 /// \brief Clone this scope, and all outer scopes, down to the given
275 LocalInstantiationScope *cloneScopes(LocalInstantiationScope *Outermost) {
276 if (this == Outermost) return this;
277 LocalInstantiationScope *newScope =
278 new LocalInstantiationScope(SemaRef, CombineWithOuterScope);
282 newScope->Outer = Outer->cloneScopes(Outermost);
284 newScope->PartiallySubstitutedPack = PartiallySubstitutedPack;
285 newScope->ArgsInPartiallySubstitutedPack = ArgsInPartiallySubstitutedPack;
286 newScope->NumArgsInPartiallySubstitutedPack =
287 NumArgsInPartiallySubstitutedPack;
289 for (LocalDeclsMap::iterator I = LocalDecls.begin(), E = LocalDecls.end();
291 const Decl *D = I->first;
292 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored =
293 newScope->LocalDecls[D];
294 if (I->second.is<Decl *>()) {
295 Stored = I->second.get<Decl *>();
297 DeclArgumentPack *OldPack = I->second.get<DeclArgumentPack *>();
298 DeclArgumentPack *NewPack = new DeclArgumentPack(*OldPack);
300 newScope->ArgumentPacks.push_back(NewPack);
306 /// \brief deletes the given scope, and all otuer scopes, down to the
307 /// given outermost scope.
308 static void deleteScopes(LocalInstantiationScope *Scope,
309 LocalInstantiationScope *Outermost) {
310 while (Scope && Scope != Outermost) {
311 LocalInstantiationScope *Out = Scope->Outer;
317 /// \brief Find the instantiation of the declaration D within the current
318 /// instantiation scope.
320 /// \param D The declaration whose instantiation we are searching for.
322 /// \returns A pointer to the declaration or argument pack of declarations
323 /// to which the declaration \c D is instantiataed, if found. Otherwise,
325 llvm::PointerUnion<Decl *, DeclArgumentPack *> *
326 findInstantiationOf(const Decl *D);
328 void InstantiatedLocal(const Decl *D, Decl *Inst);
329 void InstantiatedLocalPackArg(const Decl *D, Decl *Inst);
330 void MakeInstantiatedLocalArgPack(const Decl *D);
332 /// \brief Note that the given parameter pack has been partially substituted
333 /// via explicit specification of template arguments
334 /// (C++0x [temp.arg.explicit]p9).
336 /// \param Pack The parameter pack, which will always be a template
339 /// \param ExplicitArgs The explicitly-specified template arguments provided
340 /// for this parameter pack.
342 /// \param NumExplicitArgs The number of explicitly-specified template
343 /// arguments provided for this parameter pack.
344 void SetPartiallySubstitutedPack(NamedDecl *Pack,
345 const TemplateArgument *ExplicitArgs,
346 unsigned NumExplicitArgs);
348 /// \brief Retrieve the partially-substitued template parameter pack.
350 /// If there is no partially-substituted parameter pack, returns NULL.
351 NamedDecl *getPartiallySubstitutedPack(
352 const TemplateArgument **ExplicitArgs = 0,
353 unsigned *NumExplicitArgs = 0) const;
356 class TemplateDeclInstantiator
357 : public DeclVisitor<TemplateDeclInstantiator, Decl *>
360 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex;
362 const MultiLevelTemplateArgumentList &TemplateArgs;
363 Sema::LateInstantiatedAttrVec* LateAttrs;
364 LocalInstantiationScope *StartingScope;
366 /// \brief A list of out-of-line class template partial
367 /// specializations that will need to be instantiated after the
368 /// enclosing class's instantiation is complete.
369 SmallVector<std::pair<ClassTemplateDecl *,
370 ClassTemplatePartialSpecializationDecl *>, 4>
371 OutOfLinePartialSpecs;
374 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
375 const MultiLevelTemplateArgumentList &TemplateArgs)
377 SubstIndex(SemaRef, SemaRef.ArgumentPackSubstitutionIndex),
378 Owner(Owner), TemplateArgs(TemplateArgs), LateAttrs(0), StartingScope(0)
381 // FIXME: Once we get closer to completion, replace these manually-written
382 // declarations with automatically-generated ones from
383 // clang/AST/DeclNodes.inc.
384 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
385 Decl *VisitLabelDecl(LabelDecl *D);
386 Decl *VisitNamespaceDecl(NamespaceDecl *D);
387 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
388 Decl *VisitTypedefDecl(TypedefDecl *D);
389 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
390 Decl *VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
391 Decl *VisitVarDecl(VarDecl *D);
392 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
393 Decl *VisitFieldDecl(FieldDecl *D);
394 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
395 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
396 Decl *VisitEnumDecl(EnumDecl *D);
397 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
398 Decl *VisitFriendDecl(FriendDecl *D);
399 Decl *VisitFunctionDecl(FunctionDecl *D,
400 TemplateParameterList *TemplateParams = 0);
401 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
402 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
403 TemplateParameterList *TemplateParams = 0,
404 bool IsClassScopeSpecialization = false);
405 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
406 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
407 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
408 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
409 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
410 Decl *VisitClassTemplatePartialSpecializationDecl(
411 ClassTemplatePartialSpecializationDecl *D);
412 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
413 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
414 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
415 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
416 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
417 Decl *VisitUsingDecl(UsingDecl *D);
418 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
419 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
420 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
421 Decl *VisitClassScopeFunctionSpecializationDecl(
422 ClassScopeFunctionSpecializationDecl *D);
424 // Base case. FIXME: Remove once we can instantiate everything.
425 Decl *VisitDecl(Decl *D) {
426 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
427 DiagnosticsEngine::Error,
428 "cannot instantiate %0 yet");
429 SemaRef.Diag(D->getLocation(), DiagID)
430 << D->getDeclKindName();
435 // Enable late instantiation of attributes. Late instantiated attributes
436 // will be stored in LA.
437 void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA) {
439 StartingScope = SemaRef.CurrentInstantiationScope;
442 // Disable late instantiation of attributes.
443 void disableLateAttributeInstantiation() {
448 LocalInstantiationScope *getStartingScope() const { return StartingScope; }
451 SmallVectorImpl<std::pair<ClassTemplateDecl *,
452 ClassTemplatePartialSpecializationDecl *> >
454 delayed_partial_spec_iterator;
456 /// \brief Return an iterator to the beginning of the set of
457 /// "delayed" partial specializations, which must be passed to
458 /// InstantiateClassTemplatePartialSpecialization once the class
459 /// definition has been completed.
460 delayed_partial_spec_iterator delayed_partial_spec_begin() {
461 return OutOfLinePartialSpecs.begin();
464 /// \brief Return an iterator to the end of the set of
465 /// "delayed" partial specializations, which must be passed to
466 /// InstantiateClassTemplatePartialSpecialization once the class
467 /// definition has been completed.
468 delayed_partial_spec_iterator delayed_partial_spec_end() {
469 return OutOfLinePartialSpecs.end();
472 // Helper functions for instantiating methods.
473 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
474 SmallVectorImpl<ParmVarDecl *> &Params);
475 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
476 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
478 TemplateParameterList *
479 SubstTemplateParams(TemplateParameterList *List);
481 bool SubstQualifier(const DeclaratorDecl *OldDecl,
482 DeclaratorDecl *NewDecl);
483 bool SubstQualifier(const TagDecl *OldDecl,
486 Decl *InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias);
487 ClassTemplatePartialSpecializationDecl *
488 InstantiateClassTemplatePartialSpecialization(
489 ClassTemplateDecl *ClassTemplate,
490 ClassTemplatePartialSpecializationDecl *PartialSpec);
491 void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern);
495 #endif // LLVM_CLANG_SEMA_TEMPLATE_H