SemaTemplateVariadic.cpp 42 KB

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