SemaTemplateVariadic.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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 "TypeLocBuilder.h"
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/RecursiveASTVisitor.h"
  15. #include "clang/AST/TypeLoc.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/ParsedTemplate.h"
  18. #include "clang/Sema/ScopeInfo.h"
  19. #include "clang/Sema/SemaInternal.h"
  20. #include "clang/Sema/Template.h"
  21. using namespace clang;
  22. //----------------------------------------------------------------------------
  23. // Visitor that collects unexpanded parameter packs
  24. //----------------------------------------------------------------------------
  25. namespace {
  26. /// \brief A class that collects unexpanded parameter packs.
  27. class CollectUnexpandedParameterPacksVisitor :
  28. public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
  29. {
  30. typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
  31. inherited;
  32. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
  33. bool InLambda;
  34. public:
  35. explicit CollectUnexpandedParameterPacksVisitor(
  36. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
  37. : Unexpanded(Unexpanded), InLambda(false) { }
  38. bool shouldWalkTypesOfTypeLocs() const { return false; }
  39. //------------------------------------------------------------------------
  40. // Recording occurrences of (unexpanded) parameter packs.
  41. //------------------------------------------------------------------------
  42. /// \brief Record occurrences of template type parameter packs.
  43. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  44. if (TL.getTypePtr()->isParameterPack())
  45. Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
  46. return true;
  47. }
  48. /// \brief Record occurrences of template type parameter packs
  49. /// when we don't have proper source-location information for
  50. /// them.
  51. ///
  52. /// Ideally, this routine would never be used.
  53. bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
  54. if (T->isParameterPack())
  55. Unexpanded.push_back(std::make_pair(T, SourceLocation()));
  56. return true;
  57. }
  58. /// \brief Record occurrences of function and non-type template
  59. /// parameter packs in an expression.
  60. bool VisitDeclRefExpr(DeclRefExpr *E) {
  61. if (E->getDecl()->isParameterPack())
  62. Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
  63. return true;
  64. }
  65. /// \brief Record occurrences of template template parameter packs.
  66. bool TraverseTemplateName(TemplateName Template) {
  67. if (TemplateTemplateParmDecl *TTP
  68. = dyn_cast_or_null<TemplateTemplateParmDecl>(
  69. Template.getAsTemplateDecl()))
  70. if (TTP->isParameterPack())
  71. Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
  72. return inherited::TraverseTemplateName(Template);
  73. }
  74. /// \brief Suppress traversal into Objective-C container literal
  75. /// elements that are pack expansions.
  76. bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  77. if (!E->containsUnexpandedParameterPack())
  78. return true;
  79. for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
  80. ObjCDictionaryElement Element = E->getKeyValueElement(I);
  81. if (Element.isPackExpansion())
  82. continue;
  83. TraverseStmt(Element.Key);
  84. TraverseStmt(Element.Value);
  85. }
  86. return true;
  87. }
  88. //------------------------------------------------------------------------
  89. // Pruning the search for unexpanded parameter packs.
  90. //------------------------------------------------------------------------
  91. /// \brief Suppress traversal into statements and expressions that
  92. /// do not contain unexpanded parameter packs.
  93. bool TraverseStmt(Stmt *S) {
  94. Expr *E = dyn_cast_or_null<Expr>(S);
  95. if ((E && E->containsUnexpandedParameterPack()) || InLambda)
  96. return inherited::TraverseStmt(S);
  97. return true;
  98. }
  99. /// \brief Suppress traversal into types that do not contain
  100. /// unexpanded parameter packs.
  101. bool TraverseType(QualType T) {
  102. if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
  103. return inherited::TraverseType(T);
  104. return true;
  105. }
  106. /// \brief Suppress traversel into types with location information
  107. /// that do not contain unexpanded parameter packs.
  108. bool TraverseTypeLoc(TypeLoc TL) {
  109. if ((!TL.getType().isNull() &&
  110. TL.getType()->containsUnexpandedParameterPack()) ||
  111. InLambda)
  112. return inherited::TraverseTypeLoc(TL);
  113. return true;
  114. }
  115. /// \brief Suppress traversal of non-parameter declarations, since
  116. /// they cannot contain unexpanded parameter packs.
  117. bool TraverseDecl(Decl *D) {
  118. if ((D && isa<ParmVarDecl>(D)) || InLambda)
  119. return inherited::TraverseDecl(D);
  120. return true;
  121. }
  122. /// \brief Suppress traversal of template argument pack expansions.
  123. bool TraverseTemplateArgument(const TemplateArgument &Arg) {
  124. if (Arg.isPackExpansion())
  125. return true;
  126. return inherited::TraverseTemplateArgument(Arg);
  127. }
  128. /// \brief Suppress traversal of template argument pack expansions.
  129. bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
  130. if (ArgLoc.getArgument().isPackExpansion())
  131. return true;
  132. return inherited::TraverseTemplateArgumentLoc(ArgLoc);
  133. }
  134. /// \brief Note whether we're traversing a lambda containing an unexpanded
  135. /// parameter pack. In this case, the unexpanded pack can occur anywhere,
  136. /// including all the places where we normally wouldn't look. Within a
  137. /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
  138. /// outside an expression.
  139. bool TraverseLambdaExpr(LambdaExpr *Lambda) {
  140. // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
  141. // even if it's contained within another lambda.
  142. if (!Lambda->containsUnexpandedParameterPack())
  143. return true;
  144. bool WasInLambda = InLambda;
  145. InLambda = true;
  146. // If any capture names a function parameter pack, that pack is expanded
  147. // when the lambda is expanded.
  148. for (LambdaExpr::capture_iterator I = Lambda->capture_begin(),
  149. E = Lambda->capture_end();
  150. I != E; ++I) {
  151. if (I->capturesVariable()) {
  152. VarDecl *VD = I->getCapturedVar();
  153. if (VD->isParameterPack())
  154. Unexpanded.push_back(std::make_pair(VD, I->getLocation()));
  155. }
  156. }
  157. inherited::TraverseLambdaExpr(Lambda);
  158. InLambda = WasInLambda;
  159. return true;
  160. }
  161. };
  162. }
  163. /// \brief Determine whether it's possible for an unexpanded parameter pack to
  164. /// be valid in this location. This only happens when we're in a declaration
  165. /// that is nested within an expression that could be expanded, such as a
  166. /// lambda-expression within a function call.
  167. ///
  168. /// This is conservatively correct, but may claim that some unexpanded packs are
  169. /// permitted when they are not.
  170. bool Sema::isUnexpandedParameterPackPermitted() {
  171. for (auto *SI : FunctionScopes)
  172. if (isa<sema::LambdaScopeInfo>(SI))
  173. return true;
  174. return false;
  175. }
  176. /// \brief Diagnose all of the unexpanded parameter packs in the given
  177. /// vector.
  178. bool
  179. Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
  180. UnexpandedParameterPackContext UPPC,
  181. ArrayRef<UnexpandedParameterPack> Unexpanded) {
  182. if (Unexpanded.empty())
  183. return false;
  184. // If we are within a lambda expression, that lambda contains an unexpanded
  185. // parameter pack, and we are done.
  186. // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
  187. // later.
  188. for (unsigned N = FunctionScopes.size(); N; --N) {
  189. if (sema::LambdaScopeInfo *LSI =
  190. dyn_cast<sema::LambdaScopeInfo>(FunctionScopes[N-1])) {
  191. LSI->ContainsUnexpandedParameterPack = true;
  192. return false;
  193. }
  194. }
  195. SmallVector<SourceLocation, 4> Locations;
  196. SmallVector<IdentifierInfo *, 4> Names;
  197. llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
  198. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  199. IdentifierInfo *Name = nullptr;
  200. if (const TemplateTypeParmType *TTP
  201. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
  202. Name = TTP->getIdentifier();
  203. else
  204. Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
  205. if (Name && NamesKnown.insert(Name).second)
  206. Names.push_back(Name);
  207. if (Unexpanded[I].second.isValid())
  208. Locations.push_back(Unexpanded[I].second);
  209. }
  210. DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
  211. << (int)UPPC << (int)Names.size();
  212. for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
  213. DB << Names[I];
  214. for (unsigned I = 0, N = Locations.size(); I != N; ++I)
  215. DB << SourceRange(Locations[I]);
  216. return true;
  217. }
  218. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  219. TypeSourceInfo *T,
  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 (!T->getType()->containsUnexpandedParameterPack())
  225. return false;
  226. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  227. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
  228. T->getTypeLoc());
  229. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  230. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  231. }
  232. bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
  233. UnexpandedParameterPackContext UPPC) {
  234. // C++0x [temp.variadic]p5:
  235. // An appearance of a name of a parameter pack that is not expanded is
  236. // ill-formed.
  237. if (!E->containsUnexpandedParameterPack())
  238. return false;
  239. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  240. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
  241. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  242. return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
  243. }
  244. bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
  245. UnexpandedParameterPackContext UPPC) {
  246. // C++0x [temp.variadic]p5:
  247. // An appearance of a name of a parameter pack that is not expanded is
  248. // ill-formed.
  249. if (!SS.getScopeRep() ||
  250. !SS.getScopeRep()->containsUnexpandedParameterPack())
  251. return false;
  252. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  253. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  254. .TraverseNestedNameSpecifier(SS.getScopeRep());
  255. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  256. return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
  257. UPPC, Unexpanded);
  258. }
  259. bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
  260. UnexpandedParameterPackContext UPPC) {
  261. // C++0x [temp.variadic]p5:
  262. // An appearance of a name of a parameter pack that is not expanded is
  263. // ill-formed.
  264. switch (NameInfo.getName().getNameKind()) {
  265. case DeclarationName::Identifier:
  266. case DeclarationName::ObjCZeroArgSelector:
  267. case DeclarationName::ObjCOneArgSelector:
  268. case DeclarationName::ObjCMultiArgSelector:
  269. case DeclarationName::CXXOperatorName:
  270. case DeclarationName::CXXLiteralOperatorName:
  271. case DeclarationName::CXXUsingDirective:
  272. return false;
  273. case DeclarationName::CXXConstructorName:
  274. case DeclarationName::CXXDestructorName:
  275. case DeclarationName::CXXConversionFunctionName:
  276. // FIXME: We shouldn't need this null check!
  277. if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
  278. return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
  279. if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
  280. return false;
  281. break;
  282. }
  283. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  284. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  285. .TraverseType(NameInfo.getName().getCXXNameType());
  286. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  287. return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
  288. }
  289. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  290. TemplateName Template,
  291. UnexpandedParameterPackContext UPPC) {
  292. if (Template.isNull() || !Template.containsUnexpandedParameterPack())
  293. return false;
  294. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  295. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  296. .TraverseTemplateName(Template);
  297. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  298. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  299. }
  300. bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
  301. UnexpandedParameterPackContext UPPC) {
  302. if (Arg.getArgument().isNull() ||
  303. !Arg.getArgument().containsUnexpandedParameterPack())
  304. return false;
  305. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  306. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  307. .TraverseTemplateArgumentLoc(Arg);
  308. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  309. return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
  310. }
  311. void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
  312. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  313. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  314. .TraverseTemplateArgument(Arg);
  315. }
  316. void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
  317. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  318. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  319. .TraverseTemplateArgumentLoc(Arg);
  320. }
  321. void Sema::collectUnexpandedParameterPacks(QualType T,
  322. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  323. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
  324. }
  325. void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
  326. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  327. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
  328. }
  329. void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
  330. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  331. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  332. if (!Qualifier)
  333. return;
  334. NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
  335. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  336. .TraverseNestedNameSpecifierLoc(QualifierLoc);
  337. }
  338. void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
  339. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  340. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  341. .TraverseDeclarationNameInfo(NameInfo);
  342. }
  343. ParsedTemplateArgument
  344. Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
  345. SourceLocation EllipsisLoc) {
  346. if (Arg.isInvalid())
  347. return Arg;
  348. switch (Arg.getKind()) {
  349. case ParsedTemplateArgument::Type: {
  350. TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
  351. if (Result.isInvalid())
  352. return ParsedTemplateArgument();
  353. return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
  354. Arg.getLocation());
  355. }
  356. case ParsedTemplateArgument::NonType: {
  357. ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
  358. if (Result.isInvalid())
  359. return ParsedTemplateArgument();
  360. return ParsedTemplateArgument(Arg.getKind(), Result.get(),
  361. Arg.getLocation());
  362. }
  363. case ParsedTemplateArgument::Template:
  364. if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
  365. SourceRange R(Arg.getLocation());
  366. if (Arg.getScopeSpec().isValid())
  367. R.setBegin(Arg.getScopeSpec().getBeginLoc());
  368. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  369. << R;
  370. return ParsedTemplateArgument();
  371. }
  372. return Arg.getTemplatePackExpansion(EllipsisLoc);
  373. }
  374. llvm_unreachable("Unhandled template argument kind?");
  375. }
  376. TypeResult Sema::ActOnPackExpansion(ParsedType Type,
  377. SourceLocation EllipsisLoc) {
  378. TypeSourceInfo *TSInfo;
  379. GetTypeFromParser(Type, &TSInfo);
  380. if (!TSInfo)
  381. return true;
  382. TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
  383. if (!TSResult)
  384. return true;
  385. return CreateParsedType(TSResult->getType(), TSResult);
  386. }
  387. TypeSourceInfo *
  388. Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
  389. Optional<unsigned> NumExpansions) {
  390. // Create the pack expansion type and source-location information.
  391. QualType Result = CheckPackExpansion(Pattern->getType(),
  392. Pattern->getTypeLoc().getSourceRange(),
  393. EllipsisLoc, NumExpansions);
  394. if (Result.isNull())
  395. return nullptr;
  396. TypeLocBuilder TLB;
  397. TLB.pushFullCopy(Pattern->getTypeLoc());
  398. PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
  399. TL.setEllipsisLoc(EllipsisLoc);
  400. return TLB.getTypeSourceInfo(Context, Result);
  401. }
  402. QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
  403. SourceLocation EllipsisLoc,
  404. Optional<unsigned> NumExpansions) {
  405. // C++0x [temp.variadic]p5:
  406. // The pattern of a pack expansion shall name one or more
  407. // parameter packs that are not expanded by a nested pack
  408. // expansion.
  409. if (!Pattern->containsUnexpandedParameterPack()) {
  410. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  411. << PatternRange;
  412. return QualType();
  413. }
  414. return Context.getPackExpansionType(Pattern, NumExpansions);
  415. }
  416. ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
  417. return CheckPackExpansion(Pattern, EllipsisLoc, None);
  418. }
  419. ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
  420. Optional<unsigned> NumExpansions) {
  421. if (!Pattern)
  422. return ExprError();
  423. // C++0x [temp.variadic]p5:
  424. // The pattern of a pack expansion shall name one or more
  425. // parameter packs that are not expanded by a nested pack
  426. // expansion.
  427. if (!Pattern->containsUnexpandedParameterPack()) {
  428. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  429. << Pattern->getSourceRange();
  430. return ExprError();
  431. }
  432. // Create the pack expansion expression and source-location information.
  433. return new (Context)
  434. PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
  435. }
  436. /// \brief Retrieve the depth and index of a parameter pack.
  437. static std::pair<unsigned, unsigned>
  438. getDepthAndIndex(NamedDecl *ND) {
  439. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
  440. return std::make_pair(TTP->getDepth(), TTP->getIndex());
  441. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
  442. return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
  443. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
  444. return std::make_pair(TTP->getDepth(), TTP->getIndex());
  445. }
  446. bool Sema::CheckParameterPacksForExpansion(
  447. SourceLocation EllipsisLoc, SourceRange PatternRange,
  448. ArrayRef<UnexpandedParameterPack> Unexpanded,
  449. const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
  450. bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
  451. ShouldExpand = true;
  452. RetainExpansion = false;
  453. std::pair<IdentifierInfo *, SourceLocation> FirstPack;
  454. bool HaveFirstPack = false;
  455. for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
  456. end = Unexpanded.end();
  457. i != end; ++i) {
  458. // Compute the depth and index for this parameter pack.
  459. unsigned Depth = 0, Index = 0;
  460. IdentifierInfo *Name;
  461. bool IsFunctionParameterPack = false;
  462. if (const TemplateTypeParmType *TTP
  463. = i->first.dyn_cast<const TemplateTypeParmType *>()) {
  464. Depth = TTP->getDepth();
  465. Index = TTP->getIndex();
  466. Name = TTP->getIdentifier();
  467. } else {
  468. NamedDecl *ND = i->first.get<NamedDecl *>();
  469. if (isa<ParmVarDecl>(ND))
  470. IsFunctionParameterPack = true;
  471. else
  472. std::tie(Depth, Index) = getDepthAndIndex(ND);
  473. Name = ND->getIdentifier();
  474. }
  475. // Determine the size of this argument pack.
  476. unsigned NewPackSize;
  477. if (IsFunctionParameterPack) {
  478. // Figure out whether we're instantiating to an argument pack or not.
  479. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  480. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  481. = CurrentInstantiationScope->findInstantiationOf(
  482. i->first.get<NamedDecl *>());
  483. if (Instantiation->is<DeclArgumentPack *>()) {
  484. // We could expand this function parameter pack.
  485. NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
  486. } else {
  487. // We can't expand this function parameter pack, so we can't expand
  488. // the pack expansion.
  489. ShouldExpand = false;
  490. continue;
  491. }
  492. } else {
  493. // If we don't have a template argument at this depth/index, then we
  494. // cannot expand the pack expansion. Make a note of this, but we still
  495. // want to check any parameter packs we *do* have arguments for.
  496. if (Depth >= TemplateArgs.getNumLevels() ||
  497. !TemplateArgs.hasTemplateArgument(Depth, Index)) {
  498. ShouldExpand = false;
  499. continue;
  500. }
  501. // Determine the size of the argument pack.
  502. NewPackSize = TemplateArgs(Depth, Index).pack_size();
  503. }
  504. // C++0x [temp.arg.explicit]p9:
  505. // Template argument deduction can extend the sequence of template
  506. // arguments corresponding to a template parameter pack, even when the
  507. // sequence contains explicitly specified template arguments.
  508. if (!IsFunctionParameterPack) {
  509. if (NamedDecl *PartialPack
  510. = CurrentInstantiationScope->getPartiallySubstitutedPack()){
  511. unsigned PartialDepth, PartialIndex;
  512. std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
  513. if (PartialDepth == Depth && PartialIndex == Index)
  514. RetainExpansion = true;
  515. }
  516. }
  517. if (!NumExpansions) {
  518. // The is the first pack we've seen for which we have an argument.
  519. // Record it.
  520. NumExpansions = NewPackSize;
  521. FirstPack.first = Name;
  522. FirstPack.second = i->second;
  523. HaveFirstPack = true;
  524. continue;
  525. }
  526. if (NewPackSize != *NumExpansions) {
  527. // C++0x [temp.variadic]p5:
  528. // All of the parameter packs expanded by a pack expansion shall have
  529. // the same number of arguments specified.
  530. if (HaveFirstPack)
  531. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
  532. << FirstPack.first << Name << *NumExpansions << NewPackSize
  533. << SourceRange(FirstPack.second) << SourceRange(i->second);
  534. else
  535. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
  536. << Name << *NumExpansions << NewPackSize
  537. << SourceRange(i->second);
  538. return true;
  539. }
  540. }
  541. return false;
  542. }
  543. Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
  544. const MultiLevelTemplateArgumentList &TemplateArgs) {
  545. QualType Pattern = cast<PackExpansionType>(T)->getPattern();
  546. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  547. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
  548. Optional<unsigned> Result;
  549. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  550. // Compute the depth and index for this parameter pack.
  551. unsigned Depth;
  552. unsigned Index;
  553. if (const TemplateTypeParmType *TTP
  554. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
  555. Depth = TTP->getDepth();
  556. Index = TTP->getIndex();
  557. } else {
  558. NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
  559. if (isa<ParmVarDecl>(ND)) {
  560. // Function parameter pack.
  561. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  562. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  563. = CurrentInstantiationScope->findInstantiationOf(
  564. Unexpanded[I].first.get<NamedDecl *>());
  565. if (Instantiation->is<Decl*>())
  566. // The pattern refers to an unexpanded pack. We're not ready to expand
  567. // this pack yet.
  568. return None;
  569. unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
  570. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  571. Result = Size;
  572. continue;
  573. }
  574. std::tie(Depth, Index) = getDepthAndIndex(ND);
  575. }
  576. if (Depth >= TemplateArgs.getNumLevels() ||
  577. !TemplateArgs.hasTemplateArgument(Depth, Index))
  578. // The pattern refers to an unknown template argument. We're not ready to
  579. // expand this pack yet.
  580. return None;
  581. // Determine the size of the argument pack.
  582. unsigned Size = TemplateArgs(Depth, Index).pack_size();
  583. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  584. Result = Size;
  585. }
  586. return Result;
  587. }
  588. bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
  589. const DeclSpec &DS = D.getDeclSpec();
  590. switch (DS.getTypeSpecType()) {
  591. case TST_typename:
  592. case TST_typeofType:
  593. case TST_underlyingType:
  594. case TST_atomic: {
  595. QualType T = DS.getRepAsType().get();
  596. if (!T.isNull() && T->containsUnexpandedParameterPack())
  597. return true;
  598. break;
  599. }
  600. case TST_typeofExpr:
  601. case TST_decltype:
  602. if (DS.getRepAsExpr() &&
  603. DS.getRepAsExpr()->containsUnexpandedParameterPack())
  604. return true;
  605. break;
  606. case TST_unspecified:
  607. case TST_void:
  608. case TST_char:
  609. case TST_wchar:
  610. case TST_char16:
  611. case TST_char32:
  612. case TST_int:
  613. case TST_int128:
  614. case TST_half:
  615. case TST_float:
  616. case TST_double:
  617. case TST_bool:
  618. case TST_decimal32:
  619. case TST_decimal64:
  620. case TST_decimal128:
  621. case TST_enum:
  622. case TST_union:
  623. case TST_struct:
  624. case TST_interface:
  625. case TST_class:
  626. case TST_auto:
  627. case TST_auto_type:
  628. case TST_decltype_auto:
  629. case TST_unknown_anytype:
  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. case DeclaratorChunk::Pipe:
  640. case DeclaratorChunk::BlockPointer:
  641. // These declarator chunks cannot contain any parameter packs.
  642. break;
  643. case DeclaratorChunk::Array:
  644. if (Chunk.Arr.NumElts &&
  645. Chunk.Arr.NumElts->containsUnexpandedParameterPack())
  646. return true;
  647. break;
  648. case DeclaratorChunk::Function:
  649. for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
  650. ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
  651. QualType ParamTy = Param->getType();
  652. assert(!ParamTy.isNull() && "Couldn't parse type?");
  653. if (ParamTy->containsUnexpandedParameterPack()) return true;
  654. }
  655. if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
  656. for (unsigned i = 0; i != Chunk.Fun.NumExceptions; ++i) {
  657. if (Chunk.Fun.Exceptions[i]
  658. .Ty.get()
  659. ->containsUnexpandedParameterPack())
  660. return true;
  661. }
  662. } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
  663. Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
  664. return true;
  665. if (Chunk.Fun.hasTrailingReturnType()) {
  666. QualType T = Chunk.Fun.getTrailingReturnType().get();
  667. if (!T.isNull() && T->containsUnexpandedParameterPack())
  668. return true;
  669. }
  670. break;
  671. case DeclaratorChunk::MemberPointer:
  672. if (Chunk.Mem.Scope().getScopeRep() &&
  673. Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
  674. return true;
  675. break;
  676. }
  677. }
  678. return false;
  679. }
  680. namespace {
  681. // Callback to only accept typo corrections that refer to parameter packs.
  682. class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
  683. public:
  684. bool ValidateCandidate(const TypoCorrection &candidate) override {
  685. NamedDecl *ND = candidate.getCorrectionDecl();
  686. return ND && ND->isParameterPack();
  687. }
  688. };
  689. }
  690. /// \brief Called when an expression computing the size of a parameter pack
  691. /// is parsed.
  692. ///
  693. /// \code
  694. /// template<typename ...Types> struct count {
  695. /// static const unsigned value = sizeof...(Types);
  696. /// };
  697. /// \endcode
  698. ///
  699. //
  700. /// \param OpLoc The location of the "sizeof" keyword.
  701. /// \param Name The name of the parameter pack whose size will be determined.
  702. /// \param NameLoc The source location of the name of the parameter pack.
  703. /// \param RParenLoc The location of the closing parentheses.
  704. ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
  705. SourceLocation OpLoc,
  706. IdentifierInfo &Name,
  707. SourceLocation NameLoc,
  708. SourceLocation RParenLoc) {
  709. // C++0x [expr.sizeof]p5:
  710. // The identifier in a sizeof... expression shall name a parameter pack.
  711. LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
  712. LookupName(R, S);
  713. NamedDecl *ParameterPack = nullptr;
  714. switch (R.getResultKind()) {
  715. case LookupResult::Found:
  716. ParameterPack = R.getFoundDecl();
  717. break;
  718. case LookupResult::NotFound:
  719. case LookupResult::NotFoundInCurrentInstantiation:
  720. if (TypoCorrection Corrected =
  721. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  722. llvm::make_unique<ParameterPackValidatorCCC>(),
  723. CTK_ErrorRecovery)) {
  724. diagnoseTypo(Corrected,
  725. PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
  726. PDiag(diag::note_parameter_pack_here));
  727. ParameterPack = Corrected.getCorrectionDecl();
  728. }
  729. case LookupResult::FoundOverloaded:
  730. case LookupResult::FoundUnresolvedValue:
  731. break;
  732. case LookupResult::Ambiguous:
  733. DiagnoseAmbiguousLookup(R);
  734. return ExprError();
  735. }
  736. if (!ParameterPack || !ParameterPack->isParameterPack()) {
  737. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
  738. << &Name;
  739. return ExprError();
  740. }
  741. MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
  742. return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
  743. RParenLoc);
  744. }
  745. TemplateArgumentLoc
  746. Sema::getTemplateArgumentPackExpansionPattern(
  747. TemplateArgumentLoc OrigLoc,
  748. SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
  749. const TemplateArgument &Argument = OrigLoc.getArgument();
  750. assert(Argument.isPackExpansion());
  751. switch (Argument.getKind()) {
  752. case TemplateArgument::Type: {
  753. // FIXME: We shouldn't ever have to worry about missing
  754. // type-source info!
  755. TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
  756. if (!ExpansionTSInfo)
  757. ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
  758. Ellipsis);
  759. PackExpansionTypeLoc Expansion =
  760. ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
  761. Ellipsis = Expansion.getEllipsisLoc();
  762. TypeLoc Pattern = Expansion.getPatternLoc();
  763. NumExpansions = Expansion.getTypePtr()->getNumExpansions();
  764. // We need to copy the TypeLoc because TemplateArgumentLocs store a
  765. // TypeSourceInfo.
  766. // FIXME: Find some way to avoid the copy?
  767. TypeLocBuilder TLB;
  768. TLB.pushFullCopy(Pattern);
  769. TypeSourceInfo *PatternTSInfo =
  770. TLB.getTypeSourceInfo(Context, Pattern.getType());
  771. return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
  772. PatternTSInfo);
  773. }
  774. case TemplateArgument::Expression: {
  775. PackExpansionExpr *Expansion
  776. = cast<PackExpansionExpr>(Argument.getAsExpr());
  777. Expr *Pattern = Expansion->getPattern();
  778. Ellipsis = Expansion->getEllipsisLoc();
  779. NumExpansions = Expansion->getNumExpansions();
  780. return TemplateArgumentLoc(Pattern, Pattern);
  781. }
  782. case TemplateArgument::TemplateExpansion:
  783. Ellipsis = OrigLoc.getTemplateEllipsisLoc();
  784. NumExpansions = Argument.getNumTemplateExpansions();
  785. return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
  786. OrigLoc.getTemplateQualifierLoc(),
  787. OrigLoc.getTemplateNameLoc());
  788. case TemplateArgument::Declaration:
  789. case TemplateArgument::NullPtr:
  790. case TemplateArgument::Template:
  791. case TemplateArgument::Integral:
  792. case TemplateArgument::Pack:
  793. case TemplateArgument::Null:
  794. return TemplateArgumentLoc();
  795. }
  796. llvm_unreachable("Invalid TemplateArgument Kind!");
  797. }
  798. static void CheckFoldOperand(Sema &S, Expr *E) {
  799. if (!E)
  800. return;
  801. E = E->IgnoreImpCasts();
  802. if (isa<BinaryOperator>(E) || isa<AbstractConditionalOperator>(E)) {
  803. S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
  804. << E->getSourceRange()
  805. << FixItHint::CreateInsertion(E->getLocStart(), "(")
  806. << FixItHint::CreateInsertion(E->getLocEnd(), ")");
  807. }
  808. }
  809. ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  810. tok::TokenKind Operator,
  811. SourceLocation EllipsisLoc, Expr *RHS,
  812. SourceLocation RParenLoc) {
  813. // LHS and RHS must be cast-expressions. We allow an arbitrary expression
  814. // in the parser and reduce down to just cast-expressions here.
  815. CheckFoldOperand(*this, LHS);
  816. CheckFoldOperand(*this, RHS);
  817. // [expr.prim.fold]p3:
  818. // In a binary fold, op1 and op2 shall be the same fold-operator, and
  819. // either e1 shall contain an unexpanded parameter pack or e2 shall contain
  820. // an unexpanded parameter pack, but not both.
  821. if (LHS && RHS &&
  822. LHS->containsUnexpandedParameterPack() ==
  823. RHS->containsUnexpandedParameterPack()) {
  824. return Diag(EllipsisLoc,
  825. LHS->containsUnexpandedParameterPack()
  826. ? diag::err_fold_expression_packs_both_sides
  827. : diag::err_pack_expansion_without_parameter_packs)
  828. << LHS->getSourceRange() << RHS->getSourceRange();
  829. }
  830. // [expr.prim.fold]p2:
  831. // In a unary fold, the cast-expression shall contain an unexpanded
  832. // parameter pack.
  833. if (!LHS || !RHS) {
  834. Expr *Pack = LHS ? LHS : RHS;
  835. assert(Pack && "fold expression with neither LHS nor RHS");
  836. if (!Pack->containsUnexpandedParameterPack())
  837. return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  838. << Pack->getSourceRange();
  839. }
  840. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
  841. return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
  842. }
  843. ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  844. BinaryOperatorKind Operator,
  845. SourceLocation EllipsisLoc, Expr *RHS,
  846. SourceLocation RParenLoc) {
  847. return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
  848. Operator, EllipsisLoc, RHS, RParenLoc);
  849. }
  850. ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
  851. BinaryOperatorKind Operator) {
  852. // [temp.variadic]p9:
  853. // If N is zero for a unary fold-expression, the value of the expression is
  854. // * -> 1
  855. // + -> int()
  856. // & -> -1
  857. // | -> int()
  858. // && -> true
  859. // || -> false
  860. // , -> void()
  861. // if the operator is not listed [above], the instantiation is ill-formed.
  862. //
  863. // Note that we need to use something like int() here, not merely 0, to
  864. // prevent the result from being a null pointer constant.
  865. QualType ScalarType;
  866. switch (Operator) {
  867. case BO_Add:
  868. ScalarType = Context.IntTy;
  869. break;
  870. case BO_Mul:
  871. return ActOnIntegerConstant(EllipsisLoc, 1);
  872. case BO_Or:
  873. ScalarType = Context.IntTy;
  874. break;
  875. case BO_And:
  876. return CreateBuiltinUnaryOp(EllipsisLoc, UO_Minus,
  877. ActOnIntegerConstant(EllipsisLoc, 1).get());
  878. case BO_LOr:
  879. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
  880. case BO_LAnd:
  881. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
  882. case BO_Comma:
  883. ScalarType = Context.VoidTy;
  884. break;
  885. default:
  886. return Diag(EllipsisLoc, diag::err_fold_expression_empty)
  887. << BinaryOperator::getOpcodeStr(Operator);
  888. }
  889. return new (Context) CXXScalarValueInitExpr(
  890. ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
  891. EllipsisLoc);
  892. }