SemaTemplateInstantiate.cpp 119 KB

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