SemaTemplateVariadic.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. if (getLangOpts().HLSL) {
  456. Diag(EllipsisLoc, diag::err_hlsl_variadic_templates);
  457. return true;
  458. }
  459. for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
  460. end = Unexpanded.end();
  461. i != end; ++i) {
  462. // Compute the depth and index for this parameter pack.
  463. unsigned Depth = 0, Index = 0;
  464. IdentifierInfo *Name;
  465. bool IsFunctionParameterPack = false;
  466. if (const TemplateTypeParmType *TTP
  467. = i->first.dyn_cast<const TemplateTypeParmType *>()) {
  468. Depth = TTP->getDepth();
  469. Index = TTP->getIndex();
  470. Name = TTP->getIdentifier();
  471. } else {
  472. NamedDecl *ND = i->first.get<NamedDecl *>();
  473. if (isa<ParmVarDecl>(ND))
  474. IsFunctionParameterPack = true;
  475. else
  476. std::tie(Depth, Index) = getDepthAndIndex(ND);
  477. Name = ND->getIdentifier();
  478. }
  479. // Determine the size of this argument pack.
  480. unsigned NewPackSize;
  481. if (IsFunctionParameterPack) {
  482. // Figure out whether we're instantiating to an argument pack or not.
  483. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  484. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  485. = CurrentInstantiationScope->findInstantiationOf(
  486. i->first.get<NamedDecl *>());
  487. if (Instantiation->is<DeclArgumentPack *>()) {
  488. // We could expand this function parameter pack.
  489. NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
  490. } else {
  491. // We can't expand this function parameter pack, so we can't expand
  492. // the pack expansion.
  493. ShouldExpand = false;
  494. continue;
  495. }
  496. } else {
  497. // If we don't have a template argument at this depth/index, then we
  498. // cannot expand the pack expansion. Make a note of this, but we still
  499. // want to check any parameter packs we *do* have arguments for.
  500. if (Depth >= TemplateArgs.getNumLevels() ||
  501. !TemplateArgs.hasTemplateArgument(Depth, Index)) {
  502. ShouldExpand = false;
  503. continue;
  504. }
  505. // Determine the size of the argument pack.
  506. NewPackSize = TemplateArgs(Depth, Index).pack_size();
  507. }
  508. // C++0x [temp.arg.explicit]p9:
  509. // Template argument deduction can extend the sequence of template
  510. // arguments corresponding to a template parameter pack, even when the
  511. // sequence contains explicitly specified template arguments.
  512. if (!IsFunctionParameterPack) {
  513. if (NamedDecl *PartialPack
  514. = CurrentInstantiationScope->getPartiallySubstitutedPack()){
  515. unsigned PartialDepth, PartialIndex;
  516. std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
  517. if (PartialDepth == Depth && PartialIndex == Index)
  518. RetainExpansion = true;
  519. }
  520. }
  521. if (!NumExpansions) {
  522. // The is the first pack we've seen for which we have an argument.
  523. // Record it.
  524. NumExpansions = NewPackSize;
  525. FirstPack.first = Name;
  526. FirstPack.second = i->second;
  527. HaveFirstPack = true;
  528. continue;
  529. }
  530. if (NewPackSize != *NumExpansions) {
  531. // C++0x [temp.variadic]p5:
  532. // All of the parameter packs expanded by a pack expansion shall have
  533. // the same number of arguments specified.
  534. if (HaveFirstPack)
  535. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
  536. << FirstPack.first << Name << *NumExpansions << NewPackSize
  537. << SourceRange(FirstPack.second) << SourceRange(i->second);
  538. else
  539. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
  540. << Name << *NumExpansions << NewPackSize
  541. << SourceRange(i->second);
  542. return true;
  543. }
  544. }
  545. return false;
  546. }
  547. Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
  548. const MultiLevelTemplateArgumentList &TemplateArgs) {
  549. QualType Pattern = cast<PackExpansionType>(T)->getPattern();
  550. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  551. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
  552. Optional<unsigned> Result;
  553. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  554. // Compute the depth and index for this parameter pack.
  555. unsigned Depth;
  556. unsigned Index;
  557. if (const TemplateTypeParmType *TTP
  558. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
  559. Depth = TTP->getDepth();
  560. Index = TTP->getIndex();
  561. } else {
  562. NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
  563. if (isa<ParmVarDecl>(ND)) {
  564. // Function parameter pack.
  565. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  566. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
  567. = CurrentInstantiationScope->findInstantiationOf(
  568. Unexpanded[I].first.get<NamedDecl *>());
  569. if (Instantiation->is<Decl*>())
  570. // The pattern refers to an unexpanded pack. We're not ready to expand
  571. // this pack yet.
  572. return None;
  573. unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
  574. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  575. Result = Size;
  576. continue;
  577. }
  578. std::tie(Depth, Index) = getDepthAndIndex(ND);
  579. }
  580. if (Depth >= TemplateArgs.getNumLevels() ||
  581. !TemplateArgs.hasTemplateArgument(Depth, Index))
  582. // The pattern refers to an unknown template argument. We're not ready to
  583. // expand this pack yet.
  584. return None;
  585. // Determine the size of the argument pack.
  586. unsigned Size = TemplateArgs(Depth, Index).pack_size();
  587. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  588. Result = Size;
  589. }
  590. return Result;
  591. }
  592. bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
  593. const DeclSpec &DS = D.getDeclSpec();
  594. switch (DS.getTypeSpecType()) {
  595. case TST_typename:
  596. case TST_typeofType:
  597. case TST_underlyingType:
  598. case TST_atomic: {
  599. QualType T = DS.getRepAsType().get();
  600. if (!T.isNull() && T->containsUnexpandedParameterPack())
  601. return true;
  602. break;
  603. }
  604. case TST_typeofExpr:
  605. case TST_decltype:
  606. if (DS.getRepAsExpr() &&
  607. DS.getRepAsExpr()->containsUnexpandedParameterPack())
  608. return true;
  609. break;
  610. case TST_unspecified:
  611. case TST_void:
  612. case TST_char:
  613. case TST_wchar:
  614. case TST_char16:
  615. case TST_char32:
  616. case TST_int:
  617. case TST_int128:
  618. case TST_half:
  619. case TST_halffloat: // HLSL Change
  620. case TST_float:
  621. case TST_double:
  622. case TST_bool:
  623. case TST_decimal32:
  624. case TST_decimal64:
  625. case TST_decimal128:
  626. case TST_enum:
  627. case TST_union:
  628. case TST_struct:
  629. case TST_interface:
  630. case TST_class:
  631. case TST_auto:
  632. case TST_decltype_auto:
  633. case TST_unknown_anytype:
  634. case TST_error:
  635. // HLSL Change Start
  636. case TST_min16float:
  637. case TST_min16int:
  638. case TST_min16uint:
  639. case TST_min10float:
  640. case TST_min12int:
  641. case TST_int8_4packed:
  642. case TST_uint8_4packed:
  643. // HLSL Change End
  644. break;
  645. }
  646. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  647. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  648. switch (Chunk.Kind) {
  649. case DeclaratorChunk::Pointer:
  650. case DeclaratorChunk::Reference:
  651. case DeclaratorChunk::Paren:
  652. case DeclaratorChunk::BlockPointer:
  653. // These declarator chunks cannot contain any parameter packs.
  654. break;
  655. case DeclaratorChunk::Array:
  656. if (Chunk.Arr.NumElts &&
  657. Chunk.Arr.NumElts->containsUnexpandedParameterPack())
  658. return true;
  659. break;
  660. case DeclaratorChunk::Function:
  661. for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
  662. ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
  663. QualType ParamTy = Param->getType();
  664. assert(!ParamTy.isNull() && "Couldn't parse type?");
  665. if (ParamTy->containsUnexpandedParameterPack()) return true;
  666. }
  667. if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
  668. for (unsigned i = 0; i != Chunk.Fun.NumExceptions; ++i) {
  669. if (Chunk.Fun.Exceptions[i]
  670. .Ty.get()
  671. ->containsUnexpandedParameterPack())
  672. return true;
  673. }
  674. } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
  675. Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
  676. return true;
  677. if (Chunk.Fun.hasTrailingReturnType()) {
  678. QualType T = Chunk.Fun.getTrailingReturnType().get();
  679. if (!T.isNull() && T->containsUnexpandedParameterPack())
  680. return true;
  681. }
  682. break;
  683. case DeclaratorChunk::MemberPointer:
  684. if (Chunk.Mem.Scope().getScopeRep() &&
  685. Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
  686. return true;
  687. break;
  688. }
  689. }
  690. return false;
  691. }
  692. namespace {
  693. // Callback to only accept typo corrections that refer to parameter packs.
  694. class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
  695. public:
  696. bool ValidateCandidate(const TypoCorrection &candidate) override {
  697. NamedDecl *ND = candidate.getCorrectionDecl();
  698. return ND && ND->isParameterPack();
  699. }
  700. };
  701. }
  702. /// \brief Called when an expression computing the size of a parameter pack
  703. /// is parsed.
  704. ///
  705. /// \code
  706. /// template<typename ...Types> struct count {
  707. /// static const unsigned value = sizeof...(Types);
  708. /// };
  709. /// \endcode
  710. ///
  711. //
  712. /// \param OpLoc The location of the "sizeof" keyword.
  713. /// \param Name The name of the parameter pack whose size will be determined.
  714. /// \param NameLoc The source location of the name of the parameter pack.
  715. /// \param RParenLoc The location of the closing parentheses.
  716. ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
  717. SourceLocation OpLoc,
  718. IdentifierInfo &Name,
  719. SourceLocation NameLoc,
  720. SourceLocation RParenLoc) {
  721. // C++0x [expr.sizeof]p5:
  722. // The identifier in a sizeof... expression shall name a parameter pack.
  723. LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
  724. LookupName(R, S);
  725. NamedDecl *ParameterPack = nullptr;
  726. switch (R.getResultKind()) {
  727. case LookupResult::Found:
  728. ParameterPack = R.getFoundDecl();
  729. break;
  730. case LookupResult::NotFound:
  731. case LookupResult::NotFoundInCurrentInstantiation:
  732. if (TypoCorrection Corrected =
  733. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  734. llvm::make_unique<ParameterPackValidatorCCC>(),
  735. CTK_ErrorRecovery)) {
  736. diagnoseTypo(Corrected,
  737. PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
  738. PDiag(diag::note_parameter_pack_here));
  739. ParameterPack = Corrected.getCorrectionDecl();
  740. }
  741. case LookupResult::FoundOverloaded:
  742. case LookupResult::FoundUnresolvedValue:
  743. break;
  744. case LookupResult::Ambiguous:
  745. DiagnoseAmbiguousLookup(R);
  746. return ExprError();
  747. }
  748. if (!ParameterPack || !ParameterPack->isParameterPack()) {
  749. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
  750. << &Name;
  751. return ExprError();
  752. }
  753. MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
  754. return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc,
  755. ParameterPack, NameLoc, RParenLoc);
  756. }
  757. TemplateArgumentLoc
  758. Sema::getTemplateArgumentPackExpansionPattern(
  759. TemplateArgumentLoc OrigLoc,
  760. SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
  761. const TemplateArgument &Argument = OrigLoc.getArgument();
  762. assert(Argument.isPackExpansion());
  763. switch (Argument.getKind()) {
  764. case TemplateArgument::Type: {
  765. // FIXME: We shouldn't ever have to worry about missing
  766. // type-source info!
  767. TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
  768. if (!ExpansionTSInfo)
  769. ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
  770. Ellipsis);
  771. PackExpansionTypeLoc Expansion =
  772. ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
  773. Ellipsis = Expansion.getEllipsisLoc();
  774. TypeLoc Pattern = Expansion.getPatternLoc();
  775. NumExpansions = Expansion.getTypePtr()->getNumExpansions();
  776. // We need to copy the TypeLoc because TemplateArgumentLocs store a
  777. // TypeSourceInfo.
  778. // FIXME: Find some way to avoid the copy?
  779. TypeLocBuilder TLB;
  780. TLB.pushFullCopy(Pattern);
  781. TypeSourceInfo *PatternTSInfo =
  782. TLB.getTypeSourceInfo(Context, Pattern.getType());
  783. return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
  784. PatternTSInfo);
  785. }
  786. case TemplateArgument::Expression: {
  787. PackExpansionExpr *Expansion
  788. = cast<PackExpansionExpr>(Argument.getAsExpr());
  789. Expr *Pattern = Expansion->getPattern();
  790. Ellipsis = Expansion->getEllipsisLoc();
  791. NumExpansions = Expansion->getNumExpansions();
  792. return TemplateArgumentLoc(Pattern, Pattern);
  793. }
  794. case TemplateArgument::TemplateExpansion:
  795. Ellipsis = OrigLoc.getTemplateEllipsisLoc();
  796. NumExpansions = Argument.getNumTemplateExpansions();
  797. return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
  798. OrigLoc.getTemplateQualifierLoc(),
  799. OrigLoc.getTemplateNameLoc());
  800. case TemplateArgument::Declaration:
  801. case TemplateArgument::NullPtr:
  802. case TemplateArgument::Template:
  803. case TemplateArgument::Integral:
  804. case TemplateArgument::Pack:
  805. case TemplateArgument::Null:
  806. return TemplateArgumentLoc();
  807. }
  808. llvm_unreachable("Invalid TemplateArgument Kind!");
  809. }
  810. static void CheckFoldOperand(Sema &S, Expr *E) {
  811. if (!E)
  812. return;
  813. E = E->IgnoreImpCasts();
  814. if (isa<BinaryOperator>(E) || isa<AbstractConditionalOperator>(E)) {
  815. S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
  816. << E->getSourceRange()
  817. << FixItHint::CreateInsertion(E->getLocStart(), "(")
  818. << FixItHint::CreateInsertion(E->getLocEnd(), ")");
  819. }
  820. }
  821. ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  822. tok::TokenKind Operator,
  823. SourceLocation EllipsisLoc, Expr *RHS,
  824. SourceLocation RParenLoc) {
  825. // LHS and RHS must be cast-expressions. We allow an arbitrary expression
  826. // in the parser and reduce down to just cast-expressions here.
  827. CheckFoldOperand(*this, LHS);
  828. CheckFoldOperand(*this, RHS);
  829. // [expr.prim.fold]p3:
  830. // In a binary fold, op1 and op2 shall be the same fold-operator, and
  831. // either e1 shall contain an unexpanded parameter pack or e2 shall contain
  832. // an unexpanded parameter pack, but not both.
  833. if (LHS && RHS &&
  834. LHS->containsUnexpandedParameterPack() ==
  835. RHS->containsUnexpandedParameterPack()) {
  836. return Diag(EllipsisLoc,
  837. LHS->containsUnexpandedParameterPack()
  838. ? diag::err_fold_expression_packs_both_sides
  839. : diag::err_pack_expansion_without_parameter_packs)
  840. << LHS->getSourceRange() << RHS->getSourceRange();
  841. }
  842. // [expr.prim.fold]p2:
  843. // In a unary fold, the cast-expression shall contain an unexpanded
  844. // parameter pack.
  845. if (!LHS || !RHS) {
  846. Expr *Pack = LHS ? LHS : RHS;
  847. assert(Pack && "fold expression with neither LHS nor RHS");
  848. if (!Pack->containsUnexpandedParameterPack())
  849. return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  850. << Pack->getSourceRange();
  851. }
  852. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
  853. return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
  854. }
  855. ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
  856. BinaryOperatorKind Operator,
  857. SourceLocation EllipsisLoc, Expr *RHS,
  858. SourceLocation RParenLoc) {
  859. return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
  860. Operator, EllipsisLoc, RHS, RParenLoc);
  861. }
  862. ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
  863. BinaryOperatorKind Operator) {
  864. // [temp.variadic]p9:
  865. // If N is zero for a unary fold-expression, the value of the expression is
  866. // * -> 1
  867. // + -> int()
  868. // & -> -1
  869. // | -> int()
  870. // && -> true
  871. // || -> false
  872. // , -> void()
  873. // if the operator is not listed [above], the instantiation is ill-formed.
  874. //
  875. // Note that we need to use something like int() here, not merely 0, to
  876. // prevent the result from being a null pointer constant.
  877. QualType ScalarType;
  878. switch (Operator) {
  879. case BO_Add:
  880. ScalarType = Context.IntTy;
  881. break;
  882. case BO_Mul:
  883. return ActOnIntegerConstant(EllipsisLoc, 1);
  884. case BO_Or:
  885. ScalarType = Context.IntTy;
  886. break;
  887. case BO_And:
  888. return CreateBuiltinUnaryOp(EllipsisLoc, UO_Minus,
  889. ActOnIntegerConstant(EllipsisLoc, 1).get());
  890. case BO_LOr:
  891. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
  892. case BO_LAnd:
  893. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
  894. case BO_Comma:
  895. ScalarType = Context.VoidTy;
  896. break;
  897. default:
  898. return Diag(EllipsisLoc, diag::err_fold_expression_empty)
  899. << BinaryOperator::getOpcodeStr(Operator);
  900. }
  901. return new (Context) CXXScalarValueInitExpr(
  902. ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
  903. EllipsisLoc);
  904. }