SemaTemplateVariadic.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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_decltype_auto:
  628. case TST_unknown_anytype:
  629. case TST_error:
  630. break;
  631. }
  632. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  633. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  634. switch (Chunk.Kind) {
  635. case DeclaratorChunk::Pointer:
  636. case DeclaratorChunk::Reference:
  637. case DeclaratorChunk::Paren:
  638. case DeclaratorChunk::BlockPointer:
  639. // These declarator chunks cannot contain any parameter packs.
  640. break;
  641. case DeclaratorChunk::Array:
  642. if (Chunk.Arr.NumElts &&
  643. Chunk.Arr.NumElts->containsUnexpandedParameterPack())
  644. return true;
  645. break;
  646. case DeclaratorChunk::Function:
  647. for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
  648. ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
  649. QualType ParamTy = Param->getType();
  650. assert(!ParamTy.isNull() && "Couldn't parse type?");
  651. if (ParamTy->containsUnexpandedParameterPack()) return true;
  652. }
  653. if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
  654. for (unsigned i = 0; i != Chunk.Fun.NumExceptions; ++i) {
  655. if (Chunk.Fun.Exceptions[i]
  656. .Ty.get()
  657. ->containsUnexpandedParameterPack())
  658. return true;
  659. }
  660. } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
  661. Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
  662. return true;
  663. if (Chunk.Fun.hasTrailingReturnType()) {
  664. QualType T = Chunk.Fun.getTrailingReturnType().get();
  665. if (!T.isNull() && T->containsUnexpandedParameterPack())
  666. return true;
  667. }
  668. break;
  669. case DeclaratorChunk::MemberPointer:
  670. if (Chunk.Mem.Scope().getScopeRep() &&
  671. Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
  672. return true;
  673. break;
  674. }
  675. }
  676. return false;
  677. }
  678. namespace {
  679. // Callback to only accept typo corrections that refer to parameter packs.
  680. class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
  681. public:
  682. bool ValidateCandidate(const TypoCorrection &candidate) override {
  683. NamedDecl *ND = candidate.getCorrectionDecl();
  684. return ND && ND->isParameterPack();
  685. }
  686. };
  687. }
  688. /// \brief Called when an expression computing the size of a parameter pack
  689. /// is parsed.
  690. ///
  691. /// \code
  692. /// template<typename ...Types> struct count {
  693. /// static const unsigned value = sizeof...(Types);
  694. /// };
  695. /// \endcode
  696. ///
  697. //
  698. /// \param OpLoc The location of the "sizeof" keyword.
  699. /// \param Name The name of the parameter pack whose size will be determined.
  700. /// \param NameLoc The source location of the name of the parameter pack.
  701. /// \param RParenLoc The location of the closing parentheses.
  702. ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
  703. SourceLocation OpLoc,
  704. IdentifierInfo &Name,
  705. SourceLocation NameLoc,
  706. SourceLocation RParenLoc) {
  707. // C++0x [expr.sizeof]p5:
  708. // The identifier in a sizeof... expression shall name a parameter pack.
  709. LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
  710. LookupName(R, S);
  711. NamedDecl *ParameterPack = nullptr;
  712. switch (R.getResultKind()) {
  713. case LookupResult::Found:
  714. ParameterPack = R.getFoundDecl();
  715. break;
  716. case LookupResult::NotFound:
  717. case LookupResult::NotFoundInCurrentInstantiation:
  718. if (TypoCorrection Corrected =
  719. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  720. llvm::make_unique<ParameterPackValidatorCCC>(),
  721. CTK_ErrorRecovery)) {
  722. diagnoseTypo(Corrected,
  723. PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
  724. PDiag(diag::note_parameter_pack_here));
  725. ParameterPack = Corrected.getCorrectionDecl();
  726. }
  727. case LookupResult::FoundOverloaded:
  728. case LookupResult::FoundUnresolvedValue:
  729. break;
  730. case LookupResult::Ambiguous:
  731. DiagnoseAmbiguousLookup(R);
  732. return ExprError();
  733. }
  734. if (!ParameterPack || !ParameterPack->isParameterPack()) {
  735. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
  736. << &Name;
  737. return ExprError();
  738. }
  739. MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
  740. return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc,
  741. ParameterPack, NameLoc, RParenLoc);
  742. }
  743. TemplateArgumentLoc
  744. Sema::getTemplateArgumentPackExpansionPattern(
  745. TemplateArgumentLoc OrigLoc,
  746. SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
  747. const TemplateArgument &Argument = OrigLoc.getArgument();
  748. assert(Argument.isPackExpansion());
  749. switch (Argument.getKind()) {
  750. case TemplateArgument::Type: {
  751. // FIXME: We shouldn't ever have to worry about missing
  752. // type-source info!
  753. TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
  754. if (!ExpansionTSInfo)
  755. ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
  756. Ellipsis);
  757. PackExpansionTypeLoc Expansion =
  758. ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
  759. Ellipsis = Expansion.getEllipsisLoc();
  760. TypeLoc Pattern = Expansion.getPatternLoc();
  761. NumExpansions = Expansion.getTypePtr()->getNumExpansions();
  762. // We need to copy the TypeLoc because TemplateArgumentLocs store a
  763. // TypeSourceInfo.
  764. // FIXME: Find some way to avoid the copy?
  765. TypeLocBuilder TLB;
  766. TLB.pushFullCopy(Pattern);
  767. TypeSourceInfo *PatternTSInfo =
  768. TLB.getTypeSourceInfo(Context, Pattern.getType());
  769. return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
  770. PatternTSInfo);
  771. }
  772. case TemplateArgument::Expression: {
  773. PackExpansionExpr *Expansion
  774. = cast<PackExpansionExpr>(Argument.getAsExpr());
  775. Expr *Pattern = Expansion->getPattern();
  776. Ellipsis = Expansion->getEllipsisLoc();
  777. NumExpansions = Expansion->getNumExpansions();
  778. return TemplateArgumentLoc(Pattern, Pattern);
  779. }
  780. case TemplateArgument::TemplateExpansion:
  781. Ellipsis = OrigLoc.getTemplateEllipsisLoc();
  782. NumExpansions = Argument.getNumTemplateExpansions();
  783. return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
  784. OrigLoc.getTemplateQualifierLoc(),
  785. OrigLoc.getTemplateNameLoc());
  786. case TemplateArgument::Declaration:
  787. case TemplateArgument::NullPtr:
  788. case TemplateArgument::Template:
  789. case TemplateArgument::Integral:
  790. case TemplateArgument::Pack:
  791. case TemplateArgument::Null:
  792. return TemplateArgumentLoc();
  793. }
  794. llvm_unreachable("Invalid TemplateArgument Kind!");
  795. }
  796. static void CheckFoldOperand(Sema &S, Expr *E) {
  797. if (!E)
  798. return;
  799. E = E->IgnoreImpCasts();
  800. if (isa<BinaryOperator>(E) || isa<AbstractConditionalOperator>(E)) {
  801. S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
  802. << E->getSourceRange()
  803. << FixItHint::CreateInsertion(E->getLocStart(), "(")
  804. << FixItHint::CreateInsertion(E->getLocEnd(), ")");
  805. }
  806. }
  807. ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  808. tok::TokenKind Operator,
  809. SourceLocation EllipsisLoc, Expr *RHS,
  810. SourceLocation RParenLoc) {
  811. // LHS and RHS must be cast-expressions. We allow an arbitrary expression
  812. // in the parser and reduce down to just cast-expressions here.
  813. CheckFoldOperand(*this, LHS);
  814. CheckFoldOperand(*this, RHS);
  815. // [expr.prim.fold]p3:
  816. // In a binary fold, op1 and op2 shall be the same fold-operator, and
  817. // either e1 shall contain an unexpanded parameter pack or e2 shall contain
  818. // an unexpanded parameter pack, but not both.
  819. if (LHS && RHS &&
  820. LHS->containsUnexpandedParameterPack() ==
  821. RHS->containsUnexpandedParameterPack()) {
  822. return Diag(EllipsisLoc,
  823. LHS->containsUnexpandedParameterPack()
  824. ? diag::err_fold_expression_packs_both_sides
  825. : diag::err_pack_expansion_without_parameter_packs)
  826. << LHS->getSourceRange() << RHS->getSourceRange();
  827. }
  828. // [expr.prim.fold]p2:
  829. // In a unary fold, the cast-expression shall contain an unexpanded
  830. // parameter pack.
  831. if (!LHS || !RHS) {
  832. Expr *Pack = LHS ? LHS : RHS;
  833. assert(Pack && "fold expression with neither LHS nor RHS");
  834. if (!Pack->containsUnexpandedParameterPack())
  835. return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  836. << Pack->getSourceRange();
  837. }
  838. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
  839. return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
  840. }
  841. ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  842. BinaryOperatorKind Operator,
  843. SourceLocation EllipsisLoc, Expr *RHS,
  844. SourceLocation RParenLoc) {
  845. return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
  846. Operator, EllipsisLoc, RHS, RParenLoc);
  847. }
  848. ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
  849. BinaryOperatorKind Operator) {
  850. // [temp.variadic]p9:
  851. // If N is zero for a unary fold-expression, the value of the expression is
  852. // * -> 1
  853. // + -> int()
  854. // & -> -1
  855. // | -> int()
  856. // && -> true
  857. // || -> false
  858. // , -> void()
  859. // if the operator is not listed [above], the instantiation is ill-formed.
  860. //
  861. // Note that we need to use something like int() here, not merely 0, to
  862. // prevent the result from being a null pointer constant.
  863. QualType ScalarType;
  864. switch (Operator) {
  865. case BO_Add:
  866. ScalarType = Context.IntTy;
  867. break;
  868. case BO_Mul:
  869. return ActOnIntegerConstant(EllipsisLoc, 1);
  870. case BO_Or:
  871. ScalarType = Context.IntTy;
  872. break;
  873. case BO_And:
  874. return CreateBuiltinUnaryOp(EllipsisLoc, UO_Minus,
  875. ActOnIntegerConstant(EllipsisLoc, 1).get());
  876. case BO_LOr:
  877. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
  878. case BO_LAnd:
  879. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
  880. case BO_Comma:
  881. ScalarType = Context.VoidTy;
  882. break;
  883. default:
  884. return Diag(EllipsisLoc, diag::err_fold_expression_empty)
  885. << BinaryOperator::getOpcodeStr(Operator);
  886. }
  887. return new (Context) CXXScalarValueInitExpr(
  888. ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
  889. EllipsisLoc);
  890. }