SemaTemplateInstantiate.cpp 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065
  1. //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //===----------------------------------------------------------------------===/
  7. //
  8. // This file implements C++ template instantiation.
  9. //
  10. //===----------------------------------------------------------------------===/
  11. #include "clang/Sema/SemaInternal.h"
  12. #include "TreeTransform.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/PrettyDeclStackTrace.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Sema/DeclSpec.h"
  22. #include "clang/Sema/Initialization.h"
  23. #include "clang/Sema/Lookup.h"
  24. #include "clang/Sema/Template.h"
  25. #include "clang/Sema/TemplateDeduction.h"
  26. #include "clang/Sema/TemplateInstCallback.h"
  27. #include "llvm/Support/TimeProfiler.h"
  28. using namespace clang;
  29. using namespace sema;
  30. //===----------------------------------------------------------------------===/
  31. // Template Instantiation Support
  32. //===----------------------------------------------------------------------===/
  33. /// Retrieve the template argument list(s) that should be used to
  34. /// instantiate the definition of the given declaration.
  35. ///
  36. /// \param D the declaration for which we are computing template instantiation
  37. /// arguments.
  38. ///
  39. /// \param Innermost if non-NULL, the innermost template argument list.
  40. ///
  41. /// \param RelativeToPrimary true if we should get the template
  42. /// arguments relative to the primary template, even when we're
  43. /// dealing with a specialization. This is only relevant for function
  44. /// template specializations.
  45. ///
  46. /// \param Pattern If non-NULL, indicates the pattern from which we will be
  47. /// instantiating the definition of the given declaration, \p D. This is
  48. /// used to determine the proper set of template instantiation arguments for
  49. /// friend function template specializations.
  50. MultiLevelTemplateArgumentList
  51. Sema::getTemplateInstantiationArgs(NamedDecl *D,
  52. const TemplateArgumentList *Innermost,
  53. bool RelativeToPrimary,
  54. const FunctionDecl *Pattern) {
  55. // Accumulate the set of template argument lists in this structure.
  56. MultiLevelTemplateArgumentList Result;
  57. if (Innermost)
  58. Result.addOuterTemplateArguments(Innermost);
  59. DeclContext *Ctx = dyn_cast<DeclContext>(D);
  60. if (!Ctx) {
  61. Ctx = D->getDeclContext();
  62. // Add template arguments from a variable template instantiation. For a
  63. // class-scope explicit specialization, there are no template arguments
  64. // at this level, but there may be enclosing template arguments.
  65. VarTemplateSpecializationDecl *Spec =
  66. dyn_cast<VarTemplateSpecializationDecl>(D);
  67. if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
  68. // We're done when we hit an explicit specialization.
  69. if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  70. !isa<VarTemplatePartialSpecializationDecl>(Spec))
  71. return Result;
  72. Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
  73. // If this variable template specialization was instantiated from a
  74. // specialized member that is a variable template, we're done.
  75. assert(Spec->getSpecializedTemplate() && "No variable template?");
  76. llvm::PointerUnion<VarTemplateDecl*,
  77. VarTemplatePartialSpecializationDecl*> Specialized
  78. = Spec->getSpecializedTemplateOrPartial();
  79. if (VarTemplatePartialSpecializationDecl *Partial =
  80. Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  81. if (Partial->isMemberSpecialization())
  82. return Result;
  83. } else {
  84. VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
  85. if (Tmpl->isMemberSpecialization())
  86. return Result;
  87. }
  88. }
  89. // If we have a template template parameter with translation unit context,
  90. // then we're performing substitution into a default template argument of
  91. // this template template parameter before we've constructed the template
  92. // that will own this template template parameter. In this case, we
  93. // use empty template parameter lists for all of the outer templates
  94. // to avoid performing any substitutions.
  95. if (Ctx->isTranslationUnit()) {
  96. if (TemplateTemplateParmDecl *TTP
  97. = dyn_cast<TemplateTemplateParmDecl>(D)) {
  98. for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
  99. Result.addOuterTemplateArguments(None);
  100. return Result;
  101. }
  102. }
  103. }
  104. while (!Ctx->isFileContext()) {
  105. // Add template arguments from a class template instantiation.
  106. ClassTemplateSpecializationDecl *Spec
  107. = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
  108. if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
  109. // We're done when we hit an explicit specialization.
  110. if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  111. !isa<ClassTemplatePartialSpecializationDecl>(Spec))
  112. break;
  113. Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
  114. // If this class template specialization was instantiated from a
  115. // specialized member that is a class template, we're done.
  116. assert(Spec->getSpecializedTemplate() && "No class template?");
  117. if (Spec->getSpecializedTemplate()->isMemberSpecialization())
  118. break;
  119. }
  120. // Add template arguments from a function template specialization.
  121. else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
  122. if (!RelativeToPrimary &&
  123. Function->getTemplateSpecializationKindForInstantiation() ==
  124. TSK_ExplicitSpecialization)
  125. break;
  126. if (const TemplateArgumentList *TemplateArgs
  127. = Function->getTemplateSpecializationArgs()) {
  128. // Add the template arguments for this specialization.
  129. Result.addOuterTemplateArguments(TemplateArgs);
  130. // If this function was instantiated from a specialized member that is
  131. // a function template, we're done.
  132. assert(Function->getPrimaryTemplate() && "No function template?");
  133. if (Function->getPrimaryTemplate()->isMemberSpecialization())
  134. break;
  135. // If this function is a generic lambda specialization, we are done.
  136. if (isGenericLambdaCallOperatorSpecialization(Function))
  137. break;
  138. } else if (FunctionTemplateDecl *FunTmpl
  139. = Function->getDescribedFunctionTemplate()) {
  140. // Add the "injected" template arguments.
  141. Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
  142. }
  143. // If this is a friend declaration and it declares an entity at
  144. // namespace scope, take arguments from its lexical parent
  145. // instead of its semantic parent, unless of course the pattern we're
  146. // instantiating actually comes from the file's context!
  147. if (Function->getFriendObjectKind() &&
  148. Function->getDeclContext()->isFileContext() &&
  149. (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
  150. Ctx = Function->getLexicalDeclContext();
  151. RelativeToPrimary = false;
  152. continue;
  153. }
  154. } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
  155. if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
  156. QualType T = ClassTemplate->getInjectedClassNameSpecialization();
  157. const TemplateSpecializationType *TST =
  158. cast<TemplateSpecializationType>(Context.getCanonicalType(T));
  159. Result.addOuterTemplateArguments(
  160. llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
  161. if (ClassTemplate->isMemberSpecialization())
  162. break;
  163. }
  164. }
  165. Ctx = Ctx->getParent();
  166. RelativeToPrimary = false;
  167. }
  168. return Result;
  169. }
  170. bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
  171. switch (Kind) {
  172. case TemplateInstantiation:
  173. case ExceptionSpecInstantiation:
  174. case DefaultTemplateArgumentInstantiation:
  175. case DefaultFunctionArgumentInstantiation:
  176. case ExplicitTemplateArgumentSubstitution:
  177. case DeducedTemplateArgumentSubstitution:
  178. case PriorTemplateArgumentSubstitution:
  179. return true;
  180. case DefaultTemplateArgumentChecking:
  181. case DeclaringSpecialMember:
  182. case DefiningSynthesizedFunction:
  183. case ExceptionSpecEvaluation:
  184. return false;
  185. // This function should never be called when Kind's value is Memoization.
  186. case Memoization:
  187. break;
  188. }
  189. llvm_unreachable("Invalid SynthesisKind!");
  190. }
  191. Sema::InstantiatingTemplate::InstantiatingTemplate(
  192. Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
  193. SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
  194. Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
  195. sema::TemplateDeductionInfo *DeductionInfo)
  196. : SemaRef(SemaRef) {
  197. // Don't allow further instantiation if a fatal error and an uncompilable
  198. // error have occurred. Any diagnostics we might have raised will not be
  199. // visible, and we do not need to construct a correct AST.
  200. if (SemaRef.Diags.hasFatalErrorOccurred() &&
  201. SemaRef.Diags.hasUncompilableErrorOccurred()) {
  202. Invalid = true;
  203. return;
  204. }
  205. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  206. if (!Invalid) {
  207. CodeSynthesisContext Inst;
  208. Inst.Kind = Kind;
  209. Inst.PointOfInstantiation = PointOfInstantiation;
  210. Inst.Entity = Entity;
  211. Inst.Template = Template;
  212. Inst.TemplateArgs = TemplateArgs.data();
  213. Inst.NumTemplateArgs = TemplateArgs.size();
  214. Inst.DeductionInfo = DeductionInfo;
  215. Inst.InstantiationRange = InstantiationRange;
  216. SemaRef.pushCodeSynthesisContext(Inst);
  217. AlreadyInstantiating =
  218. !SemaRef.InstantiatingSpecializations
  219. .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
  220. .second;
  221. atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
  222. }
  223. }
  224. Sema::InstantiatingTemplate::InstantiatingTemplate(
  225. Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
  226. SourceRange InstantiationRange)
  227. : InstantiatingTemplate(SemaRef,
  228. CodeSynthesisContext::TemplateInstantiation,
  229. PointOfInstantiation, InstantiationRange, Entity) {}
  230. Sema::InstantiatingTemplate::InstantiatingTemplate(
  231. Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
  232. ExceptionSpecification, SourceRange InstantiationRange)
  233. : InstantiatingTemplate(
  234. SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
  235. PointOfInstantiation, InstantiationRange, Entity) {}
  236. Sema::InstantiatingTemplate::InstantiatingTemplate(
  237. Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
  238. TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
  239. SourceRange InstantiationRange)
  240. : InstantiatingTemplate(
  241. SemaRef,
  242. CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
  243. PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
  244. Template, TemplateArgs) {}
  245. Sema::InstantiatingTemplate::InstantiatingTemplate(
  246. Sema &SemaRef, SourceLocation PointOfInstantiation,
  247. FunctionTemplateDecl *FunctionTemplate,
  248. ArrayRef<TemplateArgument> TemplateArgs,
  249. CodeSynthesisContext::SynthesisKind Kind,
  250. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  251. : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
  252. InstantiationRange, FunctionTemplate, nullptr,
  253. TemplateArgs, &DeductionInfo) {
  254. assert(
  255. Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
  256. Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
  257. }
  258. Sema::InstantiatingTemplate::InstantiatingTemplate(
  259. Sema &SemaRef, SourceLocation PointOfInstantiation,
  260. TemplateDecl *Template,
  261. ArrayRef<TemplateArgument> TemplateArgs,
  262. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  263. : InstantiatingTemplate(
  264. SemaRef,
  265. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  266. PointOfInstantiation, InstantiationRange, Template, nullptr,
  267. TemplateArgs, &DeductionInfo) {}
  268. Sema::InstantiatingTemplate::InstantiatingTemplate(
  269. Sema &SemaRef, SourceLocation PointOfInstantiation,
  270. ClassTemplatePartialSpecializationDecl *PartialSpec,
  271. ArrayRef<TemplateArgument> TemplateArgs,
  272. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  273. : InstantiatingTemplate(
  274. SemaRef,
  275. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  276. PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
  277. TemplateArgs, &DeductionInfo) {}
  278. Sema::InstantiatingTemplate::InstantiatingTemplate(
  279. Sema &SemaRef, SourceLocation PointOfInstantiation,
  280. VarTemplatePartialSpecializationDecl *PartialSpec,
  281. ArrayRef<TemplateArgument> TemplateArgs,
  282. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  283. : InstantiatingTemplate(
  284. SemaRef,
  285. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  286. PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
  287. TemplateArgs, &DeductionInfo) {}
  288. Sema::InstantiatingTemplate::InstantiatingTemplate(
  289. Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
  290. ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
  291. : InstantiatingTemplate(
  292. SemaRef,
  293. CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
  294. PointOfInstantiation, InstantiationRange, Param, nullptr,
  295. TemplateArgs) {}
  296. Sema::InstantiatingTemplate::InstantiatingTemplate(
  297. Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
  298. NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  299. SourceRange InstantiationRange)
  300. : InstantiatingTemplate(
  301. SemaRef,
  302. CodeSynthesisContext::PriorTemplateArgumentSubstitution,
  303. PointOfInstantiation, InstantiationRange, Param, Template,
  304. TemplateArgs) {}
  305. Sema::InstantiatingTemplate::InstantiatingTemplate(
  306. Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
  307. TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  308. SourceRange InstantiationRange)
  309. : InstantiatingTemplate(
  310. SemaRef,
  311. CodeSynthesisContext::PriorTemplateArgumentSubstitution,
  312. PointOfInstantiation, InstantiationRange, Param, Template,
  313. TemplateArgs) {}
  314. Sema::InstantiatingTemplate::InstantiatingTemplate(
  315. Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
  316. NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  317. SourceRange InstantiationRange)
  318. : InstantiatingTemplate(
  319. SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
  320. PointOfInstantiation, InstantiationRange, Param, Template,
  321. TemplateArgs) {}
  322. void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
  323. Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
  324. InNonInstantiationSFINAEContext = false;
  325. CodeSynthesisContexts.push_back(Ctx);
  326. if (!Ctx.isInstantiationRecord())
  327. ++NonInstantiationEntries;
  328. }
  329. void Sema::popCodeSynthesisContext() {
  330. auto &Active = CodeSynthesisContexts.back();
  331. if (!Active.isInstantiationRecord()) {
  332. assert(NonInstantiationEntries > 0);
  333. --NonInstantiationEntries;
  334. }
  335. InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
  336. // Name lookup no longer looks in this template's defining module.
  337. assert(CodeSynthesisContexts.size() >=
  338. CodeSynthesisContextLookupModules.size() &&
  339. "forgot to remove a lookup module for a template instantiation");
  340. if (CodeSynthesisContexts.size() ==
  341. CodeSynthesisContextLookupModules.size()) {
  342. if (Module *M = CodeSynthesisContextLookupModules.back())
  343. LookupModulesCache.erase(M);
  344. CodeSynthesisContextLookupModules.pop_back();
  345. }
  346. // If we've left the code synthesis context for the current context stack,
  347. // stop remembering that we've emitted that stack.
  348. if (CodeSynthesisContexts.size() ==
  349. LastEmittedCodeSynthesisContextDepth)
  350. LastEmittedCodeSynthesisContextDepth = 0;
  351. CodeSynthesisContexts.pop_back();
  352. }
  353. void Sema::InstantiatingTemplate::Clear() {
  354. if (!Invalid) {
  355. if (!AlreadyInstantiating) {
  356. auto &Active = SemaRef.CodeSynthesisContexts.back();
  357. SemaRef.InstantiatingSpecializations.erase(
  358. std::make_pair(Active.Entity, Active.Kind));
  359. }
  360. atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
  361. SemaRef.CodeSynthesisContexts.back());
  362. SemaRef.popCodeSynthesisContext();
  363. Invalid = true;
  364. }
  365. }
  366. bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
  367. SourceLocation PointOfInstantiation,
  368. SourceRange InstantiationRange) {
  369. assert(SemaRef.NonInstantiationEntries <=
  370. SemaRef.CodeSynthesisContexts.size());
  371. if ((SemaRef.CodeSynthesisContexts.size() -
  372. SemaRef.NonInstantiationEntries)
  373. <= SemaRef.getLangOpts().InstantiationDepth)
  374. return false;
  375. SemaRef.Diag(PointOfInstantiation,
  376. diag::err_template_recursion_depth_exceeded)
  377. << SemaRef.getLangOpts().InstantiationDepth
  378. << InstantiationRange;
  379. SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
  380. << SemaRef.getLangOpts().InstantiationDepth;
  381. return true;
  382. }
  383. /// Prints the current instantiation stack through a series of
  384. /// notes.
  385. void Sema::PrintInstantiationStack() {
  386. // Determine which template instantiations to skip, if any.
  387. unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
  388. unsigned Limit = Diags.getTemplateBacktraceLimit();
  389. if (Limit && Limit < CodeSynthesisContexts.size()) {
  390. SkipStart = Limit / 2 + Limit % 2;
  391. SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
  392. }
  393. // FIXME: In all of these cases, we need to show the template arguments
  394. unsigned InstantiationIdx = 0;
  395. for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
  396. Active = CodeSynthesisContexts.rbegin(),
  397. ActiveEnd = CodeSynthesisContexts.rend();
  398. Active != ActiveEnd;
  399. ++Active, ++InstantiationIdx) {
  400. // Skip this instantiation?
  401. if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
  402. if (InstantiationIdx == SkipStart) {
  403. // Note that we're skipping instantiations.
  404. Diags.Report(Active->PointOfInstantiation,
  405. diag::note_instantiation_contexts_suppressed)
  406. << unsigned(CodeSynthesisContexts.size() - Limit);
  407. }
  408. continue;
  409. }
  410. switch (Active->Kind) {
  411. case CodeSynthesisContext::TemplateInstantiation: {
  412. Decl *D = Active->Entity;
  413. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  414. unsigned DiagID = diag::note_template_member_class_here;
  415. if (isa<ClassTemplateSpecializationDecl>(Record))
  416. DiagID = diag::note_template_class_instantiation_here;
  417. Diags.Report(Active->PointOfInstantiation, DiagID)
  418. << Record << Active->InstantiationRange;
  419. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  420. unsigned DiagID;
  421. if (Function->getPrimaryTemplate())
  422. DiagID = diag::note_function_template_spec_here;
  423. else
  424. DiagID = diag::note_template_member_function_here;
  425. Diags.Report(Active->PointOfInstantiation, DiagID)
  426. << Function
  427. << Active->InstantiationRange;
  428. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  429. Diags.Report(Active->PointOfInstantiation,
  430. VD->isStaticDataMember()?
  431. diag::note_template_static_data_member_def_here
  432. : diag::note_template_variable_def_here)
  433. << VD
  434. << Active->InstantiationRange;
  435. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  436. Diags.Report(Active->PointOfInstantiation,
  437. diag::note_template_enum_def_here)
  438. << ED
  439. << Active->InstantiationRange;
  440. } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  441. Diags.Report(Active->PointOfInstantiation,
  442. diag::note_template_nsdmi_here)
  443. << FD << Active->InstantiationRange;
  444. } else {
  445. Diags.Report(Active->PointOfInstantiation,
  446. diag::note_template_type_alias_instantiation_here)
  447. << cast<TypeAliasTemplateDecl>(D)
  448. << Active->InstantiationRange;
  449. }
  450. break;
  451. }
  452. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
  453. TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
  454. SmallVector<char, 128> TemplateArgsStr;
  455. llvm::raw_svector_ostream OS(TemplateArgsStr);
  456. Template->printName(OS);
  457. printTemplateArgumentList(OS, Active->template_arguments(),
  458. getPrintingPolicy());
  459. Diags.Report(Active->PointOfInstantiation,
  460. diag::note_default_arg_instantiation_here)
  461. << OS.str()
  462. << Active->InstantiationRange;
  463. break;
  464. }
  465. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
  466. FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
  467. Diags.Report(Active->PointOfInstantiation,
  468. diag::note_explicit_template_arg_substitution_here)
  469. << FnTmpl
  470. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  471. Active->TemplateArgs,
  472. Active->NumTemplateArgs)
  473. << Active->InstantiationRange;
  474. break;
  475. }
  476. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
  477. if (FunctionTemplateDecl *FnTmpl =
  478. dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
  479. Diags.Report(Active->PointOfInstantiation,
  480. diag::note_function_template_deduction_instantiation_here)
  481. << FnTmpl
  482. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  483. Active->TemplateArgs,
  484. Active->NumTemplateArgs)
  485. << Active->InstantiationRange;
  486. } else {
  487. bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
  488. isa<VarTemplateSpecializationDecl>(Active->Entity);
  489. bool IsTemplate = false;
  490. TemplateParameterList *Params;
  491. if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
  492. IsTemplate = true;
  493. Params = D->getTemplateParameters();
  494. } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
  495. Active->Entity)) {
  496. Params = D->getTemplateParameters();
  497. } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
  498. Active->Entity)) {
  499. Params = D->getTemplateParameters();
  500. } else {
  501. llvm_unreachable("unexpected template kind");
  502. }
  503. Diags.Report(Active->PointOfInstantiation,
  504. diag::note_deduced_template_arg_substitution_here)
  505. << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
  506. << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
  507. Active->NumTemplateArgs)
  508. << Active->InstantiationRange;
  509. }
  510. break;
  511. }
  512. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
  513. ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
  514. FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
  515. SmallVector<char, 128> TemplateArgsStr;
  516. llvm::raw_svector_ostream OS(TemplateArgsStr);
  517. FD->printName(OS);
  518. printTemplateArgumentList(OS, Active->template_arguments(),
  519. getPrintingPolicy());
  520. Diags.Report(Active->PointOfInstantiation,
  521. diag::note_default_function_arg_instantiation_here)
  522. << OS.str()
  523. << Active->InstantiationRange;
  524. break;
  525. }
  526. case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
  527. NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
  528. std::string Name;
  529. if (!Parm->getName().empty())
  530. Name = std::string(" '") + Parm->getName().str() + "'";
  531. TemplateParameterList *TemplateParams = nullptr;
  532. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  533. TemplateParams = Template->getTemplateParameters();
  534. else
  535. TemplateParams =
  536. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  537. ->getTemplateParameters();
  538. Diags.Report(Active->PointOfInstantiation,
  539. diag::note_prior_template_arg_substitution)
  540. << isa<TemplateTemplateParmDecl>(Parm)
  541. << Name
  542. << getTemplateArgumentBindingsText(TemplateParams,
  543. Active->TemplateArgs,
  544. Active->NumTemplateArgs)
  545. << Active->InstantiationRange;
  546. break;
  547. }
  548. case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
  549. TemplateParameterList *TemplateParams = nullptr;
  550. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  551. TemplateParams = Template->getTemplateParameters();
  552. else
  553. TemplateParams =
  554. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  555. ->getTemplateParameters();
  556. Diags.Report(Active->PointOfInstantiation,
  557. diag::note_template_default_arg_checking)
  558. << getTemplateArgumentBindingsText(TemplateParams,
  559. Active->TemplateArgs,
  560. Active->NumTemplateArgs)
  561. << Active->InstantiationRange;
  562. break;
  563. }
  564. case CodeSynthesisContext::ExceptionSpecEvaluation:
  565. Diags.Report(Active->PointOfInstantiation,
  566. diag::note_evaluating_exception_spec_here)
  567. << cast<FunctionDecl>(Active->Entity);
  568. break;
  569. case CodeSynthesisContext::ExceptionSpecInstantiation:
  570. Diags.Report(Active->PointOfInstantiation,
  571. diag::note_template_exception_spec_instantiation_here)
  572. << cast<FunctionDecl>(Active->Entity)
  573. << Active->InstantiationRange;
  574. break;
  575. case CodeSynthesisContext::DeclaringSpecialMember:
  576. Diags.Report(Active->PointOfInstantiation,
  577. diag::note_in_declaration_of_implicit_special_member)
  578. << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
  579. break;
  580. case CodeSynthesisContext::DefiningSynthesizedFunction: {
  581. // FIXME: For synthesized members other than special members, produce a note.
  582. auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
  583. auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
  584. if (CSM != CXXInvalid) {
  585. Diags.Report(Active->PointOfInstantiation,
  586. diag::note_member_synthesized_at)
  587. << CSM << Context.getTagDeclType(MD->getParent());
  588. }
  589. break;
  590. }
  591. case CodeSynthesisContext::Memoization:
  592. break;
  593. }
  594. }
  595. }
  596. Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
  597. if (InNonInstantiationSFINAEContext)
  598. return Optional<TemplateDeductionInfo *>(nullptr);
  599. for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
  600. Active = CodeSynthesisContexts.rbegin(),
  601. ActiveEnd = CodeSynthesisContexts.rend();
  602. Active != ActiveEnd;
  603. ++Active)
  604. {
  605. switch (Active->Kind) {
  606. case CodeSynthesisContext::TemplateInstantiation:
  607. // An instantiation of an alias template may or may not be a SFINAE
  608. // context, depending on what else is on the stack.
  609. if (isa<TypeAliasTemplateDecl>(Active->Entity))
  610. break;
  611. LLVM_FALLTHROUGH;
  612. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  613. case CodeSynthesisContext::ExceptionSpecInstantiation:
  614. // This is a template instantiation, so there is no SFINAE.
  615. return None;
  616. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  617. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  618. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  619. // A default template argument instantiation and substitution into
  620. // template parameters with arguments for prior parameters may or may
  621. // not be a SFINAE context; look further up the stack.
  622. break;
  623. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  624. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  625. // We're either substitution explicitly-specified template arguments
  626. // or deduced template arguments, so SFINAE applies.
  627. assert(Active->DeductionInfo && "Missing deduction info pointer");
  628. return Active->DeductionInfo;
  629. case CodeSynthesisContext::DeclaringSpecialMember:
  630. case CodeSynthesisContext::DefiningSynthesizedFunction:
  631. // This happens in a context unrelated to template instantiation, so
  632. // there is no SFINAE.
  633. return None;
  634. case CodeSynthesisContext::ExceptionSpecEvaluation:
  635. // FIXME: This should not be treated as a SFINAE context, because
  636. // we will cache an incorrect exception specification. However, clang
  637. // bootstrap relies this! See PR31692.
  638. break;
  639. case CodeSynthesisContext::Memoization:
  640. break;
  641. }
  642. // The inner context was transparent for SFINAE. If it occurred within a
  643. // non-instantiation SFINAE context, then SFINAE applies.
  644. if (Active->SavedInNonInstantiationSFINAEContext)
  645. return Optional<TemplateDeductionInfo *>(nullptr);
  646. }
  647. return None;
  648. }
  649. //===----------------------------------------------------------------------===/
  650. // Template Instantiation for Types
  651. //===----------------------------------------------------------------------===/
  652. namespace {
  653. class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
  654. const MultiLevelTemplateArgumentList &TemplateArgs;
  655. SourceLocation Loc;
  656. DeclarationName Entity;
  657. public:
  658. typedef TreeTransform<TemplateInstantiator> inherited;
  659. TemplateInstantiator(Sema &SemaRef,
  660. const MultiLevelTemplateArgumentList &TemplateArgs,
  661. SourceLocation Loc,
  662. DeclarationName Entity)
  663. : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
  664. Entity(Entity) { }
  665. /// Determine whether the given type \p T has already been
  666. /// transformed.
  667. ///
  668. /// For the purposes of template instantiation, a type has already been
  669. /// transformed if it is NULL or if it is not dependent.
  670. bool AlreadyTransformed(QualType T);
  671. /// Returns the location of the entity being instantiated, if known.
  672. SourceLocation getBaseLocation() { return Loc; }
  673. /// Returns the name of the entity being instantiated, if any.
  674. DeclarationName getBaseEntity() { return Entity; }
  675. /// Sets the "base" location and entity when that
  676. /// information is known based on another transformation.
  677. void setBase(SourceLocation Loc, DeclarationName Entity) {
  678. this->Loc = Loc;
  679. this->Entity = Entity;
  680. }
  681. bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
  682. SourceRange PatternRange,
  683. ArrayRef<UnexpandedParameterPack> Unexpanded,
  684. bool &ShouldExpand, bool &RetainExpansion,
  685. Optional<unsigned> &NumExpansions) {
  686. return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
  687. PatternRange, Unexpanded,
  688. TemplateArgs,
  689. ShouldExpand,
  690. RetainExpansion,
  691. NumExpansions);
  692. }
  693. void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
  694. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
  695. }
  696. TemplateArgument ForgetPartiallySubstitutedPack() {
  697. TemplateArgument Result;
  698. if (NamedDecl *PartialPack
  699. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  700. MultiLevelTemplateArgumentList &TemplateArgs
  701. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  702. unsigned Depth, Index;
  703. std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  704. if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
  705. Result = TemplateArgs(Depth, Index);
  706. TemplateArgs.setArgument(Depth, Index, TemplateArgument());
  707. }
  708. }
  709. return Result;
  710. }
  711. void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
  712. if (Arg.isNull())
  713. return;
  714. if (NamedDecl *PartialPack
  715. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  716. MultiLevelTemplateArgumentList &TemplateArgs
  717. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  718. unsigned Depth, Index;
  719. std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  720. TemplateArgs.setArgument(Depth, Index, Arg);
  721. }
  722. }
  723. /// Transform the given declaration by instantiating a reference to
  724. /// this declaration.
  725. Decl *TransformDecl(SourceLocation Loc, Decl *D);
  726. void transformAttrs(Decl *Old, Decl *New) {
  727. SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
  728. }
  729. void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
  730. if (Old->isParameterPack()) {
  731. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
  732. for (auto *New : NewDecls)
  733. SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
  734. Old, cast<VarDecl>(New));
  735. return;
  736. }
  737. assert(NewDecls.size() == 1 &&
  738. "should only have multiple expansions for a pack");
  739. Decl *New = NewDecls.front();
  740. // If we've instantiated the call operator of a lambda or the call
  741. // operator template of a generic lambda, update the "instantiation of"
  742. // information.
  743. auto *NewMD = dyn_cast<CXXMethodDecl>(New);
  744. if (NewMD && isLambdaCallOperator(NewMD)) {
  745. auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
  746. if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
  747. NewTD->setInstantiatedFromMemberTemplate(
  748. OldMD->getDescribedFunctionTemplate());
  749. else
  750. NewMD->setInstantiationOfMemberFunction(OldMD,
  751. TSK_ImplicitInstantiation);
  752. }
  753. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
  754. // We recreated a local declaration, but not by instantiating it. There
  755. // may be pending dependent diagnostics to produce.
  756. if (auto *DC = dyn_cast<DeclContext>(Old))
  757. SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
  758. }
  759. /// Transform the definition of the given declaration by
  760. /// instantiating it.
  761. Decl *TransformDefinition(SourceLocation Loc, Decl *D);
  762. /// Transform the first qualifier within a scope by instantiating the
  763. /// declaration.
  764. NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
  765. /// Rebuild the exception declaration and register the declaration
  766. /// as an instantiated local.
  767. VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
  768. TypeSourceInfo *Declarator,
  769. SourceLocation StartLoc,
  770. SourceLocation NameLoc,
  771. IdentifierInfo *Name);
  772. /// Rebuild the Objective-C exception declaration and register the
  773. /// declaration as an instantiated local.
  774. VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  775. TypeSourceInfo *TSInfo, QualType T);
  776. /// Check for tag mismatches when instantiating an
  777. /// elaborated type.
  778. QualType RebuildElaboratedType(SourceLocation KeywordLoc,
  779. ElaboratedTypeKeyword Keyword,
  780. NestedNameSpecifierLoc QualifierLoc,
  781. QualType T);
  782. TemplateName
  783. TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
  784. SourceLocation NameLoc,
  785. QualType ObjectType = QualType(),
  786. NamedDecl *FirstQualifierInScope = nullptr,
  787. bool AllowInjectedClassName = false);
  788. const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
  789. ExprResult TransformPredefinedExpr(PredefinedExpr *E);
  790. ExprResult TransformDeclRefExpr(DeclRefExpr *E);
  791. ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
  792. ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
  793. NonTypeTemplateParmDecl *D);
  794. ExprResult TransformSubstNonTypeTemplateParmPackExpr(
  795. SubstNonTypeTemplateParmPackExpr *E);
  796. /// Rebuild a DeclRefExpr for a VarDecl reference.
  797. ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
  798. /// Transform a reference to a function or init-capture parameter pack.
  799. ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
  800. /// Transform a FunctionParmPackExpr which was built when we couldn't
  801. /// expand a function parameter pack reference which refers to an expanded
  802. /// pack.
  803. ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
  804. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  805. FunctionProtoTypeLoc TL) {
  806. // Call the base version; it will forward to our overridden version below.
  807. return inherited::TransformFunctionProtoType(TLB, TL);
  808. }
  809. template<typename Fn>
  810. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  811. FunctionProtoTypeLoc TL,
  812. CXXRecordDecl *ThisContext,
  813. Qualifiers ThisTypeQuals,
  814. Fn TransformExceptionSpec);
  815. ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
  816. int indexAdjustment,
  817. Optional<unsigned> NumExpansions,
  818. bool ExpectParameterPack);
  819. /// Transforms a template type parameter type by performing
  820. /// substitution of the corresponding template type argument.
  821. QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  822. TemplateTypeParmTypeLoc TL);
  823. /// Transforms an already-substituted template type parameter pack
  824. /// into either itself (if we aren't substituting into its pack expansion)
  825. /// or the appropriate substituted argument.
  826. QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
  827. SubstTemplateTypeParmPackTypeLoc TL);
  828. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  829. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  830. return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
  831. }
  832. TemplateParameterList *TransformTemplateParameterList(
  833. TemplateParameterList *OrigTPL) {
  834. if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
  835. DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
  836. TemplateDeclInstantiator DeclInstantiator(getSema(),
  837. /* DeclContext *Owner */ Owner, TemplateArgs);
  838. return DeclInstantiator.SubstTemplateParams(OrigTPL);
  839. }
  840. private:
  841. ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
  842. SourceLocation loc,
  843. TemplateArgument arg);
  844. };
  845. }
  846. bool TemplateInstantiator::AlreadyTransformed(QualType T) {
  847. if (T.isNull())
  848. return true;
  849. if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
  850. return false;
  851. getSema().MarkDeclarationsReferencedInType(Loc, T);
  852. return true;
  853. }
  854. static TemplateArgument
  855. getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
  856. assert(S.ArgumentPackSubstitutionIndex >= 0);
  857. assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  858. Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
  859. if (Arg.isPackExpansion())
  860. Arg = Arg.getPackExpansionPattern();
  861. return Arg;
  862. }
  863. Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
  864. if (!D)
  865. return nullptr;
  866. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
  867. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  868. // If the corresponding template argument is NULL or non-existent, it's
  869. // because we are performing instantiation from explicitly-specified
  870. // template arguments in a function template, but there were some
  871. // arguments left unspecified.
  872. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  873. TTP->getPosition()))
  874. return D;
  875. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  876. if (TTP->isParameterPack()) {
  877. assert(Arg.getKind() == TemplateArgument::Pack &&
  878. "Missing argument pack");
  879. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  880. }
  881. TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
  882. assert(!Template.isNull() && Template.getAsTemplateDecl() &&
  883. "Wrong kind of template template argument");
  884. return Template.getAsTemplateDecl();
  885. }
  886. // Fall through to find the instantiated declaration for this template
  887. // template parameter.
  888. }
  889. return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
  890. }
  891. Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
  892. Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
  893. if (!Inst)
  894. return nullptr;
  895. getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  896. return Inst;
  897. }
  898. NamedDecl *
  899. TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
  900. SourceLocation Loc) {
  901. // If the first part of the nested-name-specifier was a template type
  902. // parameter, instantiate that type parameter down to a tag type.
  903. if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
  904. const TemplateTypeParmType *TTP
  905. = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
  906. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  907. // FIXME: This needs testing w/ member access expressions.
  908. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
  909. if (TTP->isParameterPack()) {
  910. assert(Arg.getKind() == TemplateArgument::Pack &&
  911. "Missing argument pack");
  912. if (getSema().ArgumentPackSubstitutionIndex == -1)
  913. return nullptr;
  914. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  915. }
  916. QualType T = Arg.getAsType();
  917. if (T.isNull())
  918. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  919. if (const TagType *Tag = T->getAs<TagType>())
  920. return Tag->getDecl();
  921. // The resulting type is not a tag; complain.
  922. getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
  923. return nullptr;
  924. }
  925. }
  926. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  927. }
  928. VarDecl *
  929. TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
  930. TypeSourceInfo *Declarator,
  931. SourceLocation StartLoc,
  932. SourceLocation NameLoc,
  933. IdentifierInfo *Name) {
  934. VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
  935. StartLoc, NameLoc, Name);
  936. if (Var)
  937. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  938. return Var;
  939. }
  940. VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  941. TypeSourceInfo *TSInfo,
  942. QualType T) {
  943. VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
  944. if (Var)
  945. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  946. return Var;
  947. }
  948. QualType
  949. TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
  950. ElaboratedTypeKeyword Keyword,
  951. NestedNameSpecifierLoc QualifierLoc,
  952. QualType T) {
  953. if (const TagType *TT = T->getAs<TagType>()) {
  954. TagDecl* TD = TT->getDecl();
  955. SourceLocation TagLocation = KeywordLoc;
  956. IdentifierInfo *Id = TD->getIdentifier();
  957. // TODO: should we even warn on struct/class mismatches for this? Seems
  958. // like it's likely to produce a lot of spurious errors.
  959. if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
  960. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
  961. if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
  962. TagLocation, Id)) {
  963. SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
  964. << Id
  965. << FixItHint::CreateReplacement(SourceRange(TagLocation),
  966. TD->getKindName());
  967. SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
  968. }
  969. }
  970. }
  971. return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
  972. Keyword,
  973. QualifierLoc,
  974. T);
  975. }
  976. TemplateName TemplateInstantiator::TransformTemplateName(
  977. CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
  978. QualType ObjectType, NamedDecl *FirstQualifierInScope,
  979. bool AllowInjectedClassName) {
  980. if (TemplateTemplateParmDecl *TTP
  981. = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
  982. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  983. // If the corresponding template argument is NULL or non-existent, it's
  984. // because we are performing instantiation from explicitly-specified
  985. // template arguments in a function template, but there were some
  986. // arguments left unspecified.
  987. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  988. TTP->getPosition()))
  989. return Name;
  990. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  991. if (TTP->isParameterPack()) {
  992. assert(Arg.getKind() == TemplateArgument::Pack &&
  993. "Missing argument pack");
  994. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  995. // We have the template argument pack to substitute, but we're not
  996. // actually expanding the enclosing pack expansion yet. So, just
  997. // keep the entire argument pack.
  998. return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
  999. }
  1000. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1001. }
  1002. TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
  1003. assert(!Template.isNull() && "Null template template argument");
  1004. assert(!Template.getAsQualifiedTemplateName() &&
  1005. "template decl to substitute is qualified?");
  1006. Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
  1007. return Template;
  1008. }
  1009. }
  1010. if (SubstTemplateTemplateParmPackStorage *SubstPack
  1011. = Name.getAsSubstTemplateTemplateParmPack()) {
  1012. if (getSema().ArgumentPackSubstitutionIndex == -1)
  1013. return Name;
  1014. TemplateArgument Arg = SubstPack->getArgumentPack();
  1015. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1016. return Arg.getAsTemplate().getNameToSubstitute();
  1017. }
  1018. return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
  1019. FirstQualifierInScope,
  1020. AllowInjectedClassName);
  1021. }
  1022. ExprResult
  1023. TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
  1024. if (!E->isTypeDependent())
  1025. return E;
  1026. return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
  1027. }
  1028. ExprResult
  1029. TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
  1030. NonTypeTemplateParmDecl *NTTP) {
  1031. // If the corresponding template argument is NULL or non-existent, it's
  1032. // because we are performing instantiation from explicitly-specified
  1033. // template arguments in a function template, but there were some
  1034. // arguments left unspecified.
  1035. if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
  1036. NTTP->getPosition()))
  1037. return E;
  1038. TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
  1039. if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
  1040. // We're performing a partial substitution, so the substituted argument
  1041. // could be dependent. As a result we can't create a SubstNonType*Expr
  1042. // node now, since that represents a fully-substituted argument.
  1043. // FIXME: We should have some AST representation for this.
  1044. if (Arg.getKind() == TemplateArgument::Pack) {
  1045. // FIXME: This won't work for alias templates.
  1046. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
  1047. "unexpected pack arguments in partial substitution");
  1048. Arg = Arg.pack_begin()->getPackExpansionPattern();
  1049. }
  1050. assert(Arg.getKind() == TemplateArgument::Expression &&
  1051. "unexpected nontype template argument kind in partial substitution");
  1052. return Arg.getAsExpr();
  1053. }
  1054. if (NTTP->isParameterPack()) {
  1055. assert(Arg.getKind() == TemplateArgument::Pack &&
  1056. "Missing argument pack");
  1057. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1058. // We have an argument pack, but we can't select a particular argument
  1059. // out of it yet. Therefore, we'll build an expression to hold on to that
  1060. // argument pack.
  1061. QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
  1062. E->getLocation(),
  1063. NTTP->getDeclName());
  1064. if (TargetType.isNull())
  1065. return ExprError();
  1066. return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
  1067. TargetType.getNonLValueExprType(SemaRef.Context),
  1068. TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
  1069. E->getLocation(), Arg);
  1070. }
  1071. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1072. }
  1073. return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
  1074. }
  1075. const LoopHintAttr *
  1076. TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
  1077. Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
  1078. if (TransformedExpr == LH->getValue())
  1079. return LH;
  1080. // Generate error if there is a problem with the value.
  1081. if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
  1082. return LH;
  1083. // Create new LoopHintValueAttr with integral expression in place of the
  1084. // non-type template parameter.
  1085. return LoopHintAttr::CreateImplicit(
  1086. getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
  1087. LH->getState(), TransformedExpr, LH->getRange());
  1088. }
  1089. ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
  1090. NonTypeTemplateParmDecl *parm,
  1091. SourceLocation loc,
  1092. TemplateArgument arg) {
  1093. ExprResult result;
  1094. QualType type;
  1095. // The template argument itself might be an expression, in which
  1096. // case we just return that expression.
  1097. if (arg.getKind() == TemplateArgument::Expression) {
  1098. Expr *argExpr = arg.getAsExpr();
  1099. result = argExpr;
  1100. type = argExpr->getType();
  1101. } else if (arg.getKind() == TemplateArgument::Declaration ||
  1102. arg.getKind() == TemplateArgument::NullPtr) {
  1103. ValueDecl *VD;
  1104. if (arg.getKind() == TemplateArgument::Declaration) {
  1105. VD = arg.getAsDecl();
  1106. // Find the instantiation of the template argument. This is
  1107. // required for nested templates.
  1108. VD = cast_or_null<ValueDecl>(
  1109. getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
  1110. if (!VD)
  1111. return ExprError();
  1112. } else {
  1113. // Propagate NULL template argument.
  1114. VD = nullptr;
  1115. }
  1116. // Derive the type we want the substituted decl to have. This had
  1117. // better be non-dependent, or these checks will have serious problems.
  1118. if (parm->isExpandedParameterPack()) {
  1119. type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
  1120. } else if (parm->isParameterPack() &&
  1121. isa<PackExpansionType>(parm->getType())) {
  1122. type = SemaRef.SubstType(
  1123. cast<PackExpansionType>(parm->getType())->getPattern(),
  1124. TemplateArgs, loc, parm->getDeclName());
  1125. } else {
  1126. type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
  1127. TemplateArgs, loc, parm->getDeclName());
  1128. }
  1129. assert(!type.isNull() && "type substitution failed for param type");
  1130. assert(!type->isDependentType() && "param type still dependent");
  1131. result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
  1132. if (!result.isInvalid()) type = result.get()->getType();
  1133. } else {
  1134. result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
  1135. // Note that this type can be different from the type of 'result',
  1136. // e.g. if it's an enum type.
  1137. type = arg.getIntegralType();
  1138. }
  1139. if (result.isInvalid()) return ExprError();
  1140. Expr *resultExpr = result.get();
  1141. return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
  1142. type, resultExpr->getValueKind(), loc, parm, resultExpr);
  1143. }
  1144. ExprResult
  1145. TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
  1146. SubstNonTypeTemplateParmPackExpr *E) {
  1147. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1148. // We aren't expanding the parameter pack, so just return ourselves.
  1149. return E;
  1150. }
  1151. TemplateArgument Arg = E->getArgumentPack();
  1152. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1153. return transformNonTypeTemplateParmRef(E->getParameterPack(),
  1154. E->getParameterPackLocation(),
  1155. Arg);
  1156. }
  1157. ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
  1158. SourceLocation Loc) {
  1159. DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
  1160. return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
  1161. }
  1162. ExprResult
  1163. TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
  1164. if (getSema().ArgumentPackSubstitutionIndex != -1) {
  1165. // We can expand this parameter pack now.
  1166. VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
  1167. VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
  1168. if (!VD)
  1169. return ExprError();
  1170. return RebuildVarDeclRefExpr(VD, E->getExprLoc());
  1171. }
  1172. QualType T = TransformType(E->getType());
  1173. if (T.isNull())
  1174. return ExprError();
  1175. // Transform each of the parameter expansions into the corresponding
  1176. // parameters in the instantiation of the function decl.
  1177. SmallVector<VarDecl *, 8> Vars;
  1178. Vars.reserve(E->getNumExpansions());
  1179. for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
  1180. I != End; ++I) {
  1181. VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
  1182. if (!D)
  1183. return ExprError();
  1184. Vars.push_back(D);
  1185. }
  1186. auto *PackExpr =
  1187. FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
  1188. E->getParameterPackLocation(), Vars);
  1189. getSema().MarkFunctionParmPackReferenced(PackExpr);
  1190. return PackExpr;
  1191. }
  1192. ExprResult
  1193. TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
  1194. VarDecl *PD) {
  1195. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  1196. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
  1197. = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
  1198. assert(Found && "no instantiation for parameter pack");
  1199. Decl *TransformedDecl;
  1200. if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
  1201. // If this is a reference to a function parameter pack which we can
  1202. // substitute but can't yet expand, build a FunctionParmPackExpr for it.
  1203. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1204. QualType T = TransformType(E->getType());
  1205. if (T.isNull())
  1206. return ExprError();
  1207. auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
  1208. E->getExprLoc(), *Pack);
  1209. getSema().MarkFunctionParmPackReferenced(PackExpr);
  1210. return PackExpr;
  1211. }
  1212. TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
  1213. } else {
  1214. TransformedDecl = Found->get<Decl*>();
  1215. }
  1216. // We have either an unexpanded pack or a specific expansion.
  1217. return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
  1218. }
  1219. ExprResult
  1220. TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
  1221. NamedDecl *D = E->getDecl();
  1222. // Handle references to non-type template parameters and non-type template
  1223. // parameter packs.
  1224. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
  1225. if (NTTP->getDepth() < TemplateArgs.getNumLevels())
  1226. return TransformTemplateParmRefExpr(E, NTTP);
  1227. // We have a non-type template parameter that isn't fully substituted;
  1228. // FindInstantiatedDecl will find it in the local instantiation scope.
  1229. }
  1230. // Handle references to function parameter packs.
  1231. if (VarDecl *PD = dyn_cast<VarDecl>(D))
  1232. if (PD->isParameterPack())
  1233. return TransformFunctionParmPackRefExpr(E, PD);
  1234. return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
  1235. }
  1236. ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
  1237. CXXDefaultArgExpr *E) {
  1238. assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
  1239. getDescribedFunctionTemplate() &&
  1240. "Default arg expressions are never formed in dependent cases.");
  1241. return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
  1242. cast<FunctionDecl>(E->getParam()->getDeclContext()),
  1243. E->getParam());
  1244. }
  1245. template<typename Fn>
  1246. QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
  1247. FunctionProtoTypeLoc TL,
  1248. CXXRecordDecl *ThisContext,
  1249. Qualifiers ThisTypeQuals,
  1250. Fn TransformExceptionSpec) {
  1251. // We need a local instantiation scope for this function prototype.
  1252. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1253. return inherited::TransformFunctionProtoType(
  1254. TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
  1255. }
  1256. ParmVarDecl *
  1257. TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
  1258. int indexAdjustment,
  1259. Optional<unsigned> NumExpansions,
  1260. bool ExpectParameterPack) {
  1261. return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
  1262. NumExpansions, ExpectParameterPack);
  1263. }
  1264. QualType
  1265. TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  1266. TemplateTypeParmTypeLoc TL) {
  1267. const TemplateTypeParmType *T = TL.getTypePtr();
  1268. if (T->getDepth() < TemplateArgs.getNumLevels()) {
  1269. // Replace the template type parameter with its corresponding
  1270. // template argument.
  1271. // If the corresponding template argument is NULL or doesn't exist, it's
  1272. // because we are performing instantiation from explicitly-specified
  1273. // template arguments in a function template class, but there were some
  1274. // arguments left unspecified.
  1275. if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
  1276. TemplateTypeParmTypeLoc NewTL
  1277. = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
  1278. NewTL.setNameLoc(TL.getNameLoc());
  1279. return TL.getType();
  1280. }
  1281. TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
  1282. if (T->isParameterPack()) {
  1283. assert(Arg.getKind() == TemplateArgument::Pack &&
  1284. "Missing argument pack");
  1285. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1286. // We have the template argument pack, but we're not expanding the
  1287. // enclosing pack expansion yet. Just save the template argument
  1288. // pack for later substitution.
  1289. QualType Result
  1290. = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
  1291. SubstTemplateTypeParmPackTypeLoc NewTL
  1292. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
  1293. NewTL.setNameLoc(TL.getNameLoc());
  1294. return Result;
  1295. }
  1296. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1297. }
  1298. assert(Arg.getKind() == TemplateArgument::Type &&
  1299. "Template argument kind mismatch");
  1300. QualType Replacement = Arg.getAsType();
  1301. // TODO: only do this uniquing once, at the start of instantiation.
  1302. QualType Result
  1303. = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
  1304. SubstTemplateTypeParmTypeLoc NewTL
  1305. = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1306. NewTL.setNameLoc(TL.getNameLoc());
  1307. return Result;
  1308. }
  1309. // The template type parameter comes from an inner template (e.g.,
  1310. // the template parameter list of a member template inside the
  1311. // template we are instantiating). Create a new template type
  1312. // parameter with the template "level" reduced by one.
  1313. TemplateTypeParmDecl *NewTTPDecl = nullptr;
  1314. if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
  1315. NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
  1316. TransformDecl(TL.getNameLoc(), OldTTPDecl));
  1317. QualType Result = getSema().Context.getTemplateTypeParmType(
  1318. T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
  1319. T->isParameterPack(), NewTTPDecl);
  1320. TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
  1321. NewTL.setNameLoc(TL.getNameLoc());
  1322. return Result;
  1323. }
  1324. QualType
  1325. TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
  1326. TypeLocBuilder &TLB,
  1327. SubstTemplateTypeParmPackTypeLoc TL) {
  1328. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1329. // We aren't expanding the parameter pack, so just return ourselves.
  1330. SubstTemplateTypeParmPackTypeLoc NewTL
  1331. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
  1332. NewTL.setNameLoc(TL.getNameLoc());
  1333. return TL.getType();
  1334. }
  1335. TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
  1336. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1337. QualType Result = Arg.getAsType();
  1338. Result = getSema().Context.getSubstTemplateTypeParmType(
  1339. TL.getTypePtr()->getReplacedParameter(),
  1340. Result);
  1341. SubstTemplateTypeParmTypeLoc NewTL
  1342. = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1343. NewTL.setNameLoc(TL.getNameLoc());
  1344. return Result;
  1345. }
  1346. /// Perform substitution on the type T with a given set of template
  1347. /// arguments.
  1348. ///
  1349. /// This routine substitutes the given template arguments into the
  1350. /// type T and produces the instantiated type.
  1351. ///
  1352. /// \param T the type into which the template arguments will be
  1353. /// substituted. If this type is not dependent, it will be returned
  1354. /// immediately.
  1355. ///
  1356. /// \param Args the template arguments that will be
  1357. /// substituted for the top-level template parameters within T.
  1358. ///
  1359. /// \param Loc the location in the source code where this substitution
  1360. /// is being performed. It will typically be the location of the
  1361. /// declarator (if we're instantiating the type of some declaration)
  1362. /// or the location of the type in the source code (if, e.g., we're
  1363. /// instantiating the type of a cast expression).
  1364. ///
  1365. /// \param Entity the name of the entity associated with a declaration
  1366. /// being instantiated (if any). May be empty to indicate that there
  1367. /// is no such entity (if, e.g., this is a type that occurs as part of
  1368. /// a cast expression) or that the entity has no name (e.g., an
  1369. /// unnamed function parameter).
  1370. ///
  1371. /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
  1372. /// acceptable as the top level type of the result.
  1373. ///
  1374. /// \returns If the instantiation succeeds, the instantiated
  1375. /// type. Otherwise, produces diagnostics and returns a NULL type.
  1376. TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
  1377. const MultiLevelTemplateArgumentList &Args,
  1378. SourceLocation Loc,
  1379. DeclarationName Entity,
  1380. bool AllowDeducedTST) {
  1381. assert(!CodeSynthesisContexts.empty() &&
  1382. "Cannot perform an instantiation without some context on the "
  1383. "instantiation stack");
  1384. if (!T->getType()->isInstantiationDependentType() &&
  1385. !T->getType()->isVariablyModifiedType())
  1386. return T;
  1387. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1388. return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
  1389. : Instantiator.TransformType(T);
  1390. }
  1391. TypeSourceInfo *Sema::SubstType(TypeLoc TL,
  1392. const MultiLevelTemplateArgumentList &Args,
  1393. SourceLocation Loc,
  1394. DeclarationName Entity) {
  1395. assert(!CodeSynthesisContexts.empty() &&
  1396. "Cannot perform an instantiation without some context on the "
  1397. "instantiation stack");
  1398. if (TL.getType().isNull())
  1399. return nullptr;
  1400. if (!TL.getType()->isInstantiationDependentType() &&
  1401. !TL.getType()->isVariablyModifiedType()) {
  1402. // FIXME: Make a copy of the TypeLoc data here, so that we can
  1403. // return a new TypeSourceInfo. Inefficient!
  1404. TypeLocBuilder TLB;
  1405. TLB.pushFullCopy(TL);
  1406. return TLB.getTypeSourceInfo(Context, TL.getType());
  1407. }
  1408. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1409. TypeLocBuilder TLB;
  1410. TLB.reserve(TL.getFullDataSize());
  1411. QualType Result = Instantiator.TransformType(TLB, TL);
  1412. if (Result.isNull())
  1413. return nullptr;
  1414. return TLB.getTypeSourceInfo(Context, Result);
  1415. }
  1416. /// Deprecated form of the above.
  1417. QualType Sema::SubstType(QualType T,
  1418. const MultiLevelTemplateArgumentList &TemplateArgs,
  1419. SourceLocation Loc, DeclarationName Entity) {
  1420. assert(!CodeSynthesisContexts.empty() &&
  1421. "Cannot perform an instantiation without some context on the "
  1422. "instantiation stack");
  1423. // If T is not a dependent type or a variably-modified type, there
  1424. // is nothing to do.
  1425. if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
  1426. return T;
  1427. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
  1428. return Instantiator.TransformType(T);
  1429. }
  1430. static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
  1431. if (T->getType()->isInstantiationDependentType() ||
  1432. T->getType()->isVariablyModifiedType())
  1433. return true;
  1434. TypeLoc TL = T->getTypeLoc().IgnoreParens();
  1435. if (!TL.getAs<FunctionProtoTypeLoc>())
  1436. return false;
  1437. FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
  1438. for (ParmVarDecl *P : FP.getParams()) {
  1439. // This must be synthesized from a typedef.
  1440. if (!P) continue;
  1441. // If there are any parameters, a new TypeSourceInfo that refers to the
  1442. // instantiated parameters must be built.
  1443. return true;
  1444. }
  1445. return false;
  1446. }
  1447. /// A form of SubstType intended specifically for instantiating the
  1448. /// type of a FunctionDecl. Its purpose is solely to force the
  1449. /// instantiation of default-argument expressions and to avoid
  1450. /// instantiating an exception-specification.
  1451. TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
  1452. const MultiLevelTemplateArgumentList &Args,
  1453. SourceLocation Loc,
  1454. DeclarationName Entity,
  1455. CXXRecordDecl *ThisContext,
  1456. Qualifiers ThisTypeQuals) {
  1457. assert(!CodeSynthesisContexts.empty() &&
  1458. "Cannot perform an instantiation without some context on the "
  1459. "instantiation stack");
  1460. if (!NeedsInstantiationAsFunctionType(T))
  1461. return T;
  1462. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1463. TypeLocBuilder TLB;
  1464. TypeLoc TL = T->getTypeLoc();
  1465. TLB.reserve(TL.getFullDataSize());
  1466. QualType Result;
  1467. if (FunctionProtoTypeLoc Proto =
  1468. TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
  1469. // Instantiate the type, other than its exception specification. The
  1470. // exception specification is instantiated in InitFunctionInstantiation
  1471. // once we've built the FunctionDecl.
  1472. // FIXME: Set the exception specification to EST_Uninstantiated here,
  1473. // instead of rebuilding the function type again later.
  1474. Result = Instantiator.TransformFunctionProtoType(
  1475. TLB, Proto, ThisContext, ThisTypeQuals,
  1476. [](FunctionProtoType::ExceptionSpecInfo &ESI,
  1477. bool &Changed) { return false; });
  1478. } else {
  1479. Result = Instantiator.TransformType(TLB, TL);
  1480. }
  1481. if (Result.isNull())
  1482. return nullptr;
  1483. return TLB.getTypeSourceInfo(Context, Result);
  1484. }
  1485. bool Sema::SubstExceptionSpec(SourceLocation Loc,
  1486. FunctionProtoType::ExceptionSpecInfo &ESI,
  1487. SmallVectorImpl<QualType> &ExceptionStorage,
  1488. const MultiLevelTemplateArgumentList &Args) {
  1489. assert(ESI.Type != EST_Uninstantiated);
  1490. bool Changed = false;
  1491. TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
  1492. return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
  1493. Changed);
  1494. }
  1495. void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
  1496. const MultiLevelTemplateArgumentList &Args) {
  1497. FunctionProtoType::ExceptionSpecInfo ESI =
  1498. Proto->getExtProtoInfo().ExceptionSpec;
  1499. SmallVector<QualType, 4> ExceptionStorage;
  1500. if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
  1501. ESI, ExceptionStorage, Args))
  1502. // On error, recover by dropping the exception specification.
  1503. ESI.Type = EST_None;
  1504. UpdateExceptionSpec(New, ESI);
  1505. }
  1506. ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
  1507. const MultiLevelTemplateArgumentList &TemplateArgs,
  1508. int indexAdjustment,
  1509. Optional<unsigned> NumExpansions,
  1510. bool ExpectParameterPack) {
  1511. TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
  1512. TypeSourceInfo *NewDI = nullptr;
  1513. TypeLoc OldTL = OldDI->getTypeLoc();
  1514. if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
  1515. // We have a function parameter pack. Substitute into the pattern of the
  1516. // expansion.
  1517. NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
  1518. OldParm->getLocation(), OldParm->getDeclName());
  1519. if (!NewDI)
  1520. return nullptr;
  1521. if (NewDI->getType()->containsUnexpandedParameterPack()) {
  1522. // We still have unexpanded parameter packs, which means that
  1523. // our function parameter is still a function parameter pack.
  1524. // Therefore, make its type a pack expansion type.
  1525. NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
  1526. NumExpansions);
  1527. } else if (ExpectParameterPack) {
  1528. // We expected to get a parameter pack but didn't (because the type
  1529. // itself is not a pack expansion type), so complain. This can occur when
  1530. // the substitution goes through an alias template that "loses" the
  1531. // pack expansion.
  1532. Diag(OldParm->getLocation(),
  1533. diag::err_function_parameter_pack_without_parameter_packs)
  1534. << NewDI->getType();
  1535. return nullptr;
  1536. }
  1537. } else {
  1538. NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
  1539. OldParm->getDeclName());
  1540. }
  1541. if (!NewDI)
  1542. return nullptr;
  1543. if (NewDI->getType()->isVoidType()) {
  1544. Diag(OldParm->getLocation(), diag::err_param_with_void_type);
  1545. return nullptr;
  1546. }
  1547. ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
  1548. OldParm->getInnerLocStart(),
  1549. OldParm->getLocation(),
  1550. OldParm->getIdentifier(),
  1551. NewDI->getType(), NewDI,
  1552. OldParm->getStorageClass());
  1553. if (!NewParm)
  1554. return nullptr;
  1555. // Mark the (new) default argument as uninstantiated (if any).
  1556. if (OldParm->hasUninstantiatedDefaultArg()) {
  1557. Expr *Arg = OldParm->getUninstantiatedDefaultArg();
  1558. NewParm->setUninstantiatedDefaultArg(Arg);
  1559. } else if (OldParm->hasUnparsedDefaultArg()) {
  1560. NewParm->setUnparsedDefaultArg();
  1561. UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
  1562. } else if (Expr *Arg = OldParm->getDefaultArg()) {
  1563. FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
  1564. if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
  1565. // Instantiate default arguments for methods of local classes (DR1484)
  1566. // and non-defining declarations.
  1567. Sema::ContextRAII SavedContext(*this, OwningFunc);
  1568. LocalInstantiationScope Local(*this, true);
  1569. ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
  1570. if (NewArg.isUsable()) {
  1571. // It would be nice if we still had this.
  1572. SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
  1573. SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
  1574. }
  1575. } else {
  1576. // FIXME: if we non-lazily instantiated non-dependent default args for
  1577. // non-dependent parameter types we could remove a bunch of duplicate
  1578. // conversion warnings for such arguments.
  1579. NewParm->setUninstantiatedDefaultArg(Arg);
  1580. }
  1581. }
  1582. NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
  1583. if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
  1584. // Add the new parameter to the instantiated parameter pack.
  1585. CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
  1586. } else {
  1587. // Introduce an Old -> New mapping
  1588. CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
  1589. }
  1590. // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
  1591. // can be anything, is this right ?
  1592. NewParm->setDeclContext(CurContext);
  1593. NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
  1594. OldParm->getFunctionScopeIndex() + indexAdjustment);
  1595. InstantiateAttrs(TemplateArgs, OldParm, NewParm);
  1596. return NewParm;
  1597. }
  1598. /// Substitute the given template arguments into the given set of
  1599. /// parameters, producing the set of parameter types that would be generated
  1600. /// from such a substitution.
  1601. bool Sema::SubstParmTypes(
  1602. SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
  1603. const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
  1604. const MultiLevelTemplateArgumentList &TemplateArgs,
  1605. SmallVectorImpl<QualType> &ParamTypes,
  1606. SmallVectorImpl<ParmVarDecl *> *OutParams,
  1607. ExtParameterInfoBuilder &ParamInfos) {
  1608. assert(!CodeSynthesisContexts.empty() &&
  1609. "Cannot perform an instantiation without some context on the "
  1610. "instantiation stack");
  1611. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  1612. DeclarationName());
  1613. return Instantiator.TransformFunctionTypeParams(
  1614. Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
  1615. }
  1616. /// Perform substitution on the base class specifiers of the
  1617. /// given class template specialization.
  1618. ///
  1619. /// Produces a diagnostic and returns true on error, returns false and
  1620. /// attaches the instantiated base classes to the class template
  1621. /// specialization if successful.
  1622. bool
  1623. Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
  1624. CXXRecordDecl *Pattern,
  1625. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1626. bool Invalid = false;
  1627. SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
  1628. for (const auto &Base : Pattern->bases()) {
  1629. if (!Base.getType()->isDependentType()) {
  1630. if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
  1631. if (RD->isInvalidDecl())
  1632. Instantiation->setInvalidDecl();
  1633. }
  1634. InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
  1635. continue;
  1636. }
  1637. SourceLocation EllipsisLoc;
  1638. TypeSourceInfo *BaseTypeLoc;
  1639. if (Base.isPackExpansion()) {
  1640. // This is a pack expansion. See whether we should expand it now, or
  1641. // wait until later.
  1642. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1643. collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
  1644. Unexpanded);
  1645. bool ShouldExpand = false;
  1646. bool RetainExpansion = false;
  1647. Optional<unsigned> NumExpansions;
  1648. if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
  1649. Base.getSourceRange(),
  1650. Unexpanded,
  1651. TemplateArgs, ShouldExpand,
  1652. RetainExpansion,
  1653. NumExpansions)) {
  1654. Invalid = true;
  1655. continue;
  1656. }
  1657. // If we should expand this pack expansion now, do so.
  1658. if (ShouldExpand) {
  1659. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1660. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  1661. TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  1662. TemplateArgs,
  1663. Base.getSourceRange().getBegin(),
  1664. DeclarationName());
  1665. if (!BaseTypeLoc) {
  1666. Invalid = true;
  1667. continue;
  1668. }
  1669. if (CXXBaseSpecifier *InstantiatedBase
  1670. = CheckBaseSpecifier(Instantiation,
  1671. Base.getSourceRange(),
  1672. Base.isVirtual(),
  1673. Base.getAccessSpecifierAsWritten(),
  1674. BaseTypeLoc,
  1675. SourceLocation()))
  1676. InstantiatedBases.push_back(InstantiatedBase);
  1677. else
  1678. Invalid = true;
  1679. }
  1680. continue;
  1681. }
  1682. // The resulting base specifier will (still) be a pack expansion.
  1683. EllipsisLoc = Base.getEllipsisLoc();
  1684. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  1685. BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  1686. TemplateArgs,
  1687. Base.getSourceRange().getBegin(),
  1688. DeclarationName());
  1689. } else {
  1690. BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  1691. TemplateArgs,
  1692. Base.getSourceRange().getBegin(),
  1693. DeclarationName());
  1694. }
  1695. if (!BaseTypeLoc) {
  1696. Invalid = true;
  1697. continue;
  1698. }
  1699. if (CXXBaseSpecifier *InstantiatedBase
  1700. = CheckBaseSpecifier(Instantiation,
  1701. Base.getSourceRange(),
  1702. Base.isVirtual(),
  1703. Base.getAccessSpecifierAsWritten(),
  1704. BaseTypeLoc,
  1705. EllipsisLoc))
  1706. InstantiatedBases.push_back(InstantiatedBase);
  1707. else
  1708. Invalid = true;
  1709. }
  1710. if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
  1711. Invalid = true;
  1712. return Invalid;
  1713. }
  1714. // Defined via #include from SemaTemplateInstantiateDecl.cpp
  1715. namespace clang {
  1716. namespace sema {
  1717. Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
  1718. const MultiLevelTemplateArgumentList &TemplateArgs);
  1719. Attr *instantiateTemplateAttributeForDecl(
  1720. const Attr *At, ASTContext &C, Sema &S,
  1721. const MultiLevelTemplateArgumentList &TemplateArgs);
  1722. }
  1723. }
  1724. /// Instantiate the definition of a class from a given pattern.
  1725. ///
  1726. /// \param PointOfInstantiation The point of instantiation within the
  1727. /// source code.
  1728. ///
  1729. /// \param Instantiation is the declaration whose definition is being
  1730. /// instantiated. This will be either a class template specialization
  1731. /// or a member class of a class template specialization.
  1732. ///
  1733. /// \param Pattern is the pattern from which the instantiation
  1734. /// occurs. This will be either the declaration of a class template or
  1735. /// the declaration of a member class of a class template.
  1736. ///
  1737. /// \param TemplateArgs The template arguments to be substituted into
  1738. /// the pattern.
  1739. ///
  1740. /// \param TSK the kind of implicit or explicit instantiation to perform.
  1741. ///
  1742. /// \param Complain whether to complain if the class cannot be instantiated due
  1743. /// to the lack of a definition.
  1744. ///
  1745. /// \returns true if an error occurred, false otherwise.
  1746. bool
  1747. Sema::InstantiateClass(SourceLocation PointOfInstantiation,
  1748. CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
  1749. const MultiLevelTemplateArgumentList &TemplateArgs,
  1750. TemplateSpecializationKind TSK,
  1751. bool Complain) {
  1752. CXXRecordDecl *PatternDef
  1753. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  1754. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
  1755. Instantiation->getInstantiatedFromMemberClass(),
  1756. Pattern, PatternDef, TSK, Complain))
  1757. return true;
  1758. llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
  1759. std::string Name;
  1760. llvm::raw_string_ostream OS(Name);
  1761. Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
  1762. /*Qualified=*/true);
  1763. return Name;
  1764. });
  1765. Pattern = PatternDef;
  1766. // Record the point of instantiation.
  1767. if (MemberSpecializationInfo *MSInfo
  1768. = Instantiation->getMemberSpecializationInfo()) {
  1769. MSInfo->setTemplateSpecializationKind(TSK);
  1770. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1771. } else if (ClassTemplateSpecializationDecl *Spec
  1772. = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
  1773. Spec->setTemplateSpecializationKind(TSK);
  1774. Spec->setPointOfInstantiation(PointOfInstantiation);
  1775. }
  1776. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  1777. if (Inst.isInvalid())
  1778. return true;
  1779. assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
  1780. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  1781. "instantiating class definition");
  1782. // Enter the scope of this instantiation. We don't use
  1783. // PushDeclContext because we don't have a scope.
  1784. ContextRAII SavedContext(*this, Instantiation);
  1785. EnterExpressionEvaluationContext EvalContext(
  1786. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  1787. // If this is an instantiation of a local class, merge this local
  1788. // instantiation scope with the enclosing scope. Otherwise, every
  1789. // instantiation of a class has its own local instantiation scope.
  1790. bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
  1791. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  1792. // Some class state isn't processed immediately but delayed till class
  1793. // instantiation completes. We may not be ready to handle any delayed state
  1794. // already on the stack as it might correspond to a different class, so save
  1795. // it now and put it back later.
  1796. SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
  1797. // Pull attributes from the pattern onto the instantiation.
  1798. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  1799. // Start the definition of this instantiation.
  1800. Instantiation->startDefinition();
  1801. // The instantiation is visible here, even if it was first declared in an
  1802. // unimported module.
  1803. Instantiation->setVisibleDespiteOwningModule();
  1804. // FIXME: This loses the as-written tag kind for an explicit instantiation.
  1805. Instantiation->setTagKind(Pattern->getTagKind());
  1806. // Do substitution on the base class specifiers.
  1807. if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
  1808. Instantiation->setInvalidDecl();
  1809. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  1810. SmallVector<Decl*, 4> Fields;
  1811. // Delay instantiation of late parsed attributes.
  1812. LateInstantiatedAttrVec LateAttrs;
  1813. Instantiator.enableLateAttributeInstantiation(&LateAttrs);
  1814. bool MightHaveConstexprVirtualFunctions = false;
  1815. for (auto *Member : Pattern->decls()) {
  1816. // Don't instantiate members not belonging in this semantic context.
  1817. // e.g. for:
  1818. // @code
  1819. // template <int i> class A {
  1820. // class B *g;
  1821. // };
  1822. // @endcode
  1823. // 'class B' has the template as lexical context but semantically it is
  1824. // introduced in namespace scope.
  1825. if (Member->getDeclContext() != Pattern)
  1826. continue;
  1827. // BlockDecls can appear in a default-member-initializer. They must be the
  1828. // child of a BlockExpr, so we only know how to instantiate them from there.
  1829. if (isa<BlockDecl>(Member))
  1830. continue;
  1831. if (Member->isInvalidDecl()) {
  1832. Instantiation->setInvalidDecl();
  1833. continue;
  1834. }
  1835. Decl *NewMember = Instantiator.Visit(Member);
  1836. if (NewMember) {
  1837. if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
  1838. Fields.push_back(Field);
  1839. } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
  1840. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  1841. // specialization causes the implicit instantiation of the definitions
  1842. // of unscoped member enumerations.
  1843. // Record a point of instantiation for this implicit instantiation.
  1844. if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
  1845. Enum->isCompleteDefinition()) {
  1846. MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
  1847. assert(MSInfo && "no spec info for member enum specialization");
  1848. MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
  1849. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1850. }
  1851. } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
  1852. if (SA->isFailed()) {
  1853. // A static_assert failed. Bail out; instantiating this
  1854. // class is probably not meaningful.
  1855. Instantiation->setInvalidDecl();
  1856. break;
  1857. }
  1858. } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
  1859. if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
  1860. (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
  1861. MightHaveConstexprVirtualFunctions = true;
  1862. }
  1863. if (NewMember->isInvalidDecl())
  1864. Instantiation->setInvalidDecl();
  1865. } else {
  1866. // FIXME: Eventually, a NULL return will mean that one of the
  1867. // instantiations was a semantic disaster, and we'll want to mark the
  1868. // declaration invalid.
  1869. // For now, we expect to skip some members that we can't yet handle.
  1870. }
  1871. }
  1872. // Finish checking fields.
  1873. ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
  1874. SourceLocation(), SourceLocation(), ParsedAttributesView());
  1875. CheckCompletedCXXClass(Instantiation);
  1876. // Default arguments are parsed, if not instantiated. We can go instantiate
  1877. // default arg exprs for default constructors if necessary now.
  1878. ActOnFinishCXXNonNestedClass(Instantiation);
  1879. // Instantiate late parsed attributes, and attach them to their decls.
  1880. // See Sema::InstantiateAttrs
  1881. for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
  1882. E = LateAttrs.end(); I != E; ++I) {
  1883. assert(CurrentInstantiationScope == Instantiator.getStartingScope());
  1884. CurrentInstantiationScope = I->Scope;
  1885. // Allow 'this' within late-parsed attributes.
  1886. NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
  1887. CXXRecordDecl *ThisContext =
  1888. dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  1889. CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
  1890. ND && ND->isCXXInstanceMember());
  1891. Attr *NewAttr =
  1892. instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
  1893. I->NewDecl->addAttr(NewAttr);
  1894. LocalInstantiationScope::deleteScopes(I->Scope,
  1895. Instantiator.getStartingScope());
  1896. }
  1897. Instantiator.disableLateAttributeInstantiation();
  1898. LateAttrs.clear();
  1899. ActOnFinishDelayedMemberInitializers(Instantiation);
  1900. // FIXME: We should do something similar for explicit instantiations so they
  1901. // end up in the right module.
  1902. if (TSK == TSK_ImplicitInstantiation) {
  1903. Instantiation->setLocation(Pattern->getLocation());
  1904. Instantiation->setLocStart(Pattern->getInnerLocStart());
  1905. Instantiation->setBraceRange(Pattern->getBraceRange());
  1906. }
  1907. if (!Instantiation->isInvalidDecl()) {
  1908. // Perform any dependent diagnostics from the pattern.
  1909. PerformDependentDiagnostics(Pattern, TemplateArgs);
  1910. // Instantiate any out-of-line class template partial
  1911. // specializations now.
  1912. for (TemplateDeclInstantiator::delayed_partial_spec_iterator
  1913. P = Instantiator.delayed_partial_spec_begin(),
  1914. PEnd = Instantiator.delayed_partial_spec_end();
  1915. P != PEnd; ++P) {
  1916. if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
  1917. P->first, P->second)) {
  1918. Instantiation->setInvalidDecl();
  1919. break;
  1920. }
  1921. }
  1922. // Instantiate any out-of-line variable template partial
  1923. // specializations now.
  1924. for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
  1925. P = Instantiator.delayed_var_partial_spec_begin(),
  1926. PEnd = Instantiator.delayed_var_partial_spec_end();
  1927. P != PEnd; ++P) {
  1928. if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
  1929. P->first, P->second)) {
  1930. Instantiation->setInvalidDecl();
  1931. break;
  1932. }
  1933. }
  1934. }
  1935. // Exit the scope of this instantiation.
  1936. SavedContext.pop();
  1937. if (!Instantiation->isInvalidDecl()) {
  1938. Consumer.HandleTagDeclDefinition(Instantiation);
  1939. // Always emit the vtable for an explicit instantiation definition
  1940. // of a polymorphic class template specialization. Otherwise, eagerly
  1941. // instantiate only constexpr virtual functions in preparation for their use
  1942. // in constant evaluation.
  1943. if (TSK == TSK_ExplicitInstantiationDefinition)
  1944. MarkVTableUsed(PointOfInstantiation, Instantiation, true);
  1945. else if (MightHaveConstexprVirtualFunctions)
  1946. MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
  1947. /*ConstexprOnly*/ true);
  1948. }
  1949. return Instantiation->isInvalidDecl();
  1950. }
  1951. /// Instantiate the definition of an enum from a given pattern.
  1952. ///
  1953. /// \param PointOfInstantiation The point of instantiation within the
  1954. /// source code.
  1955. /// \param Instantiation is the declaration whose definition is being
  1956. /// instantiated. This will be a member enumeration of a class
  1957. /// temploid specialization, or a local enumeration within a
  1958. /// function temploid specialization.
  1959. /// \param Pattern The templated declaration from which the instantiation
  1960. /// occurs.
  1961. /// \param TemplateArgs The template arguments to be substituted into
  1962. /// the pattern.
  1963. /// \param TSK The kind of implicit or explicit instantiation to perform.
  1964. ///
  1965. /// \return \c true if an error occurred, \c false otherwise.
  1966. bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
  1967. EnumDecl *Instantiation, EnumDecl *Pattern,
  1968. const MultiLevelTemplateArgumentList &TemplateArgs,
  1969. TemplateSpecializationKind TSK) {
  1970. EnumDecl *PatternDef = Pattern->getDefinition();
  1971. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
  1972. Instantiation->getInstantiatedFromMemberEnum(),
  1973. Pattern, PatternDef, TSK,/*Complain*/true))
  1974. return true;
  1975. Pattern = PatternDef;
  1976. // Record the point of instantiation.
  1977. if (MemberSpecializationInfo *MSInfo
  1978. = Instantiation->getMemberSpecializationInfo()) {
  1979. MSInfo->setTemplateSpecializationKind(TSK);
  1980. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1981. }
  1982. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  1983. if (Inst.isInvalid())
  1984. return true;
  1985. if (Inst.isAlreadyInstantiating())
  1986. return false;
  1987. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  1988. "instantiating enum definition");
  1989. // The instantiation is visible here, even if it was first declared in an
  1990. // unimported module.
  1991. Instantiation->setVisibleDespiteOwningModule();
  1992. // Enter the scope of this instantiation. We don't use
  1993. // PushDeclContext because we don't have a scope.
  1994. ContextRAII SavedContext(*this, Instantiation);
  1995. EnterExpressionEvaluationContext EvalContext(
  1996. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  1997. LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
  1998. // Pull attributes from the pattern onto the instantiation.
  1999. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  2000. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  2001. Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
  2002. // Exit the scope of this instantiation.
  2003. SavedContext.pop();
  2004. return Instantiation->isInvalidDecl();
  2005. }
  2006. /// Instantiate the definition of a field from the given pattern.
  2007. ///
  2008. /// \param PointOfInstantiation The point of instantiation within the
  2009. /// source code.
  2010. /// \param Instantiation is the declaration whose definition is being
  2011. /// instantiated. This will be a class of a class temploid
  2012. /// specialization, or a local enumeration within a function temploid
  2013. /// specialization.
  2014. /// \param Pattern The templated declaration from which the instantiation
  2015. /// occurs.
  2016. /// \param TemplateArgs The template arguments to be substituted into
  2017. /// the pattern.
  2018. ///
  2019. /// \return \c true if an error occurred, \c false otherwise.
  2020. bool Sema::InstantiateInClassInitializer(
  2021. SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
  2022. FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2023. // If there is no initializer, we don't need to do anything.
  2024. if (!Pattern->hasInClassInitializer())
  2025. return false;
  2026. assert(Instantiation->getInClassInitStyle() ==
  2027. Pattern->getInClassInitStyle() &&
  2028. "pattern and instantiation disagree about init style");
  2029. // Error out if we haven't parsed the initializer of the pattern yet because
  2030. // we are waiting for the closing brace of the outer class.
  2031. Expr *OldInit = Pattern->getInClassInitializer();
  2032. if (!OldInit) {
  2033. RecordDecl *PatternRD = Pattern->getParent();
  2034. RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
  2035. Diag(PointOfInstantiation,
  2036. diag::err_in_class_initializer_not_yet_parsed)
  2037. << OutermostClass << Pattern;
  2038. Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  2039. Instantiation->setInvalidDecl();
  2040. return true;
  2041. }
  2042. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  2043. if (Inst.isInvalid())
  2044. return true;
  2045. if (Inst.isAlreadyInstantiating()) {
  2046. // Error out if we hit an instantiation cycle for this initializer.
  2047. Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
  2048. << Instantiation;
  2049. return true;
  2050. }
  2051. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  2052. "instantiating default member init");
  2053. // Enter the scope of this instantiation. We don't use PushDeclContext because
  2054. // we don't have a scope.
  2055. ContextRAII SavedContext(*this, Instantiation->getParent());
  2056. EnterExpressionEvaluationContext EvalContext(
  2057. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  2058. LocalInstantiationScope Scope(*this, true);
  2059. // Instantiate the initializer.
  2060. ActOnStartCXXInClassMemberInitializer();
  2061. CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
  2062. ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
  2063. /*CXXDirectInit=*/false);
  2064. Expr *Init = NewInit.get();
  2065. assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
  2066. ActOnFinishCXXInClassMemberInitializer(
  2067. Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
  2068. if (auto *L = getASTMutationListener())
  2069. L->DefaultMemberInitializerInstantiated(Instantiation);
  2070. // Return true if the in-class initializer is still missing.
  2071. return !Instantiation->getInClassInitializer();
  2072. }
  2073. namespace {
  2074. /// A partial specialization whose template arguments have matched
  2075. /// a given template-id.
  2076. struct PartialSpecMatchResult {
  2077. ClassTemplatePartialSpecializationDecl *Partial;
  2078. TemplateArgumentList *Args;
  2079. };
  2080. }
  2081. bool Sema::usesPartialOrExplicitSpecialization(
  2082. SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
  2083. if (ClassTemplateSpec->getTemplateSpecializationKind() ==
  2084. TSK_ExplicitSpecialization)
  2085. return true;
  2086. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  2087. ClassTemplateSpec->getSpecializedTemplate()
  2088. ->getPartialSpecializations(PartialSpecs);
  2089. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  2090. TemplateDeductionInfo Info(Loc);
  2091. if (!DeduceTemplateArguments(PartialSpecs[I],
  2092. ClassTemplateSpec->getTemplateArgs(), Info))
  2093. return true;
  2094. }
  2095. return false;
  2096. }
  2097. /// Get the instantiation pattern to use to instantiate the definition of a
  2098. /// given ClassTemplateSpecializationDecl (either the pattern of the primary
  2099. /// template or of a partial specialization).
  2100. static CXXRecordDecl *
  2101. getPatternForClassTemplateSpecialization(
  2102. Sema &S, SourceLocation PointOfInstantiation,
  2103. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2104. TemplateSpecializationKind TSK, bool Complain) {
  2105. Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
  2106. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  2107. return nullptr;
  2108. llvm::PointerUnion<ClassTemplateDecl *,
  2109. ClassTemplatePartialSpecializationDecl *>
  2110. Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
  2111. if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
  2112. // Find best matching specialization.
  2113. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  2114. // C++ [temp.class.spec.match]p1:
  2115. // When a class template is used in a context that requires an
  2116. // instantiation of the class, it is necessary to determine
  2117. // whether the instantiation is to be generated using the primary
  2118. // template or one of the partial specializations. This is done by
  2119. // matching the template arguments of the class template
  2120. // specialization with the template argument lists of the partial
  2121. // specializations.
  2122. typedef PartialSpecMatchResult MatchResult;
  2123. SmallVector<MatchResult, 4> Matched;
  2124. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  2125. Template->getPartialSpecializations(PartialSpecs);
  2126. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
  2127. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  2128. ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  2129. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  2130. if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
  2131. Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
  2132. // Store the failed-deduction information for use in diagnostics, later.
  2133. // TODO: Actually use the failed-deduction info?
  2134. FailedCandidates.addCandidate().set(
  2135. DeclAccessPair::make(Template, AS_public), Partial,
  2136. MakeDeductionFailureInfo(S.Context, Result, Info));
  2137. (void)Result;
  2138. } else {
  2139. Matched.push_back(PartialSpecMatchResult());
  2140. Matched.back().Partial = Partial;
  2141. Matched.back().Args = Info.take();
  2142. }
  2143. }
  2144. // If we're dealing with a member template where the template parameters
  2145. // have been instantiated, this provides the original template parameters
  2146. // from which the member template's parameters were instantiated.
  2147. if (Matched.size() >= 1) {
  2148. SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
  2149. if (Matched.size() == 1) {
  2150. // -- If exactly one matching specialization is found, the
  2151. // instantiation is generated from that specialization.
  2152. // We don't need to do anything for this.
  2153. } else {
  2154. // -- If more than one matching specialization is found, the
  2155. // partial order rules (14.5.4.2) are used to determine
  2156. // whether one of the specializations is more specialized
  2157. // than the others. If none of the specializations is more
  2158. // specialized than all of the other matching
  2159. // specializations, then the use of the class template is
  2160. // ambiguous and the program is ill-formed.
  2161. for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
  2162. PEnd = Matched.end();
  2163. P != PEnd; ++P) {
  2164. if (S.getMoreSpecializedPartialSpecialization(
  2165. P->Partial, Best->Partial, PointOfInstantiation) ==
  2166. P->Partial)
  2167. Best = P;
  2168. }
  2169. // Determine if the best partial specialization is more specialized than
  2170. // the others.
  2171. bool Ambiguous = false;
  2172. for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
  2173. PEnd = Matched.end();
  2174. P != PEnd; ++P) {
  2175. if (P != Best && S.getMoreSpecializedPartialSpecialization(
  2176. P->Partial, Best->Partial,
  2177. PointOfInstantiation) != Best->Partial) {
  2178. Ambiguous = true;
  2179. break;
  2180. }
  2181. }
  2182. if (Ambiguous) {
  2183. // Partial ordering did not produce a clear winner. Complain.
  2184. Inst.Clear();
  2185. ClassTemplateSpec->setInvalidDecl();
  2186. S.Diag(PointOfInstantiation,
  2187. diag::err_partial_spec_ordering_ambiguous)
  2188. << ClassTemplateSpec;
  2189. // Print the matching partial specializations.
  2190. for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
  2191. PEnd = Matched.end();
  2192. P != PEnd; ++P)
  2193. S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
  2194. << S.getTemplateArgumentBindingsText(
  2195. P->Partial->getTemplateParameters(), *P->Args);
  2196. return nullptr;
  2197. }
  2198. }
  2199. ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
  2200. } else {
  2201. // -- If no matches are found, the instantiation is generated
  2202. // from the primary template.
  2203. }
  2204. }
  2205. CXXRecordDecl *Pattern = nullptr;
  2206. Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
  2207. if (auto *PartialSpec =
  2208. Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  2209. // Instantiate using the best class template partial specialization.
  2210. while (PartialSpec->getInstantiatedFromMember()) {
  2211. // If we've found an explicit specialization of this class template,
  2212. // stop here and use that as the pattern.
  2213. if (PartialSpec->isMemberSpecialization())
  2214. break;
  2215. PartialSpec = PartialSpec->getInstantiatedFromMember();
  2216. }
  2217. Pattern = PartialSpec;
  2218. } else {
  2219. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  2220. while (Template->getInstantiatedFromMemberTemplate()) {
  2221. // If we've found an explicit specialization of this class template,
  2222. // stop here and use that as the pattern.
  2223. if (Template->isMemberSpecialization())
  2224. break;
  2225. Template = Template->getInstantiatedFromMemberTemplate();
  2226. }
  2227. Pattern = Template->getTemplatedDecl();
  2228. }
  2229. return Pattern;
  2230. }
  2231. bool Sema::InstantiateClassTemplateSpecialization(
  2232. SourceLocation PointOfInstantiation,
  2233. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2234. TemplateSpecializationKind TSK, bool Complain) {
  2235. // Perform the actual instantiation on the canonical declaration.
  2236. ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
  2237. ClassTemplateSpec->getCanonicalDecl());
  2238. if (ClassTemplateSpec->isInvalidDecl())
  2239. return true;
  2240. CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
  2241. *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
  2242. if (!Pattern)
  2243. return true;
  2244. return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
  2245. getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
  2246. Complain);
  2247. }
  2248. /// Instantiates the definitions of all of the member
  2249. /// of the given class, which is an instantiation of a class template
  2250. /// or a member class of a template.
  2251. void
  2252. Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
  2253. CXXRecordDecl *Instantiation,
  2254. const MultiLevelTemplateArgumentList &TemplateArgs,
  2255. TemplateSpecializationKind TSK) {
  2256. // FIXME: We need to notify the ASTMutationListener that we did all of these
  2257. // things, in case we have an explicit instantiation definition in a PCM, a
  2258. // module, or preamble, and the declaration is in an imported AST.
  2259. assert(
  2260. (TSK == TSK_ExplicitInstantiationDefinition ||
  2261. TSK == TSK_ExplicitInstantiationDeclaration ||
  2262. (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
  2263. "Unexpected template specialization kind!");
  2264. for (auto *D : Instantiation->decls()) {
  2265. bool SuppressNew = false;
  2266. if (auto *Function = dyn_cast<FunctionDecl>(D)) {
  2267. if (FunctionDecl *Pattern =
  2268. Function->getInstantiatedFromMemberFunction()) {
  2269. if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  2270. continue;
  2271. MemberSpecializationInfo *MSInfo =
  2272. Function->getMemberSpecializationInfo();
  2273. assert(MSInfo && "No member specialization information?");
  2274. if (MSInfo->getTemplateSpecializationKind()
  2275. == TSK_ExplicitSpecialization)
  2276. continue;
  2277. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2278. Function,
  2279. MSInfo->getTemplateSpecializationKind(),
  2280. MSInfo->getPointOfInstantiation(),
  2281. SuppressNew) ||
  2282. SuppressNew)
  2283. continue;
  2284. // C++11 [temp.explicit]p8:
  2285. // An explicit instantiation definition that names a class template
  2286. // specialization explicitly instantiates the class template
  2287. // specialization and is only an explicit instantiation definition
  2288. // of members whose definition is visible at the point of
  2289. // instantiation.
  2290. if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
  2291. continue;
  2292. Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2293. if (Function->isDefined()) {
  2294. // Let the ASTConsumer know that this function has been explicitly
  2295. // instantiated now, and its linkage might have changed.
  2296. Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
  2297. } else if (TSK == TSK_ExplicitInstantiationDefinition) {
  2298. InstantiateFunctionDefinition(PointOfInstantiation, Function);
  2299. } else if (TSK == TSK_ImplicitInstantiation) {
  2300. PendingLocalImplicitInstantiations.push_back(
  2301. std::make_pair(Function, PointOfInstantiation));
  2302. }
  2303. }
  2304. } else if (auto *Var = dyn_cast<VarDecl>(D)) {
  2305. if (isa<VarTemplateSpecializationDecl>(Var))
  2306. continue;
  2307. if (Var->isStaticDataMember()) {
  2308. if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  2309. continue;
  2310. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  2311. assert(MSInfo && "No member specialization information?");
  2312. if (MSInfo->getTemplateSpecializationKind()
  2313. == TSK_ExplicitSpecialization)
  2314. continue;
  2315. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2316. Var,
  2317. MSInfo->getTemplateSpecializationKind(),
  2318. MSInfo->getPointOfInstantiation(),
  2319. SuppressNew) ||
  2320. SuppressNew)
  2321. continue;
  2322. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2323. // C++0x [temp.explicit]p8:
  2324. // An explicit instantiation definition that names a class template
  2325. // specialization explicitly instantiates the class template
  2326. // specialization and is only an explicit instantiation definition
  2327. // of members whose definition is visible at the point of
  2328. // instantiation.
  2329. if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
  2330. continue;
  2331. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2332. InstantiateVariableDefinition(PointOfInstantiation, Var);
  2333. } else {
  2334. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2335. }
  2336. }
  2337. } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
  2338. if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  2339. continue;
  2340. // Always skip the injected-class-name, along with any
  2341. // redeclarations of nested classes, since both would cause us
  2342. // to try to instantiate the members of a class twice.
  2343. // Skip closure types; they'll get instantiated when we instantiate
  2344. // the corresponding lambda-expression.
  2345. if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
  2346. Record->isLambda())
  2347. continue;
  2348. MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
  2349. assert(MSInfo && "No member specialization information?");
  2350. if (MSInfo->getTemplateSpecializationKind()
  2351. == TSK_ExplicitSpecialization)
  2352. continue;
  2353. if (Context.getTargetInfo().getTriple().isOSWindows() &&
  2354. TSK == TSK_ExplicitInstantiationDeclaration) {
  2355. // On Windows, explicit instantiation decl of the outer class doesn't
  2356. // affect the inner class. Typically extern template declarations are
  2357. // used in combination with dll import/export annotations, but those
  2358. // are not propagated from the outer class templates to inner classes.
  2359. // Therefore, do not instantiate inner classes on this platform, so
  2360. // that users don't end up with undefined symbols during linking.
  2361. continue;
  2362. }
  2363. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2364. Record,
  2365. MSInfo->getTemplateSpecializationKind(),
  2366. MSInfo->getPointOfInstantiation(),
  2367. SuppressNew) ||
  2368. SuppressNew)
  2369. continue;
  2370. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  2371. assert(Pattern && "Missing instantiated-from-template information");
  2372. if (!Record->getDefinition()) {
  2373. if (!Pattern->getDefinition()) {
  2374. // C++0x [temp.explicit]p8:
  2375. // An explicit instantiation definition that names a class template
  2376. // specialization explicitly instantiates the class template
  2377. // specialization and is only an explicit instantiation definition
  2378. // of members whose definition is visible at the point of
  2379. // instantiation.
  2380. if (TSK == TSK_ExplicitInstantiationDeclaration) {
  2381. MSInfo->setTemplateSpecializationKind(TSK);
  2382. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2383. }
  2384. continue;
  2385. }
  2386. InstantiateClass(PointOfInstantiation, Record, Pattern,
  2387. TemplateArgs,
  2388. TSK);
  2389. } else {
  2390. if (TSK == TSK_ExplicitInstantiationDefinition &&
  2391. Record->getTemplateSpecializationKind() ==
  2392. TSK_ExplicitInstantiationDeclaration) {
  2393. Record->setTemplateSpecializationKind(TSK);
  2394. MarkVTableUsed(PointOfInstantiation, Record, true);
  2395. }
  2396. }
  2397. Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  2398. if (Pattern)
  2399. InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
  2400. TSK);
  2401. } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
  2402. MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
  2403. assert(MSInfo && "No member specialization information?");
  2404. if (MSInfo->getTemplateSpecializationKind()
  2405. == TSK_ExplicitSpecialization)
  2406. continue;
  2407. if (CheckSpecializationInstantiationRedecl(
  2408. PointOfInstantiation, TSK, Enum,
  2409. MSInfo->getTemplateSpecializationKind(),
  2410. MSInfo->getPointOfInstantiation(), SuppressNew) ||
  2411. SuppressNew)
  2412. continue;
  2413. if (Enum->getDefinition())
  2414. continue;
  2415. EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
  2416. assert(Pattern && "Missing instantiated-from-template information");
  2417. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2418. if (!Pattern->getDefinition())
  2419. continue;
  2420. InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
  2421. } else {
  2422. MSInfo->setTemplateSpecializationKind(TSK);
  2423. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2424. }
  2425. } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
  2426. // No need to instantiate in-class initializers during explicit
  2427. // instantiation.
  2428. if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
  2429. CXXRecordDecl *ClassPattern =
  2430. Instantiation->getTemplateInstantiationPattern();
  2431. DeclContext::lookup_result Lookup =
  2432. ClassPattern->lookup(Field->getDeclName());
  2433. FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
  2434. InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
  2435. TemplateArgs);
  2436. }
  2437. }
  2438. }
  2439. }
  2440. /// Instantiate the definitions of all of the members of the
  2441. /// given class template specialization, which was named as part of an
  2442. /// explicit instantiation.
  2443. void
  2444. Sema::InstantiateClassTemplateSpecializationMembers(
  2445. SourceLocation PointOfInstantiation,
  2446. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2447. TemplateSpecializationKind TSK) {
  2448. // C++0x [temp.explicit]p7:
  2449. // An explicit instantiation that names a class template
  2450. // specialization is an explicit instantion of the same kind
  2451. // (declaration or definition) of each of its members (not
  2452. // including members inherited from base classes) that has not
  2453. // been previously explicitly specialized in the translation unit
  2454. // containing the explicit instantiation, except as described
  2455. // below.
  2456. InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
  2457. getTemplateInstantiationArgs(ClassTemplateSpec),
  2458. TSK);
  2459. }
  2460. StmtResult
  2461. Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2462. if (!S)
  2463. return S;
  2464. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2465. SourceLocation(),
  2466. DeclarationName());
  2467. return Instantiator.TransformStmt(S);
  2468. }
  2469. ExprResult
  2470. Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2471. if (!E)
  2472. return E;
  2473. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2474. SourceLocation(),
  2475. DeclarationName());
  2476. return Instantiator.TransformExpr(E);
  2477. }
  2478. ExprResult Sema::SubstInitializer(Expr *Init,
  2479. const MultiLevelTemplateArgumentList &TemplateArgs,
  2480. bool CXXDirectInit) {
  2481. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2482. SourceLocation(),
  2483. DeclarationName());
  2484. return Instantiator.TransformInitializer(Init, CXXDirectInit);
  2485. }
  2486. bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
  2487. const MultiLevelTemplateArgumentList &TemplateArgs,
  2488. SmallVectorImpl<Expr *> &Outputs) {
  2489. if (Exprs.empty())
  2490. return false;
  2491. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2492. SourceLocation(),
  2493. DeclarationName());
  2494. return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
  2495. IsCall, Outputs);
  2496. }
  2497. NestedNameSpecifierLoc
  2498. Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
  2499. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2500. if (!NNS)
  2501. return NestedNameSpecifierLoc();
  2502. TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
  2503. DeclarationName());
  2504. return Instantiator.TransformNestedNameSpecifierLoc(NNS);
  2505. }
  2506. /// Do template substitution on declaration name info.
  2507. DeclarationNameInfo
  2508. Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
  2509. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2510. TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
  2511. NameInfo.getName());
  2512. return Instantiator.TransformDeclarationNameInfo(NameInfo);
  2513. }
  2514. TemplateName
  2515. Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
  2516. TemplateName Name, SourceLocation Loc,
  2517. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2518. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  2519. DeclarationName());
  2520. CXXScopeSpec SS;
  2521. SS.Adopt(QualifierLoc);
  2522. return Instantiator.TransformTemplateName(SS, Name, Loc);
  2523. }
  2524. bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
  2525. TemplateArgumentListInfo &Result,
  2526. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2527. TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
  2528. DeclarationName());
  2529. return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
  2530. }
  2531. static const Decl *getCanonicalParmVarDecl(const Decl *D) {
  2532. // When storing ParmVarDecls in the local instantiation scope, we always
  2533. // want to use the ParmVarDecl from the canonical function declaration,
  2534. // since the map is then valid for any redeclaration or definition of that
  2535. // function.
  2536. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
  2537. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  2538. unsigned i = PV->getFunctionScopeIndex();
  2539. // This parameter might be from a freestanding function type within the
  2540. // function and isn't necessarily referring to one of FD's parameters.
  2541. if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
  2542. return FD->getCanonicalDecl()->getParamDecl(i);
  2543. }
  2544. }
  2545. return D;
  2546. }
  2547. llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
  2548. LocalInstantiationScope::findInstantiationOf(const Decl *D) {
  2549. D = getCanonicalParmVarDecl(D);
  2550. for (LocalInstantiationScope *Current = this; Current;
  2551. Current = Current->Outer) {
  2552. // Check if we found something within this scope.
  2553. const Decl *CheckD = D;
  2554. do {
  2555. LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
  2556. if (Found != Current->LocalDecls.end())
  2557. return &Found->second;
  2558. // If this is a tag declaration, it's possible that we need to look for
  2559. // a previous declaration.
  2560. if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
  2561. CheckD = Tag->getPreviousDecl();
  2562. else
  2563. CheckD = nullptr;
  2564. } while (CheckD);
  2565. // If we aren't combined with our outer scope, we're done.
  2566. if (!Current->CombineWithOuterScope)
  2567. break;
  2568. }
  2569. // If we're performing a partial substitution during template argument
  2570. // deduction, we may not have values for template parameters yet.
  2571. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  2572. isa<TemplateTemplateParmDecl>(D))
  2573. return nullptr;
  2574. // Local types referenced prior to definition may require instantiation.
  2575. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  2576. if (RD->isLocalClass())
  2577. return nullptr;
  2578. // Enumeration types referenced prior to definition may appear as a result of
  2579. // error recovery.
  2580. if (isa<EnumDecl>(D))
  2581. return nullptr;
  2582. // If we didn't find the decl, then we either have a sema bug, or we have a
  2583. // forward reference to a label declaration. Return null to indicate that
  2584. // we have an uninstantiated label.
  2585. assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
  2586. return nullptr;
  2587. }
  2588. void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
  2589. D = getCanonicalParmVarDecl(D);
  2590. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  2591. if (Stored.isNull()) {
  2592. #ifndef NDEBUG
  2593. // It should not be present in any surrounding scope either.
  2594. LocalInstantiationScope *Current = this;
  2595. while (Current->CombineWithOuterScope && Current->Outer) {
  2596. Current = Current->Outer;
  2597. assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
  2598. "Instantiated local in inner and outer scopes");
  2599. }
  2600. #endif
  2601. Stored = Inst;
  2602. } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
  2603. Pack->push_back(cast<VarDecl>(Inst));
  2604. } else {
  2605. assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
  2606. }
  2607. }
  2608. void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
  2609. VarDecl *Inst) {
  2610. D = getCanonicalParmVarDecl(D);
  2611. DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
  2612. Pack->push_back(Inst);
  2613. }
  2614. void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
  2615. #ifndef NDEBUG
  2616. // This should be the first time we've been told about this decl.
  2617. for (LocalInstantiationScope *Current = this;
  2618. Current && Current->CombineWithOuterScope; Current = Current->Outer)
  2619. assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
  2620. "Creating local pack after instantiation of local");
  2621. #endif
  2622. D = getCanonicalParmVarDecl(D);
  2623. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  2624. DeclArgumentPack *Pack = new DeclArgumentPack;
  2625. Stored = Pack;
  2626. ArgumentPacks.push_back(Pack);
  2627. }
  2628. void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
  2629. const TemplateArgument *ExplicitArgs,
  2630. unsigned NumExplicitArgs) {
  2631. assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
  2632. "Already have a partially-substituted pack");
  2633. assert((!PartiallySubstitutedPack
  2634. || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
  2635. "Wrong number of arguments in partially-substituted pack");
  2636. PartiallySubstitutedPack = Pack;
  2637. ArgsInPartiallySubstitutedPack = ExplicitArgs;
  2638. NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
  2639. }
  2640. NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
  2641. const TemplateArgument **ExplicitArgs,
  2642. unsigned *NumExplicitArgs) const {
  2643. if (ExplicitArgs)
  2644. *ExplicitArgs = nullptr;
  2645. if (NumExplicitArgs)
  2646. *NumExplicitArgs = 0;
  2647. for (const LocalInstantiationScope *Current = this; Current;
  2648. Current = Current->Outer) {
  2649. if (Current->PartiallySubstitutedPack) {
  2650. if (ExplicitArgs)
  2651. *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
  2652. if (NumExplicitArgs)
  2653. *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
  2654. return Current->PartiallySubstitutedPack;
  2655. }
  2656. if (!Current->CombineWithOuterScope)
  2657. break;
  2658. }
  2659. return nullptr;
  2660. }