SemaTemplateInstantiate.cpp 125 KB

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