SemaTemplateInstantiate.cpp 125 KB

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