SemaTemplateVariadic.cpp 37 KB

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