SemaTemplateVariadic.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  1. //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //===----------------------------------------------------------------------===/
  7. //
  8. // This file implements semantic analysis for C++0x variadic templates.
  9. //===----------------------------------------------------------------------===/
  10. #include "clang/Sema/Sema.h"
  11. #include "TypeLocBuilder.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. /// 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 = false;
  33. unsigned DepthLimit = (unsigned)-1;
  34. void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
  35. if (auto *VD = dyn_cast<VarDecl>(ND)) {
  36. // For now, the only problematic case is a generic lambda's templated
  37. // call operator, so we don't need to look for all the other ways we
  38. // could have reached a dependent parameter pack.
  39. auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
  40. auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
  41. if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
  42. return;
  43. } else if (getDepthAndIndex(ND).first >= DepthLimit)
  44. return;
  45. Unexpanded.push_back({ND, Loc});
  46. }
  47. void addUnexpanded(const TemplateTypeParmType *T,
  48. SourceLocation Loc = SourceLocation()) {
  49. if (T->getDepth() < DepthLimit)
  50. Unexpanded.push_back({T, Loc});
  51. }
  52. public:
  53. explicit CollectUnexpandedParameterPacksVisitor(
  54. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
  55. : Unexpanded(Unexpanded) {}
  56. bool shouldWalkTypesOfTypeLocs() const { return false; }
  57. //------------------------------------------------------------------------
  58. // Recording occurrences of (unexpanded) parameter packs.
  59. //------------------------------------------------------------------------
  60. /// Record occurrences of template type parameter packs.
  61. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  62. if (TL.getTypePtr()->isParameterPack())
  63. addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
  64. return true;
  65. }
  66. /// Record occurrences of template type parameter packs
  67. /// when we don't have proper source-location information for
  68. /// them.
  69. ///
  70. /// Ideally, this routine would never be used.
  71. bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
  72. if (T->isParameterPack())
  73. addUnexpanded(T);
  74. return true;
  75. }
  76. /// Record occurrences of function and non-type template
  77. /// parameter packs in an expression.
  78. bool VisitDeclRefExpr(DeclRefExpr *E) {
  79. if (E->getDecl()->isParameterPack())
  80. addUnexpanded(E->getDecl(), E->getLocation());
  81. return true;
  82. }
  83. /// Record occurrences of template template parameter packs.
  84. bool TraverseTemplateName(TemplateName Template) {
  85. if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
  86. Template.getAsTemplateDecl())) {
  87. if (TTP->isParameterPack())
  88. addUnexpanded(TTP);
  89. }
  90. return inherited::TraverseTemplateName(Template);
  91. }
  92. /// Suppress traversal into Objective-C container literal
  93. /// elements that are pack expansions.
  94. bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  95. if (!E->containsUnexpandedParameterPack())
  96. return true;
  97. for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
  98. ObjCDictionaryElement Element = E->getKeyValueElement(I);
  99. if (Element.isPackExpansion())
  100. continue;
  101. TraverseStmt(Element.Key);
  102. TraverseStmt(Element.Value);
  103. }
  104. return true;
  105. }
  106. //------------------------------------------------------------------------
  107. // Pruning the search for unexpanded parameter packs.
  108. //------------------------------------------------------------------------
  109. /// Suppress traversal into statements and expressions that
  110. /// do not contain unexpanded parameter packs.
  111. bool TraverseStmt(Stmt *S) {
  112. Expr *E = dyn_cast_or_null<Expr>(S);
  113. if ((E && E->containsUnexpandedParameterPack()) || InLambda)
  114. return inherited::TraverseStmt(S);
  115. return true;
  116. }
  117. /// Suppress traversal into types that do not contain
  118. /// unexpanded parameter packs.
  119. bool TraverseType(QualType T) {
  120. if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
  121. return inherited::TraverseType(T);
  122. return true;
  123. }
  124. /// Suppress traversal into types with location information
  125. /// that do not contain unexpanded parameter packs.
  126. bool TraverseTypeLoc(TypeLoc TL) {
  127. if ((!TL.getType().isNull() &&
  128. TL.getType()->containsUnexpandedParameterPack()) ||
  129. InLambda)
  130. return inherited::TraverseTypeLoc(TL);
  131. return true;
  132. }
  133. /// Suppress traversal of parameter packs.
  134. bool TraverseDecl(Decl *D) {
  135. // A function parameter pack is a pack expansion, so cannot contain
  136. // an unexpanded parameter pack. Likewise for a template parameter
  137. // pack that contains any references to other packs.
  138. if (D && D->isParameterPack())
  139. return true;
  140. return inherited::TraverseDecl(D);
  141. }
  142. /// Suppress traversal of pack-expanded attributes.
  143. bool TraverseAttr(Attr *A) {
  144. if (A->isPackExpansion())
  145. return true;
  146. return inherited::TraverseAttr(A);
  147. }
  148. /// Suppress traversal of pack expansion expressions and types.
  149. ///@{
  150. bool TraversePackExpansionType(PackExpansionType *T) { return true; }
  151. bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
  152. bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
  153. bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
  154. ///@}
  155. /// Suppress traversal of using-declaration pack expansion.
  156. bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  157. if (D->isPackExpansion())
  158. return true;
  159. return inherited::TraverseUnresolvedUsingValueDecl(D);
  160. }
  161. /// Suppress traversal of using-declaration pack expansion.
  162. bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
  163. if (D->isPackExpansion())
  164. return true;
  165. return inherited::TraverseUnresolvedUsingTypenameDecl(D);
  166. }
  167. /// Suppress traversal of template argument pack expansions.
  168. bool TraverseTemplateArgument(const TemplateArgument &Arg) {
  169. if (Arg.isPackExpansion())
  170. return true;
  171. return inherited::TraverseTemplateArgument(Arg);
  172. }
  173. /// Suppress traversal of template argument pack expansions.
  174. bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
  175. if (ArgLoc.getArgument().isPackExpansion())
  176. return true;
  177. return inherited::TraverseTemplateArgumentLoc(ArgLoc);
  178. }
  179. /// Suppress traversal of base specifier pack expansions.
  180. bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
  181. if (Base.isPackExpansion())
  182. return true;
  183. return inherited::TraverseCXXBaseSpecifier(Base);
  184. }
  185. /// Suppress traversal of mem-initializer pack expansions.
  186. bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
  187. if (Init->isPackExpansion())
  188. return true;
  189. return inherited::TraverseConstructorInitializer(Init);
  190. }
  191. /// Note whether we're traversing a lambda containing an unexpanded
  192. /// parameter pack. In this case, the unexpanded pack can occur anywhere,
  193. /// including all the places where we normally wouldn't look. Within a
  194. /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
  195. /// outside an expression.
  196. bool TraverseLambdaExpr(LambdaExpr *Lambda) {
  197. // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
  198. // even if it's contained within another lambda.
  199. if (!Lambda->containsUnexpandedParameterPack())
  200. return true;
  201. bool WasInLambda = InLambda;
  202. unsigned OldDepthLimit = DepthLimit;
  203. InLambda = true;
  204. if (auto *TPL = Lambda->getTemplateParameterList())
  205. DepthLimit = TPL->getDepth();
  206. inherited::TraverseLambdaExpr(Lambda);
  207. InLambda = WasInLambda;
  208. DepthLimit = OldDepthLimit;
  209. return true;
  210. }
  211. /// Suppress traversal within pack expansions in lambda captures.
  212. bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
  213. Expr *Init) {
  214. if (C->isPackExpansion())
  215. return true;
  216. return inherited::TraverseLambdaCapture(Lambda, C, Init);
  217. }
  218. };
  219. }
  220. /// Determine whether it's possible for an unexpanded parameter pack to
  221. /// be valid in this location. This only happens when we're in a declaration
  222. /// that is nested within an expression that could be expanded, such as a
  223. /// lambda-expression within a function call.
  224. ///
  225. /// This is conservatively correct, but may claim that some unexpanded packs are
  226. /// permitted when they are not.
  227. bool Sema::isUnexpandedParameterPackPermitted() {
  228. for (auto *SI : FunctionScopes)
  229. if (isa<sema::LambdaScopeInfo>(SI))
  230. return true;
  231. return false;
  232. }
  233. /// Diagnose all of the unexpanded parameter packs in the given
  234. /// vector.
  235. bool
  236. Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
  237. UnexpandedParameterPackContext UPPC,
  238. ArrayRef<UnexpandedParameterPack> Unexpanded) {
  239. if (Unexpanded.empty())
  240. return false;
  241. // If we are within a lambda expression and referencing a pack that is not
  242. // declared within the lambda itself, that lambda contains an unexpanded
  243. // parameter pack, and we are done.
  244. // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
  245. // later.
  246. SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
  247. if (auto *LSI = getEnclosingLambda()) {
  248. for (auto &Pack : Unexpanded) {
  249. auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
  250. if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
  251. auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
  252. return TTPD && TTPD->getTypeForDecl() == TTPT;
  253. }
  254. return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
  255. };
  256. if (std::find_if(LSI->LocalPacks.begin(), LSI->LocalPacks.end(),
  257. DeclaresThisPack) != LSI->LocalPacks.end())
  258. LambdaParamPackReferences.push_back(Pack);
  259. }
  260. if (LambdaParamPackReferences.empty()) {
  261. // Construct in lambda only references packs declared outside the lambda.
  262. // That's OK for now, but the lambda itself is considered to contain an
  263. // unexpanded pack in this case, which will require expansion outside the
  264. // lambda.
  265. // We do not permit pack expansion that would duplicate a statement
  266. // expression, not even within a lambda.
  267. // FIXME: We could probably support this for statement expressions that
  268. // do not contain labels.
  269. // FIXME: This is insufficient to detect this problem; consider
  270. // f( ({ bad: 0; }) + pack ... );
  271. bool EnclosingStmtExpr = false;
  272. for (unsigned N = FunctionScopes.size(); N; --N) {
  273. sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
  274. if (std::any_of(
  275. Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
  276. [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
  277. EnclosingStmtExpr = true;
  278. break;
  279. }
  280. // Coumpound-statements outside the lambda are OK for now; we'll check
  281. // for those when we finish handling the lambda.
  282. if (Func == LSI)
  283. break;
  284. }
  285. if (!EnclosingStmtExpr) {
  286. LSI->ContainsUnexpandedParameterPack = true;
  287. return false;
  288. }
  289. } else {
  290. Unexpanded = LambdaParamPackReferences;
  291. }
  292. }
  293. SmallVector<SourceLocation, 4> Locations;
  294. SmallVector<IdentifierInfo *, 4> Names;
  295. llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
  296. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  297. IdentifierInfo *Name = nullptr;
  298. if (const TemplateTypeParmType *TTP
  299. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
  300. Name = TTP->getIdentifier();
  301. else
  302. Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
  303. if (Name && NamesKnown.insert(Name).second)
  304. Names.push_back(Name);
  305. if (Unexpanded[I].second.isValid())
  306. Locations.push_back(Unexpanded[I].second);
  307. }
  308. DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
  309. << (int)UPPC << (int)Names.size();
  310. for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
  311. DB << Names[I];
  312. for (unsigned I = 0, N = Locations.size(); I != N; ++I)
  313. DB << SourceRange(Locations[I]);
  314. return true;
  315. }
  316. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  317. TypeSourceInfo *T,
  318. UnexpandedParameterPackContext UPPC) {
  319. // C++0x [temp.variadic]p5:
  320. // An appearance of a name of a parameter pack that is not expanded is
  321. // ill-formed.
  322. if (!T->getType()->containsUnexpandedParameterPack())
  323. return false;
  324. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  325. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
  326. T->getTypeLoc());
  327. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  328. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  329. }
  330. bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
  331. UnexpandedParameterPackContext UPPC) {
  332. // C++0x [temp.variadic]p5:
  333. // An appearance of a name of a parameter pack that is not expanded is
  334. // ill-formed.
  335. if (!E->containsUnexpandedParameterPack())
  336. return false;
  337. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  338. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
  339. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  340. return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
  341. }
  342. bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
  343. UnexpandedParameterPackContext UPPC) {
  344. // C++0x [temp.variadic]p5:
  345. // An appearance of a name of a parameter pack that is not expanded is
  346. // ill-formed.
  347. if (!SS.getScopeRep() ||
  348. !SS.getScopeRep()->containsUnexpandedParameterPack())
  349. return false;
  350. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  351. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  352. .TraverseNestedNameSpecifier(SS.getScopeRep());
  353. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  354. return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
  355. UPPC, Unexpanded);
  356. }
  357. bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
  358. UnexpandedParameterPackContext UPPC) {
  359. // C++0x [temp.variadic]p5:
  360. // An appearance of a name of a parameter pack that is not expanded is
  361. // ill-formed.
  362. switch (NameInfo.getName().getNameKind()) {
  363. case DeclarationName::Identifier:
  364. case DeclarationName::ObjCZeroArgSelector:
  365. case DeclarationName::ObjCOneArgSelector:
  366. case DeclarationName::ObjCMultiArgSelector:
  367. case DeclarationName::CXXOperatorName:
  368. case DeclarationName::CXXLiteralOperatorName:
  369. case DeclarationName::CXXUsingDirective:
  370. case DeclarationName::CXXDeductionGuideName:
  371. return false;
  372. case DeclarationName::CXXConstructorName:
  373. case DeclarationName::CXXDestructorName:
  374. case DeclarationName::CXXConversionFunctionName:
  375. // FIXME: We shouldn't need this null check!
  376. if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
  377. return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
  378. if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
  379. return false;
  380. break;
  381. }
  382. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  383. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  384. .TraverseType(NameInfo.getName().getCXXNameType());
  385. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  386. return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
  387. }
  388. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  389. TemplateName Template,
  390. UnexpandedParameterPackContext UPPC) {
  391. if (Template.isNull() || !Template.containsUnexpandedParameterPack())
  392. return false;
  393. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  394. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  395. .TraverseTemplateName(Template);
  396. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  397. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  398. }
  399. bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
  400. UnexpandedParameterPackContext UPPC) {
  401. if (Arg.getArgument().isNull() ||
  402. !Arg.getArgument().containsUnexpandedParameterPack())
  403. return false;
  404. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  405. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  406. .TraverseTemplateArgumentLoc(Arg);
  407. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  408. return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
  409. }
  410. void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
  411. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  412. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  413. .TraverseTemplateArgument(Arg);
  414. }
  415. void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
  416. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  417. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  418. .TraverseTemplateArgumentLoc(Arg);
  419. }
  420. void Sema::collectUnexpandedParameterPacks(QualType T,
  421. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  422. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
  423. }
  424. void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
  425. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  426. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
  427. }
  428. void Sema::collectUnexpandedParameterPacks(
  429. NestedNameSpecifierLoc NNS,
  430. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  431. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  432. .TraverseNestedNameSpecifierLoc(NNS);
  433. }
  434. void Sema::collectUnexpandedParameterPacks(
  435. const DeclarationNameInfo &NameInfo,
  436. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  437. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  438. .TraverseDeclarationNameInfo(NameInfo);
  439. }
  440. ParsedTemplateArgument
  441. Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
  442. SourceLocation EllipsisLoc) {
  443. if (Arg.isInvalid())
  444. return Arg;
  445. switch (Arg.getKind()) {
  446. case ParsedTemplateArgument::Type: {
  447. TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
  448. if (Result.isInvalid())
  449. return ParsedTemplateArgument();
  450. return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
  451. Arg.getLocation());
  452. }
  453. case ParsedTemplateArgument::NonType: {
  454. ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
  455. if (Result.isInvalid())
  456. return ParsedTemplateArgument();
  457. return ParsedTemplateArgument(Arg.getKind(), Result.get(),
  458. Arg.getLocation());
  459. }
  460. case ParsedTemplateArgument::Template:
  461. if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
  462. SourceRange R(Arg.getLocation());
  463. if (Arg.getScopeSpec().isValid())
  464. R.setBegin(Arg.getScopeSpec().getBeginLoc());
  465. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  466. << R;
  467. return ParsedTemplateArgument();
  468. }
  469. return Arg.getTemplatePackExpansion(EllipsisLoc);
  470. }
  471. llvm_unreachable("Unhandled template argument kind?");
  472. }
  473. TypeResult Sema::ActOnPackExpansion(ParsedType Type,
  474. SourceLocation EllipsisLoc) {
  475. TypeSourceInfo *TSInfo;
  476. GetTypeFromParser(Type, &TSInfo);
  477. if (!TSInfo)
  478. return true;
  479. TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
  480. if (!TSResult)
  481. return true;
  482. return CreateParsedType(TSResult->getType(), TSResult);
  483. }
  484. TypeSourceInfo *
  485. Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
  486. Optional<unsigned> NumExpansions) {
  487. // Create the pack expansion type and source-location information.
  488. QualType Result = CheckPackExpansion(Pattern->getType(),
  489. Pattern->getTypeLoc().getSourceRange(),
  490. EllipsisLoc, NumExpansions);
  491. if (Result.isNull())
  492. return nullptr;
  493. TypeLocBuilder TLB;
  494. TLB.pushFullCopy(Pattern->getTypeLoc());
  495. PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
  496. TL.setEllipsisLoc(EllipsisLoc);
  497. return TLB.getTypeSourceInfo(Context, Result);
  498. }
  499. QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
  500. SourceLocation EllipsisLoc,
  501. Optional<unsigned> NumExpansions) {
  502. // C++11 [temp.variadic]p5:
  503. // The pattern of a pack expansion shall name one or more
  504. // parameter packs that are not expanded by a nested pack
  505. // expansion.
  506. //
  507. // A pattern containing a deduced type can't occur "naturally" but arises in
  508. // the desugaring of an init-capture pack.
  509. if (!Pattern->containsUnexpandedParameterPack() &&
  510. !Pattern->getContainedDeducedType()) {
  511. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  512. << PatternRange;
  513. return QualType();
  514. }
  515. return Context.getPackExpansionType(Pattern, NumExpansions);
  516. }
  517. ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
  518. return CheckPackExpansion(Pattern, EllipsisLoc, None);
  519. }
  520. ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
  521. Optional<unsigned> NumExpansions) {
  522. if (!Pattern)
  523. return ExprError();
  524. // C++0x [temp.variadic]p5:
  525. // The pattern of a pack expansion shall name one or more
  526. // parameter packs that are not expanded by a nested pack
  527. // expansion.
  528. if (!Pattern->containsUnexpandedParameterPack()) {
  529. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  530. << Pattern->getSourceRange();
  531. CorrectDelayedTyposInExpr(Pattern);
  532. return ExprError();
  533. }
  534. // Create the pack expansion expression and source-location information.
  535. return new (Context)
  536. PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
  537. }
  538. bool Sema::CheckParameterPacksForExpansion(
  539. SourceLocation EllipsisLoc, SourceRange PatternRange,
  540. ArrayRef<UnexpandedParameterPack> Unexpanded,
  541. const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
  542. bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
  543. ShouldExpand = true;
  544. RetainExpansion = false;
  545. std::pair<IdentifierInfo *, SourceLocation> FirstPack;
  546. bool HaveFirstPack = false;
  547. Optional<unsigned> NumPartialExpansions;
  548. SourceLocation PartiallySubstitutedPackLoc;
  549. for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
  550. end = Unexpanded.end();
  551. i != end; ++i) {
  552. // Compute the depth and index for this parameter pack.
  553. unsigned Depth = 0, Index = 0;
  554. IdentifierInfo *Name;
  555. bool IsVarDeclPack = false;
  556. if (const TemplateTypeParmType *TTP
  557. = i->first.dyn_cast<const TemplateTypeParmType *>()) {
  558. Depth = TTP->getDepth();
  559. Index = TTP->getIndex();
  560. Name = TTP->getIdentifier();
  561. } else {
  562. NamedDecl *ND = i->first.get<NamedDecl *>();
  563. if (isa<VarDecl>(ND))
  564. IsVarDeclPack = true;
  565. else
  566. std::tie(Depth, Index) = getDepthAndIndex(ND);
  567. Name = ND->getIdentifier();
  568. }
  569. // Determine the size of this argument pack.
  570. unsigned NewPackSize;
  571. if (IsVarDeclPack) {
  572. // Figure out whether we're instantiating to an argument pack or not.
  573. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  574. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  575. = CurrentInstantiationScope->findInstantiationOf(
  576. i->first.get<NamedDecl *>());
  577. if (Instantiation->is<DeclArgumentPack *>()) {
  578. // We could expand this function parameter pack.
  579. NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
  580. } else {
  581. // We can't expand this function parameter pack, so we can't expand
  582. // the pack expansion.
  583. ShouldExpand = false;
  584. continue;
  585. }
  586. } else {
  587. // If we don't have a template argument at this depth/index, then we
  588. // cannot expand the pack expansion. Make a note of this, but we still
  589. // want to check any parameter packs we *do* have arguments for.
  590. if (Depth >= TemplateArgs.getNumLevels() ||
  591. !TemplateArgs.hasTemplateArgument(Depth, Index)) {
  592. ShouldExpand = false;
  593. continue;
  594. }
  595. // Determine the size of the argument pack.
  596. NewPackSize = TemplateArgs(Depth, Index).pack_size();
  597. }
  598. // C++0x [temp.arg.explicit]p9:
  599. // Template argument deduction can extend the sequence of template
  600. // arguments corresponding to a template parameter pack, even when the
  601. // sequence contains explicitly specified template arguments.
  602. if (!IsVarDeclPack && CurrentInstantiationScope) {
  603. if (NamedDecl *PartialPack
  604. = CurrentInstantiationScope->getPartiallySubstitutedPack()){
  605. unsigned PartialDepth, PartialIndex;
  606. std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
  607. if (PartialDepth == Depth && PartialIndex == Index) {
  608. RetainExpansion = true;
  609. // We don't actually know the new pack size yet.
  610. NumPartialExpansions = NewPackSize;
  611. PartiallySubstitutedPackLoc = i->second;
  612. continue;
  613. }
  614. }
  615. }
  616. if (!NumExpansions) {
  617. // The is the first pack we've seen for which we have an argument.
  618. // Record it.
  619. NumExpansions = NewPackSize;
  620. FirstPack.first = Name;
  621. FirstPack.second = i->second;
  622. HaveFirstPack = true;
  623. continue;
  624. }
  625. if (NewPackSize != *NumExpansions) {
  626. // C++0x [temp.variadic]p5:
  627. // All of the parameter packs expanded by a pack expansion shall have
  628. // the same number of arguments specified.
  629. if (HaveFirstPack)
  630. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
  631. << FirstPack.first << Name << *NumExpansions << NewPackSize
  632. << SourceRange(FirstPack.second) << SourceRange(i->second);
  633. else
  634. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
  635. << Name << *NumExpansions << NewPackSize
  636. << SourceRange(i->second);
  637. return true;
  638. }
  639. }
  640. // If we're performing a partial expansion but we also have a full expansion,
  641. // expand to the number of common arguments. For example, given:
  642. //
  643. // template<typename ...T> struct A {
  644. // template<typename ...U> void f(pair<T, U>...);
  645. // };
  646. //
  647. // ... a call to 'A<int, int>().f<int>' should expand the pack once and
  648. // retain an expansion.
  649. if (NumPartialExpansions) {
  650. if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
  651. NamedDecl *PartialPack =
  652. CurrentInstantiationScope->getPartiallySubstitutedPack();
  653. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
  654. << PartialPack << *NumPartialExpansions << *NumExpansions
  655. << SourceRange(PartiallySubstitutedPackLoc);
  656. return true;
  657. }
  658. NumExpansions = NumPartialExpansions;
  659. }
  660. return false;
  661. }
  662. Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
  663. const MultiLevelTemplateArgumentList &TemplateArgs) {
  664. QualType Pattern = cast<PackExpansionType>(T)->getPattern();
  665. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  666. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
  667. Optional<unsigned> Result;
  668. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  669. // Compute the depth and index for this parameter pack.
  670. unsigned Depth;
  671. unsigned Index;
  672. if (const TemplateTypeParmType *TTP
  673. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
  674. Depth = TTP->getDepth();
  675. Index = TTP->getIndex();
  676. } else {
  677. NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
  678. if (isa<VarDecl>(ND)) {
  679. // Function parameter pack or init-capture pack.
  680. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  681. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  682. = CurrentInstantiationScope->findInstantiationOf(
  683. Unexpanded[I].first.get<NamedDecl *>());
  684. if (Instantiation->is<Decl*>())
  685. // The pattern refers to an unexpanded pack. We're not ready to expand
  686. // this pack yet.
  687. return None;
  688. unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
  689. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  690. Result = Size;
  691. continue;
  692. }
  693. std::tie(Depth, Index) = getDepthAndIndex(ND);
  694. }
  695. if (Depth >= TemplateArgs.getNumLevels() ||
  696. !TemplateArgs.hasTemplateArgument(Depth, Index))
  697. // The pattern refers to an unknown template argument. We're not ready to
  698. // expand this pack yet.
  699. return None;
  700. // Determine the size of the argument pack.
  701. unsigned Size = TemplateArgs(Depth, Index).pack_size();
  702. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  703. Result = Size;
  704. }
  705. return Result;
  706. }
  707. bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
  708. const DeclSpec &DS = D.getDeclSpec();
  709. switch (DS.getTypeSpecType()) {
  710. case TST_typename:
  711. case TST_typeofType:
  712. case TST_underlyingType:
  713. case TST_atomic: {
  714. QualType T = DS.getRepAsType().get();
  715. if (!T.isNull() && T->containsUnexpandedParameterPack())
  716. return true;
  717. break;
  718. }
  719. case TST_typeofExpr:
  720. case TST_decltype:
  721. if (DS.getRepAsExpr() &&
  722. DS.getRepAsExpr()->containsUnexpandedParameterPack())
  723. return true;
  724. break;
  725. case TST_unspecified:
  726. case TST_void:
  727. case TST_char:
  728. case TST_wchar:
  729. case TST_char8:
  730. case TST_char16:
  731. case TST_char32:
  732. case TST_int:
  733. case TST_int128:
  734. case TST_half:
  735. case TST_float:
  736. case TST_double:
  737. case TST_Accum:
  738. case TST_Fract:
  739. case TST_Float16:
  740. case TST_float128:
  741. case TST_bool:
  742. case TST_decimal32:
  743. case TST_decimal64:
  744. case TST_decimal128:
  745. case TST_enum:
  746. case TST_union:
  747. case TST_struct:
  748. case TST_interface:
  749. case TST_class:
  750. case TST_auto:
  751. case TST_auto_type:
  752. case TST_decltype_auto:
  753. #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
  754. #include "clang/Basic/OpenCLImageTypes.def"
  755. case TST_unknown_anytype:
  756. case TST_error:
  757. break;
  758. }
  759. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  760. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  761. switch (Chunk.Kind) {
  762. case DeclaratorChunk::Pointer:
  763. case DeclaratorChunk::Reference:
  764. case DeclaratorChunk::Paren:
  765. case DeclaratorChunk::Pipe:
  766. case DeclaratorChunk::BlockPointer:
  767. // These declarator chunks cannot contain any parameter packs.
  768. break;
  769. case DeclaratorChunk::Array:
  770. if (Chunk.Arr.NumElts &&
  771. Chunk.Arr.NumElts->containsUnexpandedParameterPack())
  772. return true;
  773. break;
  774. case DeclaratorChunk::Function:
  775. for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
  776. ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
  777. QualType ParamTy = Param->getType();
  778. assert(!ParamTy.isNull() && "Couldn't parse type?");
  779. if (ParamTy->containsUnexpandedParameterPack()) return true;
  780. }
  781. if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
  782. for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
  783. if (Chunk.Fun.Exceptions[i]
  784. .Ty.get()
  785. ->containsUnexpandedParameterPack())
  786. return true;
  787. }
  788. } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
  789. Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
  790. return true;
  791. if (Chunk.Fun.hasTrailingReturnType()) {
  792. QualType T = Chunk.Fun.getTrailingReturnType().get();
  793. if (!T.isNull() && T->containsUnexpandedParameterPack())
  794. return true;
  795. }
  796. break;
  797. case DeclaratorChunk::MemberPointer:
  798. if (Chunk.Mem.Scope().getScopeRep() &&
  799. Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
  800. return true;
  801. break;
  802. }
  803. }
  804. return false;
  805. }
  806. namespace {
  807. // Callback to only accept typo corrections that refer to parameter packs.
  808. class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
  809. public:
  810. bool ValidateCandidate(const TypoCorrection &candidate) override {
  811. NamedDecl *ND = candidate.getCorrectionDecl();
  812. return ND && ND->isParameterPack();
  813. }
  814. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  815. return std::make_unique<ParameterPackValidatorCCC>(*this);
  816. }
  817. };
  818. }
  819. /// Called when an expression computing the size of a parameter pack
  820. /// is parsed.
  821. ///
  822. /// \code
  823. /// template<typename ...Types> struct count {
  824. /// static const unsigned value = sizeof...(Types);
  825. /// };
  826. /// \endcode
  827. ///
  828. //
  829. /// \param OpLoc The location of the "sizeof" keyword.
  830. /// \param Name The name of the parameter pack whose size will be determined.
  831. /// \param NameLoc The source location of the name of the parameter pack.
  832. /// \param RParenLoc The location of the closing parentheses.
  833. ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
  834. SourceLocation OpLoc,
  835. IdentifierInfo &Name,
  836. SourceLocation NameLoc,
  837. SourceLocation RParenLoc) {
  838. // C++0x [expr.sizeof]p5:
  839. // The identifier in a sizeof... expression shall name a parameter pack.
  840. LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
  841. LookupName(R, S);
  842. NamedDecl *ParameterPack = nullptr;
  843. switch (R.getResultKind()) {
  844. case LookupResult::Found:
  845. ParameterPack = R.getFoundDecl();
  846. break;
  847. case LookupResult::NotFound:
  848. case LookupResult::NotFoundInCurrentInstantiation: {
  849. ParameterPackValidatorCCC CCC{};
  850. if (TypoCorrection Corrected =
  851. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  852. CCC, CTK_ErrorRecovery)) {
  853. diagnoseTypo(Corrected,
  854. PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
  855. PDiag(diag::note_parameter_pack_here));
  856. ParameterPack = Corrected.getCorrectionDecl();
  857. }
  858. break;
  859. }
  860. case LookupResult::FoundOverloaded:
  861. case LookupResult::FoundUnresolvedValue:
  862. break;
  863. case LookupResult::Ambiguous:
  864. DiagnoseAmbiguousLookup(R);
  865. return ExprError();
  866. }
  867. if (!ParameterPack || !ParameterPack->isParameterPack()) {
  868. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
  869. << &Name;
  870. return ExprError();
  871. }
  872. MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
  873. return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
  874. RParenLoc);
  875. }
  876. TemplateArgumentLoc
  877. Sema::getTemplateArgumentPackExpansionPattern(
  878. TemplateArgumentLoc OrigLoc,
  879. SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
  880. const TemplateArgument &Argument = OrigLoc.getArgument();
  881. assert(Argument.isPackExpansion());
  882. switch (Argument.getKind()) {
  883. case TemplateArgument::Type: {
  884. // FIXME: We shouldn't ever have to worry about missing
  885. // type-source info!
  886. TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
  887. if (!ExpansionTSInfo)
  888. ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
  889. Ellipsis);
  890. PackExpansionTypeLoc Expansion =
  891. ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
  892. Ellipsis = Expansion.getEllipsisLoc();
  893. TypeLoc Pattern = Expansion.getPatternLoc();
  894. NumExpansions = Expansion.getTypePtr()->getNumExpansions();
  895. // We need to copy the TypeLoc because TemplateArgumentLocs store a
  896. // TypeSourceInfo.
  897. // FIXME: Find some way to avoid the copy?
  898. TypeLocBuilder TLB;
  899. TLB.pushFullCopy(Pattern);
  900. TypeSourceInfo *PatternTSInfo =
  901. TLB.getTypeSourceInfo(Context, Pattern.getType());
  902. return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
  903. PatternTSInfo);
  904. }
  905. case TemplateArgument::Expression: {
  906. PackExpansionExpr *Expansion
  907. = cast<PackExpansionExpr>(Argument.getAsExpr());
  908. Expr *Pattern = Expansion->getPattern();
  909. Ellipsis = Expansion->getEllipsisLoc();
  910. NumExpansions = Expansion->getNumExpansions();
  911. return TemplateArgumentLoc(Pattern, Pattern);
  912. }
  913. case TemplateArgument::TemplateExpansion:
  914. Ellipsis = OrigLoc.getTemplateEllipsisLoc();
  915. NumExpansions = Argument.getNumTemplateExpansions();
  916. return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
  917. OrigLoc.getTemplateQualifierLoc(),
  918. OrigLoc.getTemplateNameLoc());
  919. case TemplateArgument::Declaration:
  920. case TemplateArgument::NullPtr:
  921. case TemplateArgument::Template:
  922. case TemplateArgument::Integral:
  923. case TemplateArgument::Pack:
  924. case TemplateArgument::Null:
  925. return TemplateArgumentLoc();
  926. }
  927. llvm_unreachable("Invalid TemplateArgument Kind!");
  928. }
  929. Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
  930. assert(Arg.containsUnexpandedParameterPack());
  931. // If this is a substituted pack, grab that pack. If not, we don't know
  932. // the size yet.
  933. // FIXME: We could find a size in more cases by looking for a substituted
  934. // pack anywhere within this argument, but that's not necessary in the common
  935. // case for 'sizeof...(A)' handling.
  936. TemplateArgument Pack;
  937. switch (Arg.getKind()) {
  938. case TemplateArgument::Type:
  939. if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
  940. Pack = Subst->getArgumentPack();
  941. else
  942. return None;
  943. break;
  944. case TemplateArgument::Expression:
  945. if (auto *Subst =
  946. dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
  947. Pack = Subst->getArgumentPack();
  948. else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
  949. for (VarDecl *PD : *Subst)
  950. if (PD->isParameterPack())
  951. return None;
  952. return Subst->getNumExpansions();
  953. } else
  954. return None;
  955. break;
  956. case TemplateArgument::Template:
  957. if (SubstTemplateTemplateParmPackStorage *Subst =
  958. Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
  959. Pack = Subst->getArgumentPack();
  960. else
  961. return None;
  962. break;
  963. case TemplateArgument::Declaration:
  964. case TemplateArgument::NullPtr:
  965. case TemplateArgument::TemplateExpansion:
  966. case TemplateArgument::Integral:
  967. case TemplateArgument::Pack:
  968. case TemplateArgument::Null:
  969. return None;
  970. }
  971. // Check that no argument in the pack is itself a pack expansion.
  972. for (TemplateArgument Elem : Pack.pack_elements()) {
  973. // There's no point recursing in this case; we would have already
  974. // expanded this pack expansion into the enclosing pack if we could.
  975. if (Elem.isPackExpansion())
  976. return None;
  977. }
  978. return Pack.pack_size();
  979. }
  980. static void CheckFoldOperand(Sema &S, Expr *E) {
  981. if (!E)
  982. return;
  983. E = E->IgnoreImpCasts();
  984. auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
  985. if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
  986. isa<AbstractConditionalOperator>(E)) {
  987. S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
  988. << E->getSourceRange()
  989. << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
  990. << FixItHint::CreateInsertion(E->getEndLoc(), ")");
  991. }
  992. }
  993. ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  994. tok::TokenKind Operator,
  995. SourceLocation EllipsisLoc, Expr *RHS,
  996. SourceLocation RParenLoc) {
  997. // LHS and RHS must be cast-expressions. We allow an arbitrary expression
  998. // in the parser and reduce down to just cast-expressions here.
  999. CheckFoldOperand(*this, LHS);
  1000. CheckFoldOperand(*this, RHS);
  1001. auto DiscardOperands = [&] {
  1002. CorrectDelayedTyposInExpr(LHS);
  1003. CorrectDelayedTyposInExpr(RHS);
  1004. };
  1005. // [expr.prim.fold]p3:
  1006. // In a binary fold, op1 and op2 shall be the same fold-operator, and
  1007. // either e1 shall contain an unexpanded parameter pack or e2 shall contain
  1008. // an unexpanded parameter pack, but not both.
  1009. if (LHS && RHS &&
  1010. LHS->containsUnexpandedParameterPack() ==
  1011. RHS->containsUnexpandedParameterPack()) {
  1012. DiscardOperands();
  1013. return Diag(EllipsisLoc,
  1014. LHS->containsUnexpandedParameterPack()
  1015. ? diag::err_fold_expression_packs_both_sides
  1016. : diag::err_pack_expansion_without_parameter_packs)
  1017. << LHS->getSourceRange() << RHS->getSourceRange();
  1018. }
  1019. // [expr.prim.fold]p2:
  1020. // In a unary fold, the cast-expression shall contain an unexpanded
  1021. // parameter pack.
  1022. if (!LHS || !RHS) {
  1023. Expr *Pack = LHS ? LHS : RHS;
  1024. assert(Pack && "fold expression with neither LHS nor RHS");
  1025. DiscardOperands();
  1026. if (!Pack->containsUnexpandedParameterPack())
  1027. return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1028. << Pack->getSourceRange();
  1029. }
  1030. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
  1031. return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
  1032. None);
  1033. }
  1034. ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  1035. BinaryOperatorKind Operator,
  1036. SourceLocation EllipsisLoc, Expr *RHS,
  1037. SourceLocation RParenLoc,
  1038. Optional<unsigned> NumExpansions) {
  1039. return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
  1040. Operator, EllipsisLoc, RHS, RParenLoc,
  1041. NumExpansions);
  1042. }
  1043. ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
  1044. BinaryOperatorKind Operator) {
  1045. // [temp.variadic]p9:
  1046. // If N is zero for a unary fold-expression, the value of the expression is
  1047. // && -> true
  1048. // || -> false
  1049. // , -> void()
  1050. // if the operator is not listed [above], the instantiation is ill-formed.
  1051. //
  1052. // Note that we need to use something like int() here, not merely 0, to
  1053. // prevent the result from being a null pointer constant.
  1054. QualType ScalarType;
  1055. switch (Operator) {
  1056. case BO_LOr:
  1057. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
  1058. case BO_LAnd:
  1059. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
  1060. case BO_Comma:
  1061. ScalarType = Context.VoidTy;
  1062. break;
  1063. default:
  1064. return Diag(EllipsisLoc, diag::err_fold_expression_empty)
  1065. << BinaryOperator::getOpcodeStr(Operator);
  1066. }
  1067. return new (Context) CXXScalarValueInitExpr(
  1068. ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
  1069. EllipsisLoc);
  1070. }