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