SemaTemplateVariadic.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
  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 semantic analysis for C++0x variadic templates.
  10. //===----------------------------------------------------------------------===/
  11. #include "clang/Sema/Sema.h"
  12. #include "clang/AST/Expr.h"
  13. #include "clang/AST/RecursiveASTVisitor.h"
  14. #include "clang/AST/TypeLoc.h"
  15. #include "clang/Sema/Lookup.h"
  16. #include "clang/Sema/ParsedTemplate.h"
  17. #include "clang/Sema/ScopeInfo.h"
  18. #include "clang/Sema/SemaInternal.h"
  19. #include "clang/Sema/Template.h"
  20. using namespace clang;
  21. //----------------------------------------------------------------------------
  22. // Visitor that collects unexpanded parameter packs
  23. //----------------------------------------------------------------------------
  24. namespace {
  25. /// \brief A class that collects unexpanded parameter packs.
  26. class CollectUnexpandedParameterPacksVisitor :
  27. public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
  28. {
  29. typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
  30. inherited;
  31. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
  32. bool InLambda;
  33. public:
  34. explicit CollectUnexpandedParameterPacksVisitor(
  35. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
  36. : Unexpanded(Unexpanded), InLambda(false) { }
  37. bool shouldWalkTypesOfTypeLocs() const { return false; }
  38. //------------------------------------------------------------------------
  39. // Recording occurrences of (unexpanded) parameter packs.
  40. //------------------------------------------------------------------------
  41. /// \brief Record occurrences of template type parameter packs.
  42. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  43. if (TL.getTypePtr()->isParameterPack())
  44. Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
  45. return true;
  46. }
  47. /// \brief Record occurrences of template type parameter packs
  48. /// when we don't have proper source-location information for
  49. /// them.
  50. ///
  51. /// Ideally, this routine would never be used.
  52. bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
  53. if (T->isParameterPack())
  54. Unexpanded.push_back(std::make_pair(T, SourceLocation()));
  55. return true;
  56. }
  57. /// \brief Record occurrences of function and non-type template
  58. /// parameter packs in an expression.
  59. bool VisitDeclRefExpr(DeclRefExpr *E) {
  60. if (E->getDecl()->isParameterPack())
  61. Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
  62. return true;
  63. }
  64. /// \brief Record occurrences of template template parameter packs.
  65. bool TraverseTemplateName(TemplateName Template) {
  66. if (TemplateTemplateParmDecl *TTP
  67. = dyn_cast_or_null<TemplateTemplateParmDecl>(
  68. Template.getAsTemplateDecl()))
  69. if (TTP->isParameterPack())
  70. Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
  71. return inherited::TraverseTemplateName(Template);
  72. }
  73. /// \brief Suppress traversal into Objective-C container literal
  74. /// elements that are pack expansions.
  75. bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  76. if (!E->containsUnexpandedParameterPack())
  77. return true;
  78. for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
  79. ObjCDictionaryElement Element = E->getKeyValueElement(I);
  80. if (Element.isPackExpansion())
  81. continue;
  82. TraverseStmt(Element.Key);
  83. TraverseStmt(Element.Value);
  84. }
  85. return true;
  86. }
  87. //------------------------------------------------------------------------
  88. // Pruning the search for unexpanded parameter packs.
  89. //------------------------------------------------------------------------
  90. /// \brief Suppress traversal into statements and expressions that
  91. /// do not contain unexpanded parameter packs.
  92. bool TraverseStmt(Stmt *S) {
  93. Expr *E = dyn_cast_or_null<Expr>(S);
  94. if ((E && E->containsUnexpandedParameterPack()) || InLambda)
  95. return inherited::TraverseStmt(S);
  96. return true;
  97. }
  98. /// \brief Suppress traversal into types that do not contain
  99. /// unexpanded parameter packs.
  100. bool TraverseType(QualType T) {
  101. if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
  102. return inherited::TraverseType(T);
  103. return true;
  104. }
  105. /// \brief Suppress traversel into types with location information
  106. /// that do not contain unexpanded parameter packs.
  107. bool TraverseTypeLoc(TypeLoc TL) {
  108. if ((!TL.getType().isNull() &&
  109. TL.getType()->containsUnexpandedParameterPack()) ||
  110. InLambda)
  111. return inherited::TraverseTypeLoc(TL);
  112. return true;
  113. }
  114. /// \brief Suppress traversal of non-parameter declarations, since
  115. /// they cannot contain unexpanded parameter packs.
  116. bool TraverseDecl(Decl *D) {
  117. if ((D && isa<ParmVarDecl>(D)) || InLambda)
  118. return inherited::TraverseDecl(D);
  119. return true;
  120. }
  121. /// \brief Suppress traversal of template argument pack expansions.
  122. bool TraverseTemplateArgument(const TemplateArgument &Arg) {
  123. if (Arg.isPackExpansion())
  124. return true;
  125. return inherited::TraverseTemplateArgument(Arg);
  126. }
  127. /// \brief Suppress traversal of template argument pack expansions.
  128. bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
  129. if (ArgLoc.getArgument().isPackExpansion())
  130. return true;
  131. return inherited::TraverseTemplateArgumentLoc(ArgLoc);
  132. }
  133. /// \brief Note whether we're traversing a lambda containing an unexpanded
  134. /// parameter pack. In this case, the unexpanded pack can occur anywhere,
  135. /// including all the places where we normally wouldn't look. Within a
  136. /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
  137. /// outside an expression.
  138. bool TraverseLambdaExpr(LambdaExpr *Lambda) {
  139. // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
  140. // even if it's contained within another lambda.
  141. if (!Lambda->containsUnexpandedParameterPack())
  142. return true;
  143. bool WasInLambda = InLambda;
  144. InLambda = true;
  145. // If any capture names a function parameter pack, that pack is expanded
  146. // when the lambda is expanded.
  147. for (LambdaExpr::capture_iterator I = Lambda->capture_begin(),
  148. E = Lambda->capture_end(); I != E; ++I)
  149. if (VarDecl *VD = I->getCapturedVar())
  150. if (VD->isParameterPack())
  151. Unexpanded.push_back(std::make_pair(VD, I->getLocation()));
  152. inherited::TraverseLambdaExpr(Lambda);
  153. InLambda = WasInLambda;
  154. return true;
  155. }
  156. };
  157. }
  158. /// \brief Diagnose all of the unexpanded parameter packs in the given
  159. /// vector.
  160. bool
  161. Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
  162. UnexpandedParameterPackContext UPPC,
  163. ArrayRef<UnexpandedParameterPack> Unexpanded) {
  164. if (Unexpanded.empty())
  165. return false;
  166. // If we are within a lambda expression, that lambda contains an unexpanded
  167. // parameter pack, and we are done.
  168. // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
  169. // later.
  170. for (unsigned N = FunctionScopes.size(); N; --N) {
  171. if (sema::LambdaScopeInfo *LSI =
  172. dyn_cast<sema::LambdaScopeInfo>(FunctionScopes[N-1])) {
  173. LSI->ContainsUnexpandedParameterPack = true;
  174. return false;
  175. }
  176. }
  177. SmallVector<SourceLocation, 4> Locations;
  178. SmallVector<IdentifierInfo *, 4> Names;
  179. llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
  180. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  181. IdentifierInfo *Name = 0;
  182. if (const TemplateTypeParmType *TTP
  183. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
  184. Name = TTP->getIdentifier();
  185. else
  186. Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
  187. if (Name && NamesKnown.insert(Name))
  188. Names.push_back(Name);
  189. if (Unexpanded[I].second.isValid())
  190. Locations.push_back(Unexpanded[I].second);
  191. }
  192. DiagnosticBuilder DB
  193. = Names.size() == 0? Diag(Loc, diag::err_unexpanded_parameter_pack_0)
  194. << (int)UPPC
  195. : Names.size() == 1? Diag(Loc, diag::err_unexpanded_parameter_pack_1)
  196. << (int)UPPC << Names[0]
  197. : Names.size() == 2? Diag(Loc, diag::err_unexpanded_parameter_pack_2)
  198. << (int)UPPC << Names[0] << Names[1]
  199. : Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
  200. << (int)UPPC << Names[0] << Names[1];
  201. for (unsigned I = 0, N = Locations.size(); I != N; ++I)
  202. DB << SourceRange(Locations[I]);
  203. return true;
  204. }
  205. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  206. TypeSourceInfo *T,
  207. UnexpandedParameterPackContext UPPC) {
  208. // C++0x [temp.variadic]p5:
  209. // An appearance of a name of a parameter pack that is not expanded is
  210. // ill-formed.
  211. if (!T->getType()->containsUnexpandedParameterPack())
  212. return false;
  213. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  214. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
  215. T->getTypeLoc());
  216. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  217. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  218. }
  219. bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
  220. UnexpandedParameterPackContext UPPC) {
  221. // C++0x [temp.variadic]p5:
  222. // An appearance of a name of a parameter pack that is not expanded is
  223. // ill-formed.
  224. if (!E->containsUnexpandedParameterPack())
  225. return false;
  226. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  227. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
  228. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  229. return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
  230. }
  231. bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
  232. UnexpandedParameterPackContext UPPC) {
  233. // C++0x [temp.variadic]p5:
  234. // An appearance of a name of a parameter pack that is not expanded is
  235. // ill-formed.
  236. if (!SS.getScopeRep() ||
  237. !SS.getScopeRep()->containsUnexpandedParameterPack())
  238. return false;
  239. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  240. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  241. .TraverseNestedNameSpecifier(SS.getScopeRep());
  242. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  243. return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
  244. UPPC, Unexpanded);
  245. }
  246. bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
  247. UnexpandedParameterPackContext UPPC) {
  248. // C++0x [temp.variadic]p5:
  249. // An appearance of a name of a parameter pack that is not expanded is
  250. // ill-formed.
  251. switch (NameInfo.getName().getNameKind()) {
  252. case DeclarationName::Identifier:
  253. case DeclarationName::ObjCZeroArgSelector:
  254. case DeclarationName::ObjCOneArgSelector:
  255. case DeclarationName::ObjCMultiArgSelector:
  256. case DeclarationName::CXXOperatorName:
  257. case DeclarationName::CXXLiteralOperatorName:
  258. case DeclarationName::CXXUsingDirective:
  259. return false;
  260. case DeclarationName::CXXConstructorName:
  261. case DeclarationName::CXXDestructorName:
  262. case DeclarationName::CXXConversionFunctionName:
  263. // FIXME: We shouldn't need this null check!
  264. if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
  265. return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
  266. if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
  267. return false;
  268. break;
  269. }
  270. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  271. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  272. .TraverseType(NameInfo.getName().getCXXNameType());
  273. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  274. return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
  275. }
  276. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  277. TemplateName Template,
  278. UnexpandedParameterPackContext UPPC) {
  279. if (Template.isNull() || !Template.containsUnexpandedParameterPack())
  280. return false;
  281. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  282. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  283. .TraverseTemplateName(Template);
  284. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  285. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  286. }
  287. bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
  288. UnexpandedParameterPackContext UPPC) {
  289. if (Arg.getArgument().isNull() ||
  290. !Arg.getArgument().containsUnexpandedParameterPack())
  291. return false;
  292. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  293. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  294. .TraverseTemplateArgumentLoc(Arg);
  295. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  296. return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
  297. }
  298. void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
  299. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  300. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  301. .TraverseTemplateArgument(Arg);
  302. }
  303. void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
  304. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  305. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  306. .TraverseTemplateArgumentLoc(Arg);
  307. }
  308. void Sema::collectUnexpandedParameterPacks(QualType T,
  309. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  310. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
  311. }
  312. void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
  313. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  314. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
  315. }
  316. void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
  317. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  318. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  319. if (!Qualifier)
  320. return;
  321. NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
  322. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  323. .TraverseNestedNameSpecifierLoc(QualifierLoc);
  324. }
  325. void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
  326. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  327. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  328. .TraverseDeclarationNameInfo(NameInfo);
  329. }
  330. ParsedTemplateArgument
  331. Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
  332. SourceLocation EllipsisLoc) {
  333. if (Arg.isInvalid())
  334. return Arg;
  335. switch (Arg.getKind()) {
  336. case ParsedTemplateArgument::Type: {
  337. TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
  338. if (Result.isInvalid())
  339. return ParsedTemplateArgument();
  340. return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
  341. Arg.getLocation());
  342. }
  343. case ParsedTemplateArgument::NonType: {
  344. ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
  345. if (Result.isInvalid())
  346. return ParsedTemplateArgument();
  347. return ParsedTemplateArgument(Arg.getKind(), Result.get(),
  348. Arg.getLocation());
  349. }
  350. case ParsedTemplateArgument::Template:
  351. if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
  352. SourceRange R(Arg.getLocation());
  353. if (Arg.getScopeSpec().isValid())
  354. R.setBegin(Arg.getScopeSpec().getBeginLoc());
  355. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  356. << R;
  357. return ParsedTemplateArgument();
  358. }
  359. return Arg.getTemplatePackExpansion(EllipsisLoc);
  360. }
  361. llvm_unreachable("Unhandled template argument kind?");
  362. }
  363. TypeResult Sema::ActOnPackExpansion(ParsedType Type,
  364. SourceLocation EllipsisLoc) {
  365. TypeSourceInfo *TSInfo;
  366. GetTypeFromParser(Type, &TSInfo);
  367. if (!TSInfo)
  368. return true;
  369. TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc,
  370. llvm::Optional<unsigned>());
  371. if (!TSResult)
  372. return true;
  373. return CreateParsedType(TSResult->getType(), TSResult);
  374. }
  375. TypeSourceInfo *Sema::CheckPackExpansion(TypeSourceInfo *Pattern,
  376. SourceLocation EllipsisLoc,
  377. llvm::Optional<unsigned> NumExpansions) {
  378. // Create the pack expansion type and source-location information.
  379. QualType Result = CheckPackExpansion(Pattern->getType(),
  380. Pattern->getTypeLoc().getSourceRange(),
  381. EllipsisLoc, NumExpansions);
  382. if (Result.isNull())
  383. return 0;
  384. TypeSourceInfo *TSResult = Context.CreateTypeSourceInfo(Result);
  385. PackExpansionTypeLoc TL = cast<PackExpansionTypeLoc>(TSResult->getTypeLoc());
  386. TL.setEllipsisLoc(EllipsisLoc);
  387. // Copy over the source-location information from the type.
  388. memcpy(TL.getNextTypeLoc().getOpaqueData(),
  389. Pattern->getTypeLoc().getOpaqueData(),
  390. Pattern->getTypeLoc().getFullDataSize());
  391. return TSResult;
  392. }
  393. QualType Sema::CheckPackExpansion(QualType Pattern,
  394. SourceRange PatternRange,
  395. SourceLocation EllipsisLoc,
  396. llvm::Optional<unsigned> NumExpansions) {
  397. // C++0x [temp.variadic]p5:
  398. // The pattern of a pack expansion shall name one or more
  399. // parameter packs that are not expanded by a nested pack
  400. // expansion.
  401. if (!Pattern->containsUnexpandedParameterPack()) {
  402. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  403. << PatternRange;
  404. return QualType();
  405. }
  406. return Context.getPackExpansionType(Pattern, NumExpansions);
  407. }
  408. ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
  409. return CheckPackExpansion(Pattern, EllipsisLoc, llvm::Optional<unsigned>());
  410. }
  411. ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
  412. llvm::Optional<unsigned> NumExpansions) {
  413. if (!Pattern)
  414. return ExprError();
  415. // C++0x [temp.variadic]p5:
  416. // The pattern of a pack expansion shall name one or more
  417. // parameter packs that are not expanded by a nested pack
  418. // expansion.
  419. if (!Pattern->containsUnexpandedParameterPack()) {
  420. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  421. << Pattern->getSourceRange();
  422. return ExprError();
  423. }
  424. // Create the pack expansion expression and source-location information.
  425. return Owned(new (Context) PackExpansionExpr(Context.DependentTy, Pattern,
  426. EllipsisLoc, NumExpansions));
  427. }
  428. /// \brief Retrieve the depth and index of a parameter pack.
  429. static std::pair<unsigned, unsigned>
  430. getDepthAndIndex(NamedDecl *ND) {
  431. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
  432. return std::make_pair(TTP->getDepth(), TTP->getIndex());
  433. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
  434. return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
  435. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
  436. return std::make_pair(TTP->getDepth(), TTP->getIndex());
  437. }
  438. bool Sema::CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
  439. SourceRange PatternRange,
  440. ArrayRef<UnexpandedParameterPack> Unexpanded,
  441. const MultiLevelTemplateArgumentList &TemplateArgs,
  442. bool &ShouldExpand,
  443. bool &RetainExpansion,
  444. llvm::Optional<unsigned> &NumExpansions) {
  445. ShouldExpand = true;
  446. RetainExpansion = false;
  447. std::pair<IdentifierInfo *, SourceLocation> FirstPack;
  448. bool HaveFirstPack = false;
  449. for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
  450. end = Unexpanded.end();
  451. i != end; ++i) {
  452. // Compute the depth and index for this parameter pack.
  453. unsigned Depth = 0, Index = 0;
  454. IdentifierInfo *Name;
  455. bool IsFunctionParameterPack = false;
  456. if (const TemplateTypeParmType *TTP
  457. = i->first.dyn_cast<const TemplateTypeParmType *>()) {
  458. Depth = TTP->getDepth();
  459. Index = TTP->getIndex();
  460. Name = TTP->getIdentifier();
  461. } else {
  462. NamedDecl *ND = i->first.get<NamedDecl *>();
  463. if (isa<ParmVarDecl>(ND))
  464. IsFunctionParameterPack = true;
  465. else
  466. llvm::tie(Depth, Index) = getDepthAndIndex(ND);
  467. Name = ND->getIdentifier();
  468. }
  469. // Determine the size of this argument pack.
  470. unsigned NewPackSize;
  471. if (IsFunctionParameterPack) {
  472. // Figure out whether we're instantiating to an argument pack or not.
  473. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  474. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  475. = CurrentInstantiationScope->findInstantiationOf(
  476. i->first.get<NamedDecl *>());
  477. if (Instantiation->is<DeclArgumentPack *>()) {
  478. // We could expand this function parameter pack.
  479. NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
  480. } else {
  481. // We can't expand this function parameter pack, so we can't expand
  482. // the pack expansion.
  483. ShouldExpand = false;
  484. continue;
  485. }
  486. } else {
  487. // If we don't have a template argument at this depth/index, then we
  488. // cannot expand the pack expansion. Make a note of this, but we still
  489. // want to check any parameter packs we *do* have arguments for.
  490. if (Depth >= TemplateArgs.getNumLevels() ||
  491. !TemplateArgs.hasTemplateArgument(Depth, Index)) {
  492. ShouldExpand = false;
  493. continue;
  494. }
  495. // Determine the size of the argument pack.
  496. NewPackSize = TemplateArgs(Depth, Index).pack_size();
  497. }
  498. // C++0x [temp.arg.explicit]p9:
  499. // Template argument deduction can extend the sequence of template
  500. // arguments corresponding to a template parameter pack, even when the
  501. // sequence contains explicitly specified template arguments.
  502. if (!IsFunctionParameterPack) {
  503. if (NamedDecl *PartialPack
  504. = CurrentInstantiationScope->getPartiallySubstitutedPack()){
  505. unsigned PartialDepth, PartialIndex;
  506. llvm::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
  507. if (PartialDepth == Depth && PartialIndex == Index)
  508. RetainExpansion = true;
  509. }
  510. }
  511. if (!NumExpansions) {
  512. // The is the first pack we've seen for which we have an argument.
  513. // Record it.
  514. NumExpansions = NewPackSize;
  515. FirstPack.first = Name;
  516. FirstPack.second = i->second;
  517. HaveFirstPack = true;
  518. continue;
  519. }
  520. if (NewPackSize != *NumExpansions) {
  521. // C++0x [temp.variadic]p5:
  522. // All of the parameter packs expanded by a pack expansion shall have
  523. // the same number of arguments specified.
  524. if (HaveFirstPack)
  525. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
  526. << FirstPack.first << Name << *NumExpansions << NewPackSize
  527. << SourceRange(FirstPack.second) << SourceRange(i->second);
  528. else
  529. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
  530. << Name << *NumExpansions << NewPackSize
  531. << SourceRange(i->second);
  532. return true;
  533. }
  534. }
  535. return false;
  536. }
  537. llvm::Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
  538. const MultiLevelTemplateArgumentList &TemplateArgs) {
  539. QualType Pattern = cast<PackExpansionType>(T)->getPattern();
  540. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  541. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
  542. llvm::Optional<unsigned> Result;
  543. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  544. // Compute the depth and index for this parameter pack.
  545. unsigned Depth;
  546. unsigned Index;
  547. if (const TemplateTypeParmType *TTP
  548. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
  549. Depth = TTP->getDepth();
  550. Index = TTP->getIndex();
  551. } else {
  552. NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
  553. if (isa<ParmVarDecl>(ND)) {
  554. // Function parameter pack.
  555. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  556. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  557. = CurrentInstantiationScope->findInstantiationOf(
  558. Unexpanded[I].first.get<NamedDecl *>());
  559. if (Instantiation->is<Decl*>())
  560. // The pattern refers to an unexpanded pack. We're not ready to expand
  561. // this pack yet.
  562. return llvm::Optional<unsigned>();
  563. unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
  564. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  565. Result = Size;
  566. continue;
  567. }
  568. llvm::tie(Depth, Index) = getDepthAndIndex(ND);
  569. }
  570. if (Depth >= TemplateArgs.getNumLevels() ||
  571. !TemplateArgs.hasTemplateArgument(Depth, Index))
  572. // The pattern refers to an unknown template argument. We're not ready to
  573. // expand this pack yet.
  574. return llvm::Optional<unsigned>();
  575. // Determine the size of the argument pack.
  576. unsigned Size = TemplateArgs(Depth, Index).pack_size();
  577. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  578. Result = Size;
  579. }
  580. return Result;
  581. }
  582. bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
  583. const DeclSpec &DS = D.getDeclSpec();
  584. switch (DS.getTypeSpecType()) {
  585. case TST_typename:
  586. case TST_typeofType:
  587. case TST_underlyingType:
  588. case TST_atomic: {
  589. QualType T = DS.getRepAsType().get();
  590. if (!T.isNull() && T->containsUnexpandedParameterPack())
  591. return true;
  592. break;
  593. }
  594. case TST_typeofExpr:
  595. case TST_decltype:
  596. if (DS.getRepAsExpr() &&
  597. DS.getRepAsExpr()->containsUnexpandedParameterPack())
  598. return true;
  599. break;
  600. case TST_unspecified:
  601. case TST_void:
  602. case TST_char:
  603. case TST_wchar:
  604. case TST_char16:
  605. case TST_char32:
  606. case TST_int:
  607. case TST_int128:
  608. case TST_half:
  609. case TST_float:
  610. case TST_double:
  611. case TST_bool:
  612. case TST_decimal32:
  613. case TST_decimal64:
  614. case TST_decimal128:
  615. case TST_enum:
  616. case TST_union:
  617. case TST_struct:
  618. case TST_interface:
  619. case TST_class:
  620. case TST_auto:
  621. case TST_unknown_anytype:
  622. case TST_image1d_t:
  623. case TST_image1d_array_t:
  624. case TST_image1d_buffer_t:
  625. case TST_image2d_t:
  626. case TST_image2d_array_t:
  627. case TST_image3d_t:
  628. case TST_sampler_t:
  629. case TST_event_t:
  630. case TST_error:
  631. break;
  632. }
  633. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  634. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  635. switch (Chunk.Kind) {
  636. case DeclaratorChunk::Pointer:
  637. case DeclaratorChunk::Reference:
  638. case DeclaratorChunk::Paren:
  639. // These declarator chunks cannot contain any parameter packs.
  640. break;
  641. case DeclaratorChunk::Array:
  642. case DeclaratorChunk::Function:
  643. case DeclaratorChunk::BlockPointer:
  644. // Syntactically, these kinds of declarator chunks all come after the
  645. // declarator-id (conceptually), so the parser should not invoke this
  646. // routine at this time.
  647. llvm_unreachable("Could not have seen this kind of declarator chunk");
  648. case DeclaratorChunk::MemberPointer:
  649. if (Chunk.Mem.Scope().getScopeRep() &&
  650. Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
  651. return true;
  652. break;
  653. }
  654. }
  655. return false;
  656. }
  657. namespace {
  658. // Callback to only accept typo corrections that refer to parameter packs.
  659. class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
  660. public:
  661. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  662. NamedDecl *ND = candidate.getCorrectionDecl();
  663. return ND && ND->isParameterPack();
  664. }
  665. };
  666. }
  667. /// \brief Called when an expression computing the size of a parameter pack
  668. /// is parsed.
  669. ///
  670. /// \code
  671. /// template<typename ...Types> struct count {
  672. /// static const unsigned value = sizeof...(Types);
  673. /// };
  674. /// \endcode
  675. ///
  676. //
  677. /// \param OpLoc The location of the "sizeof" keyword.
  678. /// \param Name The name of the parameter pack whose size will be determined.
  679. /// \param NameLoc The source location of the name of the parameter pack.
  680. /// \param RParenLoc The location of the closing parentheses.
  681. ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
  682. SourceLocation OpLoc,
  683. IdentifierInfo &Name,
  684. SourceLocation NameLoc,
  685. SourceLocation RParenLoc) {
  686. // C++0x [expr.sizeof]p5:
  687. // The identifier in a sizeof... expression shall name a parameter pack.
  688. LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
  689. LookupName(R, S);
  690. NamedDecl *ParameterPack = 0;
  691. ParameterPackValidatorCCC Validator;
  692. switch (R.getResultKind()) {
  693. case LookupResult::Found:
  694. ParameterPack = R.getFoundDecl();
  695. break;
  696. case LookupResult::NotFound:
  697. case LookupResult::NotFoundInCurrentInstantiation:
  698. if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
  699. R.getLookupKind(), S, 0,
  700. Validator)) {
  701. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  702. ParameterPack = Corrected.getCorrectionDecl();
  703. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name_suggest)
  704. << &Name << CorrectedQuotedStr
  705. << FixItHint::CreateReplacement(
  706. NameLoc, Corrected.getAsString(getLangOpts()));
  707. Diag(ParameterPack->getLocation(), diag::note_parameter_pack_here)
  708. << CorrectedQuotedStr;
  709. }
  710. case LookupResult::FoundOverloaded:
  711. case LookupResult::FoundUnresolvedValue:
  712. break;
  713. case LookupResult::Ambiguous:
  714. DiagnoseAmbiguousLookup(R);
  715. return ExprError();
  716. }
  717. if (!ParameterPack || !ParameterPack->isParameterPack()) {
  718. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
  719. << &Name;
  720. return ExprError();
  721. }
  722. MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
  723. return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc,
  724. ParameterPack, NameLoc, RParenLoc);
  725. }