SemaTemplateInstantiate.cpp 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156
  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 "TreeTransform.h"
  12. #include "clang/AST/ASTConcept.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/DeclBase.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprConcepts.h"
  21. #include "clang/AST/PrettyDeclStackTrace.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/AST/TypeVisitor.h"
  24. #include "clang/Basic/LangOptions.h"
  25. #include "clang/Basic/Stack.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/Initialization.h"
  29. #include "clang/Sema/Lookup.h"
  30. #include "clang/Sema/Sema.h"
  31. #include "clang/Sema/SemaConcept.h"
  32. #include "clang/Sema/SemaInternal.h"
  33. #include "clang/Sema/Template.h"
  34. #include "clang/Sema/TemplateDeduction.h"
  35. #include "clang/Sema/TemplateInstCallback.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/TimeProfiler.h"
  38. #include <optional>
  39. using namespace clang;
  40. using namespace sema;
  41. //===----------------------------------------------------------------------===/
  42. // Template Instantiation Support
  43. //===----------------------------------------------------------------------===/
  44. namespace {
  45. namespace TemplateInstArgsHelpers {
  46. struct Response {
  47. const Decl *NextDecl = nullptr;
  48. bool IsDone = false;
  49. bool ClearRelativeToPrimary = true;
  50. static Response Done() {
  51. Response R;
  52. R.IsDone = true;
  53. return R;
  54. }
  55. static Response ChangeDecl(const Decl *ND) {
  56. Response R;
  57. R.NextDecl = ND;
  58. return R;
  59. }
  60. static Response ChangeDecl(const DeclContext *Ctx) {
  61. Response R;
  62. R.NextDecl = Decl::castFromDeclContext(Ctx);
  63. return R;
  64. }
  65. static Response UseNextDecl(const Decl *CurDecl) {
  66. return ChangeDecl(CurDecl->getDeclContext());
  67. }
  68. static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
  69. Response R = Response::UseNextDecl(CurDecl);
  70. R.ClearRelativeToPrimary = false;
  71. return R;
  72. }
  73. };
  74. // Add template arguments from a variable template instantiation.
  75. Response
  76. HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
  77. MultiLevelTemplateArgumentList &Result,
  78. bool SkipForSpecialization) {
  79. // For a class-scope explicit specialization, there are no template arguments
  80. // at this level, but there may be enclosing template arguments.
  81. if (VarTemplSpec->isClassScopeExplicitSpecialization())
  82. return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
  83. // We're done when we hit an explicit specialization.
  84. if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  85. !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
  86. return Response::Done();
  87. // If this variable template specialization was instantiated from a
  88. // specialized member that is a variable template, we're done.
  89. assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
  90. llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
  91. Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
  92. if (VarTemplatePartialSpecializationDecl *Partial =
  93. Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  94. if (!SkipForSpecialization)
  95. Result.addOuterTemplateArguments(
  96. Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
  97. /*Final=*/false);
  98. if (Partial->isMemberSpecialization())
  99. return Response::Done();
  100. } else {
  101. VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
  102. if (!SkipForSpecialization)
  103. Result.addOuterTemplateArguments(
  104. Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
  105. /*Final=*/false);
  106. if (Tmpl->isMemberSpecialization())
  107. return Response::Done();
  108. }
  109. return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
  110. }
  111. // If we have a template template parameter with translation unit context,
  112. // then we're performing substitution into a default template argument of
  113. // this template template parameter before we've constructed the template
  114. // that will own this template template parameter. In this case, we
  115. // use empty template parameter lists for all of the outer templates
  116. // to avoid performing any substitutions.
  117. Response
  118. HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
  119. MultiLevelTemplateArgumentList &Result) {
  120. for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
  121. Result.addOuterTemplateArguments(std::nullopt);
  122. return Response::Done();
  123. }
  124. // Add template arguments from a class template instantiation.
  125. Response
  126. HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
  127. MultiLevelTemplateArgumentList &Result,
  128. bool SkipForSpecialization) {
  129. if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
  130. // We're done when we hit an explicit specialization.
  131. if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  132. !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
  133. return Response::Done();
  134. if (!SkipForSpecialization)
  135. Result.addOuterTemplateArguments(
  136. const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
  137. ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
  138. /*Final=*/false);
  139. // If this class template specialization was instantiated from a
  140. // specialized member that is a class template, we're done.
  141. assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
  142. if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
  143. return Response::Done();
  144. }
  145. return Response::UseNextDecl(ClassTemplSpec);
  146. }
  147. Response HandleFunction(const FunctionDecl *Function,
  148. MultiLevelTemplateArgumentList &Result,
  149. const FunctionDecl *Pattern, bool RelativeToPrimary,
  150. bool ForConstraintInstantiation) {
  151. // Add template arguments from a function template specialization.
  152. if (!RelativeToPrimary &&
  153. Function->getTemplateSpecializationKindForInstantiation() ==
  154. TSK_ExplicitSpecialization)
  155. return Response::Done();
  156. if (!RelativeToPrimary &&
  157. Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
  158. // This is an implicit instantiation of an explicit specialization. We
  159. // don't get any template arguments from this function but might get
  160. // some from an enclosing template.
  161. return Response::UseNextDecl(Function);
  162. } else if (const TemplateArgumentList *TemplateArgs =
  163. Function->getTemplateSpecializationArgs()) {
  164. // Add the template arguments for this specialization.
  165. Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
  166. TemplateArgs->asArray(),
  167. /*Final=*/false);
  168. // If this function was instantiated from a specialized member that is
  169. // a function template, we're done.
  170. assert(Function->getPrimaryTemplate() && "No function template?");
  171. if (Function->getPrimaryTemplate()->isMemberSpecialization())
  172. return Response::Done();
  173. // If this function is a generic lambda specialization, we are done.
  174. if (!ForConstraintInstantiation &&
  175. isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
  176. return Response::Done();
  177. } else if (Function->getDescribedFunctionTemplate()) {
  178. assert(
  179. (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
  180. "Outer template not instantiated?");
  181. }
  182. // If this is a friend or local declaration and it declares an entity at
  183. // namespace scope, take arguments from its lexical parent
  184. // instead of its semantic parent, unless of course the pattern we're
  185. // instantiating actually comes from the file's context!
  186. if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
  187. Function->getNonTransparentDeclContext()->isFileContext() &&
  188. (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
  189. return Response::ChangeDecl(Function->getLexicalDeclContext());
  190. }
  191. return Response::UseNextDecl(Function);
  192. }
  193. Response HandleRecordDecl(const CXXRecordDecl *Rec,
  194. MultiLevelTemplateArgumentList &Result,
  195. ASTContext &Context,
  196. bool ForConstraintInstantiation) {
  197. if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
  198. assert(
  199. (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
  200. "Outer template not instantiated?");
  201. if (ClassTemplate->isMemberSpecialization())
  202. return Response::Done();
  203. if (ForConstraintInstantiation) {
  204. QualType RecordType = Context.getTypeDeclType(Rec);
  205. QualType Injected = cast<InjectedClassNameType>(RecordType)
  206. ->getInjectedSpecializationType();
  207. const auto *InjectedType = cast<TemplateSpecializationType>(Injected);
  208. Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
  209. InjectedType->template_arguments(),
  210. /*Final=*/false);
  211. }
  212. }
  213. bool IsFriend = Rec->getFriendObjectKind() ||
  214. (Rec->getDescribedClassTemplate() &&
  215. Rec->getDescribedClassTemplate()->getFriendObjectKind());
  216. if (ForConstraintInstantiation && IsFriend &&
  217. Rec->getNonTransparentDeclContext()->isFileContext()) {
  218. return Response::ChangeDecl(Rec->getLexicalDeclContext());
  219. }
  220. // This is to make sure we pick up the VarTemplateSpecializationDecl that this
  221. // lambda is defined inside of.
  222. if (Rec->isLambda())
  223. if (const Decl *LCD = Rec->getLambdaContextDecl())
  224. return Response::ChangeDecl(LCD);
  225. return Response::UseNextDecl(Rec);
  226. }
  227. Response HandleImplicitConceptSpecializationDecl(
  228. const ImplicitConceptSpecializationDecl *CSD,
  229. MultiLevelTemplateArgumentList &Result) {
  230. Result.addOuterTemplateArguments(
  231. const_cast<ImplicitConceptSpecializationDecl *>(CSD),
  232. CSD->getTemplateArguments(),
  233. /*Final=*/false);
  234. return Response::UseNextDecl(CSD);
  235. }
  236. Response HandleGenericDeclContext(const Decl *CurDecl) {
  237. return Response::UseNextDecl(CurDecl);
  238. }
  239. } // namespace TemplateInstArgsHelpers
  240. } // namespace
  241. /// Retrieve the template argument list(s) that should be used to
  242. /// instantiate the definition of the given declaration.
  243. ///
  244. /// \param ND the declaration for which we are computing template instantiation
  245. /// arguments.
  246. ///
  247. /// \param Innermost if non-NULL, specifies a template argument list for the
  248. /// template declaration passed as ND.
  249. ///
  250. /// \param RelativeToPrimary true if we should get the template
  251. /// arguments relative to the primary template, even when we're
  252. /// dealing with a specialization. This is only relevant for function
  253. /// template specializations.
  254. ///
  255. /// \param Pattern If non-NULL, indicates the pattern from which we will be
  256. /// instantiating the definition of the given declaration, \p ND. This is
  257. /// used to determine the proper set of template instantiation arguments for
  258. /// friend function template specializations.
  259. ///
  260. /// \param ForConstraintInstantiation when collecting arguments,
  261. /// ForConstraintInstantiation indicates we should continue looking when
  262. /// encountering a lambda generic call operator, and continue looking for
  263. /// arguments on an enclosing class template.
  264. MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
  265. const NamedDecl *ND, bool Final, const TemplateArgumentList *Innermost,
  266. bool RelativeToPrimary, const FunctionDecl *Pattern,
  267. bool ForConstraintInstantiation, bool SkipForSpecialization) {
  268. assert(ND && "Can't find arguments for a decl if one isn't provided");
  269. // Accumulate the set of template argument lists in this structure.
  270. MultiLevelTemplateArgumentList Result;
  271. if (Innermost)
  272. Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND),
  273. Innermost->asArray(), Final);
  274. const Decl *CurDecl = ND;
  275. while (!CurDecl->isFileContextDecl()) {
  276. using namespace TemplateInstArgsHelpers;
  277. Response R;
  278. if (const auto *VarTemplSpec =
  279. dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
  280. R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
  281. } else if (const auto *ClassTemplSpec =
  282. dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
  283. R = HandleClassTemplateSpec(ClassTemplSpec, Result,
  284. SkipForSpecialization);
  285. } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
  286. R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
  287. ForConstraintInstantiation);
  288. } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
  289. R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
  290. } else if (const auto *CSD =
  291. dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
  292. R = HandleImplicitConceptSpecializationDecl(CSD, Result);
  293. } else if (!isa<DeclContext>(CurDecl)) {
  294. R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
  295. if (CurDecl->getDeclContext()->isTranslationUnit()) {
  296. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
  297. R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
  298. }
  299. }
  300. } else {
  301. R = HandleGenericDeclContext(CurDecl);
  302. }
  303. if (R.IsDone)
  304. return Result;
  305. if (R.ClearRelativeToPrimary)
  306. RelativeToPrimary = false;
  307. assert(R.NextDecl);
  308. CurDecl = R.NextDecl;
  309. }
  310. return Result;
  311. }
  312. bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
  313. switch (Kind) {
  314. case TemplateInstantiation:
  315. case ExceptionSpecInstantiation:
  316. case DefaultTemplateArgumentInstantiation:
  317. case DefaultFunctionArgumentInstantiation:
  318. case ExplicitTemplateArgumentSubstitution:
  319. case DeducedTemplateArgumentSubstitution:
  320. case PriorTemplateArgumentSubstitution:
  321. case ConstraintsCheck:
  322. case NestedRequirementConstraintsCheck:
  323. return true;
  324. case RequirementInstantiation:
  325. case RequirementParameterInstantiation:
  326. case DefaultTemplateArgumentChecking:
  327. case DeclaringSpecialMember:
  328. case DeclaringImplicitEqualityComparison:
  329. case DefiningSynthesizedFunction:
  330. case ExceptionSpecEvaluation:
  331. case ConstraintSubstitution:
  332. case ParameterMappingSubstitution:
  333. case ConstraintNormalization:
  334. case RewritingOperatorAsSpaceship:
  335. case InitializingStructuredBinding:
  336. case MarkingClassDllexported:
  337. case BuildingBuiltinDumpStructCall:
  338. return false;
  339. // This function should never be called when Kind's value is Memoization.
  340. case Memoization:
  341. break;
  342. }
  343. llvm_unreachable("Invalid SynthesisKind!");
  344. }
  345. Sema::InstantiatingTemplate::InstantiatingTemplate(
  346. Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
  347. SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
  348. Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
  349. sema::TemplateDeductionInfo *DeductionInfo)
  350. : SemaRef(SemaRef) {
  351. // Don't allow further instantiation if a fatal error and an uncompilable
  352. // error have occurred. Any diagnostics we might have raised will not be
  353. // visible, and we do not need to construct a correct AST.
  354. if (SemaRef.Diags.hasFatalErrorOccurred() &&
  355. SemaRef.hasUncompilableErrorOccurred()) {
  356. Invalid = true;
  357. return;
  358. }
  359. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  360. if (!Invalid) {
  361. CodeSynthesisContext Inst;
  362. Inst.Kind = Kind;
  363. Inst.PointOfInstantiation = PointOfInstantiation;
  364. Inst.Entity = Entity;
  365. Inst.Template = Template;
  366. Inst.TemplateArgs = TemplateArgs.data();
  367. Inst.NumTemplateArgs = TemplateArgs.size();
  368. Inst.DeductionInfo = DeductionInfo;
  369. Inst.InstantiationRange = InstantiationRange;
  370. SemaRef.pushCodeSynthesisContext(Inst);
  371. AlreadyInstantiating = !Inst.Entity ? false :
  372. !SemaRef.InstantiatingSpecializations
  373. .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
  374. .second;
  375. atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
  376. }
  377. }
  378. Sema::InstantiatingTemplate::InstantiatingTemplate(
  379. Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
  380. SourceRange InstantiationRange)
  381. : InstantiatingTemplate(SemaRef,
  382. CodeSynthesisContext::TemplateInstantiation,
  383. PointOfInstantiation, InstantiationRange, Entity) {}
  384. Sema::InstantiatingTemplate::InstantiatingTemplate(
  385. Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
  386. ExceptionSpecification, SourceRange InstantiationRange)
  387. : InstantiatingTemplate(
  388. SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
  389. PointOfInstantiation, InstantiationRange, Entity) {}
  390. Sema::InstantiatingTemplate::InstantiatingTemplate(
  391. Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
  392. TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
  393. SourceRange InstantiationRange)
  394. : InstantiatingTemplate(
  395. SemaRef,
  396. CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
  397. PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
  398. Template, TemplateArgs) {}
  399. Sema::InstantiatingTemplate::InstantiatingTemplate(
  400. Sema &SemaRef, SourceLocation PointOfInstantiation,
  401. FunctionTemplateDecl *FunctionTemplate,
  402. ArrayRef<TemplateArgument> TemplateArgs,
  403. CodeSynthesisContext::SynthesisKind Kind,
  404. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  405. : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
  406. InstantiationRange, FunctionTemplate, nullptr,
  407. TemplateArgs, &DeductionInfo) {
  408. assert(
  409. Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
  410. Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
  411. }
  412. Sema::InstantiatingTemplate::InstantiatingTemplate(
  413. Sema &SemaRef, SourceLocation PointOfInstantiation,
  414. TemplateDecl *Template,
  415. ArrayRef<TemplateArgument> TemplateArgs,
  416. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  417. : InstantiatingTemplate(
  418. SemaRef,
  419. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  420. PointOfInstantiation, InstantiationRange, Template, nullptr,
  421. TemplateArgs, &DeductionInfo) {}
  422. Sema::InstantiatingTemplate::InstantiatingTemplate(
  423. Sema &SemaRef, SourceLocation PointOfInstantiation,
  424. ClassTemplatePartialSpecializationDecl *PartialSpec,
  425. ArrayRef<TemplateArgument> TemplateArgs,
  426. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  427. : InstantiatingTemplate(
  428. SemaRef,
  429. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  430. PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
  431. TemplateArgs, &DeductionInfo) {}
  432. Sema::InstantiatingTemplate::InstantiatingTemplate(
  433. Sema &SemaRef, SourceLocation PointOfInstantiation,
  434. VarTemplatePartialSpecializationDecl *PartialSpec,
  435. ArrayRef<TemplateArgument> TemplateArgs,
  436. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  437. : InstantiatingTemplate(
  438. SemaRef,
  439. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  440. PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
  441. TemplateArgs, &DeductionInfo) {}
  442. Sema::InstantiatingTemplate::InstantiatingTemplate(
  443. Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
  444. ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
  445. : InstantiatingTemplate(
  446. SemaRef,
  447. CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
  448. PointOfInstantiation, InstantiationRange, Param, nullptr,
  449. TemplateArgs) {}
  450. Sema::InstantiatingTemplate::InstantiatingTemplate(
  451. Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
  452. NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  453. SourceRange InstantiationRange)
  454. : InstantiatingTemplate(
  455. SemaRef,
  456. CodeSynthesisContext::PriorTemplateArgumentSubstitution,
  457. PointOfInstantiation, InstantiationRange, Param, Template,
  458. TemplateArgs) {}
  459. Sema::InstantiatingTemplate::InstantiatingTemplate(
  460. Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
  461. TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  462. SourceRange InstantiationRange)
  463. : InstantiatingTemplate(
  464. SemaRef,
  465. CodeSynthesisContext::PriorTemplateArgumentSubstitution,
  466. PointOfInstantiation, InstantiationRange, Param, Template,
  467. TemplateArgs) {}
  468. Sema::InstantiatingTemplate::InstantiatingTemplate(
  469. Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
  470. NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  471. SourceRange InstantiationRange)
  472. : InstantiatingTemplate(
  473. SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
  474. PointOfInstantiation, InstantiationRange, Param, Template,
  475. TemplateArgs) {}
  476. Sema::InstantiatingTemplate::InstantiatingTemplate(
  477. Sema &SemaRef, SourceLocation PointOfInstantiation,
  478. concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
  479. SourceRange InstantiationRange)
  480. : InstantiatingTemplate(
  481. SemaRef, CodeSynthesisContext::RequirementInstantiation,
  482. PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
  483. /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
  484. }
  485. Sema::InstantiatingTemplate::InstantiatingTemplate(
  486. Sema &SemaRef, SourceLocation PointOfInstantiation,
  487. concepts::NestedRequirement *Req, ConstraintsCheck,
  488. SourceRange InstantiationRange)
  489. : InstantiatingTemplate(
  490. SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
  491. PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
  492. /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
  493. Sema::InstantiatingTemplate::InstantiatingTemplate(
  494. Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
  495. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  496. : InstantiatingTemplate(
  497. SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
  498. PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
  499. /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
  500. }
  501. Sema::InstantiatingTemplate::InstantiatingTemplate(
  502. Sema &SemaRef, SourceLocation PointOfInstantiation,
  503. ConstraintsCheck, NamedDecl *Template,
  504. ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
  505. : InstantiatingTemplate(
  506. SemaRef, CodeSynthesisContext::ConstraintsCheck,
  507. PointOfInstantiation, InstantiationRange, Template, nullptr,
  508. TemplateArgs) {}
  509. Sema::InstantiatingTemplate::InstantiatingTemplate(
  510. Sema &SemaRef, SourceLocation PointOfInstantiation,
  511. ConstraintSubstitution, NamedDecl *Template,
  512. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  513. : InstantiatingTemplate(
  514. SemaRef, CodeSynthesisContext::ConstraintSubstitution,
  515. PointOfInstantiation, InstantiationRange, Template, nullptr,
  516. {}, &DeductionInfo) {}
  517. Sema::InstantiatingTemplate::InstantiatingTemplate(
  518. Sema &SemaRef, SourceLocation PointOfInstantiation,
  519. ConstraintNormalization, NamedDecl *Template,
  520. SourceRange InstantiationRange)
  521. : InstantiatingTemplate(
  522. SemaRef, CodeSynthesisContext::ConstraintNormalization,
  523. PointOfInstantiation, InstantiationRange, Template) {}
  524. Sema::InstantiatingTemplate::InstantiatingTemplate(
  525. Sema &SemaRef, SourceLocation PointOfInstantiation,
  526. ParameterMappingSubstitution, NamedDecl *Template,
  527. SourceRange InstantiationRange)
  528. : InstantiatingTemplate(
  529. SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
  530. PointOfInstantiation, InstantiationRange, Template) {}
  531. void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
  532. Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
  533. InNonInstantiationSFINAEContext = false;
  534. CodeSynthesisContexts.push_back(Ctx);
  535. if (!Ctx.isInstantiationRecord())
  536. ++NonInstantiationEntries;
  537. // Check to see if we're low on stack space. We can't do anything about this
  538. // from here, but we can at least warn the user.
  539. if (isStackNearlyExhausted())
  540. warnStackExhausted(Ctx.PointOfInstantiation);
  541. }
  542. void Sema::popCodeSynthesisContext() {
  543. auto &Active = CodeSynthesisContexts.back();
  544. if (!Active.isInstantiationRecord()) {
  545. assert(NonInstantiationEntries > 0);
  546. --NonInstantiationEntries;
  547. }
  548. InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
  549. // Name lookup no longer looks in this template's defining module.
  550. assert(CodeSynthesisContexts.size() >=
  551. CodeSynthesisContextLookupModules.size() &&
  552. "forgot to remove a lookup module for a template instantiation");
  553. if (CodeSynthesisContexts.size() ==
  554. CodeSynthesisContextLookupModules.size()) {
  555. if (Module *M = CodeSynthesisContextLookupModules.back())
  556. LookupModulesCache.erase(M);
  557. CodeSynthesisContextLookupModules.pop_back();
  558. }
  559. // If we've left the code synthesis context for the current context stack,
  560. // stop remembering that we've emitted that stack.
  561. if (CodeSynthesisContexts.size() ==
  562. LastEmittedCodeSynthesisContextDepth)
  563. LastEmittedCodeSynthesisContextDepth = 0;
  564. CodeSynthesisContexts.pop_back();
  565. }
  566. void Sema::InstantiatingTemplate::Clear() {
  567. if (!Invalid) {
  568. if (!AlreadyInstantiating) {
  569. auto &Active = SemaRef.CodeSynthesisContexts.back();
  570. if (Active.Entity)
  571. SemaRef.InstantiatingSpecializations.erase(
  572. {Active.Entity->getCanonicalDecl(), Active.Kind});
  573. }
  574. atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
  575. SemaRef.CodeSynthesisContexts.back());
  576. SemaRef.popCodeSynthesisContext();
  577. Invalid = true;
  578. }
  579. }
  580. static std::string convertCallArgsToString(Sema &S,
  581. llvm::ArrayRef<const Expr *> Args) {
  582. std::string Result;
  583. llvm::raw_string_ostream OS(Result);
  584. llvm::ListSeparator Comma;
  585. for (const Expr *Arg : Args) {
  586. OS << Comma;
  587. Arg->IgnoreParens()->printPretty(OS, nullptr,
  588. S.Context.getPrintingPolicy());
  589. }
  590. return Result;
  591. }
  592. bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
  593. SourceLocation PointOfInstantiation,
  594. SourceRange InstantiationRange) {
  595. assert(SemaRef.NonInstantiationEntries <=
  596. SemaRef.CodeSynthesisContexts.size());
  597. if ((SemaRef.CodeSynthesisContexts.size() -
  598. SemaRef.NonInstantiationEntries)
  599. <= SemaRef.getLangOpts().InstantiationDepth)
  600. return false;
  601. SemaRef.Diag(PointOfInstantiation,
  602. diag::err_template_recursion_depth_exceeded)
  603. << SemaRef.getLangOpts().InstantiationDepth
  604. << InstantiationRange;
  605. SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
  606. << SemaRef.getLangOpts().InstantiationDepth;
  607. return true;
  608. }
  609. /// Prints the current instantiation stack through a series of
  610. /// notes.
  611. void Sema::PrintInstantiationStack() {
  612. // Determine which template instantiations to skip, if any.
  613. unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
  614. unsigned Limit = Diags.getTemplateBacktraceLimit();
  615. if (Limit && Limit < CodeSynthesisContexts.size()) {
  616. SkipStart = Limit / 2 + Limit % 2;
  617. SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
  618. }
  619. // FIXME: In all of these cases, we need to show the template arguments
  620. unsigned InstantiationIdx = 0;
  621. for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
  622. Active = CodeSynthesisContexts.rbegin(),
  623. ActiveEnd = CodeSynthesisContexts.rend();
  624. Active != ActiveEnd;
  625. ++Active, ++InstantiationIdx) {
  626. // Skip this instantiation?
  627. if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
  628. if (InstantiationIdx == SkipStart) {
  629. // Note that we're skipping instantiations.
  630. Diags.Report(Active->PointOfInstantiation,
  631. diag::note_instantiation_contexts_suppressed)
  632. << unsigned(CodeSynthesisContexts.size() - Limit);
  633. }
  634. continue;
  635. }
  636. switch (Active->Kind) {
  637. case CodeSynthesisContext::TemplateInstantiation: {
  638. Decl *D = Active->Entity;
  639. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  640. unsigned DiagID = diag::note_template_member_class_here;
  641. if (isa<ClassTemplateSpecializationDecl>(Record))
  642. DiagID = diag::note_template_class_instantiation_here;
  643. Diags.Report(Active->PointOfInstantiation, DiagID)
  644. << Record << Active->InstantiationRange;
  645. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  646. unsigned DiagID;
  647. if (Function->getPrimaryTemplate())
  648. DiagID = diag::note_function_template_spec_here;
  649. else
  650. DiagID = diag::note_template_member_function_here;
  651. Diags.Report(Active->PointOfInstantiation, DiagID)
  652. << Function
  653. << Active->InstantiationRange;
  654. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  655. Diags.Report(Active->PointOfInstantiation,
  656. VD->isStaticDataMember()?
  657. diag::note_template_static_data_member_def_here
  658. : diag::note_template_variable_def_here)
  659. << VD
  660. << Active->InstantiationRange;
  661. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  662. Diags.Report(Active->PointOfInstantiation,
  663. diag::note_template_enum_def_here)
  664. << ED
  665. << Active->InstantiationRange;
  666. } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  667. Diags.Report(Active->PointOfInstantiation,
  668. diag::note_template_nsdmi_here)
  669. << FD << Active->InstantiationRange;
  670. } else {
  671. Diags.Report(Active->PointOfInstantiation,
  672. diag::note_template_type_alias_instantiation_here)
  673. << cast<TypeAliasTemplateDecl>(D)
  674. << Active->InstantiationRange;
  675. }
  676. break;
  677. }
  678. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
  679. TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
  680. SmallString<128> TemplateArgsStr;
  681. llvm::raw_svector_ostream OS(TemplateArgsStr);
  682. Template->printName(OS, getPrintingPolicy());
  683. printTemplateArgumentList(OS, Active->template_arguments(),
  684. getPrintingPolicy());
  685. Diags.Report(Active->PointOfInstantiation,
  686. diag::note_default_arg_instantiation_here)
  687. << OS.str()
  688. << Active->InstantiationRange;
  689. break;
  690. }
  691. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
  692. FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
  693. Diags.Report(Active->PointOfInstantiation,
  694. diag::note_explicit_template_arg_substitution_here)
  695. << FnTmpl
  696. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  697. Active->TemplateArgs,
  698. Active->NumTemplateArgs)
  699. << Active->InstantiationRange;
  700. break;
  701. }
  702. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
  703. if (FunctionTemplateDecl *FnTmpl =
  704. dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
  705. Diags.Report(Active->PointOfInstantiation,
  706. diag::note_function_template_deduction_instantiation_here)
  707. << FnTmpl
  708. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  709. Active->TemplateArgs,
  710. Active->NumTemplateArgs)
  711. << Active->InstantiationRange;
  712. } else {
  713. bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
  714. isa<VarTemplateSpecializationDecl>(Active->Entity);
  715. bool IsTemplate = false;
  716. TemplateParameterList *Params;
  717. if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
  718. IsTemplate = true;
  719. Params = D->getTemplateParameters();
  720. } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
  721. Active->Entity)) {
  722. Params = D->getTemplateParameters();
  723. } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
  724. Active->Entity)) {
  725. Params = D->getTemplateParameters();
  726. } else {
  727. llvm_unreachable("unexpected template kind");
  728. }
  729. Diags.Report(Active->PointOfInstantiation,
  730. diag::note_deduced_template_arg_substitution_here)
  731. << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
  732. << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
  733. Active->NumTemplateArgs)
  734. << Active->InstantiationRange;
  735. }
  736. break;
  737. }
  738. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
  739. ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
  740. FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
  741. SmallString<128> TemplateArgsStr;
  742. llvm::raw_svector_ostream OS(TemplateArgsStr);
  743. FD->printName(OS, getPrintingPolicy());
  744. printTemplateArgumentList(OS, Active->template_arguments(),
  745. getPrintingPolicy());
  746. Diags.Report(Active->PointOfInstantiation,
  747. diag::note_default_function_arg_instantiation_here)
  748. << OS.str()
  749. << Active->InstantiationRange;
  750. break;
  751. }
  752. case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
  753. NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
  754. std::string Name;
  755. if (!Parm->getName().empty())
  756. Name = std::string(" '") + Parm->getName().str() + "'";
  757. TemplateParameterList *TemplateParams = nullptr;
  758. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  759. TemplateParams = Template->getTemplateParameters();
  760. else
  761. TemplateParams =
  762. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  763. ->getTemplateParameters();
  764. Diags.Report(Active->PointOfInstantiation,
  765. diag::note_prior_template_arg_substitution)
  766. << isa<TemplateTemplateParmDecl>(Parm)
  767. << Name
  768. << getTemplateArgumentBindingsText(TemplateParams,
  769. Active->TemplateArgs,
  770. Active->NumTemplateArgs)
  771. << Active->InstantiationRange;
  772. break;
  773. }
  774. case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
  775. TemplateParameterList *TemplateParams = nullptr;
  776. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  777. TemplateParams = Template->getTemplateParameters();
  778. else
  779. TemplateParams =
  780. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  781. ->getTemplateParameters();
  782. Diags.Report(Active->PointOfInstantiation,
  783. diag::note_template_default_arg_checking)
  784. << getTemplateArgumentBindingsText(TemplateParams,
  785. Active->TemplateArgs,
  786. Active->NumTemplateArgs)
  787. << Active->InstantiationRange;
  788. break;
  789. }
  790. case CodeSynthesisContext::ExceptionSpecEvaluation:
  791. Diags.Report(Active->PointOfInstantiation,
  792. diag::note_evaluating_exception_spec_here)
  793. << cast<FunctionDecl>(Active->Entity);
  794. break;
  795. case CodeSynthesisContext::ExceptionSpecInstantiation:
  796. Diags.Report(Active->PointOfInstantiation,
  797. diag::note_template_exception_spec_instantiation_here)
  798. << cast<FunctionDecl>(Active->Entity)
  799. << Active->InstantiationRange;
  800. break;
  801. case CodeSynthesisContext::RequirementInstantiation:
  802. Diags.Report(Active->PointOfInstantiation,
  803. diag::note_template_requirement_instantiation_here)
  804. << Active->InstantiationRange;
  805. break;
  806. case CodeSynthesisContext::RequirementParameterInstantiation:
  807. Diags.Report(Active->PointOfInstantiation,
  808. diag::note_template_requirement_params_instantiation_here)
  809. << Active->InstantiationRange;
  810. break;
  811. case CodeSynthesisContext::NestedRequirementConstraintsCheck:
  812. Diags.Report(Active->PointOfInstantiation,
  813. diag::note_nested_requirement_here)
  814. << Active->InstantiationRange;
  815. break;
  816. case CodeSynthesisContext::DeclaringSpecialMember:
  817. Diags.Report(Active->PointOfInstantiation,
  818. diag::note_in_declaration_of_implicit_special_member)
  819. << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
  820. break;
  821. case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
  822. Diags.Report(Active->Entity->getLocation(),
  823. diag::note_in_declaration_of_implicit_equality_comparison);
  824. break;
  825. case CodeSynthesisContext::DefiningSynthesizedFunction: {
  826. // FIXME: For synthesized functions that are not defaulted,
  827. // produce a note.
  828. auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
  829. DefaultedFunctionKind DFK =
  830. FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
  831. if (DFK.isSpecialMember()) {
  832. auto *MD = cast<CXXMethodDecl>(FD);
  833. Diags.Report(Active->PointOfInstantiation,
  834. diag::note_member_synthesized_at)
  835. << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
  836. << Context.getTagDeclType(MD->getParent());
  837. } else if (DFK.isComparison()) {
  838. Diags.Report(Active->PointOfInstantiation,
  839. diag::note_comparison_synthesized_at)
  840. << (int)DFK.asComparison()
  841. << Context.getTagDeclType(
  842. cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
  843. }
  844. break;
  845. }
  846. case CodeSynthesisContext::RewritingOperatorAsSpaceship:
  847. Diags.Report(Active->Entity->getLocation(),
  848. diag::note_rewriting_operator_as_spaceship);
  849. break;
  850. case CodeSynthesisContext::InitializingStructuredBinding:
  851. Diags.Report(Active->PointOfInstantiation,
  852. diag::note_in_binding_decl_init)
  853. << cast<BindingDecl>(Active->Entity);
  854. break;
  855. case CodeSynthesisContext::MarkingClassDllexported:
  856. Diags.Report(Active->PointOfInstantiation,
  857. diag::note_due_to_dllexported_class)
  858. << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
  859. break;
  860. case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
  861. Diags.Report(Active->PointOfInstantiation,
  862. diag::note_building_builtin_dump_struct_call)
  863. << convertCallArgsToString(
  864. *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
  865. break;
  866. case CodeSynthesisContext::Memoization:
  867. break;
  868. case CodeSynthesisContext::ConstraintsCheck: {
  869. unsigned DiagID = 0;
  870. if (!Active->Entity) {
  871. Diags.Report(Active->PointOfInstantiation,
  872. diag::note_nested_requirement_here)
  873. << Active->InstantiationRange;
  874. break;
  875. }
  876. if (isa<ConceptDecl>(Active->Entity))
  877. DiagID = diag::note_concept_specialization_here;
  878. else if (isa<TemplateDecl>(Active->Entity))
  879. DiagID = diag::note_checking_constraints_for_template_id_here;
  880. else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
  881. DiagID = diag::note_checking_constraints_for_var_spec_id_here;
  882. else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
  883. DiagID = diag::note_checking_constraints_for_class_spec_id_here;
  884. else {
  885. assert(isa<FunctionDecl>(Active->Entity));
  886. DiagID = diag::note_checking_constraints_for_function_here;
  887. }
  888. SmallString<128> TemplateArgsStr;
  889. llvm::raw_svector_ostream OS(TemplateArgsStr);
  890. cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
  891. if (!isa<FunctionDecl>(Active->Entity)) {
  892. printTemplateArgumentList(OS, Active->template_arguments(),
  893. getPrintingPolicy());
  894. }
  895. Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
  896. << Active->InstantiationRange;
  897. break;
  898. }
  899. case CodeSynthesisContext::ConstraintSubstitution:
  900. Diags.Report(Active->PointOfInstantiation,
  901. diag::note_constraint_substitution_here)
  902. << Active->InstantiationRange;
  903. break;
  904. case CodeSynthesisContext::ConstraintNormalization:
  905. Diags.Report(Active->PointOfInstantiation,
  906. diag::note_constraint_normalization_here)
  907. << cast<NamedDecl>(Active->Entity)->getName()
  908. << Active->InstantiationRange;
  909. break;
  910. case CodeSynthesisContext::ParameterMappingSubstitution:
  911. Diags.Report(Active->PointOfInstantiation,
  912. diag::note_parameter_mapping_substitution_here)
  913. << Active->InstantiationRange;
  914. break;
  915. }
  916. }
  917. }
  918. std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
  919. if (InNonInstantiationSFINAEContext)
  920. return std::optional<TemplateDeductionInfo *>(nullptr);
  921. for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
  922. Active = CodeSynthesisContexts.rbegin(),
  923. ActiveEnd = CodeSynthesisContexts.rend();
  924. Active != ActiveEnd;
  925. ++Active)
  926. {
  927. switch (Active->Kind) {
  928. case CodeSynthesisContext::TemplateInstantiation:
  929. // An instantiation of an alias template may or may not be a SFINAE
  930. // context, depending on what else is on the stack.
  931. if (isa<TypeAliasTemplateDecl>(Active->Entity))
  932. break;
  933. [[fallthrough]];
  934. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  935. case CodeSynthesisContext::ExceptionSpecInstantiation:
  936. case CodeSynthesisContext::ConstraintsCheck:
  937. case CodeSynthesisContext::ParameterMappingSubstitution:
  938. case CodeSynthesisContext::ConstraintNormalization:
  939. case CodeSynthesisContext::NestedRequirementConstraintsCheck:
  940. // This is a template instantiation, so there is no SFINAE.
  941. return std::nullopt;
  942. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  943. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  944. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  945. case CodeSynthesisContext::RewritingOperatorAsSpaceship:
  946. // A default template argument instantiation and substitution into
  947. // template parameters with arguments for prior parameters may or may
  948. // not be a SFINAE context; look further up the stack.
  949. break;
  950. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  951. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  952. case CodeSynthesisContext::ConstraintSubstitution:
  953. case CodeSynthesisContext::RequirementInstantiation:
  954. case CodeSynthesisContext::RequirementParameterInstantiation:
  955. // We're either substituting explicitly-specified template arguments,
  956. // deduced template arguments, a constraint expression or a requirement
  957. // in a requires expression, so SFINAE applies.
  958. assert(Active->DeductionInfo && "Missing deduction info pointer");
  959. return Active->DeductionInfo;
  960. case CodeSynthesisContext::DeclaringSpecialMember:
  961. case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
  962. case CodeSynthesisContext::DefiningSynthesizedFunction:
  963. case CodeSynthesisContext::InitializingStructuredBinding:
  964. case CodeSynthesisContext::MarkingClassDllexported:
  965. case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
  966. // This happens in a context unrelated to template instantiation, so
  967. // there is no SFINAE.
  968. return std::nullopt;
  969. case CodeSynthesisContext::ExceptionSpecEvaluation:
  970. // FIXME: This should not be treated as a SFINAE context, because
  971. // we will cache an incorrect exception specification. However, clang
  972. // bootstrap relies this! See PR31692.
  973. break;
  974. case CodeSynthesisContext::Memoization:
  975. break;
  976. }
  977. // The inner context was transparent for SFINAE. If it occurred within a
  978. // non-instantiation SFINAE context, then SFINAE applies.
  979. if (Active->SavedInNonInstantiationSFINAEContext)
  980. return std::optional<TemplateDeductionInfo *>(nullptr);
  981. }
  982. return std::nullopt;
  983. }
  984. //===----------------------------------------------------------------------===/
  985. // Template Instantiation for Types
  986. //===----------------------------------------------------------------------===/
  987. namespace {
  988. class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
  989. const MultiLevelTemplateArgumentList &TemplateArgs;
  990. SourceLocation Loc;
  991. DeclarationName Entity;
  992. bool EvaluateConstraints = true;
  993. public:
  994. typedef TreeTransform<TemplateInstantiator> inherited;
  995. TemplateInstantiator(Sema &SemaRef,
  996. const MultiLevelTemplateArgumentList &TemplateArgs,
  997. SourceLocation Loc, DeclarationName Entity)
  998. : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
  999. Entity(Entity) {}
  1000. void setEvaluateConstraints(bool B) {
  1001. EvaluateConstraints = B;
  1002. }
  1003. bool getEvaluateConstraints() {
  1004. return EvaluateConstraints;
  1005. }
  1006. /// Determine whether the given type \p T has already been
  1007. /// transformed.
  1008. ///
  1009. /// For the purposes of template instantiation, a type has already been
  1010. /// transformed if it is NULL or if it is not dependent.
  1011. bool AlreadyTransformed(QualType T);
  1012. /// Returns the location of the entity being instantiated, if known.
  1013. SourceLocation getBaseLocation() { return Loc; }
  1014. /// Returns the name of the entity being instantiated, if any.
  1015. DeclarationName getBaseEntity() { return Entity; }
  1016. /// Sets the "base" location and entity when that
  1017. /// information is known based on another transformation.
  1018. void setBase(SourceLocation Loc, DeclarationName Entity) {
  1019. this->Loc = Loc;
  1020. this->Entity = Entity;
  1021. }
  1022. unsigned TransformTemplateDepth(unsigned Depth) {
  1023. return TemplateArgs.getNewDepth(Depth);
  1024. }
  1025. std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
  1026. int Index = getSema().ArgumentPackSubstitutionIndex;
  1027. if (Index == -1)
  1028. return std::nullopt;
  1029. return Pack.pack_size() - 1 - Index;
  1030. }
  1031. bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
  1032. SourceRange PatternRange,
  1033. ArrayRef<UnexpandedParameterPack> Unexpanded,
  1034. bool &ShouldExpand, bool &RetainExpansion,
  1035. std::optional<unsigned> &NumExpansions) {
  1036. return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
  1037. PatternRange, Unexpanded,
  1038. TemplateArgs,
  1039. ShouldExpand,
  1040. RetainExpansion,
  1041. NumExpansions);
  1042. }
  1043. void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
  1044. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
  1045. }
  1046. TemplateArgument ForgetPartiallySubstitutedPack() {
  1047. TemplateArgument Result;
  1048. if (NamedDecl *PartialPack
  1049. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  1050. MultiLevelTemplateArgumentList &TemplateArgs
  1051. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  1052. unsigned Depth, Index;
  1053. std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  1054. if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
  1055. Result = TemplateArgs(Depth, Index);
  1056. TemplateArgs.setArgument(Depth, Index, TemplateArgument());
  1057. }
  1058. }
  1059. return Result;
  1060. }
  1061. void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
  1062. if (Arg.isNull())
  1063. return;
  1064. if (NamedDecl *PartialPack
  1065. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  1066. MultiLevelTemplateArgumentList &TemplateArgs
  1067. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  1068. unsigned Depth, Index;
  1069. std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  1070. TemplateArgs.setArgument(Depth, Index, Arg);
  1071. }
  1072. }
  1073. /// Transform the given declaration by instantiating a reference to
  1074. /// this declaration.
  1075. Decl *TransformDecl(SourceLocation Loc, Decl *D);
  1076. void transformAttrs(Decl *Old, Decl *New) {
  1077. SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
  1078. }
  1079. void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
  1080. if (Old->isParameterPack()) {
  1081. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
  1082. for (auto *New : NewDecls)
  1083. SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
  1084. Old, cast<VarDecl>(New));
  1085. return;
  1086. }
  1087. assert(NewDecls.size() == 1 &&
  1088. "should only have multiple expansions for a pack");
  1089. Decl *New = NewDecls.front();
  1090. // If we've instantiated the call operator of a lambda or the call
  1091. // operator template of a generic lambda, update the "instantiation of"
  1092. // information.
  1093. auto *NewMD = dyn_cast<CXXMethodDecl>(New);
  1094. if (NewMD && isLambdaCallOperator(NewMD)) {
  1095. auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
  1096. if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
  1097. NewTD->setInstantiatedFromMemberTemplate(
  1098. OldMD->getDescribedFunctionTemplate());
  1099. else
  1100. NewMD->setInstantiationOfMemberFunction(OldMD,
  1101. TSK_ImplicitInstantiation);
  1102. }
  1103. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
  1104. // We recreated a local declaration, but not by instantiating it. There
  1105. // may be pending dependent diagnostics to produce.
  1106. if (auto *DC = dyn_cast<DeclContext>(Old); DC && DC->isDependentContext())
  1107. SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
  1108. }
  1109. /// Transform the definition of the given declaration by
  1110. /// instantiating it.
  1111. Decl *TransformDefinition(SourceLocation Loc, Decl *D);
  1112. /// Transform the first qualifier within a scope by instantiating the
  1113. /// declaration.
  1114. NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
  1115. /// Rebuild the exception declaration and register the declaration
  1116. /// as an instantiated local.
  1117. VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
  1118. TypeSourceInfo *Declarator,
  1119. SourceLocation StartLoc,
  1120. SourceLocation NameLoc,
  1121. IdentifierInfo *Name);
  1122. /// Rebuild the Objective-C exception declaration and register the
  1123. /// declaration as an instantiated local.
  1124. VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  1125. TypeSourceInfo *TSInfo, QualType T);
  1126. /// Check for tag mismatches when instantiating an
  1127. /// elaborated type.
  1128. QualType RebuildElaboratedType(SourceLocation KeywordLoc,
  1129. ElaboratedTypeKeyword Keyword,
  1130. NestedNameSpecifierLoc QualifierLoc,
  1131. QualType T);
  1132. TemplateName
  1133. TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
  1134. SourceLocation NameLoc,
  1135. QualType ObjectType = QualType(),
  1136. NamedDecl *FirstQualifierInScope = nullptr,
  1137. bool AllowInjectedClassName = false);
  1138. const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
  1139. ExprResult TransformPredefinedExpr(PredefinedExpr *E);
  1140. ExprResult TransformDeclRefExpr(DeclRefExpr *E);
  1141. ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
  1142. ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
  1143. NonTypeTemplateParmDecl *D);
  1144. ExprResult TransformSubstNonTypeTemplateParmPackExpr(
  1145. SubstNonTypeTemplateParmPackExpr *E);
  1146. ExprResult TransformSubstNonTypeTemplateParmExpr(
  1147. SubstNonTypeTemplateParmExpr *E);
  1148. /// Rebuild a DeclRefExpr for a VarDecl reference.
  1149. ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
  1150. /// Transform a reference to a function or init-capture parameter pack.
  1151. ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
  1152. /// Transform a FunctionParmPackExpr which was built when we couldn't
  1153. /// expand a function parameter pack reference which refers to an expanded
  1154. /// pack.
  1155. ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
  1156. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  1157. FunctionProtoTypeLoc TL) {
  1158. // Call the base version; it will forward to our overridden version below.
  1159. return inherited::TransformFunctionProtoType(TLB, TL);
  1160. }
  1161. template<typename Fn>
  1162. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  1163. FunctionProtoTypeLoc TL,
  1164. CXXRecordDecl *ThisContext,
  1165. Qualifiers ThisTypeQuals,
  1166. Fn TransformExceptionSpec);
  1167. ParmVarDecl *
  1168. TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
  1169. std::optional<unsigned> NumExpansions,
  1170. bool ExpectParameterPack);
  1171. using inherited::TransformTemplateTypeParmType;
  1172. /// Transforms a template type parameter type by performing
  1173. /// substitution of the corresponding template type argument.
  1174. QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  1175. TemplateTypeParmTypeLoc TL,
  1176. bool SuppressObjCLifetime);
  1177. QualType BuildSubstTemplateTypeParmType(
  1178. TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
  1179. Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
  1180. TemplateArgument Arg, SourceLocation NameLoc);
  1181. /// Transforms an already-substituted template type parameter pack
  1182. /// into either itself (if we aren't substituting into its pack expansion)
  1183. /// or the appropriate substituted argument.
  1184. using inherited::TransformSubstTemplateTypeParmPackType;
  1185. QualType
  1186. TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
  1187. SubstTemplateTypeParmPackTypeLoc TL,
  1188. bool SuppressObjCLifetime);
  1189. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  1190. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1191. Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
  1192. ExprResult Result = inherited::TransformLambdaExpr(E);
  1193. if (Result.isInvalid())
  1194. return Result;
  1195. CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
  1196. for (ParmVarDecl *PVD : MD->parameters()) {
  1197. if (!PVD->hasDefaultArg())
  1198. continue;
  1199. Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
  1200. // FIXME: Obtain the source location for the '=' token.
  1201. SourceLocation EqualLoc = UninstExpr->getBeginLoc();
  1202. if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
  1203. // If substitution fails, the default argument is set to a
  1204. // RecoveryExpr that wraps the uninstantiated default argument so
  1205. // that downstream diagnostics are omitted.
  1206. ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
  1207. UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
  1208. { UninstExpr }, UninstExpr->getType());
  1209. if (ErrorResult.isUsable())
  1210. PVD->setDefaultArg(ErrorResult.get());
  1211. }
  1212. }
  1213. return Result;
  1214. }
  1215. ExprResult TransformRequiresExpr(RequiresExpr *E) {
  1216. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1217. ExprResult TransReq = inherited::TransformRequiresExpr(E);
  1218. if (TransReq.isInvalid())
  1219. return TransReq;
  1220. assert(TransReq.get() != E &&
  1221. "Do not change value of isSatisfied for the existing expression. "
  1222. "Create a new expression instead.");
  1223. if (E->getBody()->isDependentContext()) {
  1224. Sema::SFINAETrap Trap(SemaRef);
  1225. // We recreate the RequiresExpr body, but not by instantiating it.
  1226. // Produce pending diagnostics for dependent access check.
  1227. SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
  1228. // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
  1229. if (Trap.hasErrorOccurred())
  1230. TransReq.getAs<RequiresExpr>()->setSatisfied(false);
  1231. }
  1232. return TransReq;
  1233. }
  1234. bool TransformRequiresExprRequirements(
  1235. ArrayRef<concepts::Requirement *> Reqs,
  1236. SmallVectorImpl<concepts::Requirement *> &Transformed) {
  1237. bool SatisfactionDetermined = false;
  1238. for (concepts::Requirement *Req : Reqs) {
  1239. concepts::Requirement *TransReq = nullptr;
  1240. if (!SatisfactionDetermined) {
  1241. if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
  1242. TransReq = TransformTypeRequirement(TypeReq);
  1243. else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
  1244. TransReq = TransformExprRequirement(ExprReq);
  1245. else
  1246. TransReq = TransformNestedRequirement(
  1247. cast<concepts::NestedRequirement>(Req));
  1248. if (!TransReq)
  1249. return true;
  1250. if (!TransReq->isDependent() && !TransReq->isSatisfied())
  1251. // [expr.prim.req]p6
  1252. // [...] The substitution and semantic constraint checking
  1253. // proceeds in lexical order and stops when a condition that
  1254. // determines the result of the requires-expression is
  1255. // encountered. [..]
  1256. SatisfactionDetermined = true;
  1257. } else
  1258. TransReq = Req;
  1259. Transformed.push_back(TransReq);
  1260. }
  1261. return false;
  1262. }
  1263. TemplateParameterList *TransformTemplateParameterList(
  1264. TemplateParameterList *OrigTPL) {
  1265. if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
  1266. DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
  1267. TemplateDeclInstantiator DeclInstantiator(getSema(),
  1268. /* DeclContext *Owner */ Owner, TemplateArgs);
  1269. DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
  1270. return DeclInstantiator.SubstTemplateParams(OrigTPL);
  1271. }
  1272. concepts::TypeRequirement *
  1273. TransformTypeRequirement(concepts::TypeRequirement *Req);
  1274. concepts::ExprRequirement *
  1275. TransformExprRequirement(concepts::ExprRequirement *Req);
  1276. concepts::NestedRequirement *
  1277. TransformNestedRequirement(concepts::NestedRequirement *Req);
  1278. ExprResult TransformRequiresTypeParams(
  1279. SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
  1280. RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
  1281. SmallVectorImpl<QualType> &PTypes,
  1282. SmallVectorImpl<ParmVarDecl *> &TransParams,
  1283. Sema::ExtParameterInfoBuilder &PInfos);
  1284. private:
  1285. ExprResult
  1286. transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
  1287. const NonTypeTemplateParmDecl *parm,
  1288. SourceLocation loc, TemplateArgument arg,
  1289. std::optional<unsigned> PackIndex);
  1290. };
  1291. }
  1292. bool TemplateInstantiator::AlreadyTransformed(QualType T) {
  1293. if (T.isNull())
  1294. return true;
  1295. if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
  1296. return false;
  1297. getSema().MarkDeclarationsReferencedInType(Loc, T);
  1298. return true;
  1299. }
  1300. static TemplateArgument
  1301. getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
  1302. assert(S.ArgumentPackSubstitutionIndex >= 0);
  1303. assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  1304. Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
  1305. if (Arg.isPackExpansion())
  1306. Arg = Arg.getPackExpansionPattern();
  1307. return Arg;
  1308. }
  1309. Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
  1310. if (!D)
  1311. return nullptr;
  1312. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
  1313. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  1314. // If the corresponding template argument is NULL or non-existent, it's
  1315. // because we are performing instantiation from explicitly-specified
  1316. // template arguments in a function template, but there were some
  1317. // arguments left unspecified.
  1318. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  1319. TTP->getPosition()))
  1320. return D;
  1321. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  1322. if (TTP->isParameterPack()) {
  1323. assert(Arg.getKind() == TemplateArgument::Pack &&
  1324. "Missing argument pack");
  1325. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1326. }
  1327. TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
  1328. assert(!Template.isNull() && Template.getAsTemplateDecl() &&
  1329. "Wrong kind of template template argument");
  1330. return Template.getAsTemplateDecl();
  1331. }
  1332. // Fall through to find the instantiated declaration for this template
  1333. // template parameter.
  1334. }
  1335. return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
  1336. }
  1337. Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
  1338. Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
  1339. if (!Inst)
  1340. return nullptr;
  1341. getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  1342. return Inst;
  1343. }
  1344. NamedDecl *
  1345. TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
  1346. SourceLocation Loc) {
  1347. // If the first part of the nested-name-specifier was a template type
  1348. // parameter, instantiate that type parameter down to a tag type.
  1349. if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
  1350. const TemplateTypeParmType *TTP
  1351. = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
  1352. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  1353. // FIXME: This needs testing w/ member access expressions.
  1354. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
  1355. if (TTP->isParameterPack()) {
  1356. assert(Arg.getKind() == TemplateArgument::Pack &&
  1357. "Missing argument pack");
  1358. if (getSema().ArgumentPackSubstitutionIndex == -1)
  1359. return nullptr;
  1360. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1361. }
  1362. QualType T = Arg.getAsType();
  1363. if (T.isNull())
  1364. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  1365. if (const TagType *Tag = T->getAs<TagType>())
  1366. return Tag->getDecl();
  1367. // The resulting type is not a tag; complain.
  1368. getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
  1369. return nullptr;
  1370. }
  1371. }
  1372. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  1373. }
  1374. VarDecl *
  1375. TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
  1376. TypeSourceInfo *Declarator,
  1377. SourceLocation StartLoc,
  1378. SourceLocation NameLoc,
  1379. IdentifierInfo *Name) {
  1380. VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
  1381. StartLoc, NameLoc, Name);
  1382. if (Var)
  1383. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  1384. return Var;
  1385. }
  1386. VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  1387. TypeSourceInfo *TSInfo,
  1388. QualType T) {
  1389. VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
  1390. if (Var)
  1391. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  1392. return Var;
  1393. }
  1394. QualType
  1395. TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
  1396. ElaboratedTypeKeyword Keyword,
  1397. NestedNameSpecifierLoc QualifierLoc,
  1398. QualType T) {
  1399. if (const TagType *TT = T->getAs<TagType>()) {
  1400. TagDecl* TD = TT->getDecl();
  1401. SourceLocation TagLocation = KeywordLoc;
  1402. IdentifierInfo *Id = TD->getIdentifier();
  1403. // TODO: should we even warn on struct/class mismatches for this? Seems
  1404. // like it's likely to produce a lot of spurious errors.
  1405. if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
  1406. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
  1407. if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
  1408. TagLocation, Id)) {
  1409. SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
  1410. << Id
  1411. << FixItHint::CreateReplacement(SourceRange(TagLocation),
  1412. TD->getKindName());
  1413. SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
  1414. }
  1415. }
  1416. }
  1417. return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
  1418. }
  1419. TemplateName TemplateInstantiator::TransformTemplateName(
  1420. CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
  1421. QualType ObjectType, NamedDecl *FirstQualifierInScope,
  1422. bool AllowInjectedClassName) {
  1423. if (TemplateTemplateParmDecl *TTP
  1424. = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
  1425. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  1426. // If the corresponding template argument is NULL or non-existent, it's
  1427. // because we are performing instantiation from explicitly-specified
  1428. // template arguments in a function template, but there were some
  1429. // arguments left unspecified.
  1430. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  1431. TTP->getPosition()))
  1432. return Name;
  1433. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  1434. if (TemplateArgs.isRewrite()) {
  1435. // We're rewriting the template parameter as a reference to another
  1436. // template parameter.
  1437. if (Arg.getKind() == TemplateArgument::Pack) {
  1438. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
  1439. "unexpected pack arguments in template rewrite");
  1440. Arg = Arg.pack_begin()->getPackExpansionPattern();
  1441. }
  1442. assert(Arg.getKind() == TemplateArgument::Template &&
  1443. "unexpected nontype template argument kind in template rewrite");
  1444. return Arg.getAsTemplate();
  1445. }
  1446. auto [AssociatedDecl, Final] =
  1447. TemplateArgs.getAssociatedDecl(TTP->getDepth());
  1448. std::optional<unsigned> PackIndex;
  1449. if (TTP->isParameterPack()) {
  1450. assert(Arg.getKind() == TemplateArgument::Pack &&
  1451. "Missing argument pack");
  1452. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1453. // We have the template argument pack to substitute, but we're not
  1454. // actually expanding the enclosing pack expansion yet. So, just
  1455. // keep the entire argument pack.
  1456. return getSema().Context.getSubstTemplateTemplateParmPack(
  1457. Arg, AssociatedDecl, TTP->getIndex(), Final);
  1458. }
  1459. PackIndex = getPackIndex(Arg);
  1460. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1461. }
  1462. TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
  1463. assert(!Template.isNull() && "Null template template argument");
  1464. assert(!Template.getAsQualifiedTemplateName() &&
  1465. "template decl to substitute is qualified?");
  1466. if (Final)
  1467. return Template;
  1468. return getSema().Context.getSubstTemplateTemplateParm(
  1469. Template, AssociatedDecl, TTP->getIndex(), PackIndex);
  1470. }
  1471. }
  1472. if (SubstTemplateTemplateParmPackStorage *SubstPack
  1473. = Name.getAsSubstTemplateTemplateParmPack()) {
  1474. if (getSema().ArgumentPackSubstitutionIndex == -1)
  1475. return Name;
  1476. TemplateArgument Pack = SubstPack->getArgumentPack();
  1477. TemplateName Template =
  1478. getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate();
  1479. if (SubstPack->getFinal())
  1480. return Template;
  1481. return getSema().Context.getSubstTemplateTemplateParm(
  1482. Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
  1483. SubstPack->getIndex(), getPackIndex(Pack));
  1484. }
  1485. return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
  1486. FirstQualifierInScope,
  1487. AllowInjectedClassName);
  1488. }
  1489. ExprResult
  1490. TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
  1491. if (!E->isTypeDependent())
  1492. return E;
  1493. return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
  1494. }
  1495. ExprResult
  1496. TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
  1497. NonTypeTemplateParmDecl *NTTP) {
  1498. // If the corresponding template argument is NULL or non-existent, it's
  1499. // because we are performing instantiation from explicitly-specified
  1500. // template arguments in a function template, but there were some
  1501. // arguments left unspecified.
  1502. if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
  1503. NTTP->getPosition()))
  1504. return E;
  1505. TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
  1506. if (TemplateArgs.isRewrite()) {
  1507. // We're rewriting the template parameter as a reference to another
  1508. // template parameter.
  1509. if (Arg.getKind() == TemplateArgument::Pack) {
  1510. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
  1511. "unexpected pack arguments in template rewrite");
  1512. Arg = Arg.pack_begin()->getPackExpansionPattern();
  1513. }
  1514. assert(Arg.getKind() == TemplateArgument::Expression &&
  1515. "unexpected nontype template argument kind in template rewrite");
  1516. // FIXME: This can lead to the same subexpression appearing multiple times
  1517. // in a complete expression.
  1518. return Arg.getAsExpr();
  1519. }
  1520. auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
  1521. std::optional<unsigned> PackIndex;
  1522. if (NTTP->isParameterPack()) {
  1523. assert(Arg.getKind() == TemplateArgument::Pack &&
  1524. "Missing argument pack");
  1525. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1526. // We have an argument pack, but we can't select a particular argument
  1527. // out of it yet. Therefore, we'll build an expression to hold on to that
  1528. // argument pack.
  1529. QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
  1530. E->getLocation(),
  1531. NTTP->getDeclName());
  1532. if (TargetType.isNull())
  1533. return ExprError();
  1534. QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
  1535. if (TargetType->isRecordType())
  1536. ExprType.addConst();
  1537. // FIXME: Pass in Final.
  1538. return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
  1539. ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
  1540. E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
  1541. }
  1542. PackIndex = getPackIndex(Arg);
  1543. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1544. }
  1545. // FIXME: Don't put subst node on Final replacement.
  1546. return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
  1547. Arg, PackIndex);
  1548. }
  1549. const LoopHintAttr *
  1550. TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
  1551. Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
  1552. if (TransformedExpr == LH->getValue())
  1553. return LH;
  1554. // Generate error if there is a problem with the value.
  1555. if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
  1556. return LH;
  1557. // Create new LoopHintValueAttr with integral expression in place of the
  1558. // non-type template parameter.
  1559. return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
  1560. LH->getState(), TransformedExpr, *LH);
  1561. }
  1562. ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
  1563. Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
  1564. SourceLocation loc, TemplateArgument arg,
  1565. std::optional<unsigned> PackIndex) {
  1566. ExprResult result;
  1567. // Determine the substituted parameter type. We can usually infer this from
  1568. // the template argument, but not always.
  1569. auto SubstParamType = [&] {
  1570. QualType T;
  1571. if (parm->isExpandedParameterPack())
  1572. T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
  1573. else
  1574. T = parm->getType();
  1575. if (parm->isParameterPack() && isa<PackExpansionType>(T))
  1576. T = cast<PackExpansionType>(T)->getPattern();
  1577. return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
  1578. };
  1579. bool refParam = false;
  1580. // The template argument itself might be an expression, in which case we just
  1581. // return that expression. This happens when substituting into an alias
  1582. // template.
  1583. if (arg.getKind() == TemplateArgument::Expression) {
  1584. Expr *argExpr = arg.getAsExpr();
  1585. result = argExpr;
  1586. if (argExpr->isLValue()) {
  1587. if (argExpr->getType()->isRecordType()) {
  1588. // Check whether the parameter was actually a reference.
  1589. QualType paramType = SubstParamType();
  1590. if (paramType.isNull())
  1591. return ExprError();
  1592. refParam = paramType->isReferenceType();
  1593. } else {
  1594. refParam = true;
  1595. }
  1596. }
  1597. } else if (arg.getKind() == TemplateArgument::Declaration ||
  1598. arg.getKind() == TemplateArgument::NullPtr) {
  1599. ValueDecl *VD;
  1600. if (arg.getKind() == TemplateArgument::Declaration) {
  1601. VD = arg.getAsDecl();
  1602. // Find the instantiation of the template argument. This is
  1603. // required for nested templates.
  1604. VD = cast_or_null<ValueDecl>(
  1605. getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
  1606. if (!VD)
  1607. return ExprError();
  1608. } else {
  1609. // Propagate NULL template argument.
  1610. VD = nullptr;
  1611. }
  1612. QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType();
  1613. assert(!paramType.isNull() && "type substitution failed for param type");
  1614. assert(!paramType->isDependentType() && "param type still dependent");
  1615. result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
  1616. refParam = paramType->isReferenceType();
  1617. } else {
  1618. result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
  1619. assert(result.isInvalid() ||
  1620. SemaRef.Context.hasSameType(result.get()->getType(),
  1621. arg.getIntegralType()));
  1622. }
  1623. if (result.isInvalid())
  1624. return ExprError();
  1625. Expr *resultExpr = result.get();
  1626. // FIXME: Don't put subst node on final replacement.
  1627. return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
  1628. resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
  1629. AssociatedDecl, parm->getIndex(), PackIndex, refParam);
  1630. }
  1631. ExprResult
  1632. TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
  1633. SubstNonTypeTemplateParmPackExpr *E) {
  1634. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1635. // We aren't expanding the parameter pack, so just return ourselves.
  1636. return E;
  1637. }
  1638. TemplateArgument Pack = E->getArgumentPack();
  1639. TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
  1640. // FIXME: Don't put subst node on final replacement.
  1641. return transformNonTypeTemplateParmRef(
  1642. E->getAssociatedDecl(), E->getParameterPack(),
  1643. E->getParameterPackLocation(), Arg, getPackIndex(Pack));
  1644. }
  1645. ExprResult
  1646. TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
  1647. SubstNonTypeTemplateParmExpr *E) {
  1648. ExprResult SubstReplacement = E->getReplacement();
  1649. if (!isa<ConstantExpr>(SubstReplacement.get()))
  1650. SubstReplacement = TransformExpr(E->getReplacement());
  1651. if (SubstReplacement.isInvalid())
  1652. return true;
  1653. QualType SubstType = TransformType(E->getParameterType(getSema().Context));
  1654. if (SubstType.isNull())
  1655. return true;
  1656. // The type may have been previously dependent and not now, which means we
  1657. // might have to implicit cast the argument to the new type, for example:
  1658. // template<auto T, decltype(T) U>
  1659. // concept C = sizeof(U) == 4;
  1660. // void foo() requires C<2, 'a'> { }
  1661. // When normalizing foo(), we first form the normalized constraints of C:
  1662. // AtomicExpr(sizeof(U) == 4,
  1663. // U=SubstNonTypeTemplateParmExpr(Param=U,
  1664. // Expr=DeclRef(U),
  1665. // Type=decltype(T)))
  1666. // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
  1667. // produce:
  1668. // AtomicExpr(sizeof(U) == 4,
  1669. // U=SubstNonTypeTemplateParmExpr(Param=U,
  1670. // Expr=ImpCast(
  1671. // decltype(2),
  1672. // SubstNTTPE(Param=U, Expr='a',
  1673. // Type=char)),
  1674. // Type=decltype(2)))
  1675. // The call to CheckTemplateArgument here produces the ImpCast.
  1676. TemplateArgument SugaredConverted, CanonicalConverted;
  1677. if (SemaRef
  1678. .CheckTemplateArgument(E->getParameter(), SubstType,
  1679. SubstReplacement.get(), SugaredConverted,
  1680. CanonicalConverted, Sema::CTAK_Specified)
  1681. .isInvalid())
  1682. return true;
  1683. return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
  1684. E->getParameter(), E->getExprLoc(),
  1685. SugaredConverted, E->getPackIndex());
  1686. }
  1687. ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
  1688. SourceLocation Loc) {
  1689. DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
  1690. return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
  1691. }
  1692. ExprResult
  1693. TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
  1694. if (getSema().ArgumentPackSubstitutionIndex != -1) {
  1695. // We can expand this parameter pack now.
  1696. VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
  1697. VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
  1698. if (!VD)
  1699. return ExprError();
  1700. return RebuildVarDeclRefExpr(VD, E->getExprLoc());
  1701. }
  1702. QualType T = TransformType(E->getType());
  1703. if (T.isNull())
  1704. return ExprError();
  1705. // Transform each of the parameter expansions into the corresponding
  1706. // parameters in the instantiation of the function decl.
  1707. SmallVector<VarDecl *, 8> Vars;
  1708. Vars.reserve(E->getNumExpansions());
  1709. for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
  1710. I != End; ++I) {
  1711. VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
  1712. if (!D)
  1713. return ExprError();
  1714. Vars.push_back(D);
  1715. }
  1716. auto *PackExpr =
  1717. FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
  1718. E->getParameterPackLocation(), Vars);
  1719. getSema().MarkFunctionParmPackReferenced(PackExpr);
  1720. return PackExpr;
  1721. }
  1722. ExprResult
  1723. TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
  1724. VarDecl *PD) {
  1725. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  1726. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
  1727. = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
  1728. assert(Found && "no instantiation for parameter pack");
  1729. Decl *TransformedDecl;
  1730. if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
  1731. // If this is a reference to a function parameter pack which we can
  1732. // substitute but can't yet expand, build a FunctionParmPackExpr for it.
  1733. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1734. QualType T = TransformType(E->getType());
  1735. if (T.isNull())
  1736. return ExprError();
  1737. auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
  1738. E->getExprLoc(), *Pack);
  1739. getSema().MarkFunctionParmPackReferenced(PackExpr);
  1740. return PackExpr;
  1741. }
  1742. TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
  1743. } else {
  1744. TransformedDecl = Found->get<Decl*>();
  1745. }
  1746. // We have either an unexpanded pack or a specific expansion.
  1747. return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
  1748. }
  1749. ExprResult
  1750. TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
  1751. NamedDecl *D = E->getDecl();
  1752. // Handle references to non-type template parameters and non-type template
  1753. // parameter packs.
  1754. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
  1755. if (NTTP->getDepth() < TemplateArgs.getNumLevels())
  1756. return TransformTemplateParmRefExpr(E, NTTP);
  1757. // We have a non-type template parameter that isn't fully substituted;
  1758. // FindInstantiatedDecl will find it in the local instantiation scope.
  1759. }
  1760. // Handle references to function parameter packs.
  1761. if (VarDecl *PD = dyn_cast<VarDecl>(D))
  1762. if (PD->isParameterPack())
  1763. return TransformFunctionParmPackRefExpr(E, PD);
  1764. return inherited::TransformDeclRefExpr(E);
  1765. }
  1766. ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
  1767. CXXDefaultArgExpr *E) {
  1768. assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
  1769. getDescribedFunctionTemplate() &&
  1770. "Default arg expressions are never formed in dependent cases.");
  1771. return SemaRef.BuildCXXDefaultArgExpr(
  1772. E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
  1773. E->getParam());
  1774. }
  1775. template<typename Fn>
  1776. QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
  1777. FunctionProtoTypeLoc TL,
  1778. CXXRecordDecl *ThisContext,
  1779. Qualifiers ThisTypeQuals,
  1780. Fn TransformExceptionSpec) {
  1781. // We need a local instantiation scope for this function prototype.
  1782. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1783. return inherited::TransformFunctionProtoType(
  1784. TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
  1785. }
  1786. ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
  1787. ParmVarDecl *OldParm, int indexAdjustment,
  1788. std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
  1789. auto NewParm = SemaRef.SubstParmVarDecl(
  1790. OldParm, TemplateArgs, indexAdjustment, NumExpansions,
  1791. ExpectParameterPack, EvaluateConstraints);
  1792. if (NewParm && SemaRef.getLangOpts().OpenCL)
  1793. SemaRef.deduceOpenCLAddressSpace(NewParm);
  1794. return NewParm;
  1795. }
  1796. QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
  1797. TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
  1798. Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
  1799. TemplateArgument Arg, SourceLocation NameLoc) {
  1800. QualType Replacement = Arg.getAsType();
  1801. // If the template parameter had ObjC lifetime qualifiers,
  1802. // then any such qualifiers on the replacement type are ignored.
  1803. if (SuppressObjCLifetime) {
  1804. Qualifiers RQs;
  1805. RQs = Replacement.getQualifiers();
  1806. RQs.removeObjCLifetime();
  1807. Replacement =
  1808. SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
  1809. }
  1810. if (Final) {
  1811. TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
  1812. return Replacement;
  1813. }
  1814. // TODO: only do this uniquing once, at the start of instantiation.
  1815. QualType Result = getSema().Context.getSubstTemplateTypeParmType(
  1816. Replacement, AssociatedDecl, Index, PackIndex);
  1817. SubstTemplateTypeParmTypeLoc NewTL =
  1818. TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1819. NewTL.setNameLoc(NameLoc);
  1820. return Result;
  1821. }
  1822. QualType
  1823. TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  1824. TemplateTypeParmTypeLoc TL,
  1825. bool SuppressObjCLifetime) {
  1826. const TemplateTypeParmType *T = TL.getTypePtr();
  1827. if (T->getDepth() < TemplateArgs.getNumLevels()) {
  1828. // Replace the template type parameter with its corresponding
  1829. // template argument.
  1830. // If the corresponding template argument is NULL or doesn't exist, it's
  1831. // because we are performing instantiation from explicitly-specified
  1832. // template arguments in a function template class, but there were some
  1833. // arguments left unspecified.
  1834. if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
  1835. TemplateTypeParmTypeLoc NewTL
  1836. = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
  1837. NewTL.setNameLoc(TL.getNameLoc());
  1838. return TL.getType();
  1839. }
  1840. TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
  1841. if (TemplateArgs.isRewrite()) {
  1842. // We're rewriting the template parameter as a reference to another
  1843. // template parameter.
  1844. if (Arg.getKind() == TemplateArgument::Pack) {
  1845. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
  1846. "unexpected pack arguments in template rewrite");
  1847. Arg = Arg.pack_begin()->getPackExpansionPattern();
  1848. }
  1849. assert(Arg.getKind() == TemplateArgument::Type &&
  1850. "unexpected nontype template argument kind in template rewrite");
  1851. QualType NewT = Arg.getAsType();
  1852. assert(isa<TemplateTypeParmType>(NewT) &&
  1853. "type parm not rewritten to type parm");
  1854. auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
  1855. NewTL.setNameLoc(TL.getNameLoc());
  1856. return NewT;
  1857. }
  1858. auto [AssociatedDecl, Final] =
  1859. TemplateArgs.getAssociatedDecl(T->getDepth());
  1860. std::optional<unsigned> PackIndex;
  1861. if (T->isParameterPack()) {
  1862. assert(Arg.getKind() == TemplateArgument::Pack &&
  1863. "Missing argument pack");
  1864. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1865. // We have the template argument pack, but we're not expanding the
  1866. // enclosing pack expansion yet. Just save the template argument
  1867. // pack for later substitution.
  1868. QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
  1869. AssociatedDecl, T->getIndex(), Final, Arg);
  1870. SubstTemplateTypeParmPackTypeLoc NewTL
  1871. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
  1872. NewTL.setNameLoc(TL.getNameLoc());
  1873. return Result;
  1874. }
  1875. // PackIndex starts from last element.
  1876. PackIndex = getPackIndex(Arg);
  1877. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1878. }
  1879. assert(Arg.getKind() == TemplateArgument::Type &&
  1880. "Template argument kind mismatch");
  1881. return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
  1882. AssociatedDecl, T->getIndex(),
  1883. PackIndex, Arg, TL.getNameLoc());
  1884. }
  1885. // The template type parameter comes from an inner template (e.g.,
  1886. // the template parameter list of a member template inside the
  1887. // template we are instantiating). Create a new template type
  1888. // parameter with the template "level" reduced by one.
  1889. TemplateTypeParmDecl *NewTTPDecl = nullptr;
  1890. if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
  1891. NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
  1892. TransformDecl(TL.getNameLoc(), OldTTPDecl));
  1893. QualType Result = getSema().Context.getTemplateTypeParmType(
  1894. T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
  1895. T->isParameterPack(), NewTTPDecl);
  1896. TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
  1897. NewTL.setNameLoc(TL.getNameLoc());
  1898. return Result;
  1899. }
  1900. QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
  1901. TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
  1902. bool SuppressObjCLifetime) {
  1903. const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
  1904. Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
  1905. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1906. // We aren't expanding the parameter pack, so just return ourselves.
  1907. QualType Result = TL.getType();
  1908. if (NewReplaced != T->getAssociatedDecl())
  1909. Result = getSema().Context.getSubstTemplateTypeParmPackType(
  1910. NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
  1911. SubstTemplateTypeParmPackTypeLoc NewTL =
  1912. TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
  1913. NewTL.setNameLoc(TL.getNameLoc());
  1914. return Result;
  1915. }
  1916. TemplateArgument Pack = T->getArgumentPack();
  1917. TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
  1918. return BuildSubstTemplateTypeParmType(
  1919. TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
  1920. getPackIndex(Pack), Arg, TL.getNameLoc());
  1921. }
  1922. template<typename EntityPrinter>
  1923. static concepts::Requirement::SubstitutionDiagnostic *
  1924. createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
  1925. SmallString<128> Message;
  1926. SourceLocation ErrorLoc;
  1927. if (Info.hasSFINAEDiagnostic()) {
  1928. PartialDiagnosticAt PDA(SourceLocation(),
  1929. PartialDiagnostic::NullDiagnostic{});
  1930. Info.takeSFINAEDiagnostic(PDA);
  1931. PDA.second.EmitToString(S.getDiagnostics(), Message);
  1932. ErrorLoc = PDA.first;
  1933. } else {
  1934. ErrorLoc = Info.getLocation();
  1935. }
  1936. char *MessageBuf = new (S.Context) char[Message.size()];
  1937. std::copy(Message.begin(), Message.end(), MessageBuf);
  1938. SmallString<128> Entity;
  1939. llvm::raw_svector_ostream OS(Entity);
  1940. Printer(OS);
  1941. char *EntityBuf = new (S.Context) char[Entity.size()];
  1942. std::copy(Entity.begin(), Entity.end(), EntityBuf);
  1943. return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
  1944. StringRef(EntityBuf, Entity.size()), ErrorLoc,
  1945. StringRef(MessageBuf, Message.size())};
  1946. }
  1947. ExprResult TemplateInstantiator::TransformRequiresTypeParams(
  1948. SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
  1949. RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
  1950. SmallVectorImpl<QualType> &PTypes,
  1951. SmallVectorImpl<ParmVarDecl *> &TransParams,
  1952. Sema::ExtParameterInfoBuilder &PInfos) {
  1953. TemplateDeductionInfo Info(KWLoc);
  1954. Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
  1955. RE, Info,
  1956. SourceRange{KWLoc, RBraceLoc});
  1957. Sema::SFINAETrap Trap(SemaRef);
  1958. unsigned ErrorIdx;
  1959. if (getDerived().TransformFunctionTypeParams(
  1960. KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
  1961. &TransParams, PInfos, &ErrorIdx) ||
  1962. Trap.hasErrorOccurred()) {
  1963. SmallVector<concepts::Requirement *, 4> TransReqs;
  1964. ParmVarDecl *FailedDecl = Params[ErrorIdx];
  1965. // Add a 'failed' Requirement to contain the error that caused the failure
  1966. // here.
  1967. TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
  1968. SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
  1969. return getDerived().RebuildRequiresExpr(KWLoc, Body, TransParams, TransReqs,
  1970. RBraceLoc);
  1971. }
  1972. return ExprResult{};
  1973. }
  1974. concepts::TypeRequirement *
  1975. TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
  1976. if (!Req->isDependent() && !AlwaysRebuild())
  1977. return Req;
  1978. if (Req->isSubstitutionFailure()) {
  1979. if (AlwaysRebuild())
  1980. return RebuildTypeRequirement(
  1981. Req->getSubstitutionDiagnostic());
  1982. return Req;
  1983. }
  1984. Sema::SFINAETrap Trap(SemaRef);
  1985. TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
  1986. Sema::InstantiatingTemplate TypeInst(SemaRef,
  1987. Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
  1988. Req->getType()->getTypeLoc().getSourceRange());
  1989. if (TypeInst.isInvalid())
  1990. return nullptr;
  1991. TypeSourceInfo *TransType = TransformType(Req->getType());
  1992. if (!TransType || Trap.hasErrorOccurred())
  1993. return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
  1994. [&] (llvm::raw_ostream& OS) {
  1995. Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
  1996. }));
  1997. return RebuildTypeRequirement(TransType);
  1998. }
  1999. concepts::ExprRequirement *
  2000. TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
  2001. if (!Req->isDependent() && !AlwaysRebuild())
  2002. return Req;
  2003. Sema::SFINAETrap Trap(SemaRef);
  2004. llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
  2005. TransExpr;
  2006. if (Req->isExprSubstitutionFailure())
  2007. TransExpr = Req->getExprSubstitutionDiagnostic();
  2008. else {
  2009. Expr *E = Req->getExpr();
  2010. TemplateDeductionInfo Info(E->getBeginLoc());
  2011. Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
  2012. E->getSourceRange());
  2013. if (ExprInst.isInvalid())
  2014. return nullptr;
  2015. ExprResult TransExprRes = TransformExpr(E);
  2016. if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
  2017. TransExprRes.get()->hasPlaceholderType())
  2018. TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
  2019. if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
  2020. TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
  2021. E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
  2022. });
  2023. else
  2024. TransExpr = TransExprRes.get();
  2025. }
  2026. std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
  2027. const auto &RetReq = Req->getReturnTypeRequirement();
  2028. if (RetReq.isEmpty())
  2029. TransRetReq.emplace();
  2030. else if (RetReq.isSubstitutionFailure())
  2031. TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
  2032. else if (RetReq.isTypeConstraint()) {
  2033. TemplateParameterList *OrigTPL =
  2034. RetReq.getTypeConstraintTemplateParameterList();
  2035. TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
  2036. Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
  2037. Req, Info, OrigTPL->getSourceRange());
  2038. if (TPLInst.isInvalid())
  2039. return nullptr;
  2040. TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
  2041. if (!TPL)
  2042. TransRetReq.emplace(createSubstDiag(SemaRef, Info,
  2043. [&] (llvm::raw_ostream& OS) {
  2044. RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
  2045. ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
  2046. }));
  2047. else {
  2048. TPLInst.Clear();
  2049. TransRetReq.emplace(TPL);
  2050. }
  2051. }
  2052. assert(TransRetReq && "All code paths leading here must set TransRetReq");
  2053. if (Expr *E = TransExpr.dyn_cast<Expr *>())
  2054. return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
  2055. std::move(*TransRetReq));
  2056. return RebuildExprRequirement(
  2057. TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
  2058. Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
  2059. }
  2060. concepts::NestedRequirement *
  2061. TemplateInstantiator::TransformNestedRequirement(
  2062. concepts::NestedRequirement *Req) {
  2063. if (!Req->isDependent() && !AlwaysRebuild())
  2064. return Req;
  2065. if (Req->hasInvalidConstraint()) {
  2066. if (AlwaysRebuild())
  2067. return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
  2068. Req->getConstraintSatisfaction());
  2069. return Req;
  2070. }
  2071. Sema::InstantiatingTemplate ReqInst(SemaRef,
  2072. Req->getConstraintExpr()->getBeginLoc(), Req,
  2073. Sema::InstantiatingTemplate::ConstraintsCheck{},
  2074. Req->getConstraintExpr()->getSourceRange());
  2075. ExprResult TransConstraint;
  2076. ConstraintSatisfaction Satisfaction;
  2077. TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
  2078. {
  2079. EnterExpressionEvaluationContext ContextRAII(
  2080. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  2081. Sema::SFINAETrap Trap(SemaRef);
  2082. Sema::InstantiatingTemplate ConstrInst(SemaRef,
  2083. Req->getConstraintExpr()->getBeginLoc(), Req, Info,
  2084. Req->getConstraintExpr()->getSourceRange());
  2085. if (ConstrInst.isInvalid())
  2086. return nullptr;
  2087. llvm::SmallVector<Expr *> Result;
  2088. if (!SemaRef.CheckConstraintSatisfaction(
  2089. nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
  2090. Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
  2091. !Result.empty())
  2092. TransConstraint = Result[0];
  2093. assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
  2094. "by CheckConstraintSatisfaction.");
  2095. }
  2096. if (TransConstraint.isUsable() &&
  2097. TransConstraint.get()->isInstantiationDependent())
  2098. return new (SemaRef.Context)
  2099. concepts::NestedRequirement(TransConstraint.get());
  2100. if (TransConstraint.isInvalid() || !TransConstraint.get() ||
  2101. Satisfaction.HasSubstitutionFailure()) {
  2102. SmallString<128> Entity;
  2103. llvm::raw_svector_ostream OS(Entity);
  2104. Req->getConstraintExpr()->printPretty(OS, nullptr,
  2105. SemaRef.getPrintingPolicy());
  2106. char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
  2107. std::copy(Entity.begin(), Entity.end(), EntityBuf);
  2108. return new (SemaRef.Context) concepts::NestedRequirement(
  2109. SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
  2110. }
  2111. return new (SemaRef.Context) concepts::NestedRequirement(
  2112. SemaRef.Context, TransConstraint.get(), Satisfaction);
  2113. }
  2114. /// Perform substitution on the type T with a given set of template
  2115. /// arguments.
  2116. ///
  2117. /// This routine substitutes the given template arguments into the
  2118. /// type T and produces the instantiated type.
  2119. ///
  2120. /// \param T the type into which the template arguments will be
  2121. /// substituted. If this type is not dependent, it will be returned
  2122. /// immediately.
  2123. ///
  2124. /// \param Args the template arguments that will be
  2125. /// substituted for the top-level template parameters within T.
  2126. ///
  2127. /// \param Loc the location in the source code where this substitution
  2128. /// is being performed. It will typically be the location of the
  2129. /// declarator (if we're instantiating the type of some declaration)
  2130. /// or the location of the type in the source code (if, e.g., we're
  2131. /// instantiating the type of a cast expression).
  2132. ///
  2133. /// \param Entity the name of the entity associated with a declaration
  2134. /// being instantiated (if any). May be empty to indicate that there
  2135. /// is no such entity (if, e.g., this is a type that occurs as part of
  2136. /// a cast expression) or that the entity has no name (e.g., an
  2137. /// unnamed function parameter).
  2138. ///
  2139. /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
  2140. /// acceptable as the top level type of the result.
  2141. ///
  2142. /// \returns If the instantiation succeeds, the instantiated
  2143. /// type. Otherwise, produces diagnostics and returns a NULL type.
  2144. TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
  2145. const MultiLevelTemplateArgumentList &Args,
  2146. SourceLocation Loc,
  2147. DeclarationName Entity,
  2148. bool AllowDeducedTST) {
  2149. assert(!CodeSynthesisContexts.empty() &&
  2150. "Cannot perform an instantiation without some context on the "
  2151. "instantiation stack");
  2152. if (!T->getType()->isInstantiationDependentType() &&
  2153. !T->getType()->isVariablyModifiedType())
  2154. return T;
  2155. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  2156. return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
  2157. : Instantiator.TransformType(T);
  2158. }
  2159. TypeSourceInfo *Sema::SubstType(TypeLoc TL,
  2160. const MultiLevelTemplateArgumentList &Args,
  2161. SourceLocation Loc,
  2162. DeclarationName Entity) {
  2163. assert(!CodeSynthesisContexts.empty() &&
  2164. "Cannot perform an instantiation without some context on the "
  2165. "instantiation stack");
  2166. if (TL.getType().isNull())
  2167. return nullptr;
  2168. if (!TL.getType()->isInstantiationDependentType() &&
  2169. !TL.getType()->isVariablyModifiedType()) {
  2170. // FIXME: Make a copy of the TypeLoc data here, so that we can
  2171. // return a new TypeSourceInfo. Inefficient!
  2172. TypeLocBuilder TLB;
  2173. TLB.pushFullCopy(TL);
  2174. return TLB.getTypeSourceInfo(Context, TL.getType());
  2175. }
  2176. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  2177. TypeLocBuilder TLB;
  2178. TLB.reserve(TL.getFullDataSize());
  2179. QualType Result = Instantiator.TransformType(TLB, TL);
  2180. if (Result.isNull())
  2181. return nullptr;
  2182. return TLB.getTypeSourceInfo(Context, Result);
  2183. }
  2184. /// Deprecated form of the above.
  2185. QualType Sema::SubstType(QualType T,
  2186. const MultiLevelTemplateArgumentList &TemplateArgs,
  2187. SourceLocation Loc, DeclarationName Entity) {
  2188. assert(!CodeSynthesisContexts.empty() &&
  2189. "Cannot perform an instantiation without some context on the "
  2190. "instantiation stack");
  2191. // If T is not a dependent type or a variably-modified type, there
  2192. // is nothing to do.
  2193. if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
  2194. return T;
  2195. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
  2196. return Instantiator.TransformType(T);
  2197. }
  2198. static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
  2199. if (T->getType()->isInstantiationDependentType() ||
  2200. T->getType()->isVariablyModifiedType())
  2201. return true;
  2202. TypeLoc TL = T->getTypeLoc().IgnoreParens();
  2203. if (!TL.getAs<FunctionProtoTypeLoc>())
  2204. return false;
  2205. FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
  2206. for (ParmVarDecl *P : FP.getParams()) {
  2207. // This must be synthesized from a typedef.
  2208. if (!P) continue;
  2209. // If there are any parameters, a new TypeSourceInfo that refers to the
  2210. // instantiated parameters must be built.
  2211. return true;
  2212. }
  2213. return false;
  2214. }
  2215. /// A form of SubstType intended specifically for instantiating the
  2216. /// type of a FunctionDecl. Its purpose is solely to force the
  2217. /// instantiation of default-argument expressions and to avoid
  2218. /// instantiating an exception-specification.
  2219. TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
  2220. const MultiLevelTemplateArgumentList &Args,
  2221. SourceLocation Loc,
  2222. DeclarationName Entity,
  2223. CXXRecordDecl *ThisContext,
  2224. Qualifiers ThisTypeQuals,
  2225. bool EvaluateConstraints) {
  2226. assert(!CodeSynthesisContexts.empty() &&
  2227. "Cannot perform an instantiation without some context on the "
  2228. "instantiation stack");
  2229. if (!NeedsInstantiationAsFunctionType(T))
  2230. return T;
  2231. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  2232. Instantiator.setEvaluateConstraints(EvaluateConstraints);
  2233. TypeLocBuilder TLB;
  2234. TypeLoc TL = T->getTypeLoc();
  2235. TLB.reserve(TL.getFullDataSize());
  2236. QualType Result;
  2237. if (FunctionProtoTypeLoc Proto =
  2238. TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
  2239. // Instantiate the type, other than its exception specification. The
  2240. // exception specification is instantiated in InitFunctionInstantiation
  2241. // once we've built the FunctionDecl.
  2242. // FIXME: Set the exception specification to EST_Uninstantiated here,
  2243. // instead of rebuilding the function type again later.
  2244. Result = Instantiator.TransformFunctionProtoType(
  2245. TLB, Proto, ThisContext, ThisTypeQuals,
  2246. [](FunctionProtoType::ExceptionSpecInfo &ESI,
  2247. bool &Changed) { return false; });
  2248. } else {
  2249. Result = Instantiator.TransformType(TLB, TL);
  2250. }
  2251. if (Result.isNull())
  2252. return nullptr;
  2253. return TLB.getTypeSourceInfo(Context, Result);
  2254. }
  2255. bool Sema::SubstExceptionSpec(SourceLocation Loc,
  2256. FunctionProtoType::ExceptionSpecInfo &ESI,
  2257. SmallVectorImpl<QualType> &ExceptionStorage,
  2258. const MultiLevelTemplateArgumentList &Args) {
  2259. assert(ESI.Type != EST_Uninstantiated);
  2260. bool Changed = false;
  2261. TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
  2262. return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
  2263. Changed);
  2264. }
  2265. void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
  2266. const MultiLevelTemplateArgumentList &Args) {
  2267. FunctionProtoType::ExceptionSpecInfo ESI =
  2268. Proto->getExtProtoInfo().ExceptionSpec;
  2269. SmallVector<QualType, 4> ExceptionStorage;
  2270. if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
  2271. ESI, ExceptionStorage, Args))
  2272. // On error, recover by dropping the exception specification.
  2273. ESI.Type = EST_None;
  2274. UpdateExceptionSpec(New, ESI);
  2275. }
  2276. namespace {
  2277. struct GetContainedInventedTypeParmVisitor :
  2278. public TypeVisitor<GetContainedInventedTypeParmVisitor,
  2279. TemplateTypeParmDecl *> {
  2280. using TypeVisitor<GetContainedInventedTypeParmVisitor,
  2281. TemplateTypeParmDecl *>::Visit;
  2282. TemplateTypeParmDecl *Visit(QualType T) {
  2283. if (T.isNull())
  2284. return nullptr;
  2285. return Visit(T.getTypePtr());
  2286. }
  2287. // The deduced type itself.
  2288. TemplateTypeParmDecl *VisitTemplateTypeParmType(
  2289. const TemplateTypeParmType *T) {
  2290. if (!T->getDecl() || !T->getDecl()->isImplicit())
  2291. return nullptr;
  2292. return T->getDecl();
  2293. }
  2294. // Only these types can contain 'auto' types, and subsequently be replaced
  2295. // by references to invented parameters.
  2296. TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
  2297. return Visit(T->getNamedType());
  2298. }
  2299. TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
  2300. return Visit(T->getPointeeType());
  2301. }
  2302. TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
  2303. return Visit(T->getPointeeType());
  2304. }
  2305. TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
  2306. return Visit(T->getPointeeTypeAsWritten());
  2307. }
  2308. TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
  2309. return Visit(T->getPointeeType());
  2310. }
  2311. TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
  2312. return Visit(T->getElementType());
  2313. }
  2314. TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
  2315. const DependentSizedExtVectorType *T) {
  2316. return Visit(T->getElementType());
  2317. }
  2318. TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
  2319. return Visit(T->getElementType());
  2320. }
  2321. TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
  2322. return VisitFunctionType(T);
  2323. }
  2324. TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
  2325. return Visit(T->getReturnType());
  2326. }
  2327. TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
  2328. return Visit(T->getInnerType());
  2329. }
  2330. TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
  2331. return Visit(T->getModifiedType());
  2332. }
  2333. TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
  2334. return Visit(T->getUnderlyingType());
  2335. }
  2336. TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
  2337. return Visit(T->getOriginalType());
  2338. }
  2339. TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
  2340. return Visit(T->getPattern());
  2341. }
  2342. };
  2343. } // namespace
  2344. bool Sema::SubstTypeConstraint(
  2345. TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
  2346. const MultiLevelTemplateArgumentList &TemplateArgs,
  2347. bool EvaluateConstraints) {
  2348. const ASTTemplateArgumentListInfo *TemplArgInfo =
  2349. TC->getTemplateArgsAsWritten();
  2350. if (!EvaluateConstraints) {
  2351. Inst->setTypeConstraint(TC->getNestedNameSpecifierLoc(),
  2352. TC->getConceptNameInfo(), TC->getNamedConcept(),
  2353. TC->getNamedConcept(), TemplArgInfo,
  2354. TC->getImmediatelyDeclaredConstraint());
  2355. return false;
  2356. }
  2357. TemplateArgumentListInfo InstArgs;
  2358. if (TemplArgInfo) {
  2359. InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
  2360. InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
  2361. if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
  2362. InstArgs))
  2363. return true;
  2364. }
  2365. return AttachTypeConstraint(
  2366. TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
  2367. TC->getNamedConcept(), &InstArgs, Inst,
  2368. Inst->isParameterPack()
  2369. ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
  2370. ->getEllipsisLoc()
  2371. : SourceLocation());
  2372. }
  2373. ParmVarDecl *Sema::SubstParmVarDecl(
  2374. ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
  2375. int indexAdjustment, std::optional<unsigned> NumExpansions,
  2376. bool ExpectParameterPack, bool EvaluateConstraint) {
  2377. TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
  2378. TypeSourceInfo *NewDI = nullptr;
  2379. TypeLoc OldTL = OldDI->getTypeLoc();
  2380. if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
  2381. // We have a function parameter pack. Substitute into the pattern of the
  2382. // expansion.
  2383. NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
  2384. OldParm->getLocation(), OldParm->getDeclName());
  2385. if (!NewDI)
  2386. return nullptr;
  2387. if (NewDI->getType()->containsUnexpandedParameterPack()) {
  2388. // We still have unexpanded parameter packs, which means that
  2389. // our function parameter is still a function parameter pack.
  2390. // Therefore, make its type a pack expansion type.
  2391. NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
  2392. NumExpansions);
  2393. } else if (ExpectParameterPack) {
  2394. // We expected to get a parameter pack but didn't (because the type
  2395. // itself is not a pack expansion type), so complain. This can occur when
  2396. // the substitution goes through an alias template that "loses" the
  2397. // pack expansion.
  2398. Diag(OldParm->getLocation(),
  2399. diag::err_function_parameter_pack_without_parameter_packs)
  2400. << NewDI->getType();
  2401. return nullptr;
  2402. }
  2403. } else {
  2404. NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
  2405. OldParm->getDeclName());
  2406. }
  2407. if (!NewDI)
  2408. return nullptr;
  2409. if (NewDI->getType()->isVoidType()) {
  2410. Diag(OldParm->getLocation(), diag::err_param_with_void_type);
  2411. return nullptr;
  2412. }
  2413. // In abbreviated templates, TemplateTypeParmDecls with possible
  2414. // TypeConstraints are created when the parameter list is originally parsed.
  2415. // The TypeConstraints can therefore reference other functions parameters in
  2416. // the abbreviated function template, which is why we must instantiate them
  2417. // here, when the instantiated versions of those referenced parameters are in
  2418. // scope.
  2419. if (TemplateTypeParmDecl *TTP =
  2420. GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
  2421. if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
  2422. auto *Inst = cast_or_null<TemplateTypeParmDecl>(
  2423. FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
  2424. // We will first get here when instantiating the abbreviated function
  2425. // template's described function, but we might also get here later.
  2426. // Make sure we do not instantiate the TypeConstraint more than once.
  2427. if (Inst && !Inst->getTypeConstraint()) {
  2428. if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
  2429. return nullptr;
  2430. }
  2431. }
  2432. }
  2433. ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
  2434. OldParm->getInnerLocStart(),
  2435. OldParm->getLocation(),
  2436. OldParm->getIdentifier(),
  2437. NewDI->getType(), NewDI,
  2438. OldParm->getStorageClass());
  2439. if (!NewParm)
  2440. return nullptr;
  2441. // Mark the (new) default argument as uninstantiated (if any).
  2442. if (OldParm->hasUninstantiatedDefaultArg()) {
  2443. Expr *Arg = OldParm->getUninstantiatedDefaultArg();
  2444. NewParm->setUninstantiatedDefaultArg(Arg);
  2445. } else if (OldParm->hasUnparsedDefaultArg()) {
  2446. NewParm->setUnparsedDefaultArg();
  2447. UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
  2448. } else if (Expr *Arg = OldParm->getDefaultArg()) {
  2449. // Default arguments cannot be substituted until the declaration context
  2450. // for the associated function or lambda capture class is available.
  2451. // This is necessary for cases like the following where construction of
  2452. // the lambda capture class for the outer lambda is dependent on the
  2453. // parameter types but where the default argument is dependent on the
  2454. // outer lambda's declaration context.
  2455. // template <typename T>
  2456. // auto f() {
  2457. // return [](T = []{ return T{}; }()) { return 0; };
  2458. // }
  2459. NewParm->setUninstantiatedDefaultArg(Arg);
  2460. }
  2461. NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
  2462. if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
  2463. // Add the new parameter to the instantiated parameter pack.
  2464. CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
  2465. } else {
  2466. // Introduce an Old -> New mapping
  2467. CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
  2468. }
  2469. // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
  2470. // can be anything, is this right ?
  2471. NewParm->setDeclContext(CurContext);
  2472. NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
  2473. OldParm->getFunctionScopeIndex() + indexAdjustment);
  2474. InstantiateAttrs(TemplateArgs, OldParm, NewParm);
  2475. return NewParm;
  2476. }
  2477. /// Substitute the given template arguments into the given set of
  2478. /// parameters, producing the set of parameter types that would be generated
  2479. /// from such a substitution.
  2480. bool Sema::SubstParmTypes(
  2481. SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
  2482. const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
  2483. const MultiLevelTemplateArgumentList &TemplateArgs,
  2484. SmallVectorImpl<QualType> &ParamTypes,
  2485. SmallVectorImpl<ParmVarDecl *> *OutParams,
  2486. ExtParameterInfoBuilder &ParamInfos) {
  2487. assert(!CodeSynthesisContexts.empty() &&
  2488. "Cannot perform an instantiation without some context on the "
  2489. "instantiation stack");
  2490. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  2491. DeclarationName());
  2492. return Instantiator.TransformFunctionTypeParams(
  2493. Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
  2494. }
  2495. /// Substitute the given template arguments into the default argument.
  2496. bool Sema::SubstDefaultArgument(
  2497. SourceLocation Loc,
  2498. ParmVarDecl *Param,
  2499. const MultiLevelTemplateArgumentList &TemplateArgs,
  2500. bool ForCallExpr) {
  2501. FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
  2502. Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
  2503. EnterExpressionEvaluationContext EvalContext(
  2504. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  2505. InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
  2506. if (Inst.isInvalid())
  2507. return true;
  2508. if (Inst.isAlreadyInstantiating()) {
  2509. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  2510. Param->setInvalidDecl();
  2511. return true;
  2512. }
  2513. ExprResult Result;
  2514. {
  2515. // C++ [dcl.fct.default]p5:
  2516. // The names in the [default argument] expression are bound, and
  2517. // the semantic constraints are checked, at the point where the
  2518. // default argument expression appears.
  2519. ContextRAII SavedContext(*this, FD);
  2520. std::unique_ptr<LocalInstantiationScope> LIS;
  2521. if (ForCallExpr) {
  2522. // When instantiating a default argument due to use in a call expression,
  2523. // an instantiation scope that includes the parameters of the callee is
  2524. // required to satisfy references from the default argument. For example:
  2525. // template<typename T> void f(T a, int = decltype(a)());
  2526. // void g() { f(0); }
  2527. LIS = std::make_unique<LocalInstantiationScope>(*this);
  2528. FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
  2529. /*ForDefinition*/ false);
  2530. if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
  2531. return true;
  2532. }
  2533. runWithSufficientStackSpace(Loc, [&] {
  2534. Result = SubstInitializer(PatternExpr, TemplateArgs,
  2535. /*DirectInit*/false);
  2536. });
  2537. }
  2538. if (Result.isInvalid())
  2539. return true;
  2540. if (ForCallExpr) {
  2541. // Check the expression as an initializer for the parameter.
  2542. InitializedEntity Entity
  2543. = InitializedEntity::InitializeParameter(Context, Param);
  2544. InitializationKind Kind = InitializationKind::CreateCopy(
  2545. Param->getLocation(),
  2546. /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
  2547. Expr *ResultE = Result.getAs<Expr>();
  2548. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  2549. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  2550. if (Result.isInvalid())
  2551. return true;
  2552. Result =
  2553. ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
  2554. /*DiscardedValue*/ false);
  2555. } else {
  2556. // FIXME: Obtain the source location for the '=' token.
  2557. SourceLocation EqualLoc = PatternExpr->getBeginLoc();
  2558. Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
  2559. }
  2560. if (Result.isInvalid())
  2561. return true;
  2562. // Remember the instantiated default argument.
  2563. Param->setDefaultArg(Result.getAs<Expr>());
  2564. return false;
  2565. }
  2566. /// Perform substitution on the base class specifiers of the
  2567. /// given class template specialization.
  2568. ///
  2569. /// Produces a diagnostic and returns true on error, returns false and
  2570. /// attaches the instantiated base classes to the class template
  2571. /// specialization if successful.
  2572. bool
  2573. Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
  2574. CXXRecordDecl *Pattern,
  2575. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2576. bool Invalid = false;
  2577. SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
  2578. for (const auto &Base : Pattern->bases()) {
  2579. if (!Base.getType()->isDependentType()) {
  2580. if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
  2581. if (RD->isInvalidDecl())
  2582. Instantiation->setInvalidDecl();
  2583. }
  2584. InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
  2585. continue;
  2586. }
  2587. SourceLocation EllipsisLoc;
  2588. TypeSourceInfo *BaseTypeLoc;
  2589. if (Base.isPackExpansion()) {
  2590. // This is a pack expansion. See whether we should expand it now, or
  2591. // wait until later.
  2592. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2593. collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
  2594. Unexpanded);
  2595. bool ShouldExpand = false;
  2596. bool RetainExpansion = false;
  2597. std::optional<unsigned> NumExpansions;
  2598. if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
  2599. Base.getSourceRange(),
  2600. Unexpanded,
  2601. TemplateArgs, ShouldExpand,
  2602. RetainExpansion,
  2603. NumExpansions)) {
  2604. Invalid = true;
  2605. continue;
  2606. }
  2607. // If we should expand this pack expansion now, do so.
  2608. if (ShouldExpand) {
  2609. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2610. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  2611. TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  2612. TemplateArgs,
  2613. Base.getSourceRange().getBegin(),
  2614. DeclarationName());
  2615. if (!BaseTypeLoc) {
  2616. Invalid = true;
  2617. continue;
  2618. }
  2619. if (CXXBaseSpecifier *InstantiatedBase
  2620. = CheckBaseSpecifier(Instantiation,
  2621. Base.getSourceRange(),
  2622. Base.isVirtual(),
  2623. Base.getAccessSpecifierAsWritten(),
  2624. BaseTypeLoc,
  2625. SourceLocation()))
  2626. InstantiatedBases.push_back(InstantiatedBase);
  2627. else
  2628. Invalid = true;
  2629. }
  2630. continue;
  2631. }
  2632. // The resulting base specifier will (still) be a pack expansion.
  2633. EllipsisLoc = Base.getEllipsisLoc();
  2634. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  2635. BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  2636. TemplateArgs,
  2637. Base.getSourceRange().getBegin(),
  2638. DeclarationName());
  2639. } else {
  2640. BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  2641. TemplateArgs,
  2642. Base.getSourceRange().getBegin(),
  2643. DeclarationName());
  2644. }
  2645. if (!BaseTypeLoc) {
  2646. Invalid = true;
  2647. continue;
  2648. }
  2649. if (CXXBaseSpecifier *InstantiatedBase
  2650. = CheckBaseSpecifier(Instantiation,
  2651. Base.getSourceRange(),
  2652. Base.isVirtual(),
  2653. Base.getAccessSpecifierAsWritten(),
  2654. BaseTypeLoc,
  2655. EllipsisLoc))
  2656. InstantiatedBases.push_back(InstantiatedBase);
  2657. else
  2658. Invalid = true;
  2659. }
  2660. if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
  2661. Invalid = true;
  2662. return Invalid;
  2663. }
  2664. // Defined via #include from SemaTemplateInstantiateDecl.cpp
  2665. namespace clang {
  2666. namespace sema {
  2667. Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
  2668. const MultiLevelTemplateArgumentList &TemplateArgs);
  2669. Attr *instantiateTemplateAttributeForDecl(
  2670. const Attr *At, ASTContext &C, Sema &S,
  2671. const MultiLevelTemplateArgumentList &TemplateArgs);
  2672. }
  2673. }
  2674. /// Instantiate the definition of a class from a given pattern.
  2675. ///
  2676. /// \param PointOfInstantiation The point of instantiation within the
  2677. /// source code.
  2678. ///
  2679. /// \param Instantiation is the declaration whose definition is being
  2680. /// instantiated. This will be either a class template specialization
  2681. /// or a member class of a class template specialization.
  2682. ///
  2683. /// \param Pattern is the pattern from which the instantiation
  2684. /// occurs. This will be either the declaration of a class template or
  2685. /// the declaration of a member class of a class template.
  2686. ///
  2687. /// \param TemplateArgs The template arguments to be substituted into
  2688. /// the pattern.
  2689. ///
  2690. /// \param TSK the kind of implicit or explicit instantiation to perform.
  2691. ///
  2692. /// \param Complain whether to complain if the class cannot be instantiated due
  2693. /// to the lack of a definition.
  2694. ///
  2695. /// \returns true if an error occurred, false otherwise.
  2696. bool
  2697. Sema::InstantiateClass(SourceLocation PointOfInstantiation,
  2698. CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
  2699. const MultiLevelTemplateArgumentList &TemplateArgs,
  2700. TemplateSpecializationKind TSK,
  2701. bool Complain) {
  2702. CXXRecordDecl *PatternDef
  2703. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  2704. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
  2705. Instantiation->getInstantiatedFromMemberClass(),
  2706. Pattern, PatternDef, TSK, Complain))
  2707. return true;
  2708. llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
  2709. std::string Name;
  2710. llvm::raw_string_ostream OS(Name);
  2711. Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
  2712. /*Qualified=*/true);
  2713. return Name;
  2714. });
  2715. Pattern = PatternDef;
  2716. // Record the point of instantiation.
  2717. if (MemberSpecializationInfo *MSInfo
  2718. = Instantiation->getMemberSpecializationInfo()) {
  2719. MSInfo->setTemplateSpecializationKind(TSK);
  2720. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2721. } else if (ClassTemplateSpecializationDecl *Spec
  2722. = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
  2723. Spec->setTemplateSpecializationKind(TSK);
  2724. Spec->setPointOfInstantiation(PointOfInstantiation);
  2725. }
  2726. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  2727. if (Inst.isInvalid())
  2728. return true;
  2729. assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
  2730. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  2731. "instantiating class definition");
  2732. // Enter the scope of this instantiation. We don't use
  2733. // PushDeclContext because we don't have a scope.
  2734. ContextRAII SavedContext(*this, Instantiation);
  2735. EnterExpressionEvaluationContext EvalContext(
  2736. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  2737. // If this is an instantiation of a local class, merge this local
  2738. // instantiation scope with the enclosing scope. Otherwise, every
  2739. // instantiation of a class has its own local instantiation scope.
  2740. bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
  2741. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  2742. // Some class state isn't processed immediately but delayed till class
  2743. // instantiation completes. We may not be ready to handle any delayed state
  2744. // already on the stack as it might correspond to a different class, so save
  2745. // it now and put it back later.
  2746. SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
  2747. // Pull attributes from the pattern onto the instantiation.
  2748. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  2749. // Start the definition of this instantiation.
  2750. Instantiation->startDefinition();
  2751. // The instantiation is visible here, even if it was first declared in an
  2752. // unimported module.
  2753. Instantiation->setVisibleDespiteOwningModule();
  2754. // FIXME: This loses the as-written tag kind for an explicit instantiation.
  2755. Instantiation->setTagKind(Pattern->getTagKind());
  2756. // Do substitution on the base class specifiers.
  2757. if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
  2758. Instantiation->setInvalidDecl();
  2759. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  2760. Instantiator.setEvaluateConstraints(false);
  2761. SmallVector<Decl*, 4> Fields;
  2762. // Delay instantiation of late parsed attributes.
  2763. LateInstantiatedAttrVec LateAttrs;
  2764. Instantiator.enableLateAttributeInstantiation(&LateAttrs);
  2765. bool MightHaveConstexprVirtualFunctions = false;
  2766. for (auto *Member : Pattern->decls()) {
  2767. // Don't instantiate members not belonging in this semantic context.
  2768. // e.g. for:
  2769. // @code
  2770. // template <int i> class A {
  2771. // class B *g;
  2772. // };
  2773. // @endcode
  2774. // 'class B' has the template as lexical context but semantically it is
  2775. // introduced in namespace scope.
  2776. if (Member->getDeclContext() != Pattern)
  2777. continue;
  2778. // BlockDecls can appear in a default-member-initializer. They must be the
  2779. // child of a BlockExpr, so we only know how to instantiate them from there.
  2780. // Similarly, lambda closure types are recreated when instantiating the
  2781. // corresponding LambdaExpr.
  2782. if (isa<BlockDecl>(Member) ||
  2783. (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
  2784. continue;
  2785. if (Member->isInvalidDecl()) {
  2786. Instantiation->setInvalidDecl();
  2787. continue;
  2788. }
  2789. Decl *NewMember = Instantiator.Visit(Member);
  2790. if (NewMember) {
  2791. if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
  2792. Fields.push_back(Field);
  2793. } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
  2794. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  2795. // specialization causes the implicit instantiation of the definitions
  2796. // of unscoped member enumerations.
  2797. // Record a point of instantiation for this implicit instantiation.
  2798. if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
  2799. Enum->isCompleteDefinition()) {
  2800. MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
  2801. assert(MSInfo && "no spec info for member enum specialization");
  2802. MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
  2803. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2804. }
  2805. } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
  2806. if (SA->isFailed()) {
  2807. // A static_assert failed. Bail out; instantiating this
  2808. // class is probably not meaningful.
  2809. Instantiation->setInvalidDecl();
  2810. break;
  2811. }
  2812. } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
  2813. if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
  2814. (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
  2815. MightHaveConstexprVirtualFunctions = true;
  2816. }
  2817. if (NewMember->isInvalidDecl())
  2818. Instantiation->setInvalidDecl();
  2819. } else {
  2820. // FIXME: Eventually, a NULL return will mean that one of the
  2821. // instantiations was a semantic disaster, and we'll want to mark the
  2822. // declaration invalid.
  2823. // For now, we expect to skip some members that we can't yet handle.
  2824. }
  2825. }
  2826. // Finish checking fields.
  2827. ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
  2828. SourceLocation(), SourceLocation(), ParsedAttributesView());
  2829. CheckCompletedCXXClass(nullptr, Instantiation);
  2830. // Default arguments are parsed, if not instantiated. We can go instantiate
  2831. // default arg exprs for default constructors if necessary now. Unless we're
  2832. // parsing a class, in which case wait until that's finished.
  2833. if (ParsingClassDepth == 0)
  2834. ActOnFinishCXXNonNestedClass();
  2835. // Instantiate late parsed attributes, and attach them to their decls.
  2836. // See Sema::InstantiateAttrs
  2837. for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
  2838. E = LateAttrs.end(); I != E; ++I) {
  2839. assert(CurrentInstantiationScope == Instantiator.getStartingScope());
  2840. CurrentInstantiationScope = I->Scope;
  2841. // Allow 'this' within late-parsed attributes.
  2842. auto *ND = cast<NamedDecl>(I->NewDecl);
  2843. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  2844. CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
  2845. ND->isCXXInstanceMember());
  2846. Attr *NewAttr =
  2847. instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
  2848. if (NewAttr)
  2849. I->NewDecl->addAttr(NewAttr);
  2850. LocalInstantiationScope::deleteScopes(I->Scope,
  2851. Instantiator.getStartingScope());
  2852. }
  2853. Instantiator.disableLateAttributeInstantiation();
  2854. LateAttrs.clear();
  2855. ActOnFinishDelayedMemberInitializers(Instantiation);
  2856. // FIXME: We should do something similar for explicit instantiations so they
  2857. // end up in the right module.
  2858. if (TSK == TSK_ImplicitInstantiation) {
  2859. Instantiation->setLocation(Pattern->getLocation());
  2860. Instantiation->setLocStart(Pattern->getInnerLocStart());
  2861. Instantiation->setBraceRange(Pattern->getBraceRange());
  2862. }
  2863. if (!Instantiation->isInvalidDecl()) {
  2864. // Perform any dependent diagnostics from the pattern.
  2865. if (Pattern->isDependentContext())
  2866. PerformDependentDiagnostics(Pattern, TemplateArgs);
  2867. // Instantiate any out-of-line class template partial
  2868. // specializations now.
  2869. for (TemplateDeclInstantiator::delayed_partial_spec_iterator
  2870. P = Instantiator.delayed_partial_spec_begin(),
  2871. PEnd = Instantiator.delayed_partial_spec_end();
  2872. P != PEnd; ++P) {
  2873. if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
  2874. P->first, P->second)) {
  2875. Instantiation->setInvalidDecl();
  2876. break;
  2877. }
  2878. }
  2879. // Instantiate any out-of-line variable template partial
  2880. // specializations now.
  2881. for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
  2882. P = Instantiator.delayed_var_partial_spec_begin(),
  2883. PEnd = Instantiator.delayed_var_partial_spec_end();
  2884. P != PEnd; ++P) {
  2885. if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
  2886. P->first, P->second)) {
  2887. Instantiation->setInvalidDecl();
  2888. break;
  2889. }
  2890. }
  2891. }
  2892. // Exit the scope of this instantiation.
  2893. SavedContext.pop();
  2894. if (!Instantiation->isInvalidDecl()) {
  2895. // Always emit the vtable for an explicit instantiation definition
  2896. // of a polymorphic class template specialization. Otherwise, eagerly
  2897. // instantiate only constexpr virtual functions in preparation for their use
  2898. // in constant evaluation.
  2899. if (TSK == TSK_ExplicitInstantiationDefinition)
  2900. MarkVTableUsed(PointOfInstantiation, Instantiation, true);
  2901. else if (MightHaveConstexprVirtualFunctions)
  2902. MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
  2903. /*ConstexprOnly*/ true);
  2904. }
  2905. Consumer.HandleTagDeclDefinition(Instantiation);
  2906. return Instantiation->isInvalidDecl();
  2907. }
  2908. /// Instantiate the definition of an enum from a given pattern.
  2909. ///
  2910. /// \param PointOfInstantiation The point of instantiation within the
  2911. /// source code.
  2912. /// \param Instantiation is the declaration whose definition is being
  2913. /// instantiated. This will be a member enumeration of a class
  2914. /// temploid specialization, or a local enumeration within a
  2915. /// function temploid specialization.
  2916. /// \param Pattern The templated declaration from which the instantiation
  2917. /// occurs.
  2918. /// \param TemplateArgs The template arguments to be substituted into
  2919. /// the pattern.
  2920. /// \param TSK The kind of implicit or explicit instantiation to perform.
  2921. ///
  2922. /// \return \c true if an error occurred, \c false otherwise.
  2923. bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
  2924. EnumDecl *Instantiation, EnumDecl *Pattern,
  2925. const MultiLevelTemplateArgumentList &TemplateArgs,
  2926. TemplateSpecializationKind TSK) {
  2927. EnumDecl *PatternDef = Pattern->getDefinition();
  2928. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
  2929. Instantiation->getInstantiatedFromMemberEnum(),
  2930. Pattern, PatternDef, TSK,/*Complain*/true))
  2931. return true;
  2932. Pattern = PatternDef;
  2933. // Record the point of instantiation.
  2934. if (MemberSpecializationInfo *MSInfo
  2935. = Instantiation->getMemberSpecializationInfo()) {
  2936. MSInfo->setTemplateSpecializationKind(TSK);
  2937. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2938. }
  2939. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  2940. if (Inst.isInvalid())
  2941. return true;
  2942. if (Inst.isAlreadyInstantiating())
  2943. return false;
  2944. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  2945. "instantiating enum definition");
  2946. // The instantiation is visible here, even if it was first declared in an
  2947. // unimported module.
  2948. Instantiation->setVisibleDespiteOwningModule();
  2949. // Enter the scope of this instantiation. We don't use
  2950. // PushDeclContext because we don't have a scope.
  2951. ContextRAII SavedContext(*this, Instantiation);
  2952. EnterExpressionEvaluationContext EvalContext(
  2953. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  2954. LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
  2955. // Pull attributes from the pattern onto the instantiation.
  2956. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  2957. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  2958. Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
  2959. // Exit the scope of this instantiation.
  2960. SavedContext.pop();
  2961. return Instantiation->isInvalidDecl();
  2962. }
  2963. /// Instantiate the definition of a field from the given pattern.
  2964. ///
  2965. /// \param PointOfInstantiation The point of instantiation within the
  2966. /// source code.
  2967. /// \param Instantiation is the declaration whose definition is being
  2968. /// instantiated. This will be a class of a class temploid
  2969. /// specialization, or a local enumeration within a function temploid
  2970. /// specialization.
  2971. /// \param Pattern The templated declaration from which the instantiation
  2972. /// occurs.
  2973. /// \param TemplateArgs The template arguments to be substituted into
  2974. /// the pattern.
  2975. ///
  2976. /// \return \c true if an error occurred, \c false otherwise.
  2977. bool Sema::InstantiateInClassInitializer(
  2978. SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
  2979. FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2980. // If there is no initializer, we don't need to do anything.
  2981. if (!Pattern->hasInClassInitializer())
  2982. return false;
  2983. assert(Instantiation->getInClassInitStyle() ==
  2984. Pattern->getInClassInitStyle() &&
  2985. "pattern and instantiation disagree about init style");
  2986. // Error out if we haven't parsed the initializer of the pattern yet because
  2987. // we are waiting for the closing brace of the outer class.
  2988. Expr *OldInit = Pattern->getInClassInitializer();
  2989. if (!OldInit) {
  2990. RecordDecl *PatternRD = Pattern->getParent();
  2991. RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
  2992. Diag(PointOfInstantiation,
  2993. diag::err_default_member_initializer_not_yet_parsed)
  2994. << OutermostClass << Pattern;
  2995. Diag(Pattern->getEndLoc(),
  2996. diag::note_default_member_initializer_not_yet_parsed);
  2997. Instantiation->setInvalidDecl();
  2998. return true;
  2999. }
  3000. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  3001. if (Inst.isInvalid())
  3002. return true;
  3003. if (Inst.isAlreadyInstantiating()) {
  3004. // Error out if we hit an instantiation cycle for this initializer.
  3005. Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
  3006. << Instantiation;
  3007. return true;
  3008. }
  3009. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  3010. "instantiating default member init");
  3011. // Enter the scope of this instantiation. We don't use PushDeclContext because
  3012. // we don't have a scope.
  3013. ContextRAII SavedContext(*this, Instantiation->getParent());
  3014. EnterExpressionEvaluationContext EvalContext(
  3015. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  3016. ExprEvalContexts.back().DelayedDefaultInitializationContext = {
  3017. PointOfInstantiation, Instantiation, CurContext};
  3018. LocalInstantiationScope Scope(*this, true);
  3019. // Instantiate the initializer.
  3020. ActOnStartCXXInClassMemberInitializer();
  3021. CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
  3022. ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
  3023. /*CXXDirectInit=*/false);
  3024. Expr *Init = NewInit.get();
  3025. assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
  3026. ActOnFinishCXXInClassMemberInitializer(
  3027. Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
  3028. if (auto *L = getASTMutationListener())
  3029. L->DefaultMemberInitializerInstantiated(Instantiation);
  3030. // Return true if the in-class initializer is still missing.
  3031. return !Instantiation->getInClassInitializer();
  3032. }
  3033. namespace {
  3034. /// A partial specialization whose template arguments have matched
  3035. /// a given template-id.
  3036. struct PartialSpecMatchResult {
  3037. ClassTemplatePartialSpecializationDecl *Partial;
  3038. TemplateArgumentList *Args;
  3039. };
  3040. }
  3041. bool Sema::usesPartialOrExplicitSpecialization(
  3042. SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
  3043. if (ClassTemplateSpec->getTemplateSpecializationKind() ==
  3044. TSK_ExplicitSpecialization)
  3045. return true;
  3046. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  3047. ClassTemplateSpec->getSpecializedTemplate()
  3048. ->getPartialSpecializations(PartialSpecs);
  3049. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  3050. TemplateDeductionInfo Info(Loc);
  3051. if (!DeduceTemplateArguments(PartialSpecs[I],
  3052. ClassTemplateSpec->getTemplateArgs(), Info))
  3053. return true;
  3054. }
  3055. return false;
  3056. }
  3057. /// Get the instantiation pattern to use to instantiate the definition of a
  3058. /// given ClassTemplateSpecializationDecl (either the pattern of the primary
  3059. /// template or of a partial specialization).
  3060. static ActionResult<CXXRecordDecl *>
  3061. getPatternForClassTemplateSpecialization(
  3062. Sema &S, SourceLocation PointOfInstantiation,
  3063. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  3064. TemplateSpecializationKind TSK) {
  3065. Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
  3066. if (Inst.isInvalid())
  3067. return {/*Invalid=*/true};
  3068. if (Inst.isAlreadyInstantiating())
  3069. return {/*Invalid=*/false};
  3070. llvm::PointerUnion<ClassTemplateDecl *,
  3071. ClassTemplatePartialSpecializationDecl *>
  3072. Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
  3073. if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
  3074. // Find best matching specialization.
  3075. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  3076. // C++ [temp.class.spec.match]p1:
  3077. // When a class template is used in a context that requires an
  3078. // instantiation of the class, it is necessary to determine
  3079. // whether the instantiation is to be generated using the primary
  3080. // template or one of the partial specializations. This is done by
  3081. // matching the template arguments of the class template
  3082. // specialization with the template argument lists of the partial
  3083. // specializations.
  3084. typedef PartialSpecMatchResult MatchResult;
  3085. SmallVector<MatchResult, 4> Matched;
  3086. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  3087. Template->getPartialSpecializations(PartialSpecs);
  3088. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
  3089. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  3090. ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  3091. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  3092. if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
  3093. Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
  3094. // Store the failed-deduction information for use in diagnostics, later.
  3095. // TODO: Actually use the failed-deduction info?
  3096. FailedCandidates.addCandidate().set(
  3097. DeclAccessPair::make(Template, AS_public), Partial,
  3098. MakeDeductionFailureInfo(S.Context, Result, Info));
  3099. (void)Result;
  3100. } else {
  3101. Matched.push_back(PartialSpecMatchResult());
  3102. Matched.back().Partial = Partial;
  3103. Matched.back().Args = Info.takeCanonical();
  3104. }
  3105. }
  3106. // If we're dealing with a member template where the template parameters
  3107. // have been instantiated, this provides the original template parameters
  3108. // from which the member template's parameters were instantiated.
  3109. if (Matched.size() >= 1) {
  3110. SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
  3111. if (Matched.size() == 1) {
  3112. // -- If exactly one matching specialization is found, the
  3113. // instantiation is generated from that specialization.
  3114. // We don't need to do anything for this.
  3115. } else {
  3116. // -- If more than one matching specialization is found, the
  3117. // partial order rules (14.5.4.2) are used to determine
  3118. // whether one of the specializations is more specialized
  3119. // than the others. If none of the specializations is more
  3120. // specialized than all of the other matching
  3121. // specializations, then the use of the class template is
  3122. // ambiguous and the program is ill-formed.
  3123. for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
  3124. PEnd = Matched.end();
  3125. P != PEnd; ++P) {
  3126. if (S.getMoreSpecializedPartialSpecialization(
  3127. P->Partial, Best->Partial, PointOfInstantiation) ==
  3128. P->Partial)
  3129. Best = P;
  3130. }
  3131. // Determine if the best partial specialization is more specialized than
  3132. // the others.
  3133. bool Ambiguous = false;
  3134. for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
  3135. PEnd = Matched.end();
  3136. P != PEnd; ++P) {
  3137. if (P != Best && S.getMoreSpecializedPartialSpecialization(
  3138. P->Partial, Best->Partial,
  3139. PointOfInstantiation) != Best->Partial) {
  3140. Ambiguous = true;
  3141. break;
  3142. }
  3143. }
  3144. if (Ambiguous) {
  3145. // Partial ordering did not produce a clear winner. Complain.
  3146. Inst.Clear();
  3147. ClassTemplateSpec->setInvalidDecl();
  3148. S.Diag(PointOfInstantiation,
  3149. diag::err_partial_spec_ordering_ambiguous)
  3150. << ClassTemplateSpec;
  3151. // Print the matching partial specializations.
  3152. for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
  3153. PEnd = Matched.end();
  3154. P != PEnd; ++P)
  3155. S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
  3156. << S.getTemplateArgumentBindingsText(
  3157. P->Partial->getTemplateParameters(), *P->Args);
  3158. return {/*Invalid=*/true};
  3159. }
  3160. }
  3161. ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
  3162. } else {
  3163. // -- If no matches are found, the instantiation is generated
  3164. // from the primary template.
  3165. }
  3166. }
  3167. CXXRecordDecl *Pattern = nullptr;
  3168. Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
  3169. if (auto *PartialSpec =
  3170. Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  3171. // Instantiate using the best class template partial specialization.
  3172. while (PartialSpec->getInstantiatedFromMember()) {
  3173. // If we've found an explicit specialization of this class template,
  3174. // stop here and use that as the pattern.
  3175. if (PartialSpec->isMemberSpecialization())
  3176. break;
  3177. PartialSpec = PartialSpec->getInstantiatedFromMember();
  3178. }
  3179. Pattern = PartialSpec;
  3180. } else {
  3181. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  3182. while (Template->getInstantiatedFromMemberTemplate()) {
  3183. // If we've found an explicit specialization of this class template,
  3184. // stop here and use that as the pattern.
  3185. if (Template->isMemberSpecialization())
  3186. break;
  3187. Template = Template->getInstantiatedFromMemberTemplate();
  3188. }
  3189. Pattern = Template->getTemplatedDecl();
  3190. }
  3191. return Pattern;
  3192. }
  3193. bool Sema::InstantiateClassTemplateSpecialization(
  3194. SourceLocation PointOfInstantiation,
  3195. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  3196. TemplateSpecializationKind TSK, bool Complain) {
  3197. // Perform the actual instantiation on the canonical declaration.
  3198. ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
  3199. ClassTemplateSpec->getCanonicalDecl());
  3200. if (ClassTemplateSpec->isInvalidDecl())
  3201. return true;
  3202. ActionResult<CXXRecordDecl *> Pattern =
  3203. getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
  3204. ClassTemplateSpec, TSK);
  3205. if (!Pattern.isUsable())
  3206. return Pattern.isInvalid();
  3207. return InstantiateClass(
  3208. PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
  3209. getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
  3210. }
  3211. /// Instantiates the definitions of all of the member
  3212. /// of the given class, which is an instantiation of a class template
  3213. /// or a member class of a template.
  3214. void
  3215. Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
  3216. CXXRecordDecl *Instantiation,
  3217. const MultiLevelTemplateArgumentList &TemplateArgs,
  3218. TemplateSpecializationKind TSK) {
  3219. // FIXME: We need to notify the ASTMutationListener that we did all of these
  3220. // things, in case we have an explicit instantiation definition in a PCM, a
  3221. // module, or preamble, and the declaration is in an imported AST.
  3222. assert(
  3223. (TSK == TSK_ExplicitInstantiationDefinition ||
  3224. TSK == TSK_ExplicitInstantiationDeclaration ||
  3225. (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
  3226. "Unexpected template specialization kind!");
  3227. for (auto *D : Instantiation->decls()) {
  3228. bool SuppressNew = false;
  3229. if (auto *Function = dyn_cast<FunctionDecl>(D)) {
  3230. if (FunctionDecl *Pattern =
  3231. Function->getInstantiatedFromMemberFunction()) {
  3232. if (Function->isIneligibleOrNotSelected())
  3233. continue;
  3234. if (Function->getTrailingRequiresClause()) {
  3235. ConstraintSatisfaction Satisfaction;
  3236. if (CheckFunctionConstraints(Function, Satisfaction) ||
  3237. !Satisfaction.IsSatisfied) {
  3238. continue;
  3239. }
  3240. }
  3241. if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  3242. continue;
  3243. MemberSpecializationInfo *MSInfo =
  3244. Function->getMemberSpecializationInfo();
  3245. assert(MSInfo && "No member specialization information?");
  3246. if (MSInfo->getTemplateSpecializationKind()
  3247. == TSK_ExplicitSpecialization)
  3248. continue;
  3249. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  3250. Function,
  3251. MSInfo->getTemplateSpecializationKind(),
  3252. MSInfo->getPointOfInstantiation(),
  3253. SuppressNew) ||
  3254. SuppressNew)
  3255. continue;
  3256. // C++11 [temp.explicit]p8:
  3257. // An explicit instantiation definition that names a class template
  3258. // specialization explicitly instantiates the class template
  3259. // specialization and is only an explicit instantiation definition
  3260. // of members whose definition is visible at the point of
  3261. // instantiation.
  3262. if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
  3263. continue;
  3264. Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  3265. if (Function->isDefined()) {
  3266. // Let the ASTConsumer know that this function has been explicitly
  3267. // instantiated now, and its linkage might have changed.
  3268. Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
  3269. } else if (TSK == TSK_ExplicitInstantiationDefinition) {
  3270. InstantiateFunctionDefinition(PointOfInstantiation, Function);
  3271. } else if (TSK == TSK_ImplicitInstantiation) {
  3272. PendingLocalImplicitInstantiations.push_back(
  3273. std::make_pair(Function, PointOfInstantiation));
  3274. }
  3275. }
  3276. } else if (auto *Var = dyn_cast<VarDecl>(D)) {
  3277. if (isa<VarTemplateSpecializationDecl>(Var))
  3278. continue;
  3279. if (Var->isStaticDataMember()) {
  3280. if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  3281. continue;
  3282. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  3283. assert(MSInfo && "No member specialization information?");
  3284. if (MSInfo->getTemplateSpecializationKind()
  3285. == TSK_ExplicitSpecialization)
  3286. continue;
  3287. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  3288. Var,
  3289. MSInfo->getTemplateSpecializationKind(),
  3290. MSInfo->getPointOfInstantiation(),
  3291. SuppressNew) ||
  3292. SuppressNew)
  3293. continue;
  3294. if (TSK == TSK_ExplicitInstantiationDefinition) {
  3295. // C++0x [temp.explicit]p8:
  3296. // An explicit instantiation definition that names a class template
  3297. // specialization explicitly instantiates the class template
  3298. // specialization and is only an explicit instantiation definition
  3299. // of members whose definition is visible at the point of
  3300. // instantiation.
  3301. if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
  3302. continue;
  3303. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  3304. InstantiateVariableDefinition(PointOfInstantiation, Var);
  3305. } else {
  3306. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  3307. }
  3308. }
  3309. } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
  3310. if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  3311. continue;
  3312. // Always skip the injected-class-name, along with any
  3313. // redeclarations of nested classes, since both would cause us
  3314. // to try to instantiate the members of a class twice.
  3315. // Skip closure types; they'll get instantiated when we instantiate
  3316. // the corresponding lambda-expression.
  3317. if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
  3318. Record->isLambda())
  3319. continue;
  3320. MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
  3321. assert(MSInfo && "No member specialization information?");
  3322. if (MSInfo->getTemplateSpecializationKind()
  3323. == TSK_ExplicitSpecialization)
  3324. continue;
  3325. if (Context.getTargetInfo().getTriple().isOSWindows() &&
  3326. TSK == TSK_ExplicitInstantiationDeclaration) {
  3327. // On Windows, explicit instantiation decl of the outer class doesn't
  3328. // affect the inner class. Typically extern template declarations are
  3329. // used in combination with dll import/export annotations, but those
  3330. // are not propagated from the outer class templates to inner classes.
  3331. // Therefore, do not instantiate inner classes on this platform, so
  3332. // that users don't end up with undefined symbols during linking.
  3333. continue;
  3334. }
  3335. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  3336. Record,
  3337. MSInfo->getTemplateSpecializationKind(),
  3338. MSInfo->getPointOfInstantiation(),
  3339. SuppressNew) ||
  3340. SuppressNew)
  3341. continue;
  3342. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  3343. assert(Pattern && "Missing instantiated-from-template information");
  3344. if (!Record->getDefinition()) {
  3345. if (!Pattern->getDefinition()) {
  3346. // C++0x [temp.explicit]p8:
  3347. // An explicit instantiation definition that names a class template
  3348. // specialization explicitly instantiates the class template
  3349. // specialization and is only an explicit instantiation definition
  3350. // of members whose definition is visible at the point of
  3351. // instantiation.
  3352. if (TSK == TSK_ExplicitInstantiationDeclaration) {
  3353. MSInfo->setTemplateSpecializationKind(TSK);
  3354. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  3355. }
  3356. continue;
  3357. }
  3358. InstantiateClass(PointOfInstantiation, Record, Pattern,
  3359. TemplateArgs,
  3360. TSK);
  3361. } else {
  3362. if (TSK == TSK_ExplicitInstantiationDefinition &&
  3363. Record->getTemplateSpecializationKind() ==
  3364. TSK_ExplicitInstantiationDeclaration) {
  3365. Record->setTemplateSpecializationKind(TSK);
  3366. MarkVTableUsed(PointOfInstantiation, Record, true);
  3367. }
  3368. }
  3369. Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  3370. if (Pattern)
  3371. InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
  3372. TSK);
  3373. } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
  3374. MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
  3375. assert(MSInfo && "No member specialization information?");
  3376. if (MSInfo->getTemplateSpecializationKind()
  3377. == TSK_ExplicitSpecialization)
  3378. continue;
  3379. if (CheckSpecializationInstantiationRedecl(
  3380. PointOfInstantiation, TSK, Enum,
  3381. MSInfo->getTemplateSpecializationKind(),
  3382. MSInfo->getPointOfInstantiation(), SuppressNew) ||
  3383. SuppressNew)
  3384. continue;
  3385. if (Enum->getDefinition())
  3386. continue;
  3387. EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
  3388. assert(Pattern && "Missing instantiated-from-template information");
  3389. if (TSK == TSK_ExplicitInstantiationDefinition) {
  3390. if (!Pattern->getDefinition())
  3391. continue;
  3392. InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
  3393. } else {
  3394. MSInfo->setTemplateSpecializationKind(TSK);
  3395. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  3396. }
  3397. } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
  3398. // No need to instantiate in-class initializers during explicit
  3399. // instantiation.
  3400. if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
  3401. CXXRecordDecl *ClassPattern =
  3402. Instantiation->getTemplateInstantiationPattern();
  3403. DeclContext::lookup_result Lookup =
  3404. ClassPattern->lookup(Field->getDeclName());
  3405. FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
  3406. assert(Pattern);
  3407. InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
  3408. TemplateArgs);
  3409. }
  3410. }
  3411. }
  3412. }
  3413. /// Instantiate the definitions of all of the members of the
  3414. /// given class template specialization, which was named as part of an
  3415. /// explicit instantiation.
  3416. void
  3417. Sema::InstantiateClassTemplateSpecializationMembers(
  3418. SourceLocation PointOfInstantiation,
  3419. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  3420. TemplateSpecializationKind TSK) {
  3421. // C++0x [temp.explicit]p7:
  3422. // An explicit instantiation that names a class template
  3423. // specialization is an explicit instantion of the same kind
  3424. // (declaration or definition) of each of its members (not
  3425. // including members inherited from base classes) that has not
  3426. // been previously explicitly specialized in the translation unit
  3427. // containing the explicit instantiation, except as described
  3428. // below.
  3429. InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
  3430. getTemplateInstantiationArgs(ClassTemplateSpec),
  3431. TSK);
  3432. }
  3433. StmtResult
  3434. Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
  3435. if (!S)
  3436. return S;
  3437. TemplateInstantiator Instantiator(*this, TemplateArgs,
  3438. SourceLocation(),
  3439. DeclarationName());
  3440. return Instantiator.TransformStmt(S);
  3441. }
  3442. bool Sema::SubstTemplateArguments(
  3443. ArrayRef<TemplateArgumentLoc> Args,
  3444. const MultiLevelTemplateArgumentList &TemplateArgs,
  3445. TemplateArgumentListInfo &Out) {
  3446. TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
  3447. DeclarationName());
  3448. return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
  3449. }
  3450. ExprResult
  3451. Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
  3452. if (!E)
  3453. return E;
  3454. TemplateInstantiator Instantiator(*this, TemplateArgs,
  3455. SourceLocation(),
  3456. DeclarationName());
  3457. return Instantiator.TransformExpr(E);
  3458. }
  3459. ExprResult
  3460. Sema::SubstConstraintExpr(Expr *E,
  3461. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3462. if (!E)
  3463. return E;
  3464. // This is where we need to make sure we 'know' constraint checking needs to
  3465. // happen.
  3466. TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
  3467. DeclarationName());
  3468. return Instantiator.TransformExpr(E);
  3469. }
  3470. ExprResult Sema::SubstInitializer(Expr *Init,
  3471. const MultiLevelTemplateArgumentList &TemplateArgs,
  3472. bool CXXDirectInit) {
  3473. TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
  3474. DeclarationName());
  3475. return Instantiator.TransformInitializer(Init, CXXDirectInit);
  3476. }
  3477. bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
  3478. const MultiLevelTemplateArgumentList &TemplateArgs,
  3479. SmallVectorImpl<Expr *> &Outputs) {
  3480. if (Exprs.empty())
  3481. return false;
  3482. TemplateInstantiator Instantiator(*this, TemplateArgs,
  3483. SourceLocation(),
  3484. DeclarationName());
  3485. return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
  3486. IsCall, Outputs);
  3487. }
  3488. NestedNameSpecifierLoc
  3489. Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
  3490. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3491. if (!NNS)
  3492. return NestedNameSpecifierLoc();
  3493. TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
  3494. DeclarationName());
  3495. return Instantiator.TransformNestedNameSpecifierLoc(NNS);
  3496. }
  3497. /// Do template substitution on declaration name info.
  3498. DeclarationNameInfo
  3499. Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
  3500. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3501. TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
  3502. NameInfo.getName());
  3503. return Instantiator.TransformDeclarationNameInfo(NameInfo);
  3504. }
  3505. TemplateName
  3506. Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
  3507. TemplateName Name, SourceLocation Loc,
  3508. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3509. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  3510. DeclarationName());
  3511. CXXScopeSpec SS;
  3512. SS.Adopt(QualifierLoc);
  3513. return Instantiator.TransformTemplateName(SS, Name, Loc);
  3514. }
  3515. static const Decl *getCanonicalParmVarDecl(const Decl *D) {
  3516. // When storing ParmVarDecls in the local instantiation scope, we always
  3517. // want to use the ParmVarDecl from the canonical function declaration,
  3518. // since the map is then valid for any redeclaration or definition of that
  3519. // function.
  3520. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
  3521. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  3522. unsigned i = PV->getFunctionScopeIndex();
  3523. // This parameter might be from a freestanding function type within the
  3524. // function and isn't necessarily referring to one of FD's parameters.
  3525. if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
  3526. return FD->getCanonicalDecl()->getParamDecl(i);
  3527. }
  3528. }
  3529. return D;
  3530. }
  3531. llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
  3532. LocalInstantiationScope::findInstantiationOf(const Decl *D) {
  3533. D = getCanonicalParmVarDecl(D);
  3534. for (LocalInstantiationScope *Current = this; Current;
  3535. Current = Current->Outer) {
  3536. // Check if we found something within this scope.
  3537. const Decl *CheckD = D;
  3538. do {
  3539. LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
  3540. if (Found != Current->LocalDecls.end())
  3541. return &Found->second;
  3542. // If this is a tag declaration, it's possible that we need to look for
  3543. // a previous declaration.
  3544. if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
  3545. CheckD = Tag->getPreviousDecl();
  3546. else
  3547. CheckD = nullptr;
  3548. } while (CheckD);
  3549. // If we aren't combined with our outer scope, we're done.
  3550. if (!Current->CombineWithOuterScope)
  3551. break;
  3552. }
  3553. // If we're performing a partial substitution during template argument
  3554. // deduction, we may not have values for template parameters yet.
  3555. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  3556. isa<TemplateTemplateParmDecl>(D))
  3557. return nullptr;
  3558. // Local types referenced prior to definition may require instantiation.
  3559. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  3560. if (RD->isLocalClass())
  3561. return nullptr;
  3562. // Enumeration types referenced prior to definition may appear as a result of
  3563. // error recovery.
  3564. if (isa<EnumDecl>(D))
  3565. return nullptr;
  3566. // Materialized typedefs/type alias for implicit deduction guides may require
  3567. // instantiation.
  3568. if (isa<TypedefNameDecl>(D) &&
  3569. isa<CXXDeductionGuideDecl>(D->getDeclContext()))
  3570. return nullptr;
  3571. // If we didn't find the decl, then we either have a sema bug, or we have a
  3572. // forward reference to a label declaration. Return null to indicate that
  3573. // we have an uninstantiated label.
  3574. assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
  3575. return nullptr;
  3576. }
  3577. void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
  3578. D = getCanonicalParmVarDecl(D);
  3579. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  3580. if (Stored.isNull()) {
  3581. #ifndef NDEBUG
  3582. // It should not be present in any surrounding scope either.
  3583. LocalInstantiationScope *Current = this;
  3584. while (Current->CombineWithOuterScope && Current->Outer) {
  3585. Current = Current->Outer;
  3586. assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
  3587. "Instantiated local in inner and outer scopes");
  3588. }
  3589. #endif
  3590. Stored = Inst;
  3591. } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
  3592. Pack->push_back(cast<VarDecl>(Inst));
  3593. } else {
  3594. assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
  3595. }
  3596. }
  3597. void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
  3598. VarDecl *Inst) {
  3599. D = getCanonicalParmVarDecl(D);
  3600. DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
  3601. Pack->push_back(Inst);
  3602. }
  3603. void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
  3604. #ifndef NDEBUG
  3605. // This should be the first time we've been told about this decl.
  3606. for (LocalInstantiationScope *Current = this;
  3607. Current && Current->CombineWithOuterScope; Current = Current->Outer)
  3608. assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
  3609. "Creating local pack after instantiation of local");
  3610. #endif
  3611. D = getCanonicalParmVarDecl(D);
  3612. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  3613. DeclArgumentPack *Pack = new DeclArgumentPack;
  3614. Stored = Pack;
  3615. ArgumentPacks.push_back(Pack);
  3616. }
  3617. bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
  3618. for (DeclArgumentPack *Pack : ArgumentPacks)
  3619. if (llvm::is_contained(*Pack, D))
  3620. return true;
  3621. return false;
  3622. }
  3623. void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
  3624. const TemplateArgument *ExplicitArgs,
  3625. unsigned NumExplicitArgs) {
  3626. assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
  3627. "Already have a partially-substituted pack");
  3628. assert((!PartiallySubstitutedPack
  3629. || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
  3630. "Wrong number of arguments in partially-substituted pack");
  3631. PartiallySubstitutedPack = Pack;
  3632. ArgsInPartiallySubstitutedPack = ExplicitArgs;
  3633. NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
  3634. }
  3635. NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
  3636. const TemplateArgument **ExplicitArgs,
  3637. unsigned *NumExplicitArgs) const {
  3638. if (ExplicitArgs)
  3639. *ExplicitArgs = nullptr;
  3640. if (NumExplicitArgs)
  3641. *NumExplicitArgs = 0;
  3642. for (const LocalInstantiationScope *Current = this; Current;
  3643. Current = Current->Outer) {
  3644. if (Current->PartiallySubstitutedPack) {
  3645. if (ExplicitArgs)
  3646. *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
  3647. if (NumExplicitArgs)
  3648. *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
  3649. return Current->PartiallySubstitutedPack;
  3650. }
  3651. if (!Current->CombineWithOuterScope)
  3652. break;
  3653. }
  3654. return nullptr;
  3655. }