SemaTemplateInstantiateDecl.cpp 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604
  1. //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
  9. //
  10. //===----------------------------------------------------------------------===/
  11. #include "clang/Sema/SemaInternal.h"
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTMutationListener.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/DeclVisitor.h"
  17. #include "clang/AST/DependentDiagnostic.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/PrettyDeclStackTrace.h"
  21. #include "clang/AST/TypeLoc.h"
  22. #include "clang/Sema/Initialization.h"
  23. #include "clang/Sema/Lookup.h"
  24. #include "clang/Sema/Template.h"
  25. #include "clang/Sema/TemplateInstCallback.h"
  26. #include "llvm/Support/TimeProfiler.h"
  27. using namespace clang;
  28. static bool isDeclWithinFunction(const Decl *D) {
  29. const DeclContext *DC = D->getDeclContext();
  30. if (DC->isFunctionOrMethod())
  31. return true;
  32. if (DC->isRecord())
  33. return cast<CXXRecordDecl>(DC)->isLocalClass();
  34. return false;
  35. }
  36. template<typename DeclT>
  37. static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
  38. const MultiLevelTemplateArgumentList &TemplateArgs) {
  39. if (!OldDecl->getQualifierLoc())
  40. return false;
  41. assert((NewDecl->getFriendObjectKind() ||
  42. !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
  43. "non-friend with qualified name defined in dependent context");
  44. Sema::ContextRAII SavedContext(
  45. SemaRef,
  46. const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
  47. ? NewDecl->getLexicalDeclContext()
  48. : OldDecl->getLexicalDeclContext()));
  49. NestedNameSpecifierLoc NewQualifierLoc
  50. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  51. TemplateArgs);
  52. if (!NewQualifierLoc)
  53. return true;
  54. NewDecl->setQualifierInfo(NewQualifierLoc);
  55. return false;
  56. }
  57. bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
  58. DeclaratorDecl *NewDecl) {
  59. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  60. }
  61. bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
  62. TagDecl *NewDecl) {
  63. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  64. }
  65. // Include attribute instantiation code.
  66. #include "clang/Sema/AttrTemplateInstantiate.inc"
  67. static void instantiateDependentAlignedAttr(
  68. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  69. const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
  70. if (Aligned->isAlignmentExpr()) {
  71. // The alignment expression is a constant expression.
  72. EnterExpressionEvaluationContext Unevaluated(
  73. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  74. ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
  75. if (!Result.isInvalid())
  76. S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
  77. Aligned->getSpellingListIndex(), IsPackExpansion);
  78. } else {
  79. TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
  80. TemplateArgs, Aligned->getLocation(),
  81. DeclarationName());
  82. if (Result)
  83. S.AddAlignedAttr(Aligned->getLocation(), New, Result,
  84. Aligned->getSpellingListIndex(), IsPackExpansion);
  85. }
  86. }
  87. static void instantiateDependentAlignedAttr(
  88. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  89. const AlignedAttr *Aligned, Decl *New) {
  90. if (!Aligned->isPackExpansion()) {
  91. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  92. return;
  93. }
  94. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  95. if (Aligned->isAlignmentExpr())
  96. S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
  97. Unexpanded);
  98. else
  99. S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
  100. Unexpanded);
  101. assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
  102. // Determine whether we can expand this attribute pack yet.
  103. bool Expand = true, RetainExpansion = false;
  104. Optional<unsigned> NumExpansions;
  105. // FIXME: Use the actual location of the ellipsis.
  106. SourceLocation EllipsisLoc = Aligned->getLocation();
  107. if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
  108. Unexpanded, TemplateArgs, Expand,
  109. RetainExpansion, NumExpansions))
  110. return;
  111. if (!Expand) {
  112. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
  113. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
  114. } else {
  115. for (unsigned I = 0; I != *NumExpansions; ++I) {
  116. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
  117. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  118. }
  119. }
  120. }
  121. static void instantiateDependentAssumeAlignedAttr(
  122. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  123. const AssumeAlignedAttr *Aligned, Decl *New) {
  124. // The alignment expression is a constant expression.
  125. EnterExpressionEvaluationContext Unevaluated(
  126. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  127. Expr *E, *OE = nullptr;
  128. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  129. if (Result.isInvalid())
  130. return;
  131. E = Result.getAs<Expr>();
  132. if (Aligned->getOffset()) {
  133. Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
  134. if (Result.isInvalid())
  135. return;
  136. OE = Result.getAs<Expr>();
  137. }
  138. S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
  139. Aligned->getSpellingListIndex());
  140. }
  141. static void instantiateDependentAlignValueAttr(
  142. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  143. const AlignValueAttr *Aligned, Decl *New) {
  144. // The alignment expression is a constant expression.
  145. EnterExpressionEvaluationContext Unevaluated(
  146. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  147. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  148. if (!Result.isInvalid())
  149. S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
  150. Aligned->getSpellingListIndex());
  151. }
  152. static void instantiateDependentAllocAlignAttr(
  153. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  154. const AllocAlignAttr *Align, Decl *New) {
  155. Expr *Param = IntegerLiteral::Create(
  156. S.getASTContext(),
  157. llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
  158. S.getASTContext().UnsignedLongLongTy, Align->getLocation());
  159. S.AddAllocAlignAttr(Align->getLocation(), New, Param,
  160. Align->getSpellingListIndex());
  161. }
  162. static Expr *instantiateDependentFunctionAttrCondition(
  163. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  164. const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
  165. Expr *Cond = nullptr;
  166. {
  167. Sema::ContextRAII SwitchContext(S, New);
  168. EnterExpressionEvaluationContext Unevaluated(
  169. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  170. ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
  171. if (Result.isInvalid())
  172. return nullptr;
  173. Cond = Result.getAs<Expr>();
  174. }
  175. if (!Cond->isTypeDependent()) {
  176. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  177. if (Converted.isInvalid())
  178. return nullptr;
  179. Cond = Converted.get();
  180. }
  181. SmallVector<PartialDiagnosticAt, 8> Diags;
  182. if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
  183. !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
  184. S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
  185. for (const auto &P : Diags)
  186. S.Diag(P.first, P.second);
  187. return nullptr;
  188. }
  189. return Cond;
  190. }
  191. static void instantiateDependentEnableIfAttr(
  192. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  193. const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
  194. Expr *Cond = instantiateDependentFunctionAttrCondition(
  195. S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
  196. if (Cond)
  197. New->addAttr(new (S.getASTContext()) EnableIfAttr(
  198. EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
  199. EIA->getSpellingListIndex()));
  200. }
  201. static void instantiateDependentDiagnoseIfAttr(
  202. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  203. const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
  204. Expr *Cond = instantiateDependentFunctionAttrCondition(
  205. S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
  206. if (Cond)
  207. New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
  208. DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
  209. DIA->getDiagnosticType(), DIA->getArgDependent(), New,
  210. DIA->getSpellingListIndex()));
  211. }
  212. // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
  213. // template A as the base and arguments from TemplateArgs.
  214. static void instantiateDependentCUDALaunchBoundsAttr(
  215. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  216. const CUDALaunchBoundsAttr &Attr, Decl *New) {
  217. // The alignment expression is a constant expression.
  218. EnterExpressionEvaluationContext Unevaluated(
  219. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  220. ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
  221. if (Result.isInvalid())
  222. return;
  223. Expr *MaxThreads = Result.getAs<Expr>();
  224. Expr *MinBlocks = nullptr;
  225. if (Attr.getMinBlocks()) {
  226. Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
  227. if (Result.isInvalid())
  228. return;
  229. MinBlocks = Result.getAs<Expr>();
  230. }
  231. S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
  232. Attr.getSpellingListIndex());
  233. }
  234. static void
  235. instantiateDependentModeAttr(Sema &S,
  236. const MultiLevelTemplateArgumentList &TemplateArgs,
  237. const ModeAttr &Attr, Decl *New) {
  238. S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
  239. Attr.getSpellingListIndex(), /*InInstantiation=*/true);
  240. }
  241. /// Instantiation of 'declare simd' attribute and its arguments.
  242. static void instantiateOMPDeclareSimdDeclAttr(
  243. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  244. const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
  245. // Allow 'this' in clauses with varlists.
  246. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
  247. New = FTD->getTemplatedDecl();
  248. auto *FD = cast<FunctionDecl>(New);
  249. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
  250. SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
  251. SmallVector<unsigned, 4> LinModifiers;
  252. auto SubstExpr = [&](Expr *E) -> ExprResult {
  253. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  254. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  255. Sema::ContextRAII SavedContext(S, FD);
  256. LocalInstantiationScope Local(S);
  257. if (FD->getNumParams() > PVD->getFunctionScopeIndex())
  258. Local.InstantiatedLocal(
  259. PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
  260. return S.SubstExpr(E, TemplateArgs);
  261. }
  262. Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
  263. FD->isCXXInstanceMember());
  264. return S.SubstExpr(E, TemplateArgs);
  265. };
  266. // Substitute a single OpenMP clause, which is a potentially-evaluated
  267. // full-expression.
  268. auto Subst = [&](Expr *E) -> ExprResult {
  269. EnterExpressionEvaluationContext Evaluated(
  270. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  271. ExprResult Res = SubstExpr(E);
  272. if (Res.isInvalid())
  273. return Res;
  274. return S.ActOnFinishFullExpr(Res.get(), false);
  275. };
  276. ExprResult Simdlen;
  277. if (auto *E = Attr.getSimdlen())
  278. Simdlen = Subst(E);
  279. if (Attr.uniforms_size() > 0) {
  280. for(auto *E : Attr.uniforms()) {
  281. ExprResult Inst = Subst(E);
  282. if (Inst.isInvalid())
  283. continue;
  284. Uniforms.push_back(Inst.get());
  285. }
  286. }
  287. auto AI = Attr.alignments_begin();
  288. for (auto *E : Attr.aligneds()) {
  289. ExprResult Inst = Subst(E);
  290. if (Inst.isInvalid())
  291. continue;
  292. Aligneds.push_back(Inst.get());
  293. Inst = ExprEmpty();
  294. if (*AI)
  295. Inst = S.SubstExpr(*AI, TemplateArgs);
  296. Alignments.push_back(Inst.get());
  297. ++AI;
  298. }
  299. auto SI = Attr.steps_begin();
  300. for (auto *E : Attr.linears()) {
  301. ExprResult Inst = Subst(E);
  302. if (Inst.isInvalid())
  303. continue;
  304. Linears.push_back(Inst.get());
  305. Inst = ExprEmpty();
  306. if (*SI)
  307. Inst = S.SubstExpr(*SI, TemplateArgs);
  308. Steps.push_back(Inst.get());
  309. ++SI;
  310. }
  311. LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
  312. (void)S.ActOnOpenMPDeclareSimdDirective(
  313. S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
  314. Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
  315. Attr.getRange());
  316. }
  317. static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
  318. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  319. const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
  320. // Both min and max expression are constant expressions.
  321. EnterExpressionEvaluationContext Unevaluated(
  322. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  323. ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
  324. if (Result.isInvalid())
  325. return;
  326. Expr *MinExpr = Result.getAs<Expr>();
  327. Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
  328. if (Result.isInvalid())
  329. return;
  330. Expr *MaxExpr = Result.getAs<Expr>();
  331. S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
  332. Attr.getSpellingListIndex());
  333. }
  334. static ExplicitSpecifier
  335. instantiateExplicitSpecifier(Sema &S,
  336. const MultiLevelTemplateArgumentList &TemplateArgs,
  337. ExplicitSpecifier ES, FunctionDecl *New) {
  338. if (!ES.getExpr())
  339. return ES;
  340. Expr *OldCond = ES.getExpr();
  341. Expr *Cond = nullptr;
  342. {
  343. EnterExpressionEvaluationContext Unevaluated(
  344. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  345. ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
  346. if (SubstResult.isInvalid()) {
  347. return ExplicitSpecifier::Invalid();
  348. }
  349. Cond = SubstResult.get();
  350. }
  351. ExplicitSpecifier Result(Cond, ES.getKind());
  352. if (!Cond->isTypeDependent())
  353. S.tryResolveExplicitSpecifier(Result);
  354. return Result;
  355. }
  356. static void instantiateDependentAMDGPUWavesPerEUAttr(
  357. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  358. const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
  359. // Both min and max expression are constant expressions.
  360. EnterExpressionEvaluationContext Unevaluated(
  361. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  362. ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
  363. if (Result.isInvalid())
  364. return;
  365. Expr *MinExpr = Result.getAs<Expr>();
  366. Expr *MaxExpr = nullptr;
  367. if (auto Max = Attr.getMax()) {
  368. Result = S.SubstExpr(Max, TemplateArgs);
  369. if (Result.isInvalid())
  370. return;
  371. MaxExpr = Result.getAs<Expr>();
  372. }
  373. S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
  374. Attr.getSpellingListIndex());
  375. }
  376. void Sema::InstantiateAttrsForDecl(
  377. const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
  378. Decl *New, LateInstantiatedAttrVec *LateAttrs,
  379. LocalInstantiationScope *OuterMostScope) {
  380. if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
  381. for (const auto *TmplAttr : Tmpl->attrs()) {
  382. // FIXME: If any of the special case versions from InstantiateAttrs become
  383. // applicable to template declaration, we'll need to add them here.
  384. CXXThisScopeRAII ThisScope(
  385. *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
  386. Qualifiers(), ND->isCXXInstanceMember());
  387. Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
  388. TmplAttr, Context, *this, TemplateArgs);
  389. if (NewAttr)
  390. New->addAttr(NewAttr);
  391. }
  392. }
  393. }
  394. static Sema::RetainOwnershipKind
  395. attrToRetainOwnershipKind(const Attr *A) {
  396. switch (A->getKind()) {
  397. case clang::attr::CFConsumed:
  398. return Sema::RetainOwnershipKind::CF;
  399. case clang::attr::OSConsumed:
  400. return Sema::RetainOwnershipKind::OS;
  401. case clang::attr::NSConsumed:
  402. return Sema::RetainOwnershipKind::NS;
  403. default:
  404. llvm_unreachable("Wrong argument supplied");
  405. }
  406. }
  407. void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
  408. const Decl *Tmpl, Decl *New,
  409. LateInstantiatedAttrVec *LateAttrs,
  410. LocalInstantiationScope *OuterMostScope) {
  411. for (const auto *TmplAttr : Tmpl->attrs()) {
  412. // FIXME: This should be generalized to more than just the AlignedAttr.
  413. const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
  414. if (Aligned && Aligned->isAlignmentDependent()) {
  415. instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
  416. continue;
  417. }
  418. if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
  419. instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
  420. continue;
  421. }
  422. if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
  423. instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
  424. continue;
  425. }
  426. if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
  427. instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
  428. continue;
  429. }
  430. if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
  431. instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
  432. cast<FunctionDecl>(New));
  433. continue;
  434. }
  435. if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
  436. instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
  437. cast<FunctionDecl>(New));
  438. continue;
  439. }
  440. if (const auto *CUDALaunchBounds =
  441. dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
  442. instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
  443. *CUDALaunchBounds, New);
  444. continue;
  445. }
  446. if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
  447. instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
  448. continue;
  449. }
  450. if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
  451. instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
  452. continue;
  453. }
  454. if (const auto *AMDGPUFlatWorkGroupSize =
  455. dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
  456. instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
  457. *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
  458. }
  459. if (const auto *AMDGPUFlatWorkGroupSize =
  460. dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
  461. instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
  462. *AMDGPUFlatWorkGroupSize, New);
  463. }
  464. // Existing DLL attribute on the instantiation takes precedence.
  465. if (TmplAttr->getKind() == attr::DLLExport ||
  466. TmplAttr->getKind() == attr::DLLImport) {
  467. if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
  468. continue;
  469. }
  470. }
  471. if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
  472. AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
  473. ABIAttr->getSpellingListIndex());
  474. continue;
  475. }
  476. if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
  477. isa<CFConsumedAttr>(TmplAttr)) {
  478. AddXConsumedAttr(New, TmplAttr->getRange(),
  479. TmplAttr->getSpellingListIndex(),
  480. attrToRetainOwnershipKind(TmplAttr),
  481. /*template instantiation=*/true);
  482. continue;
  483. }
  484. assert(!TmplAttr->isPackExpansion());
  485. if (TmplAttr->isLateParsed() && LateAttrs) {
  486. // Late parsed attributes must be instantiated and attached after the
  487. // enclosing class has been instantiated. See Sema::InstantiateClass.
  488. LocalInstantiationScope *Saved = nullptr;
  489. if (CurrentInstantiationScope)
  490. Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
  491. LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
  492. } else {
  493. // Allow 'this' within late-parsed attributes.
  494. NamedDecl *ND = dyn_cast<NamedDecl>(New);
  495. CXXRecordDecl *ThisContext =
  496. dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  497. CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
  498. ND && ND->isCXXInstanceMember());
  499. Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
  500. *this, TemplateArgs);
  501. if (NewAttr)
  502. New->addAttr(NewAttr);
  503. }
  504. }
  505. }
  506. /// Get the previous declaration of a declaration for the purposes of template
  507. /// instantiation. If this finds a previous declaration, then the previous
  508. /// declaration of the instantiation of D should be an instantiation of the
  509. /// result of this function.
  510. template<typename DeclT>
  511. static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
  512. DeclT *Result = D->getPreviousDecl();
  513. // If the declaration is within a class, and the previous declaration was
  514. // merged from a different definition of that class, then we don't have a
  515. // previous declaration for the purpose of template instantiation.
  516. if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
  517. D->getLexicalDeclContext() != Result->getLexicalDeclContext())
  518. return nullptr;
  519. return Result;
  520. }
  521. Decl *
  522. TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  523. llvm_unreachable("Translation units cannot be instantiated");
  524. }
  525. Decl *
  526. TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
  527. llvm_unreachable("pragma comment cannot be instantiated");
  528. }
  529. Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
  530. PragmaDetectMismatchDecl *D) {
  531. llvm_unreachable("pragma comment cannot be instantiated");
  532. }
  533. Decl *
  534. TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
  535. llvm_unreachable("extern \"C\" context cannot be instantiated");
  536. }
  537. Decl *
  538. TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
  539. LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  540. D->getIdentifier());
  541. Owner->addDecl(Inst);
  542. return Inst;
  543. }
  544. Decl *
  545. TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
  546. llvm_unreachable("Namespaces cannot be instantiated");
  547. }
  548. Decl *
  549. TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  550. NamespaceAliasDecl *Inst
  551. = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
  552. D->getNamespaceLoc(),
  553. D->getAliasLoc(),
  554. D->getIdentifier(),
  555. D->getQualifierLoc(),
  556. D->getTargetNameLoc(),
  557. D->getNamespace());
  558. Owner->addDecl(Inst);
  559. return Inst;
  560. }
  561. Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
  562. bool IsTypeAlias) {
  563. bool Invalid = false;
  564. TypeSourceInfo *DI = D->getTypeSourceInfo();
  565. if (DI->getType()->isInstantiationDependentType() ||
  566. DI->getType()->isVariablyModifiedType()) {
  567. DI = SemaRef.SubstType(DI, TemplateArgs,
  568. D->getLocation(), D->getDeclName());
  569. if (!DI) {
  570. Invalid = true;
  571. DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
  572. }
  573. } else {
  574. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  575. }
  576. // HACK: g++ has a bug where it gets the value kind of ?: wrong.
  577. // libstdc++ relies upon this bug in its implementation of common_type.
  578. // If we happen to be processing that implementation, fake up the g++ ?:
  579. // semantics. See LWG issue 2141 for more information on the bug.
  580. const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
  581. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  582. if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
  583. DT->isReferenceType() &&
  584. RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
  585. RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
  586. D->getIdentifier() && D->getIdentifier()->isStr("type") &&
  587. SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
  588. // Fold it to the (non-reference) type which g++ would have produced.
  589. DI = SemaRef.Context.getTrivialTypeSourceInfo(
  590. DI->getType().getNonReferenceType());
  591. // Create the new typedef
  592. TypedefNameDecl *Typedef;
  593. if (IsTypeAlias)
  594. Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  595. D->getLocation(), D->getIdentifier(), DI);
  596. else
  597. Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  598. D->getLocation(), D->getIdentifier(), DI);
  599. if (Invalid)
  600. Typedef->setInvalidDecl();
  601. // If the old typedef was the name for linkage purposes of an anonymous
  602. // tag decl, re-establish that relationship for the new typedef.
  603. if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
  604. TagDecl *oldTag = oldTagType->getDecl();
  605. if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
  606. TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
  607. assert(!newTag->hasNameForLinkage());
  608. newTag->setTypedefNameForAnonDecl(Typedef);
  609. }
  610. }
  611. if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
  612. NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
  613. TemplateArgs);
  614. if (!InstPrev)
  615. return nullptr;
  616. TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
  617. // If the typedef types are not identical, reject them.
  618. SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
  619. Typedef->setPreviousDecl(InstPrevTypedef);
  620. }
  621. SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
  622. Typedef->setAccess(D->getAccess());
  623. return Typedef;
  624. }
  625. Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
  626. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
  627. if (Typedef)
  628. Owner->addDecl(Typedef);
  629. return Typedef;
  630. }
  631. Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
  632. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
  633. if (Typedef)
  634. Owner->addDecl(Typedef);
  635. return Typedef;
  636. }
  637. Decl *
  638. TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  639. // Create a local instantiation scope for this type alias template, which
  640. // will contain the instantiations of the template parameters.
  641. LocalInstantiationScope Scope(SemaRef);
  642. TemplateParameterList *TempParams = D->getTemplateParameters();
  643. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  644. if (!InstParams)
  645. return nullptr;
  646. TypeAliasDecl *Pattern = D->getTemplatedDecl();
  647. TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
  648. if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
  649. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  650. if (!Found.empty()) {
  651. PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
  652. }
  653. }
  654. TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
  655. InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
  656. if (!AliasInst)
  657. return nullptr;
  658. TypeAliasTemplateDecl *Inst
  659. = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  660. D->getDeclName(), InstParams, AliasInst);
  661. AliasInst->setDescribedAliasTemplate(Inst);
  662. if (PrevAliasTemplate)
  663. Inst->setPreviousDecl(PrevAliasTemplate);
  664. Inst->setAccess(D->getAccess());
  665. if (!PrevAliasTemplate)
  666. Inst->setInstantiatedFromMemberTemplate(D);
  667. Owner->addDecl(Inst);
  668. return Inst;
  669. }
  670. Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
  671. auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  672. D->getIdentifier());
  673. NewBD->setReferenced(D->isReferenced());
  674. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
  675. return NewBD;
  676. }
  677. Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
  678. // Transform the bindings first.
  679. SmallVector<BindingDecl*, 16> NewBindings;
  680. for (auto *OldBD : D->bindings())
  681. NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
  682. ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
  683. auto *NewDD = cast_or_null<DecompositionDecl>(
  684. VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
  685. if (!NewDD || NewDD->isInvalidDecl())
  686. for (auto *NewBD : NewBindings)
  687. NewBD->setInvalidDecl();
  688. return NewDD;
  689. }
  690. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
  691. return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
  692. }
  693. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
  694. bool InstantiatingVarTemplate,
  695. ArrayRef<BindingDecl*> *Bindings) {
  696. // Do substitution on the type of the declaration
  697. TypeSourceInfo *DI = SemaRef.SubstType(
  698. D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
  699. D->getDeclName(), /*AllowDeducedTST*/true);
  700. if (!DI)
  701. return nullptr;
  702. if (DI->getType()->isFunctionType()) {
  703. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  704. << D->isStaticDataMember() << DI->getType();
  705. return nullptr;
  706. }
  707. DeclContext *DC = Owner;
  708. if (D->isLocalExternDecl())
  709. SemaRef.adjustContextForLocalExternDecl(DC);
  710. // Build the instantiated declaration.
  711. VarDecl *Var;
  712. if (Bindings)
  713. Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  714. D->getLocation(), DI->getType(), DI,
  715. D->getStorageClass(), *Bindings);
  716. else
  717. Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  718. D->getLocation(), D->getIdentifier(), DI->getType(),
  719. DI, D->getStorageClass());
  720. // In ARC, infer 'retaining' for variables of retainable type.
  721. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  722. SemaRef.inferObjCARCLifetime(Var))
  723. Var->setInvalidDecl();
  724. // Substitute the nested name specifier, if any.
  725. if (SubstQualifier(D, Var))
  726. return nullptr;
  727. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  728. StartingScope, InstantiatingVarTemplate);
  729. if (D->isNRVOVariable()) {
  730. QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
  731. if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
  732. Var->setNRVOVariable(true);
  733. }
  734. Var->setImplicit(D->isImplicit());
  735. if (Var->isStaticLocal())
  736. SemaRef.CheckStaticLocalForDllExport(Var);
  737. return Var;
  738. }
  739. Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
  740. AccessSpecDecl* AD
  741. = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
  742. D->getAccessSpecifierLoc(), D->getColonLoc());
  743. Owner->addHiddenDecl(AD);
  744. return AD;
  745. }
  746. Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
  747. bool Invalid = false;
  748. TypeSourceInfo *DI = D->getTypeSourceInfo();
  749. if (DI->getType()->isInstantiationDependentType() ||
  750. DI->getType()->isVariablyModifiedType()) {
  751. DI = SemaRef.SubstType(DI, TemplateArgs,
  752. D->getLocation(), D->getDeclName());
  753. if (!DI) {
  754. DI = D->getTypeSourceInfo();
  755. Invalid = true;
  756. } else if (DI->getType()->isFunctionType()) {
  757. // C++ [temp.arg.type]p3:
  758. // If a declaration acquires a function type through a type
  759. // dependent on a template-parameter and this causes a
  760. // declaration that does not use the syntactic form of a
  761. // function declarator to have function type, the program is
  762. // ill-formed.
  763. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  764. << DI->getType();
  765. Invalid = true;
  766. }
  767. } else {
  768. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  769. }
  770. Expr *BitWidth = D->getBitWidth();
  771. if (Invalid)
  772. BitWidth = nullptr;
  773. else if (BitWidth) {
  774. // The bit-width expression is a constant expression.
  775. EnterExpressionEvaluationContext Unevaluated(
  776. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  777. ExprResult InstantiatedBitWidth
  778. = SemaRef.SubstExpr(BitWidth, TemplateArgs);
  779. if (InstantiatedBitWidth.isInvalid()) {
  780. Invalid = true;
  781. BitWidth = nullptr;
  782. } else
  783. BitWidth = InstantiatedBitWidth.getAs<Expr>();
  784. }
  785. FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
  786. DI->getType(), DI,
  787. cast<RecordDecl>(Owner),
  788. D->getLocation(),
  789. D->isMutable(),
  790. BitWidth,
  791. D->getInClassInitStyle(),
  792. D->getInnerLocStart(),
  793. D->getAccess(),
  794. nullptr);
  795. if (!Field) {
  796. cast<Decl>(Owner)->setInvalidDecl();
  797. return nullptr;
  798. }
  799. SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
  800. if (Field->hasAttrs())
  801. SemaRef.CheckAlignasUnderalignment(Field);
  802. if (Invalid)
  803. Field->setInvalidDecl();
  804. if (!Field->getDeclName()) {
  805. // Keep track of where this decl came from.
  806. SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
  807. }
  808. if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
  809. if (Parent->isAnonymousStructOrUnion() &&
  810. Parent->getRedeclContext()->isFunctionOrMethod())
  811. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
  812. }
  813. Field->setImplicit(D->isImplicit());
  814. Field->setAccess(D->getAccess());
  815. Owner->addDecl(Field);
  816. return Field;
  817. }
  818. Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
  819. bool Invalid = false;
  820. TypeSourceInfo *DI = D->getTypeSourceInfo();
  821. if (DI->getType()->isVariablyModifiedType()) {
  822. SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
  823. << D;
  824. Invalid = true;
  825. } else if (DI->getType()->isInstantiationDependentType()) {
  826. DI = SemaRef.SubstType(DI, TemplateArgs,
  827. D->getLocation(), D->getDeclName());
  828. if (!DI) {
  829. DI = D->getTypeSourceInfo();
  830. Invalid = true;
  831. } else if (DI->getType()->isFunctionType()) {
  832. // C++ [temp.arg.type]p3:
  833. // If a declaration acquires a function type through a type
  834. // dependent on a template-parameter and this causes a
  835. // declaration that does not use the syntactic form of a
  836. // function declarator to have function type, the program is
  837. // ill-formed.
  838. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  839. << DI->getType();
  840. Invalid = true;
  841. }
  842. } else {
  843. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  844. }
  845. MSPropertyDecl *Property = MSPropertyDecl::Create(
  846. SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
  847. DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
  848. SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
  849. StartingScope);
  850. if (Invalid)
  851. Property->setInvalidDecl();
  852. Property->setAccess(D->getAccess());
  853. Owner->addDecl(Property);
  854. return Property;
  855. }
  856. Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  857. NamedDecl **NamedChain =
  858. new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
  859. int i = 0;
  860. for (auto *PI : D->chain()) {
  861. NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
  862. TemplateArgs);
  863. if (!Next)
  864. return nullptr;
  865. NamedChain[i++] = Next;
  866. }
  867. QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
  868. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  869. SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
  870. {NamedChain, D->getChainingSize()});
  871. for (const auto *Attr : D->attrs())
  872. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  873. IndirectField->setImplicit(D->isImplicit());
  874. IndirectField->setAccess(D->getAccess());
  875. Owner->addDecl(IndirectField);
  876. return IndirectField;
  877. }
  878. Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
  879. // Handle friend type expressions by simply substituting template
  880. // parameters into the pattern type and checking the result.
  881. if (TypeSourceInfo *Ty = D->getFriendType()) {
  882. TypeSourceInfo *InstTy;
  883. // If this is an unsupported friend, don't bother substituting template
  884. // arguments into it. The actual type referred to won't be used by any
  885. // parts of Clang, and may not be valid for instantiating. Just use the
  886. // same info for the instantiated friend.
  887. if (D->isUnsupportedFriend()) {
  888. InstTy = Ty;
  889. } else {
  890. InstTy = SemaRef.SubstType(Ty, TemplateArgs,
  891. D->getLocation(), DeclarationName());
  892. }
  893. if (!InstTy)
  894. return nullptr;
  895. FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
  896. D->getFriendLoc(), InstTy);
  897. if (!FD)
  898. return nullptr;
  899. FD->setAccess(AS_public);
  900. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  901. Owner->addDecl(FD);
  902. return FD;
  903. }
  904. NamedDecl *ND = D->getFriendDecl();
  905. assert(ND && "friend decl must be a decl or a type!");
  906. // All of the Visit implementations for the various potential friend
  907. // declarations have to be carefully written to work for friend
  908. // objects, with the most important detail being that the target
  909. // decl should almost certainly not be placed in Owner.
  910. Decl *NewND = Visit(ND);
  911. if (!NewND) return nullptr;
  912. FriendDecl *FD =
  913. FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  914. cast<NamedDecl>(NewND), D->getFriendLoc());
  915. FD->setAccess(AS_public);
  916. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  917. Owner->addDecl(FD);
  918. return FD;
  919. }
  920. Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
  921. Expr *AssertExpr = D->getAssertExpr();
  922. // The expression in a static assertion is a constant expression.
  923. EnterExpressionEvaluationContext Unevaluated(
  924. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  925. ExprResult InstantiatedAssertExpr
  926. = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
  927. if (InstantiatedAssertExpr.isInvalid())
  928. return nullptr;
  929. return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
  930. InstantiatedAssertExpr.get(),
  931. D->getMessage(),
  932. D->getRParenLoc(),
  933. D->isFailed());
  934. }
  935. Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
  936. EnumDecl *PrevDecl = nullptr;
  937. if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  938. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  939. PatternPrev,
  940. TemplateArgs);
  941. if (!Prev) return nullptr;
  942. PrevDecl = cast<EnumDecl>(Prev);
  943. }
  944. EnumDecl *Enum =
  945. EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  946. D->getLocation(), D->getIdentifier(), PrevDecl,
  947. D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
  948. if (D->isFixed()) {
  949. if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
  950. // If we have type source information for the underlying type, it means it
  951. // has been explicitly set by the user. Perform substitution on it before
  952. // moving on.
  953. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  954. TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
  955. DeclarationName());
  956. if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
  957. Enum->setIntegerType(SemaRef.Context.IntTy);
  958. else
  959. Enum->setIntegerTypeSourceInfo(NewTI);
  960. } else {
  961. assert(!D->getIntegerType()->isDependentType()
  962. && "Dependent type without type source info");
  963. Enum->setIntegerType(D->getIntegerType());
  964. }
  965. }
  966. SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
  967. Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
  968. Enum->setAccess(D->getAccess());
  969. // Forward the mangling number from the template to the instantiated decl.
  970. SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
  971. // See if the old tag was defined along with a declarator.
  972. // If it did, mark the new tag as being associated with that declarator.
  973. if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
  974. SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
  975. // See if the old tag was defined along with a typedef.
  976. // If it did, mark the new tag as being associated with that typedef.
  977. if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
  978. SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
  979. if (SubstQualifier(D, Enum)) return nullptr;
  980. Owner->addDecl(Enum);
  981. EnumDecl *Def = D->getDefinition();
  982. if (Def && Def != D) {
  983. // If this is an out-of-line definition of an enum member template, check
  984. // that the underlying types match in the instantiation of both
  985. // declarations.
  986. if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
  987. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  988. QualType DefnUnderlying =
  989. SemaRef.SubstType(TI->getType(), TemplateArgs,
  990. UnderlyingLoc, DeclarationName());
  991. SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
  992. DefnUnderlying, /*IsFixed=*/true, Enum);
  993. }
  994. }
  995. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  996. // specialization causes the implicit instantiation of the declarations, but
  997. // not the definitions of scoped member enumerations.
  998. //
  999. // DR1484 clarifies that enumeration definitions inside of a template
  1000. // declaration aren't considered entities that can be separately instantiated
  1001. // from the rest of the entity they are declared inside of.
  1002. if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
  1003. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
  1004. InstantiateEnumDefinition(Enum, Def);
  1005. }
  1006. return Enum;
  1007. }
  1008. void TemplateDeclInstantiator::InstantiateEnumDefinition(
  1009. EnumDecl *Enum, EnumDecl *Pattern) {
  1010. Enum->startDefinition();
  1011. // Update the location to refer to the definition.
  1012. Enum->setLocation(Pattern->getLocation());
  1013. SmallVector<Decl*, 4> Enumerators;
  1014. EnumConstantDecl *LastEnumConst = nullptr;
  1015. for (auto *EC : Pattern->enumerators()) {
  1016. // The specified value for the enumerator.
  1017. ExprResult Value((Expr *)nullptr);
  1018. if (Expr *UninstValue = EC->getInitExpr()) {
  1019. // The enumerator's value expression is a constant expression.
  1020. EnterExpressionEvaluationContext Unevaluated(
  1021. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  1022. Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
  1023. }
  1024. // Drop the initial value and continue.
  1025. bool isInvalid = false;
  1026. if (Value.isInvalid()) {
  1027. Value = nullptr;
  1028. isInvalid = true;
  1029. }
  1030. EnumConstantDecl *EnumConst
  1031. = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
  1032. EC->getLocation(), EC->getIdentifier(),
  1033. Value.get());
  1034. if (isInvalid) {
  1035. if (EnumConst)
  1036. EnumConst->setInvalidDecl();
  1037. Enum->setInvalidDecl();
  1038. }
  1039. if (EnumConst) {
  1040. SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
  1041. EnumConst->setAccess(Enum->getAccess());
  1042. Enum->addDecl(EnumConst);
  1043. Enumerators.push_back(EnumConst);
  1044. LastEnumConst = EnumConst;
  1045. if (Pattern->getDeclContext()->isFunctionOrMethod() &&
  1046. !Enum->isScoped()) {
  1047. // If the enumeration is within a function or method, record the enum
  1048. // constant as a local.
  1049. SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
  1050. }
  1051. }
  1052. }
  1053. SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
  1054. Enumerators, nullptr, ParsedAttributesView());
  1055. }
  1056. Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
  1057. llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
  1058. }
  1059. Decl *
  1060. TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
  1061. llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
  1062. }
  1063. Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  1064. bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1065. // Create a local instantiation scope for this class template, which
  1066. // will contain the instantiations of the template parameters.
  1067. LocalInstantiationScope Scope(SemaRef);
  1068. TemplateParameterList *TempParams = D->getTemplateParameters();
  1069. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1070. if (!InstParams)
  1071. return nullptr;
  1072. CXXRecordDecl *Pattern = D->getTemplatedDecl();
  1073. // Instantiate the qualifier. We have to do this first in case
  1074. // we're a friend declaration, because if we are then we need to put
  1075. // the new declaration in the appropriate context.
  1076. NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
  1077. if (QualifierLoc) {
  1078. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1079. TemplateArgs);
  1080. if (!QualifierLoc)
  1081. return nullptr;
  1082. }
  1083. CXXRecordDecl *PrevDecl = nullptr;
  1084. ClassTemplateDecl *PrevClassTemplate = nullptr;
  1085. if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
  1086. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  1087. if (!Found.empty()) {
  1088. PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
  1089. if (PrevClassTemplate)
  1090. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  1091. }
  1092. }
  1093. // If this isn't a friend, then it's a member template, in which
  1094. // case we just want to build the instantiation in the
  1095. // specialization. If it is a friend, we want to build it in
  1096. // the appropriate context.
  1097. DeclContext *DC = Owner;
  1098. if (isFriend) {
  1099. if (QualifierLoc) {
  1100. CXXScopeSpec SS;
  1101. SS.Adopt(QualifierLoc);
  1102. DC = SemaRef.computeDeclContext(SS);
  1103. if (!DC) return nullptr;
  1104. } else {
  1105. DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
  1106. Pattern->getDeclContext(),
  1107. TemplateArgs);
  1108. }
  1109. // Look for a previous declaration of the template in the owning
  1110. // context.
  1111. LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
  1112. Sema::LookupOrdinaryName,
  1113. SemaRef.forRedeclarationInCurContext());
  1114. SemaRef.LookupQualifiedName(R, DC);
  1115. if (R.isSingleResult()) {
  1116. PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
  1117. if (PrevClassTemplate)
  1118. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  1119. }
  1120. if (!PrevClassTemplate && QualifierLoc) {
  1121. SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
  1122. << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
  1123. << QualifierLoc.getSourceRange();
  1124. return nullptr;
  1125. }
  1126. bool AdoptedPreviousTemplateParams = false;
  1127. if (PrevClassTemplate) {
  1128. bool Complain = true;
  1129. // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
  1130. // template for struct std::tr1::__detail::_Map_base, where the
  1131. // template parameters of the friend declaration don't match the
  1132. // template parameters of the original declaration. In this one
  1133. // case, we don't complain about the ill-formed friend
  1134. // declaration.
  1135. if (isFriend && Pattern->getIdentifier() &&
  1136. Pattern->getIdentifier()->isStr("_Map_base") &&
  1137. DC->isNamespace() &&
  1138. cast<NamespaceDecl>(DC)->getIdentifier() &&
  1139. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
  1140. DeclContext *DCParent = DC->getParent();
  1141. if (DCParent->isNamespace() &&
  1142. cast<NamespaceDecl>(DCParent)->getIdentifier() &&
  1143. cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
  1144. if (cast<Decl>(DCParent)->isInStdNamespace())
  1145. Complain = false;
  1146. }
  1147. }
  1148. TemplateParameterList *PrevParams
  1149. = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
  1150. // Make sure the parameter lists match.
  1151. if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
  1152. Complain,
  1153. Sema::TPL_TemplateMatch)) {
  1154. if (Complain)
  1155. return nullptr;
  1156. AdoptedPreviousTemplateParams = true;
  1157. InstParams = PrevParams;
  1158. }
  1159. // Do some additional validation, then merge default arguments
  1160. // from the existing declarations.
  1161. if (!AdoptedPreviousTemplateParams &&
  1162. SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
  1163. Sema::TPC_ClassTemplate))
  1164. return nullptr;
  1165. }
  1166. }
  1167. CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
  1168. SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
  1169. Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
  1170. /*DelayTypeCreation=*/true);
  1171. if (QualifierLoc)
  1172. RecordInst->setQualifierInfo(QualifierLoc);
  1173. SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
  1174. StartingScope);
  1175. ClassTemplateDecl *Inst
  1176. = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
  1177. D->getIdentifier(), InstParams, RecordInst);
  1178. assert(!(isFriend && Owner->isDependentContext()));
  1179. Inst->setPreviousDecl(PrevClassTemplate);
  1180. RecordInst->setDescribedClassTemplate(Inst);
  1181. if (isFriend) {
  1182. if (PrevClassTemplate)
  1183. Inst->setAccess(PrevClassTemplate->getAccess());
  1184. else
  1185. Inst->setAccess(D->getAccess());
  1186. Inst->setObjectOfFriendDecl();
  1187. // TODO: do we want to track the instantiation progeny of this
  1188. // friend target decl?
  1189. } else {
  1190. Inst->setAccess(D->getAccess());
  1191. if (!PrevClassTemplate)
  1192. Inst->setInstantiatedFromMemberTemplate(D);
  1193. }
  1194. // Trigger creation of the type for the instantiation.
  1195. SemaRef.Context.getInjectedClassNameType(RecordInst,
  1196. Inst->getInjectedClassNameSpecialization());
  1197. // Finish handling of friends.
  1198. if (isFriend) {
  1199. DC->makeDeclVisibleInContext(Inst);
  1200. Inst->setLexicalDeclContext(Owner);
  1201. RecordInst->setLexicalDeclContext(Owner);
  1202. return Inst;
  1203. }
  1204. if (D->isOutOfLine()) {
  1205. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  1206. RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
  1207. }
  1208. Owner->addDecl(Inst);
  1209. if (!PrevClassTemplate) {
  1210. // Queue up any out-of-line partial specializations of this member
  1211. // class template; the client will force their instantiation once
  1212. // the enclosing class has been instantiated.
  1213. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1214. D->getPartialSpecializations(PartialSpecs);
  1215. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1216. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1217. OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
  1218. }
  1219. return Inst;
  1220. }
  1221. Decl *
  1222. TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
  1223. ClassTemplatePartialSpecializationDecl *D) {
  1224. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  1225. // Lookup the already-instantiated declaration in the instantiation
  1226. // of the class template and return that.
  1227. DeclContext::lookup_result Found
  1228. = Owner->lookup(ClassTemplate->getDeclName());
  1229. if (Found.empty())
  1230. return nullptr;
  1231. ClassTemplateDecl *InstClassTemplate
  1232. = dyn_cast<ClassTemplateDecl>(Found.front());
  1233. if (!InstClassTemplate)
  1234. return nullptr;
  1235. if (ClassTemplatePartialSpecializationDecl *Result
  1236. = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
  1237. return Result;
  1238. return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
  1239. }
  1240. Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
  1241. assert(D->getTemplatedDecl()->isStaticDataMember() &&
  1242. "Only static data member templates are allowed.");
  1243. // Create a local instantiation scope for this variable template, which
  1244. // will contain the instantiations of the template parameters.
  1245. LocalInstantiationScope Scope(SemaRef);
  1246. TemplateParameterList *TempParams = D->getTemplateParameters();
  1247. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1248. if (!InstParams)
  1249. return nullptr;
  1250. VarDecl *Pattern = D->getTemplatedDecl();
  1251. VarTemplateDecl *PrevVarTemplate = nullptr;
  1252. if (getPreviousDeclForInstantiation(Pattern)) {
  1253. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  1254. if (!Found.empty())
  1255. PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1256. }
  1257. VarDecl *VarInst =
  1258. cast_or_null<VarDecl>(VisitVarDecl(Pattern,
  1259. /*InstantiatingVarTemplate=*/true));
  1260. if (!VarInst) return nullptr;
  1261. DeclContext *DC = Owner;
  1262. VarTemplateDecl *Inst = VarTemplateDecl::Create(
  1263. SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
  1264. VarInst);
  1265. VarInst->setDescribedVarTemplate(Inst);
  1266. Inst->setPreviousDecl(PrevVarTemplate);
  1267. Inst->setAccess(D->getAccess());
  1268. if (!PrevVarTemplate)
  1269. Inst->setInstantiatedFromMemberTemplate(D);
  1270. if (D->isOutOfLine()) {
  1271. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  1272. VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
  1273. }
  1274. Owner->addDecl(Inst);
  1275. if (!PrevVarTemplate) {
  1276. // Queue up any out-of-line partial specializations of this member
  1277. // variable template; the client will force their instantiation once
  1278. // the enclosing class has been instantiated.
  1279. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1280. D->getPartialSpecializations(PartialSpecs);
  1281. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1282. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1283. OutOfLineVarPartialSpecs.push_back(
  1284. std::make_pair(Inst, PartialSpecs[I]));
  1285. }
  1286. return Inst;
  1287. }
  1288. Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
  1289. VarTemplatePartialSpecializationDecl *D) {
  1290. assert(D->isStaticDataMember() &&
  1291. "Only static data member templates are allowed.");
  1292. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  1293. // Lookup the already-instantiated declaration and return that.
  1294. DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
  1295. assert(!Found.empty() && "Instantiation found nothing?");
  1296. VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1297. assert(InstVarTemplate && "Instantiation did not find a variable template?");
  1298. if (VarTemplatePartialSpecializationDecl *Result =
  1299. InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
  1300. return Result;
  1301. return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
  1302. }
  1303. Decl *
  1304. TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  1305. // Create a local instantiation scope for this function template, which
  1306. // will contain the instantiations of the template parameters and then get
  1307. // merged with the local instantiation scope for the function template
  1308. // itself.
  1309. LocalInstantiationScope Scope(SemaRef);
  1310. TemplateParameterList *TempParams = D->getTemplateParameters();
  1311. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1312. if (!InstParams)
  1313. return nullptr;
  1314. FunctionDecl *Instantiated = nullptr;
  1315. if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
  1316. Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
  1317. InstParams));
  1318. else
  1319. Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
  1320. D->getTemplatedDecl(),
  1321. InstParams));
  1322. if (!Instantiated)
  1323. return nullptr;
  1324. // Link the instantiated function template declaration to the function
  1325. // template from which it was instantiated.
  1326. FunctionTemplateDecl *InstTemplate
  1327. = Instantiated->getDescribedFunctionTemplate();
  1328. InstTemplate->setAccess(D->getAccess());
  1329. assert(InstTemplate &&
  1330. "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
  1331. bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
  1332. // Link the instantiation back to the pattern *unless* this is a
  1333. // non-definition friend declaration.
  1334. if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
  1335. !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
  1336. InstTemplate->setInstantiatedFromMemberTemplate(D);
  1337. // Make declarations visible in the appropriate context.
  1338. if (!isFriend) {
  1339. Owner->addDecl(InstTemplate);
  1340. } else if (InstTemplate->getDeclContext()->isRecord() &&
  1341. !getPreviousDeclForInstantiation(D)) {
  1342. SemaRef.CheckFriendAccess(InstTemplate);
  1343. }
  1344. return InstTemplate;
  1345. }
  1346. Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
  1347. CXXRecordDecl *PrevDecl = nullptr;
  1348. if (D->isInjectedClassName())
  1349. PrevDecl = cast<CXXRecordDecl>(Owner);
  1350. else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  1351. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1352. PatternPrev,
  1353. TemplateArgs);
  1354. if (!Prev) return nullptr;
  1355. PrevDecl = cast<CXXRecordDecl>(Prev);
  1356. }
  1357. CXXRecordDecl *Record = CXXRecordDecl::Create(
  1358. SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
  1359. D->getLocation(), D->getIdentifier(), PrevDecl);
  1360. // Substitute the nested name specifier, if any.
  1361. if (SubstQualifier(D, Record))
  1362. return nullptr;
  1363. SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
  1364. StartingScope);
  1365. Record->setImplicit(D->isImplicit());
  1366. // FIXME: Check against AS_none is an ugly hack to work around the issue that
  1367. // the tag decls introduced by friend class declarations don't have an access
  1368. // specifier. Remove once this area of the code gets sorted out.
  1369. if (D->getAccess() != AS_none)
  1370. Record->setAccess(D->getAccess());
  1371. if (!D->isInjectedClassName())
  1372. Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  1373. // If the original function was part of a friend declaration,
  1374. // inherit its namespace state.
  1375. if (D->getFriendObjectKind())
  1376. Record->setObjectOfFriendDecl();
  1377. // Make sure that anonymous structs and unions are recorded.
  1378. if (D->isAnonymousStructOrUnion())
  1379. Record->setAnonymousStructOrUnion(true);
  1380. if (D->isLocalClass())
  1381. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
  1382. // Forward the mangling number from the template to the instantiated decl.
  1383. SemaRef.Context.setManglingNumber(Record,
  1384. SemaRef.Context.getManglingNumber(D));
  1385. // See if the old tag was defined along with a declarator.
  1386. // If it did, mark the new tag as being associated with that declarator.
  1387. if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
  1388. SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
  1389. // See if the old tag was defined along with a typedef.
  1390. // If it did, mark the new tag as being associated with that typedef.
  1391. if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
  1392. SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
  1393. Owner->addDecl(Record);
  1394. // DR1484 clarifies that the members of a local class are instantiated as part
  1395. // of the instantiation of their enclosing entity.
  1396. if (D->isCompleteDefinition() && D->isLocalClass()) {
  1397. Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
  1398. SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
  1399. TSK_ImplicitInstantiation,
  1400. /*Complain=*/true);
  1401. // For nested local classes, we will instantiate the members when we
  1402. // reach the end of the outermost (non-nested) local class.
  1403. if (!D->isCXXClassMember())
  1404. SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
  1405. TSK_ImplicitInstantiation);
  1406. // This class may have local implicit instantiations that need to be
  1407. // performed within this scope.
  1408. LocalInstantiations.perform();
  1409. }
  1410. SemaRef.DiagnoseUnusedNestedTypedefs(Record);
  1411. return Record;
  1412. }
  1413. /// Adjust the given function type for an instantiation of the
  1414. /// given declaration, to cope with modifications to the function's type that
  1415. /// aren't reflected in the type-source information.
  1416. ///
  1417. /// \param D The declaration we're instantiating.
  1418. /// \param TInfo The already-instantiated type.
  1419. static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
  1420. FunctionDecl *D,
  1421. TypeSourceInfo *TInfo) {
  1422. const FunctionProtoType *OrigFunc
  1423. = D->getType()->castAs<FunctionProtoType>();
  1424. const FunctionProtoType *NewFunc
  1425. = TInfo->getType()->castAs<FunctionProtoType>();
  1426. if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
  1427. return TInfo->getType();
  1428. FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
  1429. NewEPI.ExtInfo = OrigFunc->getExtInfo();
  1430. return Context.getFunctionType(NewFunc->getReturnType(),
  1431. NewFunc->getParamTypes(), NewEPI);
  1432. }
  1433. /// Normal class members are of more specific types and therefore
  1434. /// don't make it here. This function serves three purposes:
  1435. /// 1) instantiating function templates
  1436. /// 2) substituting friend declarations
  1437. /// 3) substituting deduction guide declarations for nested class templates
  1438. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
  1439. TemplateParameterList *TemplateParams) {
  1440. // Check whether there is already a function template specialization for
  1441. // this declaration.
  1442. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1443. if (FunctionTemplate && !TemplateParams) {
  1444. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1445. void *InsertPos = nullptr;
  1446. FunctionDecl *SpecFunc
  1447. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1448. // If we already have a function template specialization, return it.
  1449. if (SpecFunc)
  1450. return SpecFunc;
  1451. }
  1452. bool isFriend;
  1453. if (FunctionTemplate)
  1454. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1455. else
  1456. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1457. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1458. Owner->isFunctionOrMethod() ||
  1459. !(isa<Decl>(Owner) &&
  1460. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1461. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1462. ExplicitSpecifier InstantiatedExplicitSpecifier;
  1463. if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
  1464. InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
  1465. SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
  1466. if (InstantiatedExplicitSpecifier.isInvalid())
  1467. return nullptr;
  1468. }
  1469. SmallVector<ParmVarDecl *, 4> Params;
  1470. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1471. if (!TInfo)
  1472. return nullptr;
  1473. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1474. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1475. if (QualifierLoc) {
  1476. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1477. TemplateArgs);
  1478. if (!QualifierLoc)
  1479. return nullptr;
  1480. }
  1481. // If we're instantiating a local function declaration, put the result
  1482. // in the enclosing namespace; otherwise we need to find the instantiated
  1483. // context.
  1484. DeclContext *DC;
  1485. if (D->isLocalExternDecl()) {
  1486. DC = Owner;
  1487. SemaRef.adjustContextForLocalExternDecl(DC);
  1488. } else if (isFriend && QualifierLoc) {
  1489. CXXScopeSpec SS;
  1490. SS.Adopt(QualifierLoc);
  1491. DC = SemaRef.computeDeclContext(SS);
  1492. if (!DC) return nullptr;
  1493. } else {
  1494. DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
  1495. TemplateArgs);
  1496. }
  1497. DeclarationNameInfo NameInfo
  1498. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1499. FunctionDecl *Function;
  1500. if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
  1501. Function = CXXDeductionGuideDecl::Create(
  1502. SemaRef.Context, DC, D->getInnerLocStart(),
  1503. InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
  1504. D->getSourceRange().getEnd());
  1505. if (DGuide->isCopyDeductionCandidate())
  1506. cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
  1507. Function->setAccess(D->getAccess());
  1508. } else {
  1509. Function = FunctionDecl::Create(
  1510. SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
  1511. D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
  1512. D->hasWrittenPrototype(), D->getConstexprKind());
  1513. Function->setRangeEnd(D->getSourceRange().getEnd());
  1514. }
  1515. if (D->isInlined())
  1516. Function->setImplicitlyInline();
  1517. if (QualifierLoc)
  1518. Function->setQualifierInfo(QualifierLoc);
  1519. if (D->isLocalExternDecl())
  1520. Function->setLocalExternDecl();
  1521. DeclContext *LexicalDC = Owner;
  1522. if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
  1523. assert(D->getDeclContext()->isFileContext());
  1524. LexicalDC = D->getDeclContext();
  1525. }
  1526. Function->setLexicalDeclContext(LexicalDC);
  1527. // Attach the parameters
  1528. for (unsigned P = 0; P < Params.size(); ++P)
  1529. if (Params[P])
  1530. Params[P]->setOwningFunction(Function);
  1531. Function->setParams(Params);
  1532. if (TemplateParams) {
  1533. // Our resulting instantiation is actually a function template, since we
  1534. // are substituting only the outer template parameters. For example, given
  1535. //
  1536. // template<typename T>
  1537. // struct X {
  1538. // template<typename U> friend void f(T, U);
  1539. // };
  1540. //
  1541. // X<int> x;
  1542. //
  1543. // We are instantiating the friend function template "f" within X<int>,
  1544. // which means substituting int for T, but leaving "f" as a friend function
  1545. // template.
  1546. // Build the function template itself.
  1547. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
  1548. Function->getLocation(),
  1549. Function->getDeclName(),
  1550. TemplateParams, Function);
  1551. Function->setDescribedFunctionTemplate(FunctionTemplate);
  1552. FunctionTemplate->setLexicalDeclContext(LexicalDC);
  1553. if (isFriend && D->isThisDeclarationADefinition()) {
  1554. FunctionTemplate->setInstantiatedFromMemberTemplate(
  1555. D->getDescribedFunctionTemplate());
  1556. }
  1557. } else if (FunctionTemplate) {
  1558. // Record this function template specialization.
  1559. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1560. Function->setFunctionTemplateSpecialization(FunctionTemplate,
  1561. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1562. Innermost),
  1563. /*InsertPos=*/nullptr);
  1564. } else if (isFriend && D->isThisDeclarationADefinition()) {
  1565. // Do not connect the friend to the template unless it's actually a
  1566. // definition. We don't want non-template functions to be marked as being
  1567. // template instantiations.
  1568. Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1569. }
  1570. if (isFriend)
  1571. Function->setObjectOfFriendDecl();
  1572. if (InitFunctionInstantiation(Function, D))
  1573. Function->setInvalidDecl();
  1574. bool IsExplicitSpecialization = false;
  1575. LookupResult Previous(
  1576. SemaRef, Function->getDeclName(), SourceLocation(),
  1577. D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  1578. : Sema::LookupOrdinaryName,
  1579. D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
  1580. : SemaRef.forRedeclarationInCurContext());
  1581. if (DependentFunctionTemplateSpecializationInfo *Info
  1582. = D->getDependentSpecializationInfo()) {
  1583. assert(isFriend && "non-friend has dependent specialization info?");
  1584. // Instantiate the explicit template arguments.
  1585. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1586. Info->getRAngleLoc());
  1587. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1588. ExplicitArgs, TemplateArgs))
  1589. return nullptr;
  1590. // Map the candidate templates to their instantiations.
  1591. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1592. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1593. Info->getTemplate(I),
  1594. TemplateArgs);
  1595. if (!Temp) return nullptr;
  1596. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1597. }
  1598. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1599. &ExplicitArgs,
  1600. Previous))
  1601. Function->setInvalidDecl();
  1602. IsExplicitSpecialization = true;
  1603. } else if (const ASTTemplateArgumentListInfo *Info =
  1604. D->getTemplateSpecializationArgsAsWritten()) {
  1605. // The name of this function was written as a template-id.
  1606. SemaRef.LookupQualifiedName(Previous, DC);
  1607. // Instantiate the explicit template arguments.
  1608. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1609. Info->getRAngleLoc());
  1610. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1611. ExplicitArgs, TemplateArgs))
  1612. return nullptr;
  1613. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1614. &ExplicitArgs,
  1615. Previous))
  1616. Function->setInvalidDecl();
  1617. IsExplicitSpecialization = true;
  1618. } else if (TemplateParams || !FunctionTemplate) {
  1619. // Look only into the namespace where the friend would be declared to
  1620. // find a previous declaration. This is the innermost enclosing namespace,
  1621. // as described in ActOnFriendFunctionDecl.
  1622. SemaRef.LookupQualifiedName(Previous, DC);
  1623. // In C++, the previous declaration we find might be a tag type
  1624. // (class or enum). In this case, the new declaration will hide the
  1625. // tag type. Note that this does does not apply if we're declaring a
  1626. // typedef (C++ [dcl.typedef]p4).
  1627. if (Previous.isSingleTagDecl())
  1628. Previous.clear();
  1629. }
  1630. SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
  1631. IsExplicitSpecialization);
  1632. NamedDecl *PrincipalDecl = (TemplateParams
  1633. ? cast<NamedDecl>(FunctionTemplate)
  1634. : Function);
  1635. // If the original function was part of a friend declaration,
  1636. // inherit its namespace state and add it to the owner.
  1637. if (isFriend) {
  1638. Function->setObjectOfFriendDecl();
  1639. if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
  1640. FT->setObjectOfFriendDecl();
  1641. DC->makeDeclVisibleInContext(PrincipalDecl);
  1642. bool QueuedInstantiation = false;
  1643. // C++11 [temp.friend]p4 (DR329):
  1644. // When a function is defined in a friend function declaration in a class
  1645. // template, the function is instantiated when the function is odr-used.
  1646. // The same restrictions on multiple declarations and definitions that
  1647. // apply to non-template function declarations and definitions also apply
  1648. // to these implicit definitions.
  1649. if (D->isThisDeclarationADefinition()) {
  1650. SemaRef.CheckForFunctionRedefinition(Function);
  1651. if (!Function->isInvalidDecl()) {
  1652. for (auto R : Function->redecls()) {
  1653. if (R == Function)
  1654. continue;
  1655. // If some prior declaration of this function has been used, we need
  1656. // to instantiate its definition.
  1657. if (!QueuedInstantiation && R->isUsed(false)) {
  1658. if (MemberSpecializationInfo *MSInfo =
  1659. Function->getMemberSpecializationInfo()) {
  1660. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  1661. SourceLocation Loc = R->getLocation(); // FIXME
  1662. MSInfo->setPointOfInstantiation(Loc);
  1663. SemaRef.PendingLocalImplicitInstantiations.push_back(
  1664. std::make_pair(Function, Loc));
  1665. QueuedInstantiation = true;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. }
  1671. }
  1672. // Check the template parameter list against the previous declaration. The
  1673. // goal here is to pick up default arguments added since the friend was
  1674. // declared; we know the template parameter lists match, since otherwise
  1675. // we would not have picked this template as the previous declaration.
  1676. if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
  1677. SemaRef.CheckTemplateParameterList(
  1678. TemplateParams,
  1679. FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
  1680. Function->isThisDeclarationADefinition()
  1681. ? Sema::TPC_FriendFunctionTemplateDefinition
  1682. : Sema::TPC_FriendFunctionTemplate);
  1683. }
  1684. }
  1685. if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
  1686. DC->makeDeclVisibleInContext(PrincipalDecl);
  1687. if (Function->isOverloadedOperator() && !DC->isRecord() &&
  1688. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  1689. PrincipalDecl->setNonMemberOperator();
  1690. assert(!D->isDefaulted() && "only methods should be defaulted");
  1691. return Function;
  1692. }
  1693. Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
  1694. CXXMethodDecl *D, TemplateParameterList *TemplateParams,
  1695. Optional<const ASTTemplateArgumentListInfo *>
  1696. ClassScopeSpecializationArgs) {
  1697. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1698. if (FunctionTemplate && !TemplateParams) {
  1699. // We are creating a function template specialization from a function
  1700. // template. Check whether there is already a function template
  1701. // specialization for this particular set of template arguments.
  1702. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1703. void *InsertPos = nullptr;
  1704. FunctionDecl *SpecFunc
  1705. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1706. // If we already have a function template specialization, return it.
  1707. if (SpecFunc)
  1708. return SpecFunc;
  1709. }
  1710. bool isFriend;
  1711. if (FunctionTemplate)
  1712. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1713. else
  1714. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1715. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1716. !(isa<Decl>(Owner) &&
  1717. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1718. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1719. // Instantiate enclosing template arguments for friends.
  1720. SmallVector<TemplateParameterList *, 4> TempParamLists;
  1721. unsigned NumTempParamLists = 0;
  1722. if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
  1723. TempParamLists.resize(NumTempParamLists);
  1724. for (unsigned I = 0; I != NumTempParamLists; ++I) {
  1725. TemplateParameterList *TempParams = D->getTemplateParameterList(I);
  1726. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1727. if (!InstParams)
  1728. return nullptr;
  1729. TempParamLists[I] = InstParams;
  1730. }
  1731. }
  1732. ExplicitSpecifier InstantiatedExplicitSpecifier =
  1733. instantiateExplicitSpecifier(SemaRef, TemplateArgs,
  1734. ExplicitSpecifier::getFromDecl(D), D);
  1735. if (InstantiatedExplicitSpecifier.isInvalid())
  1736. return nullptr;
  1737. SmallVector<ParmVarDecl *, 4> Params;
  1738. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1739. if (!TInfo)
  1740. return nullptr;
  1741. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1742. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1743. if (QualifierLoc) {
  1744. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1745. TemplateArgs);
  1746. if (!QualifierLoc)
  1747. return nullptr;
  1748. }
  1749. DeclContext *DC = Owner;
  1750. if (isFriend) {
  1751. if (QualifierLoc) {
  1752. CXXScopeSpec SS;
  1753. SS.Adopt(QualifierLoc);
  1754. DC = SemaRef.computeDeclContext(SS);
  1755. if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
  1756. return nullptr;
  1757. } else {
  1758. DC = SemaRef.FindInstantiatedContext(D->getLocation(),
  1759. D->getDeclContext(),
  1760. TemplateArgs);
  1761. }
  1762. if (!DC) return nullptr;
  1763. }
  1764. // Build the instantiated method declaration.
  1765. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  1766. CXXMethodDecl *Method = nullptr;
  1767. SourceLocation StartLoc = D->getInnerLocStart();
  1768. DeclarationNameInfo NameInfo
  1769. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1770. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1771. Method = CXXConstructorDecl::Create(
  1772. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
  1773. InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
  1774. Constructor->getConstexprKind());
  1775. Method->setRangeEnd(Constructor->getEndLoc());
  1776. } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
  1777. Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
  1778. StartLoc, NameInfo, T, TInfo,
  1779. Destructor->isInlineSpecified(),
  1780. false);
  1781. Method->setRangeEnd(Destructor->getEndLoc());
  1782. } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  1783. Method = CXXConversionDecl::Create(
  1784. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
  1785. Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
  1786. Conversion->getConstexprKind(), Conversion->getEndLoc());
  1787. } else {
  1788. StorageClass SC = D->isStatic() ? SC_Static : SC_None;
  1789. Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
  1790. T, TInfo, SC, D->isInlineSpecified(),
  1791. D->getConstexprKind(), D->getEndLoc());
  1792. }
  1793. if (D->isInlined())
  1794. Method->setImplicitlyInline();
  1795. if (QualifierLoc)
  1796. Method->setQualifierInfo(QualifierLoc);
  1797. if (TemplateParams) {
  1798. // Our resulting instantiation is actually a function template, since we
  1799. // are substituting only the outer template parameters. For example, given
  1800. //
  1801. // template<typename T>
  1802. // struct X {
  1803. // template<typename U> void f(T, U);
  1804. // };
  1805. //
  1806. // X<int> x;
  1807. //
  1808. // We are instantiating the member template "f" within X<int>, which means
  1809. // substituting int for T, but leaving "f" as a member function template.
  1810. // Build the function template itself.
  1811. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
  1812. Method->getLocation(),
  1813. Method->getDeclName(),
  1814. TemplateParams, Method);
  1815. if (isFriend) {
  1816. FunctionTemplate->setLexicalDeclContext(Owner);
  1817. FunctionTemplate->setObjectOfFriendDecl();
  1818. } else if (D->isOutOfLine())
  1819. FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
  1820. Method->setDescribedFunctionTemplate(FunctionTemplate);
  1821. } else if (FunctionTemplate) {
  1822. // Record this function template specialization.
  1823. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1824. Method->setFunctionTemplateSpecialization(FunctionTemplate,
  1825. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1826. Innermost),
  1827. /*InsertPos=*/nullptr);
  1828. } else if (!isFriend) {
  1829. // Record that this is an instantiation of a member function.
  1830. Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1831. }
  1832. // If we are instantiating a member function defined
  1833. // out-of-line, the instantiation will have the same lexical
  1834. // context (which will be a namespace scope) as the template.
  1835. if (isFriend) {
  1836. if (NumTempParamLists)
  1837. Method->setTemplateParameterListsInfo(
  1838. SemaRef.Context,
  1839. llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
  1840. Method->setLexicalDeclContext(Owner);
  1841. Method->setObjectOfFriendDecl();
  1842. } else if (D->isOutOfLine())
  1843. Method->setLexicalDeclContext(D->getLexicalDeclContext());
  1844. // Attach the parameters
  1845. for (unsigned P = 0; P < Params.size(); ++P)
  1846. Params[P]->setOwningFunction(Method);
  1847. Method->setParams(Params);
  1848. if (InitMethodInstantiation(Method, D))
  1849. Method->setInvalidDecl();
  1850. LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
  1851. Sema::ForExternalRedeclaration);
  1852. bool IsExplicitSpecialization = false;
  1853. // If the name of this function was written as a template-id, instantiate
  1854. // the explicit template arguments.
  1855. if (DependentFunctionTemplateSpecializationInfo *Info
  1856. = D->getDependentSpecializationInfo()) {
  1857. assert(isFriend && "non-friend has dependent specialization info?");
  1858. // Instantiate the explicit template arguments.
  1859. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1860. Info->getRAngleLoc());
  1861. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1862. ExplicitArgs, TemplateArgs))
  1863. return nullptr;
  1864. // Map the candidate templates to their instantiations.
  1865. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1866. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1867. Info->getTemplate(I),
  1868. TemplateArgs);
  1869. if (!Temp) return nullptr;
  1870. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1871. }
  1872. if (SemaRef.CheckFunctionTemplateSpecialization(Method,
  1873. &ExplicitArgs,
  1874. Previous))
  1875. Method->setInvalidDecl();
  1876. IsExplicitSpecialization = true;
  1877. } else if (const ASTTemplateArgumentListInfo *Info =
  1878. ClassScopeSpecializationArgs.getValueOr(
  1879. D->getTemplateSpecializationArgsAsWritten())) {
  1880. SemaRef.LookupQualifiedName(Previous, DC);
  1881. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1882. Info->getRAngleLoc());
  1883. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1884. ExplicitArgs, TemplateArgs))
  1885. return nullptr;
  1886. if (SemaRef.CheckFunctionTemplateSpecialization(Method,
  1887. &ExplicitArgs,
  1888. Previous))
  1889. Method->setInvalidDecl();
  1890. IsExplicitSpecialization = true;
  1891. } else if (ClassScopeSpecializationArgs) {
  1892. // Class-scope explicit specialization written without explicit template
  1893. // arguments.
  1894. SemaRef.LookupQualifiedName(Previous, DC);
  1895. if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
  1896. Method->setInvalidDecl();
  1897. IsExplicitSpecialization = true;
  1898. } else if (!FunctionTemplate || TemplateParams || isFriend) {
  1899. SemaRef.LookupQualifiedName(Previous, Record);
  1900. // In C++, the previous declaration we find might be a tag type
  1901. // (class or enum). In this case, the new declaration will hide the
  1902. // tag type. Note that this does does not apply if we're declaring a
  1903. // typedef (C++ [dcl.typedef]p4).
  1904. if (Previous.isSingleTagDecl())
  1905. Previous.clear();
  1906. }
  1907. SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
  1908. IsExplicitSpecialization);
  1909. if (D->isPure())
  1910. SemaRef.CheckPureMethod(Method, SourceRange());
  1911. // Propagate access. For a non-friend declaration, the access is
  1912. // whatever we're propagating from. For a friend, it should be the
  1913. // previous declaration we just found.
  1914. if (isFriend && Method->getPreviousDecl())
  1915. Method->setAccess(Method->getPreviousDecl()->getAccess());
  1916. else
  1917. Method->setAccess(D->getAccess());
  1918. if (FunctionTemplate)
  1919. FunctionTemplate->setAccess(Method->getAccess());
  1920. SemaRef.CheckOverrideControl(Method);
  1921. // If a function is defined as defaulted or deleted, mark it as such now.
  1922. if (D->isExplicitlyDefaulted())
  1923. SemaRef.SetDeclDefaulted(Method, Method->getLocation());
  1924. if (D->isDeletedAsWritten())
  1925. SemaRef.SetDeclDeleted(Method, Method->getLocation());
  1926. // If this is an explicit specialization, mark the implicitly-instantiated
  1927. // template specialization as being an explicit specialization too.
  1928. // FIXME: Is this necessary?
  1929. if (IsExplicitSpecialization && !isFriend)
  1930. SemaRef.CompleteMemberSpecialization(Method, Previous);
  1931. // If there's a function template, let our caller handle it.
  1932. if (FunctionTemplate) {
  1933. // do nothing
  1934. // Don't hide a (potentially) valid declaration with an invalid one.
  1935. } else if (Method->isInvalidDecl() && !Previous.empty()) {
  1936. // do nothing
  1937. // Otherwise, check access to friends and make them visible.
  1938. } else if (isFriend) {
  1939. // We only need to re-check access for methods which we didn't
  1940. // manage to match during parsing.
  1941. if (!D->getPreviousDecl())
  1942. SemaRef.CheckFriendAccess(Method);
  1943. Record->makeDeclVisibleInContext(Method);
  1944. // Otherwise, add the declaration. We don't need to do this for
  1945. // class-scope specializations because we'll have matched them with
  1946. // the appropriate template.
  1947. } else {
  1948. Owner->addDecl(Method);
  1949. }
  1950. // PR17480: Honor the used attribute to instantiate member function
  1951. // definitions
  1952. if (Method->hasAttr<UsedAttr>()) {
  1953. if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
  1954. SourceLocation Loc;
  1955. if (const MemberSpecializationInfo *MSInfo =
  1956. A->getMemberSpecializationInfo())
  1957. Loc = MSInfo->getPointOfInstantiation();
  1958. else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
  1959. Loc = Spec->getPointOfInstantiation();
  1960. SemaRef.MarkFunctionReferenced(Loc, Method);
  1961. }
  1962. }
  1963. return Method;
  1964. }
  1965. Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1966. return VisitCXXMethodDecl(D);
  1967. }
  1968. Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1969. return VisitCXXMethodDecl(D);
  1970. }
  1971. Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1972. return VisitCXXMethodDecl(D);
  1973. }
  1974. Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
  1975. return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
  1976. /*ExpectParameterPack=*/ false);
  1977. }
  1978. Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
  1979. TemplateTypeParmDecl *D) {
  1980. // TODO: don't always clone when decls are refcounted.
  1981. assert(D->getTypeForDecl()->isTemplateTypeParmType());
  1982. TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
  1983. SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
  1984. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
  1985. D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
  1986. Inst->setAccess(AS_public);
  1987. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  1988. TypeSourceInfo *InstantiatedDefaultArg =
  1989. SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
  1990. D->getDefaultArgumentLoc(), D->getDeclName());
  1991. if (InstantiatedDefaultArg)
  1992. Inst->setDefaultArgument(InstantiatedDefaultArg);
  1993. }
  1994. // Introduce this template parameter's instantiation into the instantiation
  1995. // scope.
  1996. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  1997. return Inst;
  1998. }
  1999. Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
  2000. NonTypeTemplateParmDecl *D) {
  2001. // Substitute into the type of the non-type template parameter.
  2002. TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
  2003. SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
  2004. SmallVector<QualType, 4> ExpandedParameterPackTypes;
  2005. bool IsExpandedParameterPack = false;
  2006. TypeSourceInfo *DI;
  2007. QualType T;
  2008. bool Invalid = false;
  2009. if (D->isExpandedParameterPack()) {
  2010. // The non-type template parameter pack is an already-expanded pack
  2011. // expansion of types. Substitute into each of the expanded types.
  2012. ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
  2013. ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
  2014. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  2015. TypeSourceInfo *NewDI =
  2016. SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
  2017. D->getLocation(), D->getDeclName());
  2018. if (!NewDI)
  2019. return nullptr;
  2020. QualType NewT =
  2021. SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
  2022. if (NewT.isNull())
  2023. return nullptr;
  2024. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  2025. ExpandedParameterPackTypes.push_back(NewT);
  2026. }
  2027. IsExpandedParameterPack = true;
  2028. DI = D->getTypeSourceInfo();
  2029. T = DI->getType();
  2030. } else if (D->isPackExpansion()) {
  2031. // The non-type template parameter pack's type is a pack expansion of types.
  2032. // Determine whether we need to expand this parameter pack into separate
  2033. // types.
  2034. PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
  2035. TypeLoc Pattern = Expansion.getPatternLoc();
  2036. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2037. SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  2038. // Determine whether the set of unexpanded parameter packs can and should
  2039. // be expanded.
  2040. bool Expand = true;
  2041. bool RetainExpansion = false;
  2042. Optional<unsigned> OrigNumExpansions
  2043. = Expansion.getTypePtr()->getNumExpansions();
  2044. Optional<unsigned> NumExpansions = OrigNumExpansions;
  2045. if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
  2046. Pattern.getSourceRange(),
  2047. Unexpanded,
  2048. TemplateArgs,
  2049. Expand, RetainExpansion,
  2050. NumExpansions))
  2051. return nullptr;
  2052. if (Expand) {
  2053. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2054. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2055. TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
  2056. D->getLocation(),
  2057. D->getDeclName());
  2058. if (!NewDI)
  2059. return nullptr;
  2060. QualType NewT =
  2061. SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
  2062. if (NewT.isNull())
  2063. return nullptr;
  2064. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  2065. ExpandedParameterPackTypes.push_back(NewT);
  2066. }
  2067. // Note that we have an expanded parameter pack. The "type" of this
  2068. // expanded parameter pack is the original expansion type, but callers
  2069. // will end up using the expanded parameter pack types for type-checking.
  2070. IsExpandedParameterPack = true;
  2071. DI = D->getTypeSourceInfo();
  2072. T = DI->getType();
  2073. } else {
  2074. // We cannot fully expand the pack expansion now, so substitute into the
  2075. // pattern and create a new pack expansion type.
  2076. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2077. TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
  2078. D->getLocation(),
  2079. D->getDeclName());
  2080. if (!NewPattern)
  2081. return nullptr;
  2082. SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
  2083. DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
  2084. NumExpansions);
  2085. if (!DI)
  2086. return nullptr;
  2087. T = DI->getType();
  2088. }
  2089. } else {
  2090. // Simple case: substitution into a parameter that is not a parameter pack.
  2091. DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  2092. D->getLocation(), D->getDeclName());
  2093. if (!DI)
  2094. return nullptr;
  2095. // Check that this type is acceptable for a non-type template parameter.
  2096. T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
  2097. if (T.isNull()) {
  2098. T = SemaRef.Context.IntTy;
  2099. Invalid = true;
  2100. }
  2101. }
  2102. NonTypeTemplateParmDecl *Param;
  2103. if (IsExpandedParameterPack)
  2104. Param = NonTypeTemplateParmDecl::Create(
  2105. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2106. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2107. D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
  2108. ExpandedParameterPackTypesAsWritten);
  2109. else
  2110. Param = NonTypeTemplateParmDecl::Create(
  2111. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2112. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2113. D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
  2114. Param->setAccess(AS_public);
  2115. if (Invalid)
  2116. Param->setInvalidDecl();
  2117. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  2118. EnterExpressionEvaluationContext ConstantEvaluated(
  2119. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  2120. ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
  2121. if (!Value.isInvalid())
  2122. Param->setDefaultArgument(Value.get());
  2123. }
  2124. // Introduce this template parameter's instantiation into the instantiation
  2125. // scope.
  2126. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  2127. return Param;
  2128. }
  2129. static void collectUnexpandedParameterPacks(
  2130. Sema &S,
  2131. TemplateParameterList *Params,
  2132. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  2133. for (const auto &P : *Params) {
  2134. if (P->isTemplateParameterPack())
  2135. continue;
  2136. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
  2137. S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
  2138. Unexpanded);
  2139. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
  2140. collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
  2141. Unexpanded);
  2142. }
  2143. }
  2144. Decl *
  2145. TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
  2146. TemplateTemplateParmDecl *D) {
  2147. // Instantiate the template parameter list of the template template parameter.
  2148. TemplateParameterList *TempParams = D->getTemplateParameters();
  2149. TemplateParameterList *InstParams;
  2150. SmallVector<TemplateParameterList*, 8> ExpandedParams;
  2151. bool IsExpandedParameterPack = false;
  2152. if (D->isExpandedParameterPack()) {
  2153. // The template template parameter pack is an already-expanded pack
  2154. // expansion of template parameters. Substitute into each of the expanded
  2155. // parameters.
  2156. ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
  2157. for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
  2158. I != N; ++I) {
  2159. LocalInstantiationScope Scope(SemaRef);
  2160. TemplateParameterList *Expansion =
  2161. SubstTemplateParams(D->getExpansionTemplateParameters(I));
  2162. if (!Expansion)
  2163. return nullptr;
  2164. ExpandedParams.push_back(Expansion);
  2165. }
  2166. IsExpandedParameterPack = true;
  2167. InstParams = TempParams;
  2168. } else if (D->isPackExpansion()) {
  2169. // The template template parameter pack expands to a pack of template
  2170. // template parameters. Determine whether we need to expand this parameter
  2171. // pack into separate parameters.
  2172. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2173. collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
  2174. Unexpanded);
  2175. // Determine whether the set of unexpanded parameter packs can and should
  2176. // be expanded.
  2177. bool Expand = true;
  2178. bool RetainExpansion = false;
  2179. Optional<unsigned> NumExpansions;
  2180. if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
  2181. TempParams->getSourceRange(),
  2182. Unexpanded,
  2183. TemplateArgs,
  2184. Expand, RetainExpansion,
  2185. NumExpansions))
  2186. return nullptr;
  2187. if (Expand) {
  2188. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2189. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2190. LocalInstantiationScope Scope(SemaRef);
  2191. TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
  2192. if (!Expansion)
  2193. return nullptr;
  2194. ExpandedParams.push_back(Expansion);
  2195. }
  2196. // Note that we have an expanded parameter pack. The "type" of this
  2197. // expanded parameter pack is the original expansion type, but callers
  2198. // will end up using the expanded parameter pack types for type-checking.
  2199. IsExpandedParameterPack = true;
  2200. InstParams = TempParams;
  2201. } else {
  2202. // We cannot fully expand the pack expansion now, so just substitute
  2203. // into the pattern.
  2204. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2205. LocalInstantiationScope Scope(SemaRef);
  2206. InstParams = SubstTemplateParams(TempParams);
  2207. if (!InstParams)
  2208. return nullptr;
  2209. }
  2210. } else {
  2211. // Perform the actual substitution of template parameters within a new,
  2212. // local instantiation scope.
  2213. LocalInstantiationScope Scope(SemaRef);
  2214. InstParams = SubstTemplateParams(TempParams);
  2215. if (!InstParams)
  2216. return nullptr;
  2217. }
  2218. // Build the template template parameter.
  2219. TemplateTemplateParmDecl *Param;
  2220. if (IsExpandedParameterPack)
  2221. Param = TemplateTemplateParmDecl::Create(
  2222. SemaRef.Context, Owner, D->getLocation(),
  2223. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2224. D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
  2225. else
  2226. Param = TemplateTemplateParmDecl::Create(
  2227. SemaRef.Context, Owner, D->getLocation(),
  2228. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2229. D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
  2230. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  2231. NestedNameSpecifierLoc QualifierLoc =
  2232. D->getDefaultArgument().getTemplateQualifierLoc();
  2233. QualifierLoc =
  2234. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
  2235. TemplateName TName = SemaRef.SubstTemplateName(
  2236. QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
  2237. D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
  2238. if (!TName.isNull())
  2239. Param->setDefaultArgument(
  2240. SemaRef.Context,
  2241. TemplateArgumentLoc(TemplateArgument(TName),
  2242. D->getDefaultArgument().getTemplateQualifierLoc(),
  2243. D->getDefaultArgument().getTemplateNameLoc()));
  2244. }
  2245. Param->setAccess(AS_public);
  2246. // Introduce this template parameter's instantiation into the instantiation
  2247. // scope.
  2248. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  2249. return Param;
  2250. }
  2251. Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  2252. // Using directives are never dependent (and never contain any types or
  2253. // expressions), so they require no explicit instantiation work.
  2254. UsingDirectiveDecl *Inst
  2255. = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  2256. D->getNamespaceKeyLocation(),
  2257. D->getQualifierLoc(),
  2258. D->getIdentLocation(),
  2259. D->getNominatedNamespace(),
  2260. D->getCommonAncestor());
  2261. // Add the using directive to its declaration context
  2262. // only if this is not a function or method.
  2263. if (!Owner->isFunctionOrMethod())
  2264. Owner->addDecl(Inst);
  2265. return Inst;
  2266. }
  2267. Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
  2268. // The nested name specifier may be dependent, for example
  2269. // template <typename T> struct t {
  2270. // struct s1 { T f1(); };
  2271. // struct s2 : s1 { using s1::f1; };
  2272. // };
  2273. // template struct t<int>;
  2274. // Here, in using s1::f1, s1 refers to t<T>::s1;
  2275. // we need to substitute for t<int>::s1.
  2276. NestedNameSpecifierLoc QualifierLoc
  2277. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2278. TemplateArgs);
  2279. if (!QualifierLoc)
  2280. return nullptr;
  2281. // For an inheriting constructor declaration, the name of the using
  2282. // declaration is the name of a constructor in this class, not in the
  2283. // base class.
  2284. DeclarationNameInfo NameInfo = D->getNameInfo();
  2285. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
  2286. if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
  2287. NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
  2288. SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
  2289. // We only need to do redeclaration lookups if we're in a class
  2290. // scope (in fact, it's not really even possible in non-class
  2291. // scopes).
  2292. bool CheckRedeclaration = Owner->isRecord();
  2293. LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
  2294. Sema::ForVisibleRedeclaration);
  2295. UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
  2296. D->getUsingLoc(),
  2297. QualifierLoc,
  2298. NameInfo,
  2299. D->hasTypename());
  2300. CXXScopeSpec SS;
  2301. SS.Adopt(QualifierLoc);
  2302. if (CheckRedeclaration) {
  2303. Prev.setHideTags(false);
  2304. SemaRef.LookupQualifiedName(Prev, Owner);
  2305. // Check for invalid redeclarations.
  2306. if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
  2307. D->hasTypename(), SS,
  2308. D->getLocation(), Prev))
  2309. NewUD->setInvalidDecl();
  2310. }
  2311. if (!NewUD->isInvalidDecl() &&
  2312. SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
  2313. SS, NameInfo, D->getLocation()))
  2314. NewUD->setInvalidDecl();
  2315. SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
  2316. NewUD->setAccess(D->getAccess());
  2317. Owner->addDecl(NewUD);
  2318. // Don't process the shadow decls for an invalid decl.
  2319. if (NewUD->isInvalidDecl())
  2320. return NewUD;
  2321. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
  2322. SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
  2323. bool isFunctionScope = Owner->isFunctionOrMethod();
  2324. // Process the shadow decls.
  2325. for (auto *Shadow : D->shadows()) {
  2326. // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
  2327. // reconstruct it in the case where it matters.
  2328. NamedDecl *OldTarget = Shadow->getTargetDecl();
  2329. if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
  2330. if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
  2331. OldTarget = BaseShadow;
  2332. NamedDecl *InstTarget =
  2333. cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
  2334. Shadow->getLocation(), OldTarget, TemplateArgs));
  2335. if (!InstTarget)
  2336. return nullptr;
  2337. UsingShadowDecl *PrevDecl = nullptr;
  2338. if (CheckRedeclaration) {
  2339. if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
  2340. continue;
  2341. } else if (UsingShadowDecl *OldPrev =
  2342. getPreviousDeclForInstantiation(Shadow)) {
  2343. PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
  2344. Shadow->getLocation(), OldPrev, TemplateArgs));
  2345. }
  2346. UsingShadowDecl *InstShadow =
  2347. SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
  2348. PrevDecl);
  2349. SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
  2350. if (isFunctionScope)
  2351. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
  2352. }
  2353. return NewUD;
  2354. }
  2355. Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
  2356. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2357. return nullptr;
  2358. }
  2359. Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
  2360. ConstructorUsingShadowDecl *D) {
  2361. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2362. return nullptr;
  2363. }
  2364. template <typename T>
  2365. Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
  2366. T *D, bool InstantiatingPackElement) {
  2367. // If this is a pack expansion, expand it now.
  2368. if (D->isPackExpansion() && !InstantiatingPackElement) {
  2369. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2370. SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
  2371. SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
  2372. // Determine whether the set of unexpanded parameter packs can and should
  2373. // be expanded.
  2374. bool Expand = true;
  2375. bool RetainExpansion = false;
  2376. Optional<unsigned> NumExpansions;
  2377. if (SemaRef.CheckParameterPacksForExpansion(
  2378. D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
  2379. Expand, RetainExpansion, NumExpansions))
  2380. return nullptr;
  2381. // This declaration cannot appear within a function template signature,
  2382. // so we can't have a partial argument list for a parameter pack.
  2383. assert(!RetainExpansion &&
  2384. "should never need to retain an expansion for UsingPackDecl");
  2385. if (!Expand) {
  2386. // We cannot fully expand the pack expansion now, so substitute into the
  2387. // pattern and create a new pack expansion.
  2388. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2389. return instantiateUnresolvedUsingDecl(D, true);
  2390. }
  2391. // Within a function, we don't have any normal way to check for conflicts
  2392. // between shadow declarations from different using declarations in the
  2393. // same pack expansion, but this is always ill-formed because all expansions
  2394. // must produce (conflicting) enumerators.
  2395. //
  2396. // Sadly we can't just reject this in the template definition because it
  2397. // could be valid if the pack is empty or has exactly one expansion.
  2398. if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
  2399. SemaRef.Diag(D->getEllipsisLoc(),
  2400. diag::err_using_decl_redeclaration_expansion);
  2401. return nullptr;
  2402. }
  2403. // Instantiate the slices of this pack and build a UsingPackDecl.
  2404. SmallVector<NamedDecl*, 8> Expansions;
  2405. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2406. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2407. Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
  2408. if (!Slice)
  2409. return nullptr;
  2410. // Note that we can still get unresolved using declarations here, if we
  2411. // had arguments for all packs but the pattern also contained other
  2412. // template arguments (this only happens during partial substitution, eg
  2413. // into the body of a generic lambda in a function template).
  2414. Expansions.push_back(cast<NamedDecl>(Slice));
  2415. }
  2416. auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
  2417. if (isDeclWithinFunction(D))
  2418. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
  2419. return NewD;
  2420. }
  2421. UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
  2422. SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
  2423. NestedNameSpecifierLoc QualifierLoc
  2424. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2425. TemplateArgs);
  2426. if (!QualifierLoc)
  2427. return nullptr;
  2428. CXXScopeSpec SS;
  2429. SS.Adopt(QualifierLoc);
  2430. DeclarationNameInfo NameInfo
  2431. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  2432. // Produce a pack expansion only if we're not instantiating a particular
  2433. // slice of a pack expansion.
  2434. bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
  2435. SemaRef.ArgumentPackSubstitutionIndex != -1;
  2436. SourceLocation EllipsisLoc =
  2437. InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
  2438. NamedDecl *UD = SemaRef.BuildUsingDeclaration(
  2439. /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
  2440. /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
  2441. ParsedAttributesView(),
  2442. /*IsInstantiation*/ true);
  2443. if (UD)
  2444. SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
  2445. return UD;
  2446. }
  2447. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
  2448. UnresolvedUsingTypenameDecl *D) {
  2449. return instantiateUnresolvedUsingDecl(D);
  2450. }
  2451. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
  2452. UnresolvedUsingValueDecl *D) {
  2453. return instantiateUnresolvedUsingDecl(D);
  2454. }
  2455. Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
  2456. SmallVector<NamedDecl*, 8> Expansions;
  2457. for (auto *UD : D->expansions()) {
  2458. if (NamedDecl *NewUD =
  2459. SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
  2460. Expansions.push_back(NewUD);
  2461. else
  2462. return nullptr;
  2463. }
  2464. auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
  2465. if (isDeclWithinFunction(D))
  2466. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
  2467. return NewD;
  2468. }
  2469. Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
  2470. ClassScopeFunctionSpecializationDecl *Decl) {
  2471. CXXMethodDecl *OldFD = Decl->getSpecialization();
  2472. return cast_or_null<CXXMethodDecl>(
  2473. VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
  2474. }
  2475. Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
  2476. OMPThreadPrivateDecl *D) {
  2477. SmallVector<Expr *, 5> Vars;
  2478. for (auto *I : D->varlists()) {
  2479. Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
  2480. assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
  2481. Vars.push_back(Var);
  2482. }
  2483. OMPThreadPrivateDecl *TD =
  2484. SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
  2485. TD->setAccess(AS_public);
  2486. Owner->addDecl(TD);
  2487. return TD;
  2488. }
  2489. Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
  2490. SmallVector<Expr *, 5> Vars;
  2491. for (auto *I : D->varlists()) {
  2492. Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
  2493. assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
  2494. Vars.push_back(Var);
  2495. }
  2496. SmallVector<OMPClause *, 4> Clauses;
  2497. // Copy map clauses from the original mapper.
  2498. for (OMPClause *C : D->clauselists()) {
  2499. auto *AC = cast<OMPAllocatorClause>(C);
  2500. ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
  2501. if (!NewE.isUsable())
  2502. continue;
  2503. OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
  2504. NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
  2505. Clauses.push_back(IC);
  2506. }
  2507. Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
  2508. D->getLocation(), Vars, Clauses, Owner);
  2509. if (Res.get().isNull())
  2510. return nullptr;
  2511. return Res.get().getSingleDecl();
  2512. }
  2513. Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
  2514. llvm_unreachable(
  2515. "Requires directive cannot be instantiated within a dependent context");
  2516. }
  2517. Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
  2518. OMPDeclareReductionDecl *D) {
  2519. // Instantiate type and check if it is allowed.
  2520. const bool RequiresInstantiation =
  2521. D->getType()->isDependentType() ||
  2522. D->getType()->isInstantiationDependentType() ||
  2523. D->getType()->containsUnexpandedParameterPack();
  2524. QualType SubstReductionType;
  2525. if (RequiresInstantiation) {
  2526. SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
  2527. D->getLocation(),
  2528. ParsedType::make(SemaRef.SubstType(
  2529. D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
  2530. } else {
  2531. SubstReductionType = D->getType();
  2532. }
  2533. if (SubstReductionType.isNull())
  2534. return nullptr;
  2535. bool IsCorrect = !SubstReductionType.isNull();
  2536. // Create instantiated copy.
  2537. std::pair<QualType, SourceLocation> ReductionTypes[] = {
  2538. std::make_pair(SubstReductionType, D->getLocation())};
  2539. auto *PrevDeclInScope = D->getPrevDeclInScope();
  2540. if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
  2541. PrevDeclInScope = cast<OMPDeclareReductionDecl>(
  2542. SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
  2543. ->get<Decl *>());
  2544. }
  2545. auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
  2546. /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
  2547. PrevDeclInScope);
  2548. auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
  2549. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
  2550. if (!RequiresInstantiation) {
  2551. if (Expr *Combiner = D->getCombiner()) {
  2552. NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
  2553. NewDRD->setCombiner(Combiner);
  2554. if (Expr *Init = D->getInitializer()) {
  2555. NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
  2556. NewDRD->setInitializer(Init, D->getInitializerKind());
  2557. }
  2558. }
  2559. (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
  2560. /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
  2561. return NewDRD;
  2562. }
  2563. Expr *SubstCombiner = nullptr;
  2564. Expr *SubstInitializer = nullptr;
  2565. // Combiners instantiation sequence.
  2566. if (D->getCombiner()) {
  2567. SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
  2568. /*S=*/nullptr, NewDRD);
  2569. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2570. cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
  2571. cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
  2572. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2573. cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
  2574. cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
  2575. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
  2576. Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
  2577. ThisContext);
  2578. SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
  2579. SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
  2580. // Initializers instantiation sequence.
  2581. if (D->getInitializer()) {
  2582. VarDecl *OmpPrivParm =
  2583. SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
  2584. /*S=*/nullptr, NewDRD);
  2585. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2586. cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
  2587. cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
  2588. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2589. cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
  2590. cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
  2591. if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
  2592. SubstInitializer =
  2593. SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
  2594. } else {
  2595. IsCorrect = IsCorrect && OmpPrivParm->hasInit();
  2596. }
  2597. SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
  2598. NewDRD, SubstInitializer, OmpPrivParm);
  2599. }
  2600. IsCorrect =
  2601. IsCorrect && SubstCombiner &&
  2602. (!D->getInitializer() ||
  2603. (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
  2604. SubstInitializer) ||
  2605. (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
  2606. !SubstInitializer && !SubstInitializer));
  2607. } else {
  2608. IsCorrect = false;
  2609. }
  2610. (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
  2611. IsCorrect);
  2612. return NewDRD;
  2613. }
  2614. Decl *
  2615. TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
  2616. // Instantiate type and check if it is allowed.
  2617. const bool RequiresInstantiation =
  2618. D->getType()->isDependentType() ||
  2619. D->getType()->isInstantiationDependentType() ||
  2620. D->getType()->containsUnexpandedParameterPack();
  2621. QualType SubstMapperTy;
  2622. DeclarationName VN = D->getVarName();
  2623. if (RequiresInstantiation) {
  2624. SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
  2625. D->getLocation(),
  2626. ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
  2627. D->getLocation(), VN)));
  2628. } else {
  2629. SubstMapperTy = D->getType();
  2630. }
  2631. if (SubstMapperTy.isNull())
  2632. return nullptr;
  2633. // Create an instantiated copy of mapper.
  2634. auto *PrevDeclInScope = D->getPrevDeclInScope();
  2635. if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
  2636. PrevDeclInScope = cast<OMPDeclareMapperDecl>(
  2637. SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
  2638. ->get<Decl *>());
  2639. }
  2640. OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
  2641. /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
  2642. VN, D->getAccess(), PrevDeclInScope);
  2643. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
  2644. SmallVector<OMPClause *, 6> Clauses;
  2645. bool IsCorrect = true;
  2646. if (!RequiresInstantiation) {
  2647. // Copy the mapper variable.
  2648. NewDMD->setMapperVarRef(D->getMapperVarRef());
  2649. // Copy map clauses from the original mapper.
  2650. for (OMPClause *C : D->clauselists())
  2651. Clauses.push_back(C);
  2652. } else {
  2653. // Instantiate the mapper variable.
  2654. DeclarationNameInfo DirName;
  2655. SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
  2656. (*D->clauselist_begin())->getBeginLoc());
  2657. SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
  2658. NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
  2659. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2660. cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
  2661. cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
  2662. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
  2663. Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
  2664. ThisContext);
  2665. // Instantiate map clauses.
  2666. for (OMPClause *C : D->clauselists()) {
  2667. auto *OldC = cast<OMPMapClause>(C);
  2668. SmallVector<Expr *, 4> NewVars;
  2669. for (Expr *OE : OldC->varlists()) {
  2670. Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
  2671. if (!NE) {
  2672. IsCorrect = false;
  2673. break;
  2674. }
  2675. NewVars.push_back(NE);
  2676. }
  2677. if (!IsCorrect)
  2678. break;
  2679. NestedNameSpecifierLoc NewQualifierLoc =
  2680. SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
  2681. TemplateArgs);
  2682. CXXScopeSpec SS;
  2683. SS.Adopt(NewQualifierLoc);
  2684. DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
  2685. OldC->getMapperIdInfo(), TemplateArgs);
  2686. OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
  2687. OldC->getEndLoc());
  2688. OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
  2689. OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
  2690. NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
  2691. OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
  2692. Clauses.push_back(NewC);
  2693. }
  2694. SemaRef.EndOpenMPDSABlock(nullptr);
  2695. }
  2696. (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
  2697. Clauses);
  2698. if (!IsCorrect)
  2699. return nullptr;
  2700. return NewDMD;
  2701. }
  2702. Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
  2703. OMPCapturedExprDecl * /*D*/) {
  2704. llvm_unreachable("Should not be met in templates");
  2705. }
  2706. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
  2707. return VisitFunctionDecl(D, nullptr);
  2708. }
  2709. Decl *
  2710. TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
  2711. Decl *Inst = VisitFunctionDecl(D, nullptr);
  2712. if (Inst && !D->getDescribedFunctionTemplate())
  2713. Owner->addDecl(Inst);
  2714. return Inst;
  2715. }
  2716. Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
  2717. return VisitCXXMethodDecl(D, nullptr);
  2718. }
  2719. Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
  2720. llvm_unreachable("There are only CXXRecordDecls in C++");
  2721. }
  2722. Decl *
  2723. TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
  2724. ClassTemplateSpecializationDecl *D) {
  2725. // As a MS extension, we permit class-scope explicit specialization
  2726. // of member class templates.
  2727. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  2728. assert(ClassTemplate->getDeclContext()->isRecord() &&
  2729. D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  2730. "can only instantiate an explicit specialization "
  2731. "for a member class template");
  2732. // Lookup the already-instantiated declaration in the instantiation
  2733. // of the class template.
  2734. ClassTemplateDecl *InstClassTemplate =
  2735. cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
  2736. D->getLocation(), ClassTemplate, TemplateArgs));
  2737. if (!InstClassTemplate)
  2738. return nullptr;
  2739. // Substitute into the template arguments of the class template explicit
  2740. // specialization.
  2741. TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
  2742. castAs<TemplateSpecializationTypeLoc>();
  2743. TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
  2744. Loc.getRAngleLoc());
  2745. SmallVector<TemplateArgumentLoc, 4> ArgLocs;
  2746. for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
  2747. ArgLocs.push_back(Loc.getArgLoc(I));
  2748. if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
  2749. InstTemplateArgs, TemplateArgs))
  2750. return nullptr;
  2751. // Check that the template argument list is well-formed for this
  2752. // class template.
  2753. SmallVector<TemplateArgument, 4> Converted;
  2754. if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
  2755. D->getLocation(),
  2756. InstTemplateArgs,
  2757. false,
  2758. Converted))
  2759. return nullptr;
  2760. // Figure out where to insert this class template explicit specialization
  2761. // in the member template's set of class template explicit specializations.
  2762. void *InsertPos = nullptr;
  2763. ClassTemplateSpecializationDecl *PrevDecl =
  2764. InstClassTemplate->findSpecialization(Converted, InsertPos);
  2765. // Check whether we've already seen a conflicting instantiation of this
  2766. // declaration (for instance, if there was a prior implicit instantiation).
  2767. bool Ignored;
  2768. if (PrevDecl &&
  2769. SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
  2770. D->getSpecializationKind(),
  2771. PrevDecl,
  2772. PrevDecl->getSpecializationKind(),
  2773. PrevDecl->getPointOfInstantiation(),
  2774. Ignored))
  2775. return nullptr;
  2776. // If PrevDecl was a definition and D is also a definition, diagnose.
  2777. // This happens in cases like:
  2778. //
  2779. // template<typename T, typename U>
  2780. // struct Outer {
  2781. // template<typename X> struct Inner;
  2782. // template<> struct Inner<T> {};
  2783. // template<> struct Inner<U> {};
  2784. // };
  2785. //
  2786. // Outer<int, int> outer; // error: the explicit specializations of Inner
  2787. // // have the same signature.
  2788. if (PrevDecl && PrevDecl->getDefinition() &&
  2789. D->isThisDeclarationADefinition()) {
  2790. SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
  2791. SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
  2792. diag::note_previous_definition);
  2793. return nullptr;
  2794. }
  2795. // Create the class template partial specialization declaration.
  2796. ClassTemplateSpecializationDecl *InstD =
  2797. ClassTemplateSpecializationDecl::Create(
  2798. SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
  2799. D->getLocation(), InstClassTemplate, Converted, PrevDecl);
  2800. // Add this partial specialization to the set of class template partial
  2801. // specializations.
  2802. if (!PrevDecl)
  2803. InstClassTemplate->AddSpecialization(InstD, InsertPos);
  2804. // Substitute the nested name specifier, if any.
  2805. if (SubstQualifier(D, InstD))
  2806. return nullptr;
  2807. // Build the canonical type that describes the converted template
  2808. // arguments of the class template explicit specialization.
  2809. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  2810. TemplateName(InstClassTemplate), Converted,
  2811. SemaRef.Context.getRecordType(InstD));
  2812. // Build the fully-sugared type for this class template
  2813. // specialization as the user wrote in the specialization
  2814. // itself. This means that we'll pretty-print the type retrieved
  2815. // from the specialization's declaration the way that the user
  2816. // actually wrote the specialization, rather than formatting the
  2817. // name based on the "canonical" representation used to store the
  2818. // template arguments in the specialization.
  2819. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2820. TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
  2821. CanonType);
  2822. InstD->setAccess(D->getAccess());
  2823. InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  2824. InstD->setSpecializationKind(D->getSpecializationKind());
  2825. InstD->setTypeAsWritten(WrittenTy);
  2826. InstD->setExternLoc(D->getExternLoc());
  2827. InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
  2828. Owner->addDecl(InstD);
  2829. // Instantiate the members of the class-scope explicit specialization eagerly.
  2830. // We don't have support for lazy instantiation of an explicit specialization
  2831. // yet, and MSVC eagerly instantiates in this case.
  2832. // FIXME: This is wrong in standard C++.
  2833. if (D->isThisDeclarationADefinition() &&
  2834. SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
  2835. TSK_ImplicitInstantiation,
  2836. /*Complain=*/true))
  2837. return nullptr;
  2838. return InstD;
  2839. }
  2840. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  2841. VarTemplateSpecializationDecl *D) {
  2842. TemplateArgumentListInfo VarTemplateArgsInfo;
  2843. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  2844. assert(VarTemplate &&
  2845. "A template specialization without specialized template?");
  2846. VarTemplateDecl *InstVarTemplate =
  2847. cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
  2848. D->getLocation(), VarTemplate, TemplateArgs));
  2849. if (!InstVarTemplate)
  2850. return nullptr;
  2851. // Substitute the current template arguments.
  2852. const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
  2853. VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
  2854. VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
  2855. if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
  2856. TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
  2857. return nullptr;
  2858. // Check that the template argument list is well-formed for this template.
  2859. SmallVector<TemplateArgument, 4> Converted;
  2860. if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
  2861. VarTemplateArgsInfo, false, Converted))
  2862. return nullptr;
  2863. // Check whether we've already seen a declaration of this specialization.
  2864. void *InsertPos = nullptr;
  2865. VarTemplateSpecializationDecl *PrevDecl =
  2866. InstVarTemplate->findSpecialization(Converted, InsertPos);
  2867. // Check whether we've already seen a conflicting instantiation of this
  2868. // declaration (for instance, if there was a prior implicit instantiation).
  2869. bool Ignored;
  2870. if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
  2871. D->getLocation(), D->getSpecializationKind(), PrevDecl,
  2872. PrevDecl->getSpecializationKind(),
  2873. PrevDecl->getPointOfInstantiation(), Ignored))
  2874. return nullptr;
  2875. return VisitVarTemplateSpecializationDecl(
  2876. InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
  2877. }
  2878. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  2879. VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
  2880. const TemplateArgumentListInfo &TemplateArgsInfo,
  2881. ArrayRef<TemplateArgument> Converted,
  2882. VarTemplateSpecializationDecl *PrevDecl) {
  2883. // Do substitution on the type of the declaration
  2884. TypeSourceInfo *DI =
  2885. SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  2886. D->getTypeSpecStartLoc(), D->getDeclName());
  2887. if (!DI)
  2888. return nullptr;
  2889. if (DI->getType()->isFunctionType()) {
  2890. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  2891. << D->isStaticDataMember() << DI->getType();
  2892. return nullptr;
  2893. }
  2894. // Build the instantiated declaration
  2895. VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
  2896. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2897. VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
  2898. Var->setTemplateArgsInfo(TemplateArgsInfo);
  2899. if (InsertPos)
  2900. VarTemplate->AddSpecialization(Var, InsertPos);
  2901. // Substitute the nested name specifier, if any.
  2902. if (SubstQualifier(D, Var))
  2903. return nullptr;
  2904. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  2905. StartingScope, false, PrevDecl);
  2906. return Var;
  2907. }
  2908. Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
  2909. llvm_unreachable("@defs is not supported in Objective-C++");
  2910. }
  2911. Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
  2912. // FIXME: We need to be able to instantiate FriendTemplateDecls.
  2913. unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
  2914. DiagnosticsEngine::Error,
  2915. "cannot instantiate %0 yet");
  2916. SemaRef.Diag(D->getLocation(), DiagID)
  2917. << D->getDeclKindName();
  2918. return nullptr;
  2919. }
  2920. Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
  2921. llvm_unreachable("Concept definitions cannot reside inside a template");
  2922. }
  2923. Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
  2924. llvm_unreachable("Unexpected decl");
  2925. }
  2926. Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
  2927. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2928. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  2929. if (D->isInvalidDecl())
  2930. return nullptr;
  2931. Decl *SubstD;
  2932. runWithSufficientStackSpace(D->getLocation(), [&] {
  2933. SubstD = Instantiator.Visit(D);
  2934. });
  2935. return SubstD;
  2936. }
  2937. /// Instantiates a nested template parameter list in the current
  2938. /// instantiation context.
  2939. ///
  2940. /// \param L The parameter list to instantiate
  2941. ///
  2942. /// \returns NULL if there was an error
  2943. TemplateParameterList *
  2944. TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
  2945. // Get errors for all the parameters before bailing out.
  2946. bool Invalid = false;
  2947. unsigned N = L->size();
  2948. typedef SmallVector<NamedDecl *, 8> ParamVector;
  2949. ParamVector Params;
  2950. Params.reserve(N);
  2951. for (auto &P : *L) {
  2952. NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
  2953. Params.push_back(D);
  2954. Invalid = Invalid || !D || D->isInvalidDecl();
  2955. }
  2956. // Clean up if we had an error.
  2957. if (Invalid)
  2958. return nullptr;
  2959. // Note: we substitute into associated constraints later
  2960. Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
  2961. TemplateParameterList *InstL
  2962. = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
  2963. L->getLAngleLoc(), Params,
  2964. L->getRAngleLoc(),
  2965. UninstantiatedRequiresClause);
  2966. return InstL;
  2967. }
  2968. TemplateParameterList *
  2969. Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
  2970. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2971. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  2972. return Instantiator.SubstTemplateParams(Params);
  2973. }
  2974. /// Instantiate the declaration of a class template partial
  2975. /// specialization.
  2976. ///
  2977. /// \param ClassTemplate the (instantiated) class template that is partially
  2978. // specialized by the instantiation of \p PartialSpec.
  2979. ///
  2980. /// \param PartialSpec the (uninstantiated) class template partial
  2981. /// specialization that we are instantiating.
  2982. ///
  2983. /// \returns The instantiated partial specialization, if successful; otherwise,
  2984. /// NULL to indicate an error.
  2985. ClassTemplatePartialSpecializationDecl *
  2986. TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
  2987. ClassTemplateDecl *ClassTemplate,
  2988. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  2989. // Create a local instantiation scope for this class template partial
  2990. // specialization, which will contain the instantiations of the template
  2991. // parameters.
  2992. LocalInstantiationScope Scope(SemaRef);
  2993. // Substitute into the template parameters of the class template partial
  2994. // specialization.
  2995. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  2996. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  2997. if (!InstParams)
  2998. return nullptr;
  2999. // Substitute into the template arguments of the class template partial
  3000. // specialization.
  3001. const ASTTemplateArgumentListInfo *TemplArgInfo
  3002. = PartialSpec->getTemplateArgsAsWritten();
  3003. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  3004. TemplArgInfo->RAngleLoc);
  3005. if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
  3006. TemplArgInfo->NumTemplateArgs,
  3007. InstTemplateArgs, TemplateArgs))
  3008. return nullptr;
  3009. // Check that the template argument list is well-formed for this
  3010. // class template.
  3011. SmallVector<TemplateArgument, 4> Converted;
  3012. if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
  3013. PartialSpec->getLocation(),
  3014. InstTemplateArgs,
  3015. false,
  3016. Converted))
  3017. return nullptr;
  3018. // Check these arguments are valid for a template partial specialization.
  3019. if (SemaRef.CheckTemplatePartialSpecializationArgs(
  3020. PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
  3021. Converted))
  3022. return nullptr;
  3023. // Figure out where to insert this class template partial specialization
  3024. // in the member template's set of class template partial specializations.
  3025. void *InsertPos = nullptr;
  3026. ClassTemplateSpecializationDecl *PrevDecl
  3027. = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
  3028. // Build the canonical type that describes the converted template
  3029. // arguments of the class template partial specialization.
  3030. QualType CanonType
  3031. = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
  3032. Converted);
  3033. // Build the fully-sugared type for this class template
  3034. // specialization as the user wrote in the specialization
  3035. // itself. This means that we'll pretty-print the type retrieved
  3036. // from the specialization's declaration the way that the user
  3037. // actually wrote the specialization, rather than formatting the
  3038. // name based on the "canonical" representation used to store the
  3039. // template arguments in the specialization.
  3040. TypeSourceInfo *WrittenTy
  3041. = SemaRef.Context.getTemplateSpecializationTypeInfo(
  3042. TemplateName(ClassTemplate),
  3043. PartialSpec->getLocation(),
  3044. InstTemplateArgs,
  3045. CanonType);
  3046. if (PrevDecl) {
  3047. // We've already seen a partial specialization with the same template
  3048. // parameters and template arguments. This can happen, for example, when
  3049. // substituting the outer template arguments ends up causing two
  3050. // class template partial specializations of a member class template
  3051. // to have identical forms, e.g.,
  3052. //
  3053. // template<typename T, typename U>
  3054. // struct Outer {
  3055. // template<typename X, typename Y> struct Inner;
  3056. // template<typename Y> struct Inner<T, Y>;
  3057. // template<typename Y> struct Inner<U, Y>;
  3058. // };
  3059. //
  3060. // Outer<int, int> outer; // error: the partial specializations of Inner
  3061. // // have the same signature.
  3062. SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
  3063. << WrittenTy->getType();
  3064. SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
  3065. << SemaRef.Context.getTypeDeclType(PrevDecl);
  3066. return nullptr;
  3067. }
  3068. // Create the class template partial specialization declaration.
  3069. ClassTemplatePartialSpecializationDecl *InstPartialSpec =
  3070. ClassTemplatePartialSpecializationDecl::Create(
  3071. SemaRef.Context, PartialSpec->getTagKind(), Owner,
  3072. PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
  3073. ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
  3074. // Substitute the nested name specifier, if any.
  3075. if (SubstQualifier(PartialSpec, InstPartialSpec))
  3076. return nullptr;
  3077. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  3078. InstPartialSpec->setTypeAsWritten(WrittenTy);
  3079. // Check the completed partial specialization.
  3080. SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
  3081. // Add this partial specialization to the set of class template partial
  3082. // specializations.
  3083. ClassTemplate->AddPartialSpecialization(InstPartialSpec,
  3084. /*InsertPos=*/nullptr);
  3085. return InstPartialSpec;
  3086. }
  3087. /// Instantiate the declaration of a variable template partial
  3088. /// specialization.
  3089. ///
  3090. /// \param VarTemplate the (instantiated) variable template that is partially
  3091. /// specialized by the instantiation of \p PartialSpec.
  3092. ///
  3093. /// \param PartialSpec the (uninstantiated) variable template partial
  3094. /// specialization that we are instantiating.
  3095. ///
  3096. /// \returns The instantiated partial specialization, if successful; otherwise,
  3097. /// NULL to indicate an error.
  3098. VarTemplatePartialSpecializationDecl *
  3099. TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
  3100. VarTemplateDecl *VarTemplate,
  3101. VarTemplatePartialSpecializationDecl *PartialSpec) {
  3102. // Create a local instantiation scope for this variable template partial
  3103. // specialization, which will contain the instantiations of the template
  3104. // parameters.
  3105. LocalInstantiationScope Scope(SemaRef);
  3106. // Substitute into the template parameters of the variable template partial
  3107. // specialization.
  3108. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  3109. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  3110. if (!InstParams)
  3111. return nullptr;
  3112. // Substitute into the template arguments of the variable template partial
  3113. // specialization.
  3114. const ASTTemplateArgumentListInfo *TemplArgInfo
  3115. = PartialSpec->getTemplateArgsAsWritten();
  3116. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  3117. TemplArgInfo->RAngleLoc);
  3118. if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
  3119. TemplArgInfo->NumTemplateArgs,
  3120. InstTemplateArgs, TemplateArgs))
  3121. return nullptr;
  3122. // Check that the template argument list is well-formed for this
  3123. // class template.
  3124. SmallVector<TemplateArgument, 4> Converted;
  3125. if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
  3126. InstTemplateArgs, false, Converted))
  3127. return nullptr;
  3128. // Check these arguments are valid for a template partial specialization.
  3129. if (SemaRef.CheckTemplatePartialSpecializationArgs(
  3130. PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
  3131. Converted))
  3132. return nullptr;
  3133. // Figure out where to insert this variable template partial specialization
  3134. // in the member template's set of variable template partial specializations.
  3135. void *InsertPos = nullptr;
  3136. VarTemplateSpecializationDecl *PrevDecl =
  3137. VarTemplate->findPartialSpecialization(Converted, InsertPos);
  3138. // Build the canonical type that describes the converted template
  3139. // arguments of the variable template partial specialization.
  3140. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  3141. TemplateName(VarTemplate), Converted);
  3142. // Build the fully-sugared type for this variable template
  3143. // specialization as the user wrote in the specialization
  3144. // itself. This means that we'll pretty-print the type retrieved
  3145. // from the specialization's declaration the way that the user
  3146. // actually wrote the specialization, rather than formatting the
  3147. // name based on the "canonical" representation used to store the
  3148. // template arguments in the specialization.
  3149. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  3150. TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
  3151. CanonType);
  3152. if (PrevDecl) {
  3153. // We've already seen a partial specialization with the same template
  3154. // parameters and template arguments. This can happen, for example, when
  3155. // substituting the outer template arguments ends up causing two
  3156. // variable template partial specializations of a member variable template
  3157. // to have identical forms, e.g.,
  3158. //
  3159. // template<typename T, typename U>
  3160. // struct Outer {
  3161. // template<typename X, typename Y> pair<X,Y> p;
  3162. // template<typename Y> pair<T, Y> p;
  3163. // template<typename Y> pair<U, Y> p;
  3164. // };
  3165. //
  3166. // Outer<int, int> outer; // error: the partial specializations of Inner
  3167. // // have the same signature.
  3168. SemaRef.Diag(PartialSpec->getLocation(),
  3169. diag::err_var_partial_spec_redeclared)
  3170. << WrittenTy->getType();
  3171. SemaRef.Diag(PrevDecl->getLocation(),
  3172. diag::note_var_prev_partial_spec_here);
  3173. return nullptr;
  3174. }
  3175. // Do substitution on the type of the declaration
  3176. TypeSourceInfo *DI = SemaRef.SubstType(
  3177. PartialSpec->getTypeSourceInfo(), TemplateArgs,
  3178. PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
  3179. if (!DI)
  3180. return nullptr;
  3181. if (DI->getType()->isFunctionType()) {
  3182. SemaRef.Diag(PartialSpec->getLocation(),
  3183. diag::err_variable_instantiates_to_function)
  3184. << PartialSpec->isStaticDataMember() << DI->getType();
  3185. return nullptr;
  3186. }
  3187. // Create the variable template partial specialization declaration.
  3188. VarTemplatePartialSpecializationDecl *InstPartialSpec =
  3189. VarTemplatePartialSpecializationDecl::Create(
  3190. SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
  3191. PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
  3192. DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
  3193. // Substitute the nested name specifier, if any.
  3194. if (SubstQualifier(PartialSpec, InstPartialSpec))
  3195. return nullptr;
  3196. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  3197. InstPartialSpec->setTypeAsWritten(WrittenTy);
  3198. // Check the completed partial specialization.
  3199. SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
  3200. // Add this partial specialization to the set of variable template partial
  3201. // specializations. The instantiation of the initializer is not necessary.
  3202. VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
  3203. SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
  3204. LateAttrs, Owner, StartingScope);
  3205. return InstPartialSpec;
  3206. }
  3207. TypeSourceInfo*
  3208. TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
  3209. SmallVectorImpl<ParmVarDecl *> &Params) {
  3210. TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
  3211. assert(OldTInfo && "substituting function without type source info");
  3212. assert(Params.empty() && "parameter vector is non-empty at start");
  3213. CXXRecordDecl *ThisContext = nullptr;
  3214. Qualifiers ThisTypeQuals;
  3215. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  3216. ThisContext = cast<CXXRecordDecl>(Owner);
  3217. ThisTypeQuals = Method->getMethodQualifiers();
  3218. }
  3219. TypeSourceInfo *NewTInfo
  3220. = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
  3221. D->getTypeSpecStartLoc(),
  3222. D->getDeclName(),
  3223. ThisContext, ThisTypeQuals);
  3224. if (!NewTInfo)
  3225. return nullptr;
  3226. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  3227. if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
  3228. if (NewTInfo != OldTInfo) {
  3229. // Get parameters from the new type info.
  3230. TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
  3231. FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
  3232. unsigned NewIdx = 0;
  3233. for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
  3234. OldIdx != NumOldParams; ++OldIdx) {
  3235. ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
  3236. LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
  3237. Optional<unsigned> NumArgumentsInExpansion;
  3238. if (OldParam->isParameterPack())
  3239. NumArgumentsInExpansion =
  3240. SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
  3241. TemplateArgs);
  3242. if (!NumArgumentsInExpansion) {
  3243. // Simple case: normal parameter, or a parameter pack that's
  3244. // instantiated to a (still-dependent) parameter pack.
  3245. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  3246. Params.push_back(NewParam);
  3247. Scope->InstantiatedLocal(OldParam, NewParam);
  3248. } else {
  3249. // Parameter pack expansion: make the instantiation an argument pack.
  3250. Scope->MakeInstantiatedLocalArgPack(OldParam);
  3251. for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
  3252. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  3253. Params.push_back(NewParam);
  3254. Scope->InstantiatedLocalPackArg(OldParam, NewParam);
  3255. }
  3256. }
  3257. }
  3258. } else {
  3259. // The function type itself was not dependent and therefore no
  3260. // substitution occurred. However, we still need to instantiate
  3261. // the function parameters themselves.
  3262. const FunctionProtoType *OldProto =
  3263. cast<FunctionProtoType>(OldProtoLoc.getType());
  3264. for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
  3265. ++i) {
  3266. ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
  3267. if (!OldParam) {
  3268. Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
  3269. D, D->getLocation(), OldProto->getParamType(i)));
  3270. continue;
  3271. }
  3272. ParmVarDecl *Parm =
  3273. cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
  3274. if (!Parm)
  3275. return nullptr;
  3276. Params.push_back(Parm);
  3277. }
  3278. }
  3279. } else {
  3280. // If the type of this function, after ignoring parentheses, is not
  3281. // *directly* a function type, then we're instantiating a function that
  3282. // was declared via a typedef or with attributes, e.g.,
  3283. //
  3284. // typedef int functype(int, int);
  3285. // functype func;
  3286. // int __cdecl meth(int, int);
  3287. //
  3288. // In this case, we'll just go instantiate the ParmVarDecls that we
  3289. // synthesized in the method declaration.
  3290. SmallVector<QualType, 4> ParamTypes;
  3291. Sema::ExtParameterInfoBuilder ExtParamInfos;
  3292. if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
  3293. TemplateArgs, ParamTypes, &Params,
  3294. ExtParamInfos))
  3295. return nullptr;
  3296. }
  3297. return NewTInfo;
  3298. }
  3299. /// Introduce the instantiated function parameters into the local
  3300. /// instantiation scope, and set the parameter names to those used
  3301. /// in the template.
  3302. static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
  3303. const FunctionDecl *PatternDecl,
  3304. LocalInstantiationScope &Scope,
  3305. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3306. unsigned FParamIdx = 0;
  3307. for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
  3308. const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
  3309. if (!PatternParam->isParameterPack()) {
  3310. // Simple case: not a parameter pack.
  3311. assert(FParamIdx < Function->getNumParams());
  3312. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  3313. FunctionParam->setDeclName(PatternParam->getDeclName());
  3314. // If the parameter's type is not dependent, update it to match the type
  3315. // in the pattern. They can differ in top-level cv-qualifiers, and we want
  3316. // the pattern's type here. If the type is dependent, they can't differ,
  3317. // per core issue 1668. Substitute into the type from the pattern, in case
  3318. // it's instantiation-dependent.
  3319. // FIXME: Updating the type to work around this is at best fragile.
  3320. if (!PatternDecl->getType()->isDependentType()) {
  3321. QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
  3322. FunctionParam->getLocation(),
  3323. FunctionParam->getDeclName());
  3324. if (T.isNull())
  3325. return true;
  3326. FunctionParam->setType(T);
  3327. }
  3328. Scope.InstantiatedLocal(PatternParam, FunctionParam);
  3329. ++FParamIdx;
  3330. continue;
  3331. }
  3332. // Expand the parameter pack.
  3333. Scope.MakeInstantiatedLocalArgPack(PatternParam);
  3334. Optional<unsigned> NumArgumentsInExpansion
  3335. = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
  3336. if (NumArgumentsInExpansion) {
  3337. QualType PatternType =
  3338. PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
  3339. for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
  3340. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  3341. FunctionParam->setDeclName(PatternParam->getDeclName());
  3342. if (!PatternDecl->getType()->isDependentType()) {
  3343. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
  3344. QualType T = S.SubstType(PatternType, TemplateArgs,
  3345. FunctionParam->getLocation(),
  3346. FunctionParam->getDeclName());
  3347. if (T.isNull())
  3348. return true;
  3349. FunctionParam->setType(T);
  3350. }
  3351. Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
  3352. ++FParamIdx;
  3353. }
  3354. }
  3355. }
  3356. return false;
  3357. }
  3358. void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
  3359. FunctionDecl *Decl) {
  3360. const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
  3361. if (Proto->getExceptionSpecType() != EST_Uninstantiated)
  3362. return;
  3363. InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
  3364. InstantiatingTemplate::ExceptionSpecification());
  3365. if (Inst.isInvalid()) {
  3366. // We hit the instantiation depth limit. Clear the exception specification
  3367. // so that our callers don't have to cope with EST_Uninstantiated.
  3368. UpdateExceptionSpec(Decl, EST_None);
  3369. return;
  3370. }
  3371. if (Inst.isAlreadyInstantiating()) {
  3372. // This exception specification indirectly depends on itself. Reject.
  3373. // FIXME: Corresponding rule in the standard?
  3374. Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
  3375. UpdateExceptionSpec(Decl, EST_None);
  3376. return;
  3377. }
  3378. // Enter the scope of this instantiation. We don't use
  3379. // PushDeclContext because we don't have a scope.
  3380. Sema::ContextRAII savedContext(*this, Decl);
  3381. LocalInstantiationScope Scope(*this);
  3382. MultiLevelTemplateArgumentList TemplateArgs =
  3383. getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
  3384. FunctionDecl *Template = Proto->getExceptionSpecTemplate();
  3385. if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
  3386. TemplateArgs)) {
  3387. UpdateExceptionSpec(Decl, EST_None);
  3388. return;
  3389. }
  3390. SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
  3391. TemplateArgs);
  3392. }
  3393. /// Initializes the common fields of an instantiation function
  3394. /// declaration (New) from the corresponding fields of its template (Tmpl).
  3395. ///
  3396. /// \returns true if there was an error
  3397. bool
  3398. TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
  3399. FunctionDecl *Tmpl) {
  3400. if (Tmpl->isDeleted())
  3401. New->setDeletedAsWritten();
  3402. New->setImplicit(Tmpl->isImplicit());
  3403. // Forward the mangling number from the template to the instantiated decl.
  3404. SemaRef.Context.setManglingNumber(New,
  3405. SemaRef.Context.getManglingNumber(Tmpl));
  3406. // If we are performing substituting explicitly-specified template arguments
  3407. // or deduced template arguments into a function template and we reach this
  3408. // point, we are now past the point where SFINAE applies and have committed
  3409. // to keeping the new function template specialization. We therefore
  3410. // convert the active template instantiation for the function template
  3411. // into a template instantiation for this specific function template
  3412. // specialization, which is not a SFINAE context, so that we diagnose any
  3413. // further errors in the declaration itself.
  3414. typedef Sema::CodeSynthesisContext ActiveInstType;
  3415. ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
  3416. if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
  3417. ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
  3418. if (FunctionTemplateDecl *FunTmpl
  3419. = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
  3420. assert(FunTmpl->getTemplatedDecl() == Tmpl &&
  3421. "Deduction from the wrong function template?");
  3422. (void) FunTmpl;
  3423. atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
  3424. ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
  3425. ActiveInst.Entity = New;
  3426. atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
  3427. }
  3428. }
  3429. const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
  3430. assert(Proto && "Function template without prototype?");
  3431. if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
  3432. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  3433. // DR1330: In C++11, defer instantiation of a non-trivial
  3434. // exception specification.
  3435. // DR1484: Local classes and their members are instantiated along with the
  3436. // containing function.
  3437. if (SemaRef.getLangOpts().CPlusPlus11 &&
  3438. EPI.ExceptionSpec.Type != EST_None &&
  3439. EPI.ExceptionSpec.Type != EST_DynamicNone &&
  3440. EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
  3441. !Tmpl->isLexicallyWithinFunctionOrMethod()) {
  3442. FunctionDecl *ExceptionSpecTemplate = Tmpl;
  3443. if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
  3444. ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
  3445. ExceptionSpecificationType NewEST = EST_Uninstantiated;
  3446. if (EPI.ExceptionSpec.Type == EST_Unevaluated)
  3447. NewEST = EST_Unevaluated;
  3448. // Mark the function has having an uninstantiated exception specification.
  3449. const FunctionProtoType *NewProto
  3450. = New->getType()->getAs<FunctionProtoType>();
  3451. assert(NewProto && "Template instantiation without function prototype?");
  3452. EPI = NewProto->getExtProtoInfo();
  3453. EPI.ExceptionSpec.Type = NewEST;
  3454. EPI.ExceptionSpec.SourceDecl = New;
  3455. EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
  3456. New->setType(SemaRef.Context.getFunctionType(
  3457. NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
  3458. } else {
  3459. Sema::ContextRAII SwitchContext(SemaRef, New);
  3460. SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
  3461. }
  3462. }
  3463. // Get the definition. Leaves the variable unchanged if undefined.
  3464. const FunctionDecl *Definition = Tmpl;
  3465. Tmpl->isDefined(Definition);
  3466. SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
  3467. LateAttrs, StartingScope);
  3468. return false;
  3469. }
  3470. /// Initializes common fields of an instantiated method
  3471. /// declaration (New) from the corresponding fields of its template
  3472. /// (Tmpl).
  3473. ///
  3474. /// \returns true if there was an error
  3475. bool
  3476. TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
  3477. CXXMethodDecl *Tmpl) {
  3478. if (InitFunctionInstantiation(New, Tmpl))
  3479. return true;
  3480. if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
  3481. SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
  3482. New->setAccess(Tmpl->getAccess());
  3483. if (Tmpl->isVirtualAsWritten())
  3484. New->setVirtualAsWritten(true);
  3485. // FIXME: New needs a pointer to Tmpl
  3486. return false;
  3487. }
  3488. /// Instantiate (or find existing instantiation of) a function template with a
  3489. /// given set of template arguments.
  3490. ///
  3491. /// Usually this should not be used, and template argument deduction should be
  3492. /// used in its place.
  3493. FunctionDecl *
  3494. Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
  3495. const TemplateArgumentList *Args,
  3496. SourceLocation Loc) {
  3497. FunctionDecl *FD = FTD->getTemplatedDecl();
  3498. sema::TemplateDeductionInfo Info(Loc);
  3499. InstantiatingTemplate Inst(
  3500. *this, Loc, FTD, Args->asArray(),
  3501. CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
  3502. if (Inst.isInvalid())
  3503. return nullptr;
  3504. ContextRAII SavedContext(*this, FD);
  3505. MultiLevelTemplateArgumentList MArgs(*Args);
  3506. return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
  3507. }
  3508. /// In the MS ABI, we need to instantiate default arguments of dllexported
  3509. /// default constructors along with the constructor definition. This allows IR
  3510. /// gen to emit a constructor closure which calls the default constructor with
  3511. /// its default arguments.
  3512. static void InstantiateDefaultCtorDefaultArgs(Sema &S,
  3513. CXXConstructorDecl *Ctor) {
  3514. assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  3515. Ctor->isDefaultConstructor());
  3516. unsigned NumParams = Ctor->getNumParams();
  3517. if (NumParams == 0)
  3518. return;
  3519. DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
  3520. if (!Attr)
  3521. return;
  3522. for (unsigned I = 0; I != NumParams; ++I) {
  3523. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
  3524. Ctor->getParamDecl(I));
  3525. S.DiscardCleanupsInEvaluationContext();
  3526. }
  3527. }
  3528. /// Instantiate the definition of the given function from its
  3529. /// template.
  3530. ///
  3531. /// \param PointOfInstantiation the point at which the instantiation was
  3532. /// required. Note that this is not precisely a "point of instantiation"
  3533. /// for the function, but it's close.
  3534. ///
  3535. /// \param Function the already-instantiated declaration of a
  3536. /// function template specialization or member function of a class template
  3537. /// specialization.
  3538. ///
  3539. /// \param Recursive if true, recursively instantiates any functions that
  3540. /// are required by this instantiation.
  3541. ///
  3542. /// \param DefinitionRequired if true, then we are performing an explicit
  3543. /// instantiation where the body of the function is required. Complain if
  3544. /// there is no such body.
  3545. void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
  3546. FunctionDecl *Function,
  3547. bool Recursive,
  3548. bool DefinitionRequired,
  3549. bool AtEndOfTU) {
  3550. if (Function->isInvalidDecl() || Function->isDefined() ||
  3551. isa<CXXDeductionGuideDecl>(Function))
  3552. return;
  3553. // Never instantiate an explicit specialization except if it is a class scope
  3554. // explicit specialization.
  3555. TemplateSpecializationKind TSK =
  3556. Function->getTemplateSpecializationKindForInstantiation();
  3557. if (TSK == TSK_ExplicitSpecialization)
  3558. return;
  3559. // Find the function body that we'll be substituting.
  3560. const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
  3561. assert(PatternDecl && "instantiating a non-template");
  3562. const FunctionDecl *PatternDef = PatternDecl->getDefinition();
  3563. Stmt *Pattern = nullptr;
  3564. if (PatternDef) {
  3565. Pattern = PatternDef->getBody(PatternDef);
  3566. PatternDecl = PatternDef;
  3567. if (PatternDef->willHaveBody())
  3568. PatternDef = nullptr;
  3569. }
  3570. // FIXME: We need to track the instantiation stack in order to know which
  3571. // definitions should be visible within this instantiation.
  3572. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
  3573. Function->getInstantiatedFromMemberFunction(),
  3574. PatternDecl, PatternDef, TSK,
  3575. /*Complain*/DefinitionRequired)) {
  3576. if (DefinitionRequired)
  3577. Function->setInvalidDecl();
  3578. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  3579. // Try again at the end of the translation unit (at which point a
  3580. // definition will be required).
  3581. assert(!Recursive);
  3582. Function->setInstantiationIsPending(true);
  3583. PendingInstantiations.push_back(
  3584. std::make_pair(Function, PointOfInstantiation));
  3585. } else if (TSK == TSK_ImplicitInstantiation) {
  3586. if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
  3587. !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
  3588. Diag(PointOfInstantiation, diag::warn_func_template_missing)
  3589. << Function;
  3590. Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
  3591. if (getLangOpts().CPlusPlus11)
  3592. Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
  3593. << Function;
  3594. }
  3595. }
  3596. return;
  3597. }
  3598. // Postpone late parsed template instantiations.
  3599. if (PatternDecl->isLateTemplateParsed() &&
  3600. !LateTemplateParser) {
  3601. Function->setInstantiationIsPending(true);
  3602. LateParsedInstantiations.push_back(
  3603. std::make_pair(Function, PointOfInstantiation));
  3604. return;
  3605. }
  3606. llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
  3607. std::string Name;
  3608. llvm::raw_string_ostream OS(Name);
  3609. Function->getNameForDiagnostic(OS, getPrintingPolicy(),
  3610. /*Qualified=*/true);
  3611. return Name;
  3612. });
  3613. // If we're performing recursive template instantiation, create our own
  3614. // queue of pending implicit instantiations that we will instantiate later,
  3615. // while we're still within our own instantiation context.
  3616. // This has to happen before LateTemplateParser below is called, so that
  3617. // it marks vtables used in late parsed templates as used.
  3618. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  3619. /*Enabled=*/Recursive);
  3620. LocalEagerInstantiationScope LocalInstantiations(*this);
  3621. // Call the LateTemplateParser callback if there is a need to late parse
  3622. // a templated function definition.
  3623. if (!Pattern && PatternDecl->isLateTemplateParsed() &&
  3624. LateTemplateParser) {
  3625. // FIXME: Optimize to allow individual templates to be deserialized.
  3626. if (PatternDecl->isFromASTFile())
  3627. ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
  3628. auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
  3629. assert(LPTIter != LateParsedTemplateMap.end() &&
  3630. "missing LateParsedTemplate");
  3631. LateTemplateParser(OpaqueParser, *LPTIter->second);
  3632. Pattern = PatternDecl->getBody(PatternDecl);
  3633. }
  3634. // Note, we should never try to instantiate a deleted function template.
  3635. assert((Pattern || PatternDecl->isDefaulted() ||
  3636. PatternDecl->hasSkippedBody()) &&
  3637. "unexpected kind of function template definition");
  3638. // C++1y [temp.explicit]p10:
  3639. // Except for inline functions, declarations with types deduced from their
  3640. // initializer or return value, and class template specializations, other
  3641. // explicit instantiation declarations have the effect of suppressing the
  3642. // implicit instantiation of the entity to which they refer.
  3643. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  3644. !PatternDecl->isInlined() &&
  3645. !PatternDecl->getReturnType()->getContainedAutoType())
  3646. return;
  3647. if (PatternDecl->isInlined()) {
  3648. // Function, and all later redeclarations of it (from imported modules,
  3649. // for instance), are now implicitly inline.
  3650. for (auto *D = Function->getMostRecentDecl(); /**/;
  3651. D = D->getPreviousDecl()) {
  3652. D->setImplicitlyInline();
  3653. if (D == Function)
  3654. break;
  3655. }
  3656. }
  3657. InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
  3658. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  3659. return;
  3660. PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
  3661. "instantiating function definition");
  3662. // The instantiation is visible here, even if it was first declared in an
  3663. // unimported module.
  3664. Function->setVisibleDespiteOwningModule();
  3665. // Copy the inner loc start from the pattern.
  3666. Function->setInnerLocStart(PatternDecl->getInnerLocStart());
  3667. EnterExpressionEvaluationContext EvalContext(
  3668. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  3669. // Introduce a new scope where local variable instantiations will be
  3670. // recorded, unless we're actually a member function within a local
  3671. // class, in which case we need to merge our results with the parent
  3672. // scope (of the enclosing function).
  3673. bool MergeWithParentScope = false;
  3674. if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
  3675. MergeWithParentScope = Rec->isLocalClass();
  3676. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  3677. if (PatternDecl->isDefaulted())
  3678. SetDeclDefaulted(Function, PatternDecl->getLocation());
  3679. else {
  3680. MultiLevelTemplateArgumentList TemplateArgs =
  3681. getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
  3682. // Substitute into the qualifier; we can get a substitution failure here
  3683. // through evil use of alias templates.
  3684. // FIXME: Is CurContext correct for this? Should we go to the (instantiation
  3685. // of the) lexical context of the pattern?
  3686. SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
  3687. ActOnStartOfFunctionDef(nullptr, Function);
  3688. // Enter the scope of this instantiation. We don't use
  3689. // PushDeclContext because we don't have a scope.
  3690. Sema::ContextRAII savedContext(*this, Function);
  3691. if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
  3692. TemplateArgs))
  3693. return;
  3694. StmtResult Body;
  3695. if (PatternDecl->hasSkippedBody()) {
  3696. ActOnSkippedFunctionBody(Function);
  3697. Body = nullptr;
  3698. } else {
  3699. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
  3700. // If this is a constructor, instantiate the member initializers.
  3701. InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
  3702. TemplateArgs);
  3703. // If this is an MS ABI dllexport default constructor, instantiate any
  3704. // default arguments.
  3705. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  3706. Ctor->isDefaultConstructor()) {
  3707. InstantiateDefaultCtorDefaultArgs(*this, Ctor);
  3708. }
  3709. }
  3710. // Instantiate the function body.
  3711. Body = SubstStmt(Pattern, TemplateArgs);
  3712. if (Body.isInvalid())
  3713. Function->setInvalidDecl();
  3714. }
  3715. // FIXME: finishing the function body while in an expression evaluation
  3716. // context seems wrong. Investigate more.
  3717. ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
  3718. PerformDependentDiagnostics(PatternDecl, TemplateArgs);
  3719. if (auto *Listener = getASTMutationListener())
  3720. Listener->FunctionDefinitionInstantiated(Function);
  3721. savedContext.pop();
  3722. }
  3723. DeclGroupRef DG(Function);
  3724. Consumer.HandleTopLevelDecl(DG);
  3725. // This class may have local implicit instantiations that need to be
  3726. // instantiation within this scope.
  3727. LocalInstantiations.perform();
  3728. Scope.Exit();
  3729. GlobalInstantiations.perform();
  3730. }
  3731. VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
  3732. VarTemplateDecl *VarTemplate, VarDecl *FromVar,
  3733. const TemplateArgumentList &TemplateArgList,
  3734. const TemplateArgumentListInfo &TemplateArgsInfo,
  3735. SmallVectorImpl<TemplateArgument> &Converted,
  3736. SourceLocation PointOfInstantiation, void *InsertPos,
  3737. LateInstantiatedAttrVec *LateAttrs,
  3738. LocalInstantiationScope *StartingScope) {
  3739. if (FromVar->isInvalidDecl())
  3740. return nullptr;
  3741. InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
  3742. if (Inst.isInvalid())
  3743. return nullptr;
  3744. MultiLevelTemplateArgumentList TemplateArgLists;
  3745. TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
  3746. // Instantiate the first declaration of the variable template: for a partial
  3747. // specialization of a static data member template, the first declaration may
  3748. // or may not be the declaration in the class; if it's in the class, we want
  3749. // to instantiate a member in the class (a declaration), and if it's outside,
  3750. // we want to instantiate a definition.
  3751. //
  3752. // If we're instantiating an explicitly-specialized member template or member
  3753. // partial specialization, don't do this. The member specialization completely
  3754. // replaces the original declaration in this case.
  3755. bool IsMemberSpec = false;
  3756. if (VarTemplatePartialSpecializationDecl *PartialSpec =
  3757. dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
  3758. IsMemberSpec = PartialSpec->isMemberSpecialization();
  3759. else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
  3760. IsMemberSpec = FromTemplate->isMemberSpecialization();
  3761. if (!IsMemberSpec)
  3762. FromVar = FromVar->getFirstDecl();
  3763. MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
  3764. TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
  3765. MultiLevelList);
  3766. // TODO: Set LateAttrs and StartingScope ...
  3767. return cast_or_null<VarTemplateSpecializationDecl>(
  3768. Instantiator.VisitVarTemplateSpecializationDecl(
  3769. VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
  3770. }
  3771. /// Instantiates a variable template specialization by completing it
  3772. /// with appropriate type information and initializer.
  3773. VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
  3774. VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
  3775. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3776. assert(PatternDecl->isThisDeclarationADefinition() &&
  3777. "don't have a definition to instantiate from");
  3778. // Do substitution on the type of the declaration
  3779. TypeSourceInfo *DI =
  3780. SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
  3781. PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
  3782. if (!DI)
  3783. return nullptr;
  3784. // Update the type of this variable template specialization.
  3785. VarSpec->setType(DI->getType());
  3786. // Convert the declaration into a definition now.
  3787. VarSpec->setCompleteDefinition();
  3788. // Instantiate the initializer.
  3789. InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
  3790. return VarSpec;
  3791. }
  3792. /// BuildVariableInstantiation - Used after a new variable has been created.
  3793. /// Sets basic variable data and decides whether to postpone the
  3794. /// variable instantiation.
  3795. void Sema::BuildVariableInstantiation(
  3796. VarDecl *NewVar, VarDecl *OldVar,
  3797. const MultiLevelTemplateArgumentList &TemplateArgs,
  3798. LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
  3799. LocalInstantiationScope *StartingScope,
  3800. bool InstantiatingVarTemplate,
  3801. VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
  3802. // Instantiating a partial specialization to produce a partial
  3803. // specialization.
  3804. bool InstantiatingVarTemplatePartialSpec =
  3805. isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
  3806. isa<VarTemplatePartialSpecializationDecl>(NewVar);
  3807. // Instantiating from a variable template (or partial specialization) to
  3808. // produce a variable template specialization.
  3809. bool InstantiatingSpecFromTemplate =
  3810. isa<VarTemplateSpecializationDecl>(NewVar) &&
  3811. (OldVar->getDescribedVarTemplate() ||
  3812. isa<VarTemplatePartialSpecializationDecl>(OldVar));
  3813. // If we are instantiating a local extern declaration, the
  3814. // instantiation belongs lexically to the containing function.
  3815. // If we are instantiating a static data member defined
  3816. // out-of-line, the instantiation will have the same lexical
  3817. // context (which will be a namespace scope) as the template.
  3818. if (OldVar->isLocalExternDecl()) {
  3819. NewVar->setLocalExternDecl();
  3820. NewVar->setLexicalDeclContext(Owner);
  3821. } else if (OldVar->isOutOfLine())
  3822. NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
  3823. NewVar->setTSCSpec(OldVar->getTSCSpec());
  3824. NewVar->setInitStyle(OldVar->getInitStyle());
  3825. NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
  3826. NewVar->setObjCForDecl(OldVar->isObjCForDecl());
  3827. NewVar->setConstexpr(OldVar->isConstexpr());
  3828. NewVar->setInitCapture(OldVar->isInitCapture());
  3829. NewVar->setPreviousDeclInSameBlockScope(
  3830. OldVar->isPreviousDeclInSameBlockScope());
  3831. NewVar->setAccess(OldVar->getAccess());
  3832. if (!OldVar->isStaticDataMember()) {
  3833. if (OldVar->isUsed(false))
  3834. NewVar->setIsUsed();
  3835. NewVar->setReferenced(OldVar->isReferenced());
  3836. }
  3837. InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
  3838. LookupResult Previous(
  3839. *this, NewVar->getDeclName(), NewVar->getLocation(),
  3840. NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  3841. : Sema::LookupOrdinaryName,
  3842. NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
  3843. : forRedeclarationInCurContext());
  3844. if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
  3845. (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
  3846. OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
  3847. // We have a previous declaration. Use that one, so we merge with the
  3848. // right type.
  3849. if (NamedDecl *NewPrev = FindInstantiatedDecl(
  3850. NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
  3851. Previous.addDecl(NewPrev);
  3852. } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
  3853. OldVar->hasLinkage()) {
  3854. LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
  3855. } else if (PrevDeclForVarTemplateSpecialization) {
  3856. Previous.addDecl(PrevDeclForVarTemplateSpecialization);
  3857. }
  3858. CheckVariableDeclaration(NewVar, Previous);
  3859. if (!InstantiatingVarTemplate) {
  3860. NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
  3861. if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
  3862. NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
  3863. }
  3864. if (!OldVar->isOutOfLine()) {
  3865. if (NewVar->getDeclContext()->isFunctionOrMethod())
  3866. CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
  3867. }
  3868. // Link instantiations of static data members back to the template from
  3869. // which they were instantiated.
  3870. //
  3871. // Don't do this when instantiating a template (we link the template itself
  3872. // back in that case) nor when instantiating a static data member template
  3873. // (that's not a member specialization).
  3874. if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
  3875. !InstantiatingSpecFromTemplate)
  3876. NewVar->setInstantiationOfStaticDataMember(OldVar,
  3877. TSK_ImplicitInstantiation);
  3878. // If the pattern is an (in-class) explicit specialization, then the result
  3879. // is also an explicit specialization.
  3880. if (VarTemplateSpecializationDecl *OldVTSD =
  3881. dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
  3882. if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
  3883. !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
  3884. cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
  3885. TSK_ExplicitSpecialization);
  3886. }
  3887. // Forward the mangling number from the template to the instantiated decl.
  3888. Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
  3889. Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
  3890. // Figure out whether to eagerly instantiate the initializer.
  3891. if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
  3892. // We're producing a template. Don't instantiate the initializer yet.
  3893. } else if (NewVar->getType()->isUndeducedType()) {
  3894. // We need the type to complete the declaration of the variable.
  3895. InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
  3896. } else if (InstantiatingSpecFromTemplate ||
  3897. (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
  3898. !NewVar->isThisDeclarationADefinition())) {
  3899. // Delay instantiation of the initializer for variable template
  3900. // specializations or inline static data members until a definition of the
  3901. // variable is needed.
  3902. } else {
  3903. InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
  3904. }
  3905. // Diagnose unused local variables with dependent types, where the diagnostic
  3906. // will have been deferred.
  3907. if (!NewVar->isInvalidDecl() &&
  3908. NewVar->getDeclContext()->isFunctionOrMethod() &&
  3909. OldVar->getType()->isDependentType())
  3910. DiagnoseUnusedDecl(NewVar);
  3911. }
  3912. /// Instantiate the initializer of a variable.
  3913. void Sema::InstantiateVariableInitializer(
  3914. VarDecl *Var, VarDecl *OldVar,
  3915. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3916. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  3917. L->VariableDefinitionInstantiated(Var);
  3918. // We propagate the 'inline' flag with the initializer, because it
  3919. // would otherwise imply that the variable is a definition for a
  3920. // non-static data member.
  3921. if (OldVar->isInlineSpecified())
  3922. Var->setInlineSpecified();
  3923. else if (OldVar->isInline())
  3924. Var->setImplicitlyInline();
  3925. if (OldVar->getInit()) {
  3926. EnterExpressionEvaluationContext Evaluated(
  3927. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
  3928. // Instantiate the initializer.
  3929. ExprResult Init;
  3930. {
  3931. ContextRAII SwitchContext(*this, Var->getDeclContext());
  3932. Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
  3933. OldVar->getInitStyle() == VarDecl::CallInit);
  3934. }
  3935. if (!Init.isInvalid()) {
  3936. Expr *InitExpr = Init.get();
  3937. if (Var->hasAttr<DLLImportAttr>() &&
  3938. (!InitExpr ||
  3939. !InitExpr->isConstantInitializer(getASTContext(), false))) {
  3940. // Do not dynamically initialize dllimport variables.
  3941. } else if (InitExpr) {
  3942. bool DirectInit = OldVar->isDirectInit();
  3943. AddInitializerToDecl(Var, InitExpr, DirectInit);
  3944. } else
  3945. ActOnUninitializedDecl(Var);
  3946. } else {
  3947. // FIXME: Not too happy about invalidating the declaration
  3948. // because of a bogus initializer.
  3949. Var->setInvalidDecl();
  3950. }
  3951. } else {
  3952. // `inline` variables are a definition and declaration all in one; we won't
  3953. // pick up an initializer from anywhere else.
  3954. if (Var->isStaticDataMember() && !Var->isInline()) {
  3955. if (!Var->isOutOfLine())
  3956. return;
  3957. // If the declaration inside the class had an initializer, don't add
  3958. // another one to the out-of-line definition.
  3959. if (OldVar->getFirstDecl()->hasInit())
  3960. return;
  3961. }
  3962. // We'll add an initializer to a for-range declaration later.
  3963. if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
  3964. return;
  3965. ActOnUninitializedDecl(Var);
  3966. }
  3967. if (getLangOpts().CUDA)
  3968. checkAllowedCUDAInitializer(Var);
  3969. }
  3970. /// Instantiate the definition of the given variable from its
  3971. /// template.
  3972. ///
  3973. /// \param PointOfInstantiation the point at which the instantiation was
  3974. /// required. Note that this is not precisely a "point of instantiation"
  3975. /// for the variable, but it's close.
  3976. ///
  3977. /// \param Var the already-instantiated declaration of a templated variable.
  3978. ///
  3979. /// \param Recursive if true, recursively instantiates any functions that
  3980. /// are required by this instantiation.
  3981. ///
  3982. /// \param DefinitionRequired if true, then we are performing an explicit
  3983. /// instantiation where a definition of the variable is required. Complain
  3984. /// if there is no such definition.
  3985. void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
  3986. VarDecl *Var, bool Recursive,
  3987. bool DefinitionRequired, bool AtEndOfTU) {
  3988. if (Var->isInvalidDecl())
  3989. return;
  3990. // Never instantiate an explicitly-specialized entity.
  3991. TemplateSpecializationKind TSK =
  3992. Var->getTemplateSpecializationKindForInstantiation();
  3993. if (TSK == TSK_ExplicitSpecialization)
  3994. return;
  3995. // Find the pattern and the arguments to substitute into it.
  3996. VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
  3997. assert(PatternDecl && "no pattern for templated variable");
  3998. MultiLevelTemplateArgumentList TemplateArgs =
  3999. getTemplateInstantiationArgs(Var);
  4000. VarTemplateSpecializationDecl *VarSpec =
  4001. dyn_cast<VarTemplateSpecializationDecl>(Var);
  4002. if (VarSpec) {
  4003. // If this is a variable template specialization, make sure that it is
  4004. // non-dependent.
  4005. bool InstantiationDependent = false;
  4006. assert(!TemplateSpecializationType::anyDependentTemplateArguments(
  4007. VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
  4008. "Only instantiate variable template specializations that are "
  4009. "not type-dependent");
  4010. (void)InstantiationDependent;
  4011. // If this is a static data member template, there might be an
  4012. // uninstantiated initializer on the declaration. If so, instantiate
  4013. // it now.
  4014. //
  4015. // FIXME: This largely duplicates what we would do below. The difference
  4016. // is that along this path we may instantiate an initializer from an
  4017. // in-class declaration of the template and instantiate the definition
  4018. // from a separate out-of-class definition.
  4019. if (PatternDecl->isStaticDataMember() &&
  4020. (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
  4021. !Var->hasInit()) {
  4022. // FIXME: Factor out the duplicated instantiation context setup/tear down
  4023. // code here.
  4024. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  4025. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  4026. return;
  4027. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  4028. "instantiating variable initializer");
  4029. // The instantiation is visible here, even if it was first declared in an
  4030. // unimported module.
  4031. Var->setVisibleDespiteOwningModule();
  4032. // If we're performing recursive template instantiation, create our own
  4033. // queue of pending implicit instantiations that we will instantiate
  4034. // later, while we're still within our own instantiation context.
  4035. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  4036. /*Enabled=*/Recursive);
  4037. LocalInstantiationScope Local(*this);
  4038. LocalEagerInstantiationScope LocalInstantiations(*this);
  4039. // Enter the scope of this instantiation. We don't use
  4040. // PushDeclContext because we don't have a scope.
  4041. ContextRAII PreviousContext(*this, Var->getDeclContext());
  4042. InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
  4043. PreviousContext.pop();
  4044. // This variable may have local implicit instantiations that need to be
  4045. // instantiated within this scope.
  4046. LocalInstantiations.perform();
  4047. Local.Exit();
  4048. GlobalInstantiations.perform();
  4049. }
  4050. } else {
  4051. assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
  4052. "not a static data member?");
  4053. }
  4054. VarDecl *Def = PatternDecl->getDefinition(getASTContext());
  4055. // If we don't have a definition of the variable template, we won't perform
  4056. // any instantiation. Rather, we rely on the user to instantiate this
  4057. // definition (or provide a specialization for it) in another translation
  4058. // unit.
  4059. if (!Def && !DefinitionRequired) {
  4060. if (TSK == TSK_ExplicitInstantiationDefinition) {
  4061. PendingInstantiations.push_back(
  4062. std::make_pair(Var, PointOfInstantiation));
  4063. } else if (TSK == TSK_ImplicitInstantiation) {
  4064. // Warn about missing definition at the end of translation unit.
  4065. if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
  4066. !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
  4067. Diag(PointOfInstantiation, diag::warn_var_template_missing)
  4068. << Var;
  4069. Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
  4070. if (getLangOpts().CPlusPlus11)
  4071. Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
  4072. }
  4073. return;
  4074. }
  4075. }
  4076. // FIXME: We need to track the instantiation stack in order to know which
  4077. // definitions should be visible within this instantiation.
  4078. // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
  4079. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
  4080. /*InstantiatedFromMember*/false,
  4081. PatternDecl, Def, TSK,
  4082. /*Complain*/DefinitionRequired))
  4083. return;
  4084. // C++11 [temp.explicit]p10:
  4085. // Except for inline functions, const variables of literal types, variables
  4086. // of reference types, [...] explicit instantiation declarations
  4087. // have the effect of suppressing the implicit instantiation of the entity
  4088. // to which they refer.
  4089. //
  4090. // FIXME: That's not exactly the same as "might be usable in constant
  4091. // expressions", which only allows constexpr variables and const integral
  4092. // types, not arbitrary const literal types.
  4093. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  4094. !Var->mightBeUsableInConstantExpressions(getASTContext()))
  4095. return;
  4096. // Make sure to pass the instantiated variable to the consumer at the end.
  4097. struct PassToConsumerRAII {
  4098. ASTConsumer &Consumer;
  4099. VarDecl *Var;
  4100. PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
  4101. : Consumer(Consumer), Var(Var) { }
  4102. ~PassToConsumerRAII() {
  4103. Consumer.HandleCXXStaticMemberVarInstantiation(Var);
  4104. }
  4105. } PassToConsumerRAII(Consumer, Var);
  4106. // If we already have a definition, we're done.
  4107. if (VarDecl *Def = Var->getDefinition()) {
  4108. // We may be explicitly instantiating something we've already implicitly
  4109. // instantiated.
  4110. Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
  4111. PointOfInstantiation);
  4112. return;
  4113. }
  4114. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  4115. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  4116. return;
  4117. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  4118. "instantiating variable definition");
  4119. // If we're performing recursive template instantiation, create our own
  4120. // queue of pending implicit instantiations that we will instantiate later,
  4121. // while we're still within our own instantiation context.
  4122. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  4123. /*Enabled=*/Recursive);
  4124. // Enter the scope of this instantiation. We don't use
  4125. // PushDeclContext because we don't have a scope.
  4126. ContextRAII PreviousContext(*this, Var->getDeclContext());
  4127. LocalInstantiationScope Local(*this);
  4128. LocalEagerInstantiationScope LocalInstantiations(*this);
  4129. VarDecl *OldVar = Var;
  4130. if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
  4131. // We're instantiating an inline static data member whose definition was
  4132. // provided inside the class.
  4133. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  4134. } else if (!VarSpec) {
  4135. Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
  4136. TemplateArgs));
  4137. } else if (Var->isStaticDataMember() &&
  4138. Var->getLexicalDeclContext()->isRecord()) {
  4139. // We need to instantiate the definition of a static data member template,
  4140. // and all we have is the in-class declaration of it. Instantiate a separate
  4141. // declaration of the definition.
  4142. TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
  4143. TemplateArgs);
  4144. Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
  4145. VarSpec->getSpecializedTemplate(), Def, nullptr,
  4146. VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
  4147. if (Var) {
  4148. llvm::PointerUnion<VarTemplateDecl *,
  4149. VarTemplatePartialSpecializationDecl *> PatternPtr =
  4150. VarSpec->getSpecializedTemplateOrPartial();
  4151. if (VarTemplatePartialSpecializationDecl *Partial =
  4152. PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
  4153. cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
  4154. Partial, &VarSpec->getTemplateInstantiationArgs());
  4155. // Merge the definition with the declaration.
  4156. LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
  4157. LookupOrdinaryName, forRedeclarationInCurContext());
  4158. R.addDecl(OldVar);
  4159. MergeVarDecl(Var, R);
  4160. // Attach the initializer.
  4161. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  4162. }
  4163. } else
  4164. // Complete the existing variable's definition with an appropriately
  4165. // substituted type and initializer.
  4166. Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
  4167. PreviousContext.pop();
  4168. if (Var) {
  4169. PassToConsumerRAII.Var = Var;
  4170. Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
  4171. OldVar->getPointOfInstantiation());
  4172. }
  4173. // This variable may have local implicit instantiations that need to be
  4174. // instantiated within this scope.
  4175. LocalInstantiations.perform();
  4176. Local.Exit();
  4177. GlobalInstantiations.perform();
  4178. }
  4179. void
  4180. Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
  4181. const CXXConstructorDecl *Tmpl,
  4182. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4183. SmallVector<CXXCtorInitializer*, 4> NewInits;
  4184. bool AnyErrors = Tmpl->isInvalidDecl();
  4185. // Instantiate all the initializers.
  4186. for (const auto *Init : Tmpl->inits()) {
  4187. // Only instantiate written initializers, let Sema re-construct implicit
  4188. // ones.
  4189. if (!Init->isWritten())
  4190. continue;
  4191. SourceLocation EllipsisLoc;
  4192. if (Init->isPackExpansion()) {
  4193. // This is a pack expansion. We should expand it now.
  4194. TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
  4195. SmallVector<UnexpandedParameterPack, 4> Unexpanded;
  4196. collectUnexpandedParameterPacks(BaseTL, Unexpanded);
  4197. collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
  4198. bool ShouldExpand = false;
  4199. bool RetainExpansion = false;
  4200. Optional<unsigned> NumExpansions;
  4201. if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
  4202. BaseTL.getSourceRange(),
  4203. Unexpanded,
  4204. TemplateArgs, ShouldExpand,
  4205. RetainExpansion,
  4206. NumExpansions)) {
  4207. AnyErrors = true;
  4208. New->setInvalidDecl();
  4209. continue;
  4210. }
  4211. assert(ShouldExpand && "Partial instantiation of base initializer?");
  4212. // Loop over all of the arguments in the argument pack(s),
  4213. for (unsigned I = 0; I != *NumExpansions; ++I) {
  4214. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  4215. // Instantiate the initializer.
  4216. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  4217. /*CXXDirectInit=*/true);
  4218. if (TempInit.isInvalid()) {
  4219. AnyErrors = true;
  4220. break;
  4221. }
  4222. // Instantiate the base type.
  4223. TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
  4224. TemplateArgs,
  4225. Init->getSourceLocation(),
  4226. New->getDeclName());
  4227. if (!BaseTInfo) {
  4228. AnyErrors = true;
  4229. break;
  4230. }
  4231. // Build the initializer.
  4232. MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
  4233. BaseTInfo, TempInit.get(),
  4234. New->getParent(),
  4235. SourceLocation());
  4236. if (NewInit.isInvalid()) {
  4237. AnyErrors = true;
  4238. break;
  4239. }
  4240. NewInits.push_back(NewInit.get());
  4241. }
  4242. continue;
  4243. }
  4244. // Instantiate the initializer.
  4245. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  4246. /*CXXDirectInit=*/true);
  4247. if (TempInit.isInvalid()) {
  4248. AnyErrors = true;
  4249. continue;
  4250. }
  4251. MemInitResult NewInit;
  4252. if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
  4253. TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
  4254. TemplateArgs,
  4255. Init->getSourceLocation(),
  4256. New->getDeclName());
  4257. if (!TInfo) {
  4258. AnyErrors = true;
  4259. New->setInvalidDecl();
  4260. continue;
  4261. }
  4262. if (Init->isBaseInitializer())
  4263. NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
  4264. New->getParent(), EllipsisLoc);
  4265. else
  4266. NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
  4267. cast<CXXRecordDecl>(CurContext->getParent()));
  4268. } else if (Init->isMemberInitializer()) {
  4269. FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
  4270. Init->getMemberLocation(),
  4271. Init->getMember(),
  4272. TemplateArgs));
  4273. if (!Member) {
  4274. AnyErrors = true;
  4275. New->setInvalidDecl();
  4276. continue;
  4277. }
  4278. NewInit = BuildMemberInitializer(Member, TempInit.get(),
  4279. Init->getSourceLocation());
  4280. } else if (Init->isIndirectMemberInitializer()) {
  4281. IndirectFieldDecl *IndirectMember =
  4282. cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
  4283. Init->getMemberLocation(),
  4284. Init->getIndirectMember(), TemplateArgs));
  4285. if (!IndirectMember) {
  4286. AnyErrors = true;
  4287. New->setInvalidDecl();
  4288. continue;
  4289. }
  4290. NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
  4291. Init->getSourceLocation());
  4292. }
  4293. if (NewInit.isInvalid()) {
  4294. AnyErrors = true;
  4295. New->setInvalidDecl();
  4296. } else {
  4297. NewInits.push_back(NewInit.get());
  4298. }
  4299. }
  4300. // Assign all the initializers to the new constructor.
  4301. ActOnMemInitializers(New,
  4302. /*FIXME: ColonLoc */
  4303. SourceLocation(),
  4304. NewInits,
  4305. AnyErrors);
  4306. }
  4307. // TODO: this could be templated if the various decl types used the
  4308. // same method name.
  4309. static bool isInstantiationOf(ClassTemplateDecl *Pattern,
  4310. ClassTemplateDecl *Instance) {
  4311. Pattern = Pattern->getCanonicalDecl();
  4312. do {
  4313. Instance = Instance->getCanonicalDecl();
  4314. if (Pattern == Instance) return true;
  4315. Instance = Instance->getInstantiatedFromMemberTemplate();
  4316. } while (Instance);
  4317. return false;
  4318. }
  4319. static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
  4320. FunctionTemplateDecl *Instance) {
  4321. Pattern = Pattern->getCanonicalDecl();
  4322. do {
  4323. Instance = Instance->getCanonicalDecl();
  4324. if (Pattern == Instance) return true;
  4325. Instance = Instance->getInstantiatedFromMemberTemplate();
  4326. } while (Instance);
  4327. return false;
  4328. }
  4329. static bool
  4330. isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
  4331. ClassTemplatePartialSpecializationDecl *Instance) {
  4332. Pattern
  4333. = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
  4334. do {
  4335. Instance = cast<ClassTemplatePartialSpecializationDecl>(
  4336. Instance->getCanonicalDecl());
  4337. if (Pattern == Instance)
  4338. return true;
  4339. Instance = Instance->getInstantiatedFromMember();
  4340. } while (Instance);
  4341. return false;
  4342. }
  4343. static bool isInstantiationOf(CXXRecordDecl *Pattern,
  4344. CXXRecordDecl *Instance) {
  4345. Pattern = Pattern->getCanonicalDecl();
  4346. do {
  4347. Instance = Instance->getCanonicalDecl();
  4348. if (Pattern == Instance) return true;
  4349. Instance = Instance->getInstantiatedFromMemberClass();
  4350. } while (Instance);
  4351. return false;
  4352. }
  4353. static bool isInstantiationOf(FunctionDecl *Pattern,
  4354. FunctionDecl *Instance) {
  4355. Pattern = Pattern->getCanonicalDecl();
  4356. do {
  4357. Instance = Instance->getCanonicalDecl();
  4358. if (Pattern == Instance) return true;
  4359. Instance = Instance->getInstantiatedFromMemberFunction();
  4360. } while (Instance);
  4361. return false;
  4362. }
  4363. static bool isInstantiationOf(EnumDecl *Pattern,
  4364. EnumDecl *Instance) {
  4365. Pattern = Pattern->getCanonicalDecl();
  4366. do {
  4367. Instance = Instance->getCanonicalDecl();
  4368. if (Pattern == Instance) return true;
  4369. Instance = Instance->getInstantiatedFromMemberEnum();
  4370. } while (Instance);
  4371. return false;
  4372. }
  4373. static bool isInstantiationOf(UsingShadowDecl *Pattern,
  4374. UsingShadowDecl *Instance,
  4375. ASTContext &C) {
  4376. return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
  4377. Pattern);
  4378. }
  4379. static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
  4380. ASTContext &C) {
  4381. return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
  4382. }
  4383. template<typename T>
  4384. static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
  4385. ASTContext &Ctx) {
  4386. // An unresolved using declaration can instantiate to an unresolved using
  4387. // declaration, or to a using declaration or a using declaration pack.
  4388. //
  4389. // Multiple declarations can claim to be instantiated from an unresolved
  4390. // using declaration if it's a pack expansion. We want the UsingPackDecl
  4391. // in that case, not the individual UsingDecls within the pack.
  4392. bool OtherIsPackExpansion;
  4393. NamedDecl *OtherFrom;
  4394. if (auto *OtherUUD = dyn_cast<T>(Other)) {
  4395. OtherIsPackExpansion = OtherUUD->isPackExpansion();
  4396. OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
  4397. } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
  4398. OtherIsPackExpansion = true;
  4399. OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
  4400. } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
  4401. OtherIsPackExpansion = false;
  4402. OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
  4403. } else {
  4404. return false;
  4405. }
  4406. return Pattern->isPackExpansion() == OtherIsPackExpansion &&
  4407. declaresSameEntity(OtherFrom, Pattern);
  4408. }
  4409. static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
  4410. VarDecl *Instance) {
  4411. assert(Instance->isStaticDataMember());
  4412. Pattern = Pattern->getCanonicalDecl();
  4413. do {
  4414. Instance = Instance->getCanonicalDecl();
  4415. if (Pattern == Instance) return true;
  4416. Instance = Instance->getInstantiatedFromStaticDataMember();
  4417. } while (Instance);
  4418. return false;
  4419. }
  4420. // Other is the prospective instantiation
  4421. // D is the prospective pattern
  4422. static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
  4423. if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
  4424. return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
  4425. if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
  4426. return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
  4427. if (D->getKind() != Other->getKind())
  4428. return false;
  4429. if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
  4430. return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
  4431. if (auto *Function = dyn_cast<FunctionDecl>(Other))
  4432. return isInstantiationOf(cast<FunctionDecl>(D), Function);
  4433. if (auto *Enum = dyn_cast<EnumDecl>(Other))
  4434. return isInstantiationOf(cast<EnumDecl>(D), Enum);
  4435. if (auto *Var = dyn_cast<VarDecl>(Other))
  4436. if (Var->isStaticDataMember())
  4437. return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
  4438. if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
  4439. return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
  4440. if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
  4441. return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
  4442. if (auto *PartialSpec =
  4443. dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
  4444. return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
  4445. PartialSpec);
  4446. if (auto *Field = dyn_cast<FieldDecl>(Other)) {
  4447. if (!Field->getDeclName()) {
  4448. // This is an unnamed field.
  4449. return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
  4450. cast<FieldDecl>(D));
  4451. }
  4452. }
  4453. if (auto *Using = dyn_cast<UsingDecl>(Other))
  4454. return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
  4455. if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
  4456. return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
  4457. return D->getDeclName() &&
  4458. D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
  4459. }
  4460. template<typename ForwardIterator>
  4461. static NamedDecl *findInstantiationOf(ASTContext &Ctx,
  4462. NamedDecl *D,
  4463. ForwardIterator first,
  4464. ForwardIterator last) {
  4465. for (; first != last; ++first)
  4466. if (isInstantiationOf(Ctx, D, *first))
  4467. return cast<NamedDecl>(*first);
  4468. return nullptr;
  4469. }
  4470. /// Finds the instantiation of the given declaration context
  4471. /// within the current instantiation.
  4472. ///
  4473. /// \returns NULL if there was an error
  4474. DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
  4475. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4476. if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
  4477. Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
  4478. return cast_or_null<DeclContext>(ID);
  4479. } else return DC;
  4480. }
  4481. /// Find the instantiation of the given declaration within the
  4482. /// current instantiation.
  4483. ///
  4484. /// This routine is intended to be used when \p D is a declaration
  4485. /// referenced from within a template, that needs to mapped into the
  4486. /// corresponding declaration within an instantiation. For example,
  4487. /// given:
  4488. ///
  4489. /// \code
  4490. /// template<typename T>
  4491. /// struct X {
  4492. /// enum Kind {
  4493. /// KnownValue = sizeof(T)
  4494. /// };
  4495. ///
  4496. /// bool getKind() const { return KnownValue; }
  4497. /// };
  4498. ///
  4499. /// template struct X<int>;
  4500. /// \endcode
  4501. ///
  4502. /// In the instantiation of X<int>::getKind(), we need to map the \p
  4503. /// EnumConstantDecl for \p KnownValue (which refers to
  4504. /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
  4505. /// \p FindInstantiatedDecl performs this mapping from within the instantiation
  4506. /// of X<int>.
  4507. NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
  4508. const MultiLevelTemplateArgumentList &TemplateArgs,
  4509. bool FindingInstantiatedContext) {
  4510. DeclContext *ParentDC = D->getDeclContext();
  4511. // FIXME: Parmeters of pointer to functions (y below) that are themselves
  4512. // parameters (p below) can have their ParentDC set to the translation-unit
  4513. // - thus we can not consistently check if the ParentDC of such a parameter
  4514. // is Dependent or/and a FunctionOrMethod.
  4515. // For e.g. this code, during Template argument deduction tries to
  4516. // find an instantiated decl for (T y) when the ParentDC for y is
  4517. // the translation unit.
  4518. // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
  4519. // float baz(float(*)()) { return 0.0; }
  4520. // Foo(baz);
  4521. // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
  4522. // it gets here, always has a FunctionOrMethod as its ParentDC??
  4523. // For now:
  4524. // - as long as we have a ParmVarDecl whose parent is non-dependent and
  4525. // whose type is not instantiation dependent, do nothing to the decl
  4526. // - otherwise find its instantiated decl.
  4527. if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
  4528. !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
  4529. return D;
  4530. if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
  4531. isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
  4532. ((ParentDC->isFunctionOrMethod() ||
  4533. isa<OMPDeclareReductionDecl>(ParentDC) ||
  4534. isa<OMPDeclareMapperDecl>(ParentDC)) &&
  4535. ParentDC->isDependentContext()) ||
  4536. (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
  4537. // D is a local of some kind. Look into the map of local
  4538. // declarations to their instantiations.
  4539. if (CurrentInstantiationScope) {
  4540. if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
  4541. if (Decl *FD = Found->dyn_cast<Decl *>())
  4542. return cast<NamedDecl>(FD);
  4543. int PackIdx = ArgumentPackSubstitutionIndex;
  4544. assert(PackIdx != -1 &&
  4545. "found declaration pack but not pack expanding");
  4546. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  4547. return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
  4548. }
  4549. }
  4550. // If we're performing a partial substitution during template argument
  4551. // deduction, we may not have values for template parameters yet. They
  4552. // just map to themselves.
  4553. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  4554. isa<TemplateTemplateParmDecl>(D))
  4555. return D;
  4556. if (D->isInvalidDecl())
  4557. return nullptr;
  4558. // Normally this function only searches for already instantiated declaration
  4559. // however we have to make an exclusion for local types used before
  4560. // definition as in the code:
  4561. //
  4562. // template<typename T> void f1() {
  4563. // void g1(struct x1);
  4564. // struct x1 {};
  4565. // }
  4566. //
  4567. // In this case instantiation of the type of 'g1' requires definition of
  4568. // 'x1', which is defined later. Error recovery may produce an enum used
  4569. // before definition. In these cases we need to instantiate relevant
  4570. // declarations here.
  4571. bool NeedInstantiate = false;
  4572. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  4573. NeedInstantiate = RD->isLocalClass();
  4574. else
  4575. NeedInstantiate = isa<EnumDecl>(D);
  4576. if (NeedInstantiate) {
  4577. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  4578. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  4579. return cast<TypeDecl>(Inst);
  4580. }
  4581. // If we didn't find the decl, then we must have a label decl that hasn't
  4582. // been found yet. Lazily instantiate it and return it now.
  4583. assert(isa<LabelDecl>(D));
  4584. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  4585. assert(Inst && "Failed to instantiate label??");
  4586. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  4587. return cast<LabelDecl>(Inst);
  4588. }
  4589. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  4590. if (!Record->isDependentContext())
  4591. return D;
  4592. // Determine whether this record is the "templated" declaration describing
  4593. // a class template or class template partial specialization.
  4594. ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
  4595. if (ClassTemplate)
  4596. ClassTemplate = ClassTemplate->getCanonicalDecl();
  4597. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  4598. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
  4599. ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
  4600. // Walk the current context to find either the record or an instantiation of
  4601. // it.
  4602. DeclContext *DC = CurContext;
  4603. while (!DC->isFileContext()) {
  4604. // If we're performing substitution while we're inside the template
  4605. // definition, we'll find our own context. We're done.
  4606. if (DC->Equals(Record))
  4607. return Record;
  4608. if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
  4609. // Check whether we're in the process of instantiating a class template
  4610. // specialization of the template we're mapping.
  4611. if (ClassTemplateSpecializationDecl *InstSpec
  4612. = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
  4613. ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
  4614. if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
  4615. return InstRecord;
  4616. }
  4617. // Check whether we're in the process of instantiating a member class.
  4618. if (isInstantiationOf(Record, InstRecord))
  4619. return InstRecord;
  4620. }
  4621. // Move to the outer template scope.
  4622. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
  4623. if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
  4624. DC = FD->getLexicalDeclContext();
  4625. continue;
  4626. }
  4627. // An implicit deduction guide acts as if it's within the class template
  4628. // specialization described by its name and first N template params.
  4629. auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
  4630. if (Guide && Guide->isImplicit()) {
  4631. TemplateDecl *TD = Guide->getDeducedTemplate();
  4632. // Convert the arguments to an "as-written" list.
  4633. TemplateArgumentListInfo Args(Loc, Loc);
  4634. for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
  4635. TD->getTemplateParameters()->size())) {
  4636. ArrayRef<TemplateArgument> Unpacked(Arg);
  4637. if (Arg.getKind() == TemplateArgument::Pack)
  4638. Unpacked = Arg.pack_elements();
  4639. for (TemplateArgument UnpackedArg : Unpacked)
  4640. Args.addArgument(
  4641. getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
  4642. }
  4643. QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
  4644. if (T.isNull())
  4645. return nullptr;
  4646. auto *SubstRecord = T->getAsCXXRecordDecl();
  4647. assert(SubstRecord && "class template id not a class type?");
  4648. // Check that this template-id names the primary template and not a
  4649. // partial or explicit specialization. (In the latter cases, it's
  4650. // meaningless to attempt to find an instantiation of D within the
  4651. // specialization.)
  4652. // FIXME: The standard doesn't say what should happen here.
  4653. if (FindingInstantiatedContext &&
  4654. usesPartialOrExplicitSpecialization(
  4655. Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
  4656. Diag(Loc, diag::err_specialization_not_primary_template)
  4657. << T << (SubstRecord->getTemplateSpecializationKind() ==
  4658. TSK_ExplicitSpecialization);
  4659. return nullptr;
  4660. }
  4661. DC = SubstRecord;
  4662. continue;
  4663. }
  4664. }
  4665. DC = DC->getParent();
  4666. }
  4667. // Fall through to deal with other dependent record types (e.g.,
  4668. // anonymous unions in class templates).
  4669. }
  4670. if (!ParentDC->isDependentContext())
  4671. return D;
  4672. ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
  4673. if (!ParentDC)
  4674. return nullptr;
  4675. if (ParentDC != D->getDeclContext()) {
  4676. // We performed some kind of instantiation in the parent context,
  4677. // so now we need to look into the instantiated parent context to
  4678. // find the instantiation of the declaration D.
  4679. // If our context used to be dependent, we may need to instantiate
  4680. // it before performing lookup into that context.
  4681. bool IsBeingInstantiated = false;
  4682. if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
  4683. if (!Spec->isDependentContext()) {
  4684. QualType T = Context.getTypeDeclType(Spec);
  4685. const RecordType *Tag = T->getAs<RecordType>();
  4686. assert(Tag && "type of non-dependent record is not a RecordType");
  4687. if (Tag->isBeingDefined())
  4688. IsBeingInstantiated = true;
  4689. if (!Tag->isBeingDefined() &&
  4690. RequireCompleteType(Loc, T, diag::err_incomplete_type))
  4691. return nullptr;
  4692. ParentDC = Tag->getDecl();
  4693. }
  4694. }
  4695. NamedDecl *Result = nullptr;
  4696. // FIXME: If the name is a dependent name, this lookup won't necessarily
  4697. // find it. Does that ever matter?
  4698. if (auto Name = D->getDeclName()) {
  4699. DeclarationNameInfo NameInfo(Name, D->getLocation());
  4700. DeclarationNameInfo NewNameInfo =
  4701. SubstDeclarationNameInfo(NameInfo, TemplateArgs);
  4702. Name = NewNameInfo.getName();
  4703. if (!Name)
  4704. return nullptr;
  4705. DeclContext::lookup_result Found = ParentDC->lookup(Name);
  4706. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
  4707. VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>(
  4708. findInstantiationOf(Context, VTSD->getSpecializedTemplate(),
  4709. Found.begin(), Found.end()));
  4710. if (!Templ)
  4711. return nullptr;
  4712. Result = getVarTemplateSpecialization(
  4713. Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation());
  4714. } else
  4715. Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
  4716. } else {
  4717. // Since we don't have a name for the entity we're looking for,
  4718. // our only option is to walk through all of the declarations to
  4719. // find that name. This will occur in a few cases:
  4720. //
  4721. // - anonymous struct/union within a template
  4722. // - unnamed class/struct/union/enum within a template
  4723. //
  4724. // FIXME: Find a better way to find these instantiations!
  4725. Result = findInstantiationOf(Context, D,
  4726. ParentDC->decls_begin(),
  4727. ParentDC->decls_end());
  4728. }
  4729. if (!Result) {
  4730. if (isa<UsingShadowDecl>(D)) {
  4731. // UsingShadowDecls can instantiate to nothing because of using hiding.
  4732. } else if (Diags.hasErrorOccurred()) {
  4733. // We've already complained about something, so most likely this
  4734. // declaration failed to instantiate. There's no point in complaining
  4735. // further, since this is normal in invalid code.
  4736. } else if (IsBeingInstantiated) {
  4737. // The class in which this member exists is currently being
  4738. // instantiated, and we haven't gotten around to instantiating this
  4739. // member yet. This can happen when the code uses forward declarations
  4740. // of member classes, and introduces ordering dependencies via
  4741. // template instantiation.
  4742. Diag(Loc, diag::err_member_not_yet_instantiated)
  4743. << D->getDeclName()
  4744. << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
  4745. Diag(D->getLocation(), diag::note_non_instantiated_member_here);
  4746. } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  4747. // This enumeration constant was found when the template was defined,
  4748. // but can't be found in the instantiation. This can happen if an
  4749. // unscoped enumeration member is explicitly specialized.
  4750. EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
  4751. EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
  4752. TemplateArgs));
  4753. assert(Spec->getTemplateSpecializationKind() ==
  4754. TSK_ExplicitSpecialization);
  4755. Diag(Loc, diag::err_enumerator_does_not_exist)
  4756. << D->getDeclName()
  4757. << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
  4758. Diag(Spec->getLocation(), diag::note_enum_specialized_here)
  4759. << Context.getTypeDeclType(Spec);
  4760. } else {
  4761. // We should have found something, but didn't.
  4762. llvm_unreachable("Unable to find instantiation of declaration!");
  4763. }
  4764. }
  4765. D = Result;
  4766. }
  4767. return D;
  4768. }
  4769. /// Performs template instantiation for all implicit template
  4770. /// instantiations we have seen until this point.
  4771. void Sema::PerformPendingInstantiations(bool LocalOnly) {
  4772. while (!PendingLocalImplicitInstantiations.empty() ||
  4773. (!LocalOnly && !PendingInstantiations.empty())) {
  4774. PendingImplicitInstantiation Inst;
  4775. if (PendingLocalImplicitInstantiations.empty()) {
  4776. Inst = PendingInstantiations.front();
  4777. PendingInstantiations.pop_front();
  4778. } else {
  4779. Inst = PendingLocalImplicitInstantiations.front();
  4780. PendingLocalImplicitInstantiations.pop_front();
  4781. }
  4782. // Instantiate function definitions
  4783. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
  4784. bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
  4785. TSK_ExplicitInstantiationDefinition;
  4786. if (Function->isMultiVersion()) {
  4787. getASTContext().forEachMultiversionedFunctionVersion(
  4788. Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
  4789. InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
  4790. DefinitionRequired, true);
  4791. if (CurFD->isDefined())
  4792. CurFD->setInstantiationIsPending(false);
  4793. });
  4794. } else {
  4795. InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
  4796. DefinitionRequired, true);
  4797. if (Function->isDefined())
  4798. Function->setInstantiationIsPending(false);
  4799. }
  4800. continue;
  4801. }
  4802. // Instantiate variable definitions
  4803. VarDecl *Var = cast<VarDecl>(Inst.first);
  4804. assert((Var->isStaticDataMember() ||
  4805. isa<VarTemplateSpecializationDecl>(Var)) &&
  4806. "Not a static data member, nor a variable template"
  4807. " specialization?");
  4808. // Don't try to instantiate declarations if the most recent redeclaration
  4809. // is invalid.
  4810. if (Var->getMostRecentDecl()->isInvalidDecl())
  4811. continue;
  4812. // Check if the most recent declaration has changed the specialization kind
  4813. // and removed the need for implicit instantiation.
  4814. switch (Var->getMostRecentDecl()
  4815. ->getTemplateSpecializationKindForInstantiation()) {
  4816. case TSK_Undeclared:
  4817. llvm_unreachable("Cannot instantitiate an undeclared specialization.");
  4818. case TSK_ExplicitInstantiationDeclaration:
  4819. case TSK_ExplicitSpecialization:
  4820. continue; // No longer need to instantiate this type.
  4821. case TSK_ExplicitInstantiationDefinition:
  4822. // We only need an instantiation if the pending instantiation *is* the
  4823. // explicit instantiation.
  4824. if (Var != Var->getMostRecentDecl())
  4825. continue;
  4826. break;
  4827. case TSK_ImplicitInstantiation:
  4828. break;
  4829. }
  4830. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  4831. "instantiating variable definition");
  4832. bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
  4833. TSK_ExplicitInstantiationDefinition;
  4834. // Instantiate static data member definitions or variable template
  4835. // specializations.
  4836. InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
  4837. DefinitionRequired, true);
  4838. }
  4839. }
  4840. void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
  4841. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4842. for (auto DD : Pattern->ddiags()) {
  4843. switch (DD->getKind()) {
  4844. case DependentDiagnostic::Access:
  4845. HandleDependentAccessCheck(*DD, TemplateArgs);
  4846. break;
  4847. }
  4848. }
  4849. }