1 //===--- TemplateBase.cpp - Common template AST class implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements common classes used throughout C++ template
13 //===----------------------------------------------------------------------===//
15 #include "clang/AST/TemplateBase.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclBase.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/Type.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
31 /// \brief Print a template integral argument value.
33 /// \param TemplArg the TemplateArgument instance to print.
35 /// \param Out the raw_ostream instance to use for printing.
37 /// \param Policy the printing policy for EnumConstantDecl printing.
38 static void printIntegral(const TemplateArgument &TemplArg,
39 raw_ostream &Out, const PrintingPolicy& Policy) {
40 const ::clang::Type *T = TemplArg.getIntegralType().getTypePtr();
41 const llvm::APSInt &Val = TemplArg.getAsIntegral();
43 if (const EnumType *ET = T->getAs<EnumType>()) {
44 for (const EnumConstantDecl* ECD : ET->getDecl()->enumerators()) {
45 // In Sema::CheckTemplateArugment, enum template arguments value are
46 // extended to the size of the integer underlying the enum type. This
47 // may create a size difference between the enum value and template
48 // argument value, requiring isSameValue here instead of operator==.
49 if (llvm::APSInt::isSameValue(ECD->getInitVal(), Val)) {
50 ECD->printQualifiedName(Out, Policy);
56 if (T->isBooleanType() && !Policy.MSVCFormatting) {
57 Out << (Val.getBoolValue() ? "true" : "false");
58 } else if (T->isCharType()) {
59 const char Ch = Val.getZExtValue();
60 Out << ((Ch == '\'') ? "'\\" : "'");
61 Out.write_escaped(StringRef(&Ch, 1), /*UseHexEscapes=*/ true);
68 //===----------------------------------------------------------------------===//
69 // TemplateArgument Implementation
70 //===----------------------------------------------------------------------===//
72 TemplateArgument::TemplateArgument(ASTContext &Ctx, const llvm::APSInt &Value,
74 Integer.Kind = Integral;
75 // Copy the APSInt value into our decomposed form.
76 Integer.BitWidth = Value.getBitWidth();
77 Integer.IsUnsigned = Value.isUnsigned();
78 // If the value is large, we have to get additional memory from the ASTContext
79 unsigned NumWords = Value.getNumWords();
81 void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t));
82 std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
83 Integer.pVal = static_cast<uint64_t *>(Mem);
85 Integer.VAL = Value.getZExtValue();
88 Integer.Type = Type.getAsOpaquePtr();
92 TemplateArgument::CreatePackCopy(ASTContext &Context,
93 ArrayRef<TemplateArgument> Args) {
95 return getEmptyPack();
97 return TemplateArgument(Args.copy(Context));
100 bool TemplateArgument::isDependent() const {
103 llvm_unreachable("Should not have a NULL template argument");
106 return getAsType()->isDependentType() ||
107 isa<PackExpansionType>(getAsType());
110 return getAsTemplate().isDependent();
112 case TemplateExpansion:
116 if (DeclContext *DC = dyn_cast<DeclContext>(getAsDecl()))
117 return DC->isDependentContext();
118 return getAsDecl()->getDeclContext()->isDependentContext();
128 return (getAsExpr()->isTypeDependent() || getAsExpr()->isValueDependent() ||
129 isa<PackExpansionExpr>(getAsExpr()));
132 for (const auto &P : pack_elements())
138 llvm_unreachable("Invalid TemplateArgument Kind!");
141 bool TemplateArgument::isInstantiationDependent() const {
144 llvm_unreachable("Should not have a NULL template argument");
147 return getAsType()->isInstantiationDependentType();
150 return getAsTemplate().isInstantiationDependent();
152 case TemplateExpansion:
156 if (DeclContext *DC = dyn_cast<DeclContext>(getAsDecl()))
157 return DC->isDependentContext();
158 return getAsDecl()->getDeclContext()->isDependentContext();
168 return getAsExpr()->isInstantiationDependent();
171 for (const auto &P : pack_elements())
172 if (P.isInstantiationDependent())
177 llvm_unreachable("Invalid TemplateArgument Kind!");
180 bool TemplateArgument::isPackExpansion() const {
190 case TemplateExpansion:
194 return isa<PackExpansionType>(getAsType());
197 return isa<PackExpansionExpr>(getAsExpr());
200 llvm_unreachable("Invalid TemplateArgument Kind!");
203 bool TemplateArgument::containsUnexpandedParameterPack() const {
208 case TemplateExpansion:
213 if (getAsType()->containsUnexpandedParameterPack())
218 if (getAsTemplate().containsUnexpandedParameterPack())
223 if (getAsExpr()->containsUnexpandedParameterPack())
228 for (const auto &P : pack_elements())
229 if (P.containsUnexpandedParameterPack())
238 Optional<unsigned> TemplateArgument::getNumTemplateExpansions() const {
239 assert(getKind() == TemplateExpansion);
240 if (TemplateArg.NumExpansions)
241 return TemplateArg.NumExpansions - 1;
246 void TemplateArgument::Profile(llvm::FoldingSetNodeID &ID,
247 const ASTContext &Context) const {
248 ID.AddInteger(getKind());
254 getAsType().Profile(ID);
258 getNullPtrType().Profile(ID);
262 ID.AddPointer(getAsDecl()? getAsDecl()->getCanonicalDecl() : nullptr);
266 case TemplateExpansion: {
267 TemplateName Template = getAsTemplateOrTemplatePattern();
268 if (TemplateTemplateParmDecl *TTP
269 = dyn_cast_or_null<TemplateTemplateParmDecl>(
270 Template.getAsTemplateDecl())) {
272 ID.AddInteger(TTP->getDepth());
273 ID.AddInteger(TTP->getPosition());
274 ID.AddBoolean(TTP->isParameterPack());
276 ID.AddBoolean(false);
277 ID.AddPointer(Context.getCanonicalTemplateName(Template)
278 .getAsVoidPointer());
284 getAsIntegral().Profile(ID);
285 getIntegralType().Profile(ID);
289 getAsExpr()->Profile(ID, Context, true);
293 ID.AddInteger(Args.NumArgs);
294 for (unsigned I = 0; I != Args.NumArgs; ++I)
295 Args.Args[I].Profile(ID, Context);
299 bool TemplateArgument::structurallyEquals(const TemplateArgument &Other) const {
300 if (getKind() != Other.getKind()) return false;
307 case TemplateExpansion:
309 return TypeOrValue.V == Other.TypeOrValue.V;
312 return getAsDecl() == Other.getAsDecl();
315 return getIntegralType() == Other.getIntegralType() &&
316 getAsIntegral() == Other.getAsIntegral();
319 if (Args.NumArgs != Other.Args.NumArgs) return false;
320 for (unsigned I = 0, E = Args.NumArgs; I != E; ++I)
321 if (!Args.Args[I].structurallyEquals(Other.Args.Args[I]))
326 llvm_unreachable("Invalid TemplateArgument Kind!");
329 TemplateArgument TemplateArgument::getPackExpansionPattern() const {
330 assert(isPackExpansion());
334 return getAsType()->getAs<PackExpansionType>()->getPattern();
337 return cast<PackExpansionExpr>(getAsExpr())->getPattern();
339 case TemplateExpansion:
340 return TemplateArgument(getAsTemplateOrTemplatePattern());
348 return TemplateArgument();
351 llvm_unreachable("Invalid TemplateArgument Kind!");
354 void TemplateArgument::print(const PrintingPolicy &Policy,
355 raw_ostream &Out) const {
362 PrintingPolicy SubPolicy(Policy);
363 SubPolicy.SuppressStrongLifetime = true;
364 getAsType().print(Out, SubPolicy);
369 NamedDecl *ND = cast<NamedDecl>(getAsDecl());
371 if (ND->getDeclName()) {
372 // FIXME: distinguish between pointer and reference args?
373 ND->printQualifiedName(Out);
375 Out << "(anonymous)";
385 getAsTemplate().print(Out, Policy);
388 case TemplateExpansion:
389 getAsTemplateOrTemplatePattern().print(Out, Policy);
394 printIntegral(*this, Out, Policy);
399 getAsExpr()->printPretty(Out, nullptr, Policy);
405 for (const auto &P : pack_elements()) {
411 P.print(Policy, Out);
418 //===----------------------------------------------------------------------===//
419 // TemplateArgumentLoc Implementation
420 //===----------------------------------------------------------------------===//
422 TemplateArgumentLocInfo::TemplateArgumentLocInfo() {
423 memset((void*)this, 0, sizeof(TemplateArgumentLocInfo));
426 SourceRange TemplateArgumentLoc::getSourceRange() const {
427 switch (Argument.getKind()) {
428 case TemplateArgument::Expression:
429 return getSourceExpression()->getSourceRange();
431 case TemplateArgument::Declaration:
432 return getSourceDeclExpression()->getSourceRange();
434 case TemplateArgument::NullPtr:
435 return getSourceNullPtrExpression()->getSourceRange();
437 case TemplateArgument::Type:
438 if (TypeSourceInfo *TSI = getTypeSourceInfo())
439 return TSI->getTypeLoc().getSourceRange();
441 return SourceRange();
443 case TemplateArgument::Template:
444 if (getTemplateQualifierLoc())
445 return SourceRange(getTemplateQualifierLoc().getBeginLoc(),
446 getTemplateNameLoc());
447 return SourceRange(getTemplateNameLoc());
449 case TemplateArgument::TemplateExpansion:
450 if (getTemplateQualifierLoc())
451 return SourceRange(getTemplateQualifierLoc().getBeginLoc(),
452 getTemplateEllipsisLoc());
453 return SourceRange(getTemplateNameLoc(), getTemplateEllipsisLoc());
455 case TemplateArgument::Integral:
456 return getSourceIntegralExpression()->getSourceRange();
458 case TemplateArgument::Pack:
459 case TemplateArgument::Null:
460 return SourceRange();
463 llvm_unreachable("Invalid TemplateArgument Kind!");
466 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
467 const TemplateArgument &Arg) {
468 switch (Arg.getKind()) {
469 case TemplateArgument::Null:
470 // This is bad, but not as bad as crashing because of argument
472 return DB << "(null template argument)";
474 case TemplateArgument::Type:
475 return DB << Arg.getAsType();
477 case TemplateArgument::Declaration:
478 return DB << Arg.getAsDecl();
480 case TemplateArgument::NullPtr:
481 return DB << "nullptr";
483 case TemplateArgument::Integral:
484 return DB << Arg.getAsIntegral().toString(10);
486 case TemplateArgument::Template:
487 return DB << Arg.getAsTemplate();
489 case TemplateArgument::TemplateExpansion:
490 return DB << Arg.getAsTemplateOrTemplatePattern() << "...";
492 case TemplateArgument::Expression: {
493 // This shouldn't actually ever happen, so it's okay that we're
494 // regurgitating an expression here.
495 // FIXME: We're guessing at LangOptions!
497 llvm::raw_svector_ostream OS(Str);
498 LangOptions LangOpts;
499 LangOpts.CPlusPlus = true;
500 PrintingPolicy Policy(LangOpts);
501 Arg.getAsExpr()->printPretty(OS, nullptr, Policy);
502 return DB << OS.str();
505 case TemplateArgument::Pack: {
506 // FIXME: We're guessing at LangOptions!
508 llvm::raw_svector_ostream OS(Str);
509 LangOptions LangOpts;
510 LangOpts.CPlusPlus = true;
511 PrintingPolicy Policy(LangOpts);
512 Arg.print(Policy, OS);
513 return DB << OS.str();
517 llvm_unreachable("Invalid TemplateArgument Kind!");
520 const ASTTemplateArgumentListInfo *
521 ASTTemplateArgumentListInfo::Create(ASTContext &C,
522 const TemplateArgumentListInfo &List) {
523 std::size_t size = totalSizeToAlloc<TemplateArgumentLoc>(List.size());
524 void *Mem = C.Allocate(size, llvm::alignOf<ASTTemplateArgumentListInfo>());
525 return new (Mem) ASTTemplateArgumentListInfo(List);
528 ASTTemplateArgumentListInfo::ASTTemplateArgumentListInfo(
529 const TemplateArgumentListInfo &Info) {
530 LAngleLoc = Info.getLAngleLoc();
531 RAngleLoc = Info.getRAngleLoc();
532 NumTemplateArgs = Info.size();
534 TemplateArgumentLoc *ArgBuffer = getTrailingObjects<TemplateArgumentLoc>();
535 for (unsigned i = 0; i != NumTemplateArgs; ++i)
536 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
539 void ASTTemplateKWAndArgsInfo::initializeFrom(
540 SourceLocation TemplateKWLoc, const TemplateArgumentListInfo &Info) {
541 this->TemplateKWLoc = TemplateKWLoc;
542 LAngleLoc = Info.getLAngleLoc();
543 RAngleLoc = Info.getRAngleLoc();
544 NumTemplateArgs = Info.size();
546 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
547 for (unsigned i = 0; i != NumTemplateArgs; ++i)
548 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
551 void ASTTemplateKWAndArgsInfo::initializeFrom(SourceLocation TemplateKWLoc) {
552 assert(TemplateKWLoc.isValid());
553 LAngleLoc = SourceLocation();
554 RAngleLoc = SourceLocation();
555 this->TemplateKWLoc = TemplateKWLoc;
559 void ASTTemplateKWAndArgsInfo::initializeFrom(
560 SourceLocation TemplateKWLoc, const TemplateArgumentListInfo &Info,
561 bool &Dependent, bool &InstantiationDependent,
562 bool &ContainsUnexpandedParameterPack) {
563 this->TemplateKWLoc = TemplateKWLoc;
564 LAngleLoc = Info.getLAngleLoc();
565 RAngleLoc = Info.getRAngleLoc();
566 NumTemplateArgs = Info.size();
568 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
569 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
570 Dependent = Dependent || Info[i].getArgument().isDependent();
571 InstantiationDependent = InstantiationDependent ||
572 Info[i].getArgument().isInstantiationDependent();
573 ContainsUnexpandedParameterPack =
574 ContainsUnexpandedParameterPack ||
575 Info[i].getArgument().containsUnexpandedParameterPack();
577 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
581 void ASTTemplateKWAndArgsInfo::copyInto(TemplateArgumentListInfo &Info) const {
582 Info.setLAngleLoc(LAngleLoc);
583 Info.setRAngleLoc(RAngleLoc);
584 for (unsigned I = 0; I != NumTemplateArgs; ++I)
585 Info.addArgument(getTemplateArgs()[I]);
588 std::size_t ASTTemplateKWAndArgsInfo::sizeFor(unsigned NumTemplateArgs) {
589 return totalSizeToAlloc<TemplateArgumentLoc>(NumTemplateArgs);