clang API Documentation

SemaTemplateVariadic.cpp
Go to the documentation of this file.
00001 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file implements semantic analysis for C++0x variadic templates.
00010 //===----------------------------------------------------------------------===/
00011 
00012 #include "clang/Sema/Sema.h"
00013 #include "TypeLocBuilder.h"
00014 #include "clang/AST/Expr.h"
00015 #include "clang/AST/RecursiveASTVisitor.h"
00016 #include "clang/AST/TypeLoc.h"
00017 #include "clang/Sema/Lookup.h"
00018 #include "clang/Sema/ParsedTemplate.h"
00019 #include "clang/Sema/ScopeInfo.h"
00020 #include "clang/Sema/SemaInternal.h"
00021 #include "clang/Sema/Template.h"
00022 
00023 using namespace clang;
00024 
00025 //----------------------------------------------------------------------------
00026 // Visitor that collects unexpanded parameter packs
00027 //----------------------------------------------------------------------------
00028 
00029 namespace {
00030   /// \brief A class that collects unexpanded parameter packs.
00031   class CollectUnexpandedParameterPacksVisitor :
00032     public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> 
00033   {
00034     typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
00035       inherited;
00036 
00037     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
00038 
00039     bool InLambda;
00040 
00041   public:
00042     explicit CollectUnexpandedParameterPacksVisitor(
00043                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
00044       : Unexpanded(Unexpanded), InLambda(false) { }
00045 
00046     bool shouldWalkTypesOfTypeLocs() const { return false; }
00047     
00048     //------------------------------------------------------------------------
00049     // Recording occurrences of (unexpanded) parameter packs.
00050     //------------------------------------------------------------------------
00051 
00052     /// \brief Record occurrences of template type parameter packs.
00053     bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
00054       if (TL.getTypePtr()->isParameterPack())
00055         Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
00056       return true;
00057     }
00058 
00059     /// \brief Record occurrences of template type parameter packs
00060     /// when we don't have proper source-location information for
00061     /// them.
00062     ///
00063     /// Ideally, this routine would never be used.
00064     bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
00065       if (T->isParameterPack())
00066         Unexpanded.push_back(std::make_pair(T, SourceLocation()));
00067 
00068       return true;
00069     }
00070 
00071     /// \brief Record occurrences of function and non-type template
00072     /// parameter packs in an expression.
00073     bool VisitDeclRefExpr(DeclRefExpr *E) {
00074       if (E->getDecl()->isParameterPack())
00075         Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
00076       
00077       return true;
00078     }
00079     
00080     /// \brief Record occurrences of template template parameter packs.
00081     bool TraverseTemplateName(TemplateName Template) {
00082       if (TemplateTemplateParmDecl *TTP 
00083             = dyn_cast_or_null<TemplateTemplateParmDecl>(
00084                                                   Template.getAsTemplateDecl()))
00085         if (TTP->isParameterPack())
00086           Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
00087       
00088       return inherited::TraverseTemplateName(Template);
00089     }
00090 
00091     /// \brief Suppress traversal into Objective-C container literal
00092     /// elements that are pack expansions.
00093     bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
00094       if (!E->containsUnexpandedParameterPack())
00095         return true;
00096 
00097       for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
00098         ObjCDictionaryElement Element = E->getKeyValueElement(I);
00099         if (Element.isPackExpansion())
00100           continue;
00101 
00102         TraverseStmt(Element.Key);
00103         TraverseStmt(Element.Value);
00104       }
00105       return true;
00106     }
00107     //------------------------------------------------------------------------
00108     // Pruning the search for unexpanded parameter packs.
00109     //------------------------------------------------------------------------
00110 
00111     /// \brief Suppress traversal into statements and expressions that
00112     /// do not contain unexpanded parameter packs.
00113     bool TraverseStmt(Stmt *S) { 
00114       Expr *E = dyn_cast_or_null<Expr>(S);
00115       if ((E && E->containsUnexpandedParameterPack()) || InLambda)
00116         return inherited::TraverseStmt(S);
00117 
00118       return true;
00119     }
00120 
00121     /// \brief Suppress traversal into types that do not contain
00122     /// unexpanded parameter packs.
00123     bool TraverseType(QualType T) {
00124       if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
00125         return inherited::TraverseType(T);
00126 
00127       return true;
00128     }
00129 
00130     /// \brief Suppress traversel into types with location information
00131     /// that do not contain unexpanded parameter packs.
00132     bool TraverseTypeLoc(TypeLoc TL) {
00133       if ((!TL.getType().isNull() && 
00134            TL.getType()->containsUnexpandedParameterPack()) ||
00135           InLambda)
00136         return inherited::TraverseTypeLoc(TL);
00137 
00138       return true;
00139     }
00140 
00141     /// \brief Suppress traversal of non-parameter declarations, since
00142     /// they cannot contain unexpanded parameter packs.
00143     bool TraverseDecl(Decl *D) { 
00144       if ((D && isa<ParmVarDecl>(D)) || InLambda)
00145         return inherited::TraverseDecl(D);
00146 
00147       return true;
00148     }
00149 
00150     /// \brief Suppress traversal of template argument pack expansions.
00151     bool TraverseTemplateArgument(const TemplateArgument &Arg) {
00152       if (Arg.isPackExpansion())
00153         return true;
00154 
00155       return inherited::TraverseTemplateArgument(Arg);
00156     }
00157 
00158     /// \brief Suppress traversal of template argument pack expansions.
00159     bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
00160       if (ArgLoc.getArgument().isPackExpansion())
00161         return true;
00162       
00163       return inherited::TraverseTemplateArgumentLoc(ArgLoc);
00164     }
00165 
00166     /// \brief Note whether we're traversing a lambda containing an unexpanded
00167     /// parameter pack. In this case, the unexpanded pack can occur anywhere,
00168     /// including all the places where we normally wouldn't look. Within a
00169     /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
00170     /// outside an expression.
00171     bool TraverseLambdaExpr(LambdaExpr *Lambda) {
00172       // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
00173       // even if it's contained within another lambda.
00174       if (!Lambda->containsUnexpandedParameterPack())
00175         return true;
00176 
00177       bool WasInLambda = InLambda;
00178       InLambda = true;
00179 
00180       // If any capture names a function parameter pack, that pack is expanded
00181       // when the lambda is expanded.
00182       for (LambdaExpr::capture_iterator I = Lambda->capture_begin(),
00183                                         E = Lambda->capture_end();
00184            I != E; ++I) {
00185         if (I->capturesVariable()) {
00186           VarDecl *VD = I->getCapturedVar();
00187           if (VD->isParameterPack())
00188             Unexpanded.push_back(std::make_pair(VD, I->getLocation()));
00189         }
00190       }
00191 
00192       inherited::TraverseLambdaExpr(Lambda);
00193 
00194       InLambda = WasInLambda;
00195       return true;
00196     }
00197   };
00198 }
00199 
00200 /// \brief Determine whether it's possible for an unexpanded parameter pack to
00201 /// be valid in this location. This only happens when we're in a declaration
00202 /// that is nested within an expression that could be expanded, such as a
00203 /// lambda-expression within a function call.
00204 ///
00205 /// This is conservatively correct, but may claim that some unexpanded packs are
00206 /// permitted when they are not.
00207 bool Sema::isUnexpandedParameterPackPermitted() {
00208   for (auto *SI : FunctionScopes)
00209     if (isa<sema::LambdaScopeInfo>(SI))
00210       return true;
00211   return false;
00212 }
00213 
00214 /// \brief Diagnose all of the unexpanded parameter packs in the given
00215 /// vector.
00216 bool
00217 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
00218                                        UnexpandedParameterPackContext UPPC,
00219                                  ArrayRef<UnexpandedParameterPack> Unexpanded) {
00220   if (Unexpanded.empty())
00221     return false;
00222 
00223   // If we are within a lambda expression, that lambda contains an unexpanded
00224   // parameter pack, and we are done.
00225   // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
00226   // later.
00227   for (unsigned N = FunctionScopes.size(); N; --N) {
00228     if (sema::LambdaScopeInfo *LSI =
00229           dyn_cast<sema::LambdaScopeInfo>(FunctionScopes[N-1])) {
00230       LSI->ContainsUnexpandedParameterPack = true;
00231       return false;
00232     }
00233   }
00234   
00235   SmallVector<SourceLocation, 4> Locations;
00236   SmallVector<IdentifierInfo *, 4> Names;
00237   llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
00238 
00239   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
00240     IdentifierInfo *Name = nullptr;
00241     if (const TemplateTypeParmType *TTP
00242           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
00243       Name = TTP->getIdentifier();
00244     else
00245       Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
00246 
00247     if (Name && NamesKnown.insert(Name))
00248       Names.push_back(Name);
00249 
00250     if (Unexpanded[I].second.isValid())
00251       Locations.push_back(Unexpanded[I].second);
00252   }
00253 
00254   DiagnosticBuilder DB
00255     = Names.size() == 0? Diag(Loc, diag::err_unexpanded_parameter_pack_0)
00256                            << (int)UPPC
00257     : Names.size() == 1? Diag(Loc, diag::err_unexpanded_parameter_pack_1)
00258                            << (int)UPPC << Names[0]
00259     : Names.size() == 2? Diag(Loc, diag::err_unexpanded_parameter_pack_2)
00260                            << (int)UPPC << Names[0] << Names[1]
00261     : Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
00262         << (int)UPPC << Names[0] << Names[1];
00263 
00264   for (unsigned I = 0, N = Locations.size(); I != N; ++I)
00265     DB << SourceRange(Locations[I]);
00266   return true;
00267 }
00268 
00269 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, 
00270                                            TypeSourceInfo *T,
00271                                          UnexpandedParameterPackContext UPPC) {
00272   // C++0x [temp.variadic]p5:
00273   //   An appearance of a name of a parameter pack that is not expanded is 
00274   //   ill-formed.
00275   if (!T->getType()->containsUnexpandedParameterPack())
00276     return false;
00277 
00278   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00279   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
00280                                                               T->getTypeLoc());
00281   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00282   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
00283 }
00284 
00285 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
00286                                         UnexpandedParameterPackContext UPPC) {
00287   // C++0x [temp.variadic]p5:
00288   //   An appearance of a name of a parameter pack that is not expanded is 
00289   //   ill-formed.
00290   if (!E->containsUnexpandedParameterPack())
00291     return false;
00292 
00293   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00294   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
00295   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00296   return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
00297 }
00298 
00299 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
00300                                         UnexpandedParameterPackContext UPPC) {
00301   // C++0x [temp.variadic]p5:
00302   //   An appearance of a name of a parameter pack that is not expanded is 
00303   //   ill-formed.
00304   if (!SS.getScopeRep() || 
00305       !SS.getScopeRep()->containsUnexpandedParameterPack())
00306     return false;
00307 
00308   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00309   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00310     .TraverseNestedNameSpecifier(SS.getScopeRep());
00311   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00312   return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
00313                                           UPPC, Unexpanded);
00314 }
00315 
00316 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
00317                                          UnexpandedParameterPackContext UPPC) {
00318   // C++0x [temp.variadic]p5:
00319   //   An appearance of a name of a parameter pack that is not expanded is 
00320   //   ill-formed.
00321   switch (NameInfo.getName().getNameKind()) {
00322   case DeclarationName::Identifier:
00323   case DeclarationName::ObjCZeroArgSelector:
00324   case DeclarationName::ObjCOneArgSelector:
00325   case DeclarationName::ObjCMultiArgSelector:
00326   case DeclarationName::CXXOperatorName:
00327   case DeclarationName::CXXLiteralOperatorName:
00328   case DeclarationName::CXXUsingDirective:
00329     return false;
00330 
00331   case DeclarationName::CXXConstructorName:
00332   case DeclarationName::CXXDestructorName:
00333   case DeclarationName::CXXConversionFunctionName:
00334     // FIXME: We shouldn't need this null check!
00335     if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
00336       return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
00337 
00338     if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
00339       return false;
00340 
00341     break;
00342   }
00343 
00344   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00345   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00346     .TraverseType(NameInfo.getName().getCXXNameType());
00347   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00348   return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
00349 }
00350 
00351 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
00352                                            TemplateName Template,
00353                                        UnexpandedParameterPackContext UPPC) {
00354   
00355   if (Template.isNull() || !Template.containsUnexpandedParameterPack())
00356     return false;
00357 
00358   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00359   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00360     .TraverseTemplateName(Template);
00361   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00362   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
00363 }
00364 
00365 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
00366                                          UnexpandedParameterPackContext UPPC) {
00367   if (Arg.getArgument().isNull() || 
00368       !Arg.getArgument().containsUnexpandedParameterPack())
00369     return false;
00370   
00371   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00372   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00373     .TraverseTemplateArgumentLoc(Arg);
00374   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
00375   return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
00376 }
00377 
00378 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
00379                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00380   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00381     .TraverseTemplateArgument(Arg);
00382 }
00383 
00384 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
00385                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00386   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00387     .TraverseTemplateArgumentLoc(Arg);
00388 }
00389 
00390 void Sema::collectUnexpandedParameterPacks(QualType T,
00391                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00392   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);  
00393 }  
00394 
00395 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
00396                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00397   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);  
00398 }  
00399 
00400 void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
00401                                            SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00402   NestedNameSpecifier *Qualifier = SS.getScopeRep();
00403   if (!Qualifier)
00404     return;
00405   
00406   NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
00407   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00408     .TraverseNestedNameSpecifierLoc(QualifierLoc);
00409 }
00410 
00411 void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
00412                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
00413   CollectUnexpandedParameterPacksVisitor(Unexpanded)
00414     .TraverseDeclarationNameInfo(NameInfo);
00415 }
00416 
00417 
00418 ParsedTemplateArgument 
00419 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
00420                          SourceLocation EllipsisLoc) {
00421   if (Arg.isInvalid())
00422     return Arg;
00423 
00424   switch (Arg.getKind()) {
00425   case ParsedTemplateArgument::Type: {
00426     TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
00427     if (Result.isInvalid())
00428       return ParsedTemplateArgument();
00429 
00430     return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), 
00431                                   Arg.getLocation());
00432   }
00433 
00434   case ParsedTemplateArgument::NonType: {
00435     ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
00436     if (Result.isInvalid())
00437       return ParsedTemplateArgument();
00438     
00439     return ParsedTemplateArgument(Arg.getKind(), Result.get(), 
00440                                   Arg.getLocation());
00441   }
00442     
00443   case ParsedTemplateArgument::Template:
00444     if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
00445       SourceRange R(Arg.getLocation());
00446       if (Arg.getScopeSpec().isValid())
00447         R.setBegin(Arg.getScopeSpec().getBeginLoc());
00448       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00449         << R;
00450       return ParsedTemplateArgument();
00451     }
00452       
00453     return Arg.getTemplatePackExpansion(EllipsisLoc);
00454   }
00455   llvm_unreachable("Unhandled template argument kind?");
00456 }
00457 
00458 TypeResult Sema::ActOnPackExpansion(ParsedType Type, 
00459                                     SourceLocation EllipsisLoc) {
00460   TypeSourceInfo *TSInfo;
00461   GetTypeFromParser(Type, &TSInfo);
00462   if (!TSInfo)
00463     return true;
00464 
00465   TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
00466   if (!TSResult)
00467     return true;
00468   
00469   return CreateParsedType(TSResult->getType(), TSResult);
00470 }
00471 
00472 TypeSourceInfo *
00473 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
00474                          Optional<unsigned> NumExpansions) {
00475   // Create the pack expansion type and source-location information.
00476   QualType Result = CheckPackExpansion(Pattern->getType(), 
00477                                        Pattern->getTypeLoc().getSourceRange(),
00478                                        EllipsisLoc, NumExpansions);
00479   if (Result.isNull())
00480     return nullptr;
00481 
00482   TypeLocBuilder TLB;
00483   TLB.pushFullCopy(Pattern->getTypeLoc());
00484   PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
00485   TL.setEllipsisLoc(EllipsisLoc);
00486 
00487   return TLB.getTypeSourceInfo(Context, Result);
00488 }
00489 
00490 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
00491                                   SourceLocation EllipsisLoc,
00492                                   Optional<unsigned> NumExpansions) {
00493   // C++0x [temp.variadic]p5:
00494   //   The pattern of a pack expansion shall name one or more
00495   //   parameter packs that are not expanded by a nested pack
00496   //   expansion.
00497   if (!Pattern->containsUnexpandedParameterPack()) {
00498     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00499       << PatternRange;
00500     return QualType();
00501   }
00502 
00503   return Context.getPackExpansionType(Pattern, NumExpansions);
00504 }
00505 
00506 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
00507   return CheckPackExpansion(Pattern, EllipsisLoc, None);
00508 }
00509 
00510 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
00511                                     Optional<unsigned> NumExpansions) {
00512   if (!Pattern)
00513     return ExprError();
00514   
00515   // C++0x [temp.variadic]p5:
00516   //   The pattern of a pack expansion shall name one or more
00517   //   parameter packs that are not expanded by a nested pack
00518   //   expansion.
00519   if (!Pattern->containsUnexpandedParameterPack()) {
00520     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00521     << Pattern->getSourceRange();
00522     return ExprError();
00523   }
00524   
00525   // Create the pack expansion expression and source-location information.
00526   return new (Context)
00527     PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
00528 }
00529 
00530 /// \brief Retrieve the depth and index of a parameter pack.
00531 static std::pair<unsigned, unsigned> 
00532 getDepthAndIndex(NamedDecl *ND) {
00533   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
00534     return std::make_pair(TTP->getDepth(), TTP->getIndex());
00535   
00536   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
00537     return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
00538   
00539   TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
00540   return std::make_pair(TTP->getDepth(), TTP->getIndex());
00541 }
00542 
00543 bool Sema::CheckParameterPacksForExpansion(
00544     SourceLocation EllipsisLoc, SourceRange PatternRange,
00545     ArrayRef<UnexpandedParameterPack> Unexpanded,
00546     const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
00547     bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
00548   ShouldExpand = true;
00549   RetainExpansion = false;
00550   std::pair<IdentifierInfo *, SourceLocation> FirstPack;
00551   bool HaveFirstPack = false;
00552   
00553   for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
00554                                                  end = Unexpanded.end();
00555                                                   i != end; ++i) {
00556     // Compute the depth and index for this parameter pack.
00557     unsigned Depth = 0, Index = 0;
00558     IdentifierInfo *Name;
00559     bool IsFunctionParameterPack = false;
00560     
00561     if (const TemplateTypeParmType *TTP
00562         = i->first.dyn_cast<const TemplateTypeParmType *>()) {
00563       Depth = TTP->getDepth();
00564       Index = TTP->getIndex();
00565       Name = TTP->getIdentifier();
00566     } else {
00567       NamedDecl *ND = i->first.get<NamedDecl *>();
00568       if (isa<ParmVarDecl>(ND))
00569         IsFunctionParameterPack = true;
00570       else
00571         std::tie(Depth, Index) = getDepthAndIndex(ND);
00572 
00573       Name = ND->getIdentifier();
00574     }
00575     
00576     // Determine the size of this argument pack.
00577     unsigned NewPackSize;    
00578     if (IsFunctionParameterPack) {
00579       // Figure out whether we're instantiating to an argument pack or not.
00580       typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
00581       
00582       llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
00583         = CurrentInstantiationScope->findInstantiationOf(
00584                                         i->first.get<NamedDecl *>());
00585       if (Instantiation->is<DeclArgumentPack *>()) {
00586         // We could expand this function parameter pack.
00587         NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
00588       } else {
00589         // We can't expand this function parameter pack, so we can't expand
00590         // the pack expansion.
00591         ShouldExpand = false;
00592         continue;
00593       }
00594     } else {
00595       // If we don't have a template argument at this depth/index, then we 
00596       // cannot expand the pack expansion. Make a note of this, but we still 
00597       // want to check any parameter packs we *do* have arguments for.
00598       if (Depth >= TemplateArgs.getNumLevels() ||
00599           !TemplateArgs.hasTemplateArgument(Depth, Index)) {
00600         ShouldExpand = false;
00601         continue;
00602       }
00603       
00604       // Determine the size of the argument pack.
00605       NewPackSize = TemplateArgs(Depth, Index).pack_size();
00606     }
00607     
00608     // C++0x [temp.arg.explicit]p9:
00609     //   Template argument deduction can extend the sequence of template 
00610     //   arguments corresponding to a template parameter pack, even when the
00611     //   sequence contains explicitly specified template arguments.
00612     if (!IsFunctionParameterPack) {
00613       if (NamedDecl *PartialPack 
00614                     = CurrentInstantiationScope->getPartiallySubstitutedPack()){
00615         unsigned PartialDepth, PartialIndex;
00616         std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
00617         if (PartialDepth == Depth && PartialIndex == Index)
00618           RetainExpansion = true;
00619       }
00620     }
00621     
00622     if (!NumExpansions) {
00623       // The is the first pack we've seen for which we have an argument. 
00624       // Record it.
00625       NumExpansions = NewPackSize;
00626       FirstPack.first = Name;
00627       FirstPack.second = i->second;
00628       HaveFirstPack = true;
00629       continue;
00630     }
00631     
00632     if (NewPackSize != *NumExpansions) {
00633       // C++0x [temp.variadic]p5:
00634       //   All of the parameter packs expanded by a pack expansion shall have 
00635       //   the same number of arguments specified.
00636       if (HaveFirstPack)
00637         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
00638           << FirstPack.first << Name << *NumExpansions << NewPackSize
00639           << SourceRange(FirstPack.second) << SourceRange(i->second);
00640       else
00641         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
00642           << Name << *NumExpansions << NewPackSize
00643           << SourceRange(i->second);
00644       return true;
00645     }
00646   }
00647   
00648   return false;
00649 }
00650 
00651 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
00652                           const MultiLevelTemplateArgumentList &TemplateArgs) {
00653   QualType Pattern = cast<PackExpansionType>(T)->getPattern();
00654   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
00655   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
00656 
00657   Optional<unsigned> Result;
00658   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
00659     // Compute the depth and index for this parameter pack.
00660     unsigned Depth;
00661     unsigned Index;
00662     
00663     if (const TemplateTypeParmType *TTP
00664           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
00665       Depth = TTP->getDepth();
00666       Index = TTP->getIndex();
00667     } else {      
00668       NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
00669       if (isa<ParmVarDecl>(ND)) {
00670         // Function parameter pack.
00671         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
00672         
00673         llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
00674           = CurrentInstantiationScope->findInstantiationOf(
00675                                         Unexpanded[I].first.get<NamedDecl *>());
00676         if (Instantiation->is<Decl*>())
00677           // The pattern refers to an unexpanded pack. We're not ready to expand
00678           // this pack yet.
00679           return None;
00680 
00681         unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
00682         assert((!Result || *Result == Size) && "inconsistent pack sizes");
00683         Result = Size;
00684         continue;
00685       }
00686 
00687       std::tie(Depth, Index) = getDepthAndIndex(ND);
00688     }
00689     if (Depth >= TemplateArgs.getNumLevels() ||
00690         !TemplateArgs.hasTemplateArgument(Depth, Index))
00691       // The pattern refers to an unknown template argument. We're not ready to
00692       // expand this pack yet.
00693       return None;
00694     
00695     // Determine the size of the argument pack.
00696     unsigned Size = TemplateArgs(Depth, Index).pack_size();
00697     assert((!Result || *Result == Size) && "inconsistent pack sizes");
00698     Result = Size;
00699   }
00700   
00701   return Result;
00702 }
00703 
00704 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
00705   const DeclSpec &DS = D.getDeclSpec();
00706   switch (DS.getTypeSpecType()) {
00707   case TST_typename:
00708   case TST_typeofType:
00709   case TST_underlyingType:
00710   case TST_atomic: {
00711     QualType T = DS.getRepAsType().get();
00712     if (!T.isNull() && T->containsUnexpandedParameterPack())
00713       return true;
00714     break;
00715   }
00716       
00717   case TST_typeofExpr:
00718   case TST_decltype:
00719     if (DS.getRepAsExpr() && 
00720         DS.getRepAsExpr()->containsUnexpandedParameterPack())
00721       return true;
00722     break;
00723       
00724   case TST_unspecified:
00725   case TST_void:
00726   case TST_char:
00727   case TST_wchar:
00728   case TST_char16:
00729   case TST_char32:
00730   case TST_int:
00731   case TST_int128:
00732   case TST_half:
00733   case TST_float:
00734   case TST_double:
00735   case TST_bool:
00736   case TST_decimal32:
00737   case TST_decimal64:
00738   case TST_decimal128:
00739   case TST_enum:
00740   case TST_union:
00741   case TST_struct:
00742   case TST_interface:
00743   case TST_class:
00744   case TST_auto:
00745   case TST_decltype_auto:
00746   case TST_unknown_anytype:
00747   case TST_error:
00748     break;
00749   }
00750 
00751   for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
00752     const DeclaratorChunk &Chunk = D.getTypeObject(I);
00753     switch (Chunk.Kind) {
00754     case DeclaratorChunk::Pointer:
00755     case DeclaratorChunk::Reference:
00756     case DeclaratorChunk::Paren:
00757     case DeclaratorChunk::BlockPointer:
00758       // These declarator chunks cannot contain any parameter packs.
00759       break;
00760         
00761     case DeclaratorChunk::Array:
00762       if (Chunk.Arr.NumElts &&
00763           Chunk.Arr.NumElts->containsUnexpandedParameterPack())
00764         return true;
00765       break;
00766     case DeclaratorChunk::Function:
00767       for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
00768         ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
00769         QualType ParamTy = Param->getType();
00770         assert(!ParamTy.isNull() && "Couldn't parse type?");
00771         if (ParamTy->containsUnexpandedParameterPack()) return true;
00772       }
00773 
00774       if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
00775         for (unsigned i = 0; i != Chunk.Fun.NumExceptions; ++i) {
00776           if (Chunk.Fun.Exceptions[i]
00777                   .Ty.get()
00778                   ->containsUnexpandedParameterPack())
00779             return true;
00780         }
00781       } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
00782                  Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
00783         return true;
00784 
00785       if (Chunk.Fun.hasTrailingReturnType() &&
00786           Chunk.Fun.getTrailingReturnType()
00787               .get()
00788               ->containsUnexpandedParameterPack())
00789         return true;
00790       break;
00791 
00792     case DeclaratorChunk::MemberPointer:
00793       if (Chunk.Mem.Scope().getScopeRep() &&
00794           Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
00795         return true;
00796       break;
00797     }
00798   }
00799   
00800   return false;
00801 }
00802 
00803 namespace {
00804 
00805 // Callback to only accept typo corrections that refer to parameter packs.
00806 class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
00807  public:
00808   bool ValidateCandidate(const TypoCorrection &candidate) override {
00809     NamedDecl *ND = candidate.getCorrectionDecl();
00810     return ND && ND->isParameterPack();
00811   }
00812 };
00813 
00814 }
00815 
00816 /// \brief Called when an expression computing the size of a parameter pack
00817 /// is parsed.
00818 ///
00819 /// \code
00820 /// template<typename ...Types> struct count {
00821 ///   static const unsigned value = sizeof...(Types);
00822 /// };
00823 /// \endcode
00824 ///
00825 //
00826 /// \param OpLoc The location of the "sizeof" keyword.
00827 /// \param Name The name of the parameter pack whose size will be determined.
00828 /// \param NameLoc The source location of the name of the parameter pack.
00829 /// \param RParenLoc The location of the closing parentheses.
00830 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
00831                                               SourceLocation OpLoc,
00832                                               IdentifierInfo &Name,
00833                                               SourceLocation NameLoc,
00834                                               SourceLocation RParenLoc) {
00835   // C++0x [expr.sizeof]p5:
00836   //   The identifier in a sizeof... expression shall name a parameter pack.
00837   LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
00838   LookupName(R, S);
00839 
00840   NamedDecl *ParameterPack = nullptr;
00841   switch (R.getResultKind()) {
00842   case LookupResult::Found:
00843     ParameterPack = R.getFoundDecl();
00844     break;
00845     
00846   case LookupResult::NotFound:
00847   case LookupResult::NotFoundInCurrentInstantiation:
00848     if (TypoCorrection Corrected =
00849             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
00850                         llvm::make_unique<ParameterPackValidatorCCC>(),
00851                         CTK_ErrorRecovery)) {
00852       diagnoseTypo(Corrected,
00853                    PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
00854                    PDiag(diag::note_parameter_pack_here));
00855       ParameterPack = Corrected.getCorrectionDecl();
00856     }
00857 
00858   case LookupResult::FoundOverloaded:
00859   case LookupResult::FoundUnresolvedValue:
00860     break;
00861     
00862   case LookupResult::Ambiguous:
00863     DiagnoseAmbiguousLookup(R);
00864     return ExprError();
00865   }
00866   
00867   if (!ParameterPack || !ParameterPack->isParameterPack()) {
00868     Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
00869       << &Name;
00870     return ExprError();
00871   }
00872 
00873   MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
00874 
00875   return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc, 
00876                                       ParameterPack, NameLoc, RParenLoc);
00877 }
00878 
00879 TemplateArgumentLoc
00880 Sema::getTemplateArgumentPackExpansionPattern(
00881       TemplateArgumentLoc OrigLoc,
00882       SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
00883   const TemplateArgument &Argument = OrigLoc.getArgument();
00884   assert(Argument.isPackExpansion());
00885   switch (Argument.getKind()) {
00886   case TemplateArgument::Type: {
00887     // FIXME: We shouldn't ever have to worry about missing
00888     // type-source info!
00889     TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
00890     if (!ExpansionTSInfo)
00891       ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
00892                                                          Ellipsis);
00893     PackExpansionTypeLoc Expansion =
00894         ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
00895     Ellipsis = Expansion.getEllipsisLoc();
00896 
00897     TypeLoc Pattern = Expansion.getPatternLoc();
00898     NumExpansions = Expansion.getTypePtr()->getNumExpansions();
00899 
00900     // We need to copy the TypeLoc because TemplateArgumentLocs store a
00901     // TypeSourceInfo.
00902     // FIXME: Find some way to avoid the copy?
00903     TypeLocBuilder TLB;
00904     TLB.pushFullCopy(Pattern);
00905     TypeSourceInfo *PatternTSInfo =
00906         TLB.getTypeSourceInfo(Context, Pattern.getType());
00907     return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
00908                                PatternTSInfo);
00909   }
00910 
00911   case TemplateArgument::Expression: {
00912     PackExpansionExpr *Expansion
00913       = cast<PackExpansionExpr>(Argument.getAsExpr());
00914     Expr *Pattern = Expansion->getPattern();
00915     Ellipsis = Expansion->getEllipsisLoc();
00916     NumExpansions = Expansion->getNumExpansions();
00917     return TemplateArgumentLoc(Pattern, Pattern);
00918   }
00919 
00920   case TemplateArgument::TemplateExpansion:
00921     Ellipsis = OrigLoc.getTemplateEllipsisLoc();
00922     NumExpansions = Argument.getNumTemplateExpansions();
00923     return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
00924                                OrigLoc.getTemplateQualifierLoc(),
00925                                OrigLoc.getTemplateNameLoc());
00926 
00927   case TemplateArgument::Declaration:
00928   case TemplateArgument::NullPtr:
00929   case TemplateArgument::Template:
00930   case TemplateArgument::Integral:
00931   case TemplateArgument::Pack:
00932   case TemplateArgument::Null:
00933     return TemplateArgumentLoc();
00934   }
00935 
00936   llvm_unreachable("Invalid TemplateArgument Kind!");
00937 }
00938 
00939 static void CheckFoldOperand(Sema &S, Expr *E) {
00940   if (!E)
00941     return;
00942 
00943   E = E->IgnoreImpCasts();
00944   if (isa<BinaryOperator>(E) || isa<AbstractConditionalOperator>(E)) {
00945     S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
00946         << E->getSourceRange()
00947         << FixItHint::CreateInsertion(E->getLocStart(), "(")
00948         << FixItHint::CreateInsertion(E->getLocEnd(), ")");
00949   }
00950 }
00951 
00952 ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
00953                                   tok::TokenKind Operator,
00954                                   SourceLocation EllipsisLoc, Expr *RHS,
00955                                   SourceLocation RParenLoc) {
00956   // LHS and RHS must be cast-expressions. We allow an arbitrary expression
00957   // in the parser and reduce down to just cast-expressions here.
00958   CheckFoldOperand(*this, LHS);
00959   CheckFoldOperand(*this, RHS);
00960 
00961   // [expr.prim.fold]p3:
00962   //   In a binary fold, op1 and op2 shall be the same fold-operator, and
00963   //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
00964   //   an unexpanded parameter pack, but not both.
00965   if (LHS && RHS &&
00966       LHS->containsUnexpandedParameterPack() ==
00967           RHS->containsUnexpandedParameterPack()) {
00968     return Diag(EllipsisLoc,
00969                 LHS->containsUnexpandedParameterPack()
00970                     ? diag::err_fold_expression_packs_both_sides
00971                     : diag::err_pack_expansion_without_parameter_packs)
00972         << LHS->getSourceRange() << RHS->getSourceRange();
00973   }
00974 
00975   // [expr.prim.fold]p2:
00976   //   In a unary fold, the cast-expression shall contain an unexpanded
00977   //   parameter pack.
00978   if (!LHS || !RHS) {
00979     Expr *Pack = LHS ? LHS : RHS;
00980     assert(Pack && "fold expression with neither LHS nor RHS");
00981     if (!Pack->containsUnexpandedParameterPack())
00982       return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
00983              << Pack->getSourceRange();
00984   }
00985 
00986   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
00987   return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
00988 }
00989 
00990 ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
00991                                   BinaryOperatorKind Operator,
00992                                   SourceLocation EllipsisLoc, Expr *RHS,
00993                                   SourceLocation RParenLoc) {
00994   return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
00995                                    Operator, EllipsisLoc, RHS, RParenLoc);
00996 }
00997 
00998 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
00999                                        BinaryOperatorKind Operator) {
01000   // [temp.variadic]p9:
01001   //   If N is zero for a unary fold-expression, the value of the expression is
01002   //       *   ->  1
01003   //       +   ->  int()
01004   //       &   ->  -1
01005   //       |   ->  int()
01006   //       &&  ->  true
01007   //       ||  ->  false
01008   //       ,   ->  void()
01009   //   if the operator is not listed [above], the instantiation is ill-formed.
01010   //
01011   // Note that we need to use something like int() here, not merely 0, to
01012   // prevent the result from being a null pointer constant.
01013   QualType ScalarType;
01014   switch (Operator) {
01015   case BO_Add:
01016     ScalarType = Context.IntTy;
01017     break;
01018   case BO_Mul:
01019     return ActOnIntegerConstant(EllipsisLoc, 1);
01020   case BO_Or:
01021     ScalarType = Context.IntTy;
01022     break;
01023   case BO_And:
01024     return CreateBuiltinUnaryOp(EllipsisLoc, UO_Minus,
01025                                 ActOnIntegerConstant(EllipsisLoc, 1).get());
01026   case BO_LOr:
01027     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
01028   case BO_LAnd:
01029     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
01030   case BO_Comma:
01031     ScalarType = Context.VoidTy;
01032     break;
01033 
01034   default:
01035     return Diag(EllipsisLoc, diag::err_fold_expression_empty)
01036         << BinaryOperator::getOpcodeStr(Operator);
01037   }
01038 
01039   return new (Context) CXXScalarValueInitExpr(
01040       ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
01041       EllipsisLoc);
01042 }