SemaTemplateInstantiate.cpp 150 KB

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