SemaTemplateInstantiate.cpp 127 KB

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