SemaTemplateVariadic.cpp 39 KB

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