SemaTemplate.cpp 391 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693
  1. //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for C++ templates.
  10. //===----------------------------------------------------------------------===//
  11. #include "TreeTransform.h"
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/DeclFriend.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/RecursiveASTVisitor.h"
  19. #include "clang/AST/TypeVisitor.h"
  20. #include "clang/Basic/Builtins.h"
  21. #include "clang/Basic/LangOptions.h"
  22. #include "clang/Basic/PartialDiagnostic.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Sema/DeclSpec.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/ParsedTemplate.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/SemaInternal.h"
  29. #include "clang/Sema/Template.h"
  30. #include "clang/Sema/TemplateDeduction.h"
  31. #include "llvm/ADT/SmallBitVector.h"
  32. #include "llvm/ADT/SmallString.h"
  33. #include "llvm/ADT/StringExtras.h"
  34. #include <iterator>
  35. using namespace clang;
  36. using namespace sema;
  37. // Exported for use by Parser.
  38. SourceRange
  39. clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
  40. unsigned N) {
  41. if (!N) return SourceRange();
  42. return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
  43. }
  44. namespace clang {
  45. /// \brief [temp.constr.decl]p2: A template's associated constraints are
  46. /// defined as a single constraint-expression derived from the introduced
  47. /// constraint-expressions [ ... ].
  48. ///
  49. /// \param Params The template parameter list and optional requires-clause.
  50. ///
  51. /// \param FD The underlying templated function declaration for a function
  52. /// template.
  53. static Expr *formAssociatedConstraints(TemplateParameterList *Params,
  54. FunctionDecl *FD);
  55. }
  56. static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
  57. FunctionDecl *FD) {
  58. // FIXME: Concepts: collect additional introduced constraint-expressions
  59. assert(!FD && "Cannot collect constraints from function declaration yet.");
  60. return Params->getRequiresClause();
  61. }
  62. /// \brief Determine whether the declaration found is acceptable as the name
  63. /// of a template and, if so, return that template declaration. Otherwise,
  64. /// returns NULL.
  65. static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
  66. NamedDecl *Orig,
  67. bool AllowFunctionTemplates) {
  68. NamedDecl *D = Orig->getUnderlyingDecl();
  69. if (isa<TemplateDecl>(D)) {
  70. if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
  71. return nullptr;
  72. return Orig;
  73. }
  74. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  75. // C++ [temp.local]p1:
  76. // Like normal (non-template) classes, class templates have an
  77. // injected-class-name (Clause 9). The injected-class-name
  78. // can be used with or without a template-argument-list. When
  79. // it is used without a template-argument-list, it is
  80. // equivalent to the injected-class-name followed by the
  81. // template-parameters of the class template enclosed in
  82. // <>. When it is used with a template-argument-list, it
  83. // refers to the specified class template specialization,
  84. // which could be the current specialization or another
  85. // specialization.
  86. if (Record->isInjectedClassName()) {
  87. Record = cast<CXXRecordDecl>(Record->getDeclContext());
  88. if (Record->getDescribedClassTemplate())
  89. return Record->getDescribedClassTemplate();
  90. if (ClassTemplateSpecializationDecl *Spec
  91. = dyn_cast<ClassTemplateSpecializationDecl>(Record))
  92. return Spec->getSpecializedTemplate();
  93. }
  94. return nullptr;
  95. }
  96. return nullptr;
  97. }
  98. void Sema::FilterAcceptableTemplateNames(LookupResult &R,
  99. bool AllowFunctionTemplates) {
  100. // The set of class templates we've already seen.
  101. llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
  102. LookupResult::Filter filter = R.makeFilter();
  103. while (filter.hasNext()) {
  104. NamedDecl *Orig = filter.next();
  105. NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
  106. AllowFunctionTemplates);
  107. if (!Repl)
  108. filter.erase();
  109. else if (Repl != Orig) {
  110. // C++ [temp.local]p3:
  111. // A lookup that finds an injected-class-name (10.2) can result in an
  112. // ambiguity in certain cases (for example, if it is found in more than
  113. // one base class). If all of the injected-class-names that are found
  114. // refer to specializations of the same class template, and if the name
  115. // is used as a template-name, the reference refers to the class
  116. // template itself and not a specialization thereof, and is not
  117. // ambiguous.
  118. if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
  119. if (!ClassTemplates.insert(ClassTmpl).second) {
  120. filter.erase();
  121. continue;
  122. }
  123. // FIXME: we promote access to public here as a workaround to
  124. // the fact that LookupResult doesn't let us remember that we
  125. // found this template through a particular injected class name,
  126. // which means we end up doing nasty things to the invariants.
  127. // Pretending that access is public is *much* safer.
  128. filter.replace(Repl, AS_public);
  129. }
  130. }
  131. filter.done();
  132. }
  133. bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
  134. bool AllowFunctionTemplates) {
  135. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
  136. if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
  137. return true;
  138. return false;
  139. }
  140. TemplateNameKind Sema::isTemplateName(Scope *S,
  141. CXXScopeSpec &SS,
  142. bool hasTemplateKeyword,
  143. UnqualifiedId &Name,
  144. ParsedType ObjectTypePtr,
  145. bool EnteringContext,
  146. TemplateTy &TemplateResult,
  147. bool &MemberOfUnknownSpecialization) {
  148. assert(getLangOpts().CPlusPlus && "No template names in C!");
  149. DeclarationName TName;
  150. MemberOfUnknownSpecialization = false;
  151. switch (Name.getKind()) {
  152. case UnqualifiedId::IK_Identifier:
  153. TName = DeclarationName(Name.Identifier);
  154. break;
  155. case UnqualifiedId::IK_OperatorFunctionId:
  156. TName = Context.DeclarationNames.getCXXOperatorName(
  157. Name.OperatorFunctionId.Operator);
  158. break;
  159. case UnqualifiedId::IK_LiteralOperatorId:
  160. TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
  161. break;
  162. default:
  163. return TNK_Non_template;
  164. }
  165. QualType ObjectType = ObjectTypePtr.get();
  166. LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
  167. LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
  168. MemberOfUnknownSpecialization);
  169. if (R.empty()) return TNK_Non_template;
  170. if (R.isAmbiguous()) {
  171. // Suppress diagnostics; we'll redo this lookup later.
  172. R.suppressDiagnostics();
  173. // FIXME: we might have ambiguous templates, in which case we
  174. // should at least parse them properly!
  175. return TNK_Non_template;
  176. }
  177. TemplateName Template;
  178. TemplateNameKind TemplateKind;
  179. unsigned ResultCount = R.end() - R.begin();
  180. if (ResultCount > 1) {
  181. // We assume that we'll preserve the qualifier from a function
  182. // template name in other ways.
  183. Template = Context.getOverloadedTemplateName(R.begin(), R.end());
  184. TemplateKind = TNK_Function_template;
  185. // We'll do this lookup again later.
  186. R.suppressDiagnostics();
  187. } else {
  188. TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
  189. if (SS.isSet() && !SS.isInvalid()) {
  190. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  191. Template = Context.getQualifiedTemplateName(Qualifier,
  192. hasTemplateKeyword, TD);
  193. } else {
  194. Template = TemplateName(TD);
  195. }
  196. if (isa<FunctionTemplateDecl>(TD)) {
  197. TemplateKind = TNK_Function_template;
  198. // We'll do this lookup again later.
  199. R.suppressDiagnostics();
  200. } else {
  201. assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
  202. isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
  203. isa<BuiltinTemplateDecl>(TD));
  204. TemplateKind =
  205. isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
  206. }
  207. }
  208. TemplateResult = TemplateTy::make(Template);
  209. return TemplateKind;
  210. }
  211. bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
  212. SourceLocation NameLoc,
  213. ParsedTemplateTy *Template) {
  214. CXXScopeSpec SS;
  215. bool MemberOfUnknownSpecialization = false;
  216. // We could use redeclaration lookup here, but we don't need to: the
  217. // syntactic form of a deduction guide is enough to identify it even
  218. // if we can't look up the template name at all.
  219. LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
  220. LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
  221. /*EnteringContext*/false, MemberOfUnknownSpecialization);
  222. if (R.empty()) return false;
  223. if (R.isAmbiguous()) {
  224. // FIXME: Diagnose an ambiguity if we find at least one template.
  225. R.suppressDiagnostics();
  226. return false;
  227. }
  228. // We only treat template-names that name type templates as valid deduction
  229. // guide names.
  230. TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
  231. if (!TD || !getAsTypeTemplateDecl(TD))
  232. return false;
  233. if (Template)
  234. *Template = TemplateTy::make(TemplateName(TD));
  235. return true;
  236. }
  237. bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
  238. SourceLocation IILoc,
  239. Scope *S,
  240. const CXXScopeSpec *SS,
  241. TemplateTy &SuggestedTemplate,
  242. TemplateNameKind &SuggestedKind) {
  243. // We can't recover unless there's a dependent scope specifier preceding the
  244. // template name.
  245. // FIXME: Typo correction?
  246. if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
  247. computeDeclContext(*SS))
  248. return false;
  249. // The code is missing a 'template' keyword prior to the dependent template
  250. // name.
  251. NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
  252. Diag(IILoc, diag::err_template_kw_missing)
  253. << Qualifier << II.getName()
  254. << FixItHint::CreateInsertion(IILoc, "template ");
  255. SuggestedTemplate
  256. = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
  257. SuggestedKind = TNK_Dependent_template_name;
  258. return true;
  259. }
  260. void Sema::LookupTemplateName(LookupResult &Found,
  261. Scope *S, CXXScopeSpec &SS,
  262. QualType ObjectType,
  263. bool EnteringContext,
  264. bool &MemberOfUnknownSpecialization) {
  265. // Determine where to perform name lookup
  266. MemberOfUnknownSpecialization = false;
  267. DeclContext *LookupCtx = nullptr;
  268. bool isDependent = false;
  269. if (!ObjectType.isNull()) {
  270. // This nested-name-specifier occurs in a member access expression, e.g.,
  271. // x->B::f, and we are looking into the type of the object.
  272. assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
  273. LookupCtx = computeDeclContext(ObjectType);
  274. isDependent = ObjectType->isDependentType();
  275. assert((isDependent || !ObjectType->isIncompleteType() ||
  276. ObjectType->castAs<TagType>()->isBeingDefined()) &&
  277. "Caller should have completed object type");
  278. // Template names cannot appear inside an Objective-C class or object type.
  279. if (ObjectType->isObjCObjectOrInterfaceType()) {
  280. Found.clear();
  281. return;
  282. }
  283. } else if (SS.isSet()) {
  284. // This nested-name-specifier occurs after another nested-name-specifier,
  285. // so long into the context associated with the prior nested-name-specifier.
  286. LookupCtx = computeDeclContext(SS, EnteringContext);
  287. isDependent = isDependentScopeSpecifier(SS);
  288. // The declaration context must be complete.
  289. if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
  290. return;
  291. }
  292. bool ObjectTypeSearchedInScope = false;
  293. bool AllowFunctionTemplatesInLookup = true;
  294. if (LookupCtx) {
  295. // Perform "qualified" name lookup into the declaration context we
  296. // computed, which is either the type of the base of a member access
  297. // expression or the declaration context associated with a prior
  298. // nested-name-specifier.
  299. LookupQualifiedName(Found, LookupCtx);
  300. if (!ObjectType.isNull() && Found.empty()) {
  301. // C++ [basic.lookup.classref]p1:
  302. // In a class member access expression (5.2.5), if the . or -> token is
  303. // immediately followed by an identifier followed by a <, the
  304. // identifier must be looked up to determine whether the < is the
  305. // beginning of a template argument list (14.2) or a less-than operator.
  306. // The identifier is first looked up in the class of the object
  307. // expression. If the identifier is not found, it is then looked up in
  308. // the context of the entire postfix-expression and shall name a class
  309. // or function template.
  310. if (S) LookupName(Found, S);
  311. ObjectTypeSearchedInScope = true;
  312. AllowFunctionTemplatesInLookup = false;
  313. }
  314. } else if (isDependent && (!S || ObjectType.isNull())) {
  315. // We cannot look into a dependent object type or nested nme
  316. // specifier.
  317. MemberOfUnknownSpecialization = true;
  318. return;
  319. } else {
  320. // Perform unqualified name lookup in the current scope.
  321. LookupName(Found, S);
  322. if (!ObjectType.isNull())
  323. AllowFunctionTemplatesInLookup = false;
  324. }
  325. if (Found.empty() && !isDependent) {
  326. // If we did not find any names, attempt to correct any typos.
  327. DeclarationName Name = Found.getLookupName();
  328. Found.clear();
  329. // Simple filter callback that, for keywords, only accepts the C++ *_cast
  330. auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
  331. FilterCCC->WantTypeSpecifiers = false;
  332. FilterCCC->WantExpressionKeywords = false;
  333. FilterCCC->WantRemainingKeywords = false;
  334. FilterCCC->WantCXXNamedCasts = true;
  335. if (TypoCorrection Corrected = CorrectTypo(
  336. Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
  337. std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
  338. Found.setLookupName(Corrected.getCorrection());
  339. if (auto *ND = Corrected.getFoundDecl())
  340. Found.addDecl(ND);
  341. FilterAcceptableTemplateNames(Found);
  342. if (!Found.empty()) {
  343. if (LookupCtx) {
  344. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  345. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  346. Name.getAsString() == CorrectedStr;
  347. diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
  348. << Name << LookupCtx << DroppedSpecifier
  349. << SS.getRange());
  350. } else {
  351. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
  352. }
  353. }
  354. } else {
  355. Found.setLookupName(Name);
  356. }
  357. }
  358. FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
  359. if (Found.empty()) {
  360. if (isDependent)
  361. MemberOfUnknownSpecialization = true;
  362. return;
  363. }
  364. if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
  365. !getLangOpts().CPlusPlus11) {
  366. // C++03 [basic.lookup.classref]p1:
  367. // [...] If the lookup in the class of the object expression finds a
  368. // template, the name is also looked up in the context of the entire
  369. // postfix-expression and [...]
  370. //
  371. // Note: C++11 does not perform this second lookup.
  372. LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
  373. LookupOrdinaryName);
  374. LookupName(FoundOuter, S);
  375. FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
  376. if (FoundOuter.empty()) {
  377. // - if the name is not found, the name found in the class of the
  378. // object expression is used, otherwise
  379. } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
  380. FoundOuter.isAmbiguous()) {
  381. // - if the name is found in the context of the entire
  382. // postfix-expression and does not name a class template, the name
  383. // found in the class of the object expression is used, otherwise
  384. FoundOuter.clear();
  385. } else if (!Found.isSuppressingDiagnostics()) {
  386. // - if the name found is a class template, it must refer to the same
  387. // entity as the one found in the class of the object expression,
  388. // otherwise the program is ill-formed.
  389. if (!Found.isSingleResult() ||
  390. Found.getFoundDecl()->getCanonicalDecl()
  391. != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
  392. Diag(Found.getNameLoc(),
  393. diag::ext_nested_name_member_ref_lookup_ambiguous)
  394. << Found.getLookupName()
  395. << ObjectType;
  396. Diag(Found.getRepresentativeDecl()->getLocation(),
  397. diag::note_ambig_member_ref_object_type)
  398. << ObjectType;
  399. Diag(FoundOuter.getFoundDecl()->getLocation(),
  400. diag::note_ambig_member_ref_scope);
  401. // Recover by taking the template that we found in the object
  402. // expression's type.
  403. }
  404. }
  405. }
  406. }
  407. /// ActOnDependentIdExpression - Handle a dependent id-expression that
  408. /// was just parsed. This is only possible with an explicit scope
  409. /// specifier naming a dependent type.
  410. ExprResult
  411. Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
  412. SourceLocation TemplateKWLoc,
  413. const DeclarationNameInfo &NameInfo,
  414. bool isAddressOfOperand,
  415. const TemplateArgumentListInfo *TemplateArgs) {
  416. DeclContext *DC = getFunctionLevelDeclContext();
  417. // C++11 [expr.prim.general]p12:
  418. // An id-expression that denotes a non-static data member or non-static
  419. // member function of a class can only be used:
  420. // (...)
  421. // - if that id-expression denotes a non-static data member and it
  422. // appears in an unevaluated operand.
  423. //
  424. // If this might be the case, form a DependentScopeDeclRefExpr instead of a
  425. // CXXDependentScopeMemberExpr. The former can instantiate to either
  426. // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
  427. // always a MemberExpr.
  428. bool MightBeCxx11UnevalField =
  429. getLangOpts().CPlusPlus11 && isUnevaluatedContext();
  430. // Check if the nested name specifier is an enum type.
  431. bool IsEnum = false;
  432. if (NestedNameSpecifier *NNS = SS.getScopeRep())
  433. IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
  434. if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
  435. isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
  436. QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
  437. // Since the 'this' expression is synthesized, we don't need to
  438. // perform the double-lookup check.
  439. NamedDecl *FirstQualifierInScope = nullptr;
  440. return CXXDependentScopeMemberExpr::Create(
  441. Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
  442. /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
  443. FirstQualifierInScope, NameInfo, TemplateArgs);
  444. }
  445. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  446. }
  447. ExprResult
  448. Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
  449. SourceLocation TemplateKWLoc,
  450. const DeclarationNameInfo &NameInfo,
  451. const TemplateArgumentListInfo *TemplateArgs) {
  452. return DependentScopeDeclRefExpr::Create(
  453. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  454. TemplateArgs);
  455. }
  456. /// Determine whether we would be unable to instantiate this template (because
  457. /// it either has no definition, or is in the process of being instantiated).
  458. bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
  459. NamedDecl *Instantiation,
  460. bool InstantiatedFromMember,
  461. const NamedDecl *Pattern,
  462. const NamedDecl *PatternDef,
  463. TemplateSpecializationKind TSK,
  464. bool Complain /*= true*/) {
  465. assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
  466. isa<VarDecl>(Instantiation));
  467. bool IsEntityBeingDefined = false;
  468. if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
  469. IsEntityBeingDefined = TD->isBeingDefined();
  470. if (PatternDef && !IsEntityBeingDefined) {
  471. NamedDecl *SuggestedDef = nullptr;
  472. if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
  473. /*OnlyNeedComplete*/false)) {
  474. // If we're allowed to diagnose this and recover, do so.
  475. bool Recover = Complain && !isSFINAEContext();
  476. if (Complain)
  477. diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
  478. Sema::MissingImportKind::Definition, Recover);
  479. return !Recover;
  480. }
  481. return false;
  482. }
  483. if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
  484. return true;
  485. llvm::Optional<unsigned> Note;
  486. QualType InstantiationTy;
  487. if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
  488. InstantiationTy = Context.getTypeDeclType(TD);
  489. if (PatternDef) {
  490. Diag(PointOfInstantiation,
  491. diag::err_template_instantiate_within_definition)
  492. << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
  493. << InstantiationTy;
  494. // Not much point in noting the template declaration here, since
  495. // we're lexically inside it.
  496. Instantiation->setInvalidDecl();
  497. } else if (InstantiatedFromMember) {
  498. if (isa<FunctionDecl>(Instantiation)) {
  499. Diag(PointOfInstantiation,
  500. diag::err_explicit_instantiation_undefined_member)
  501. << /*member function*/ 1 << Instantiation->getDeclName()
  502. << Instantiation->getDeclContext();
  503. Note = diag::note_explicit_instantiation_here;
  504. } else {
  505. assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
  506. Diag(PointOfInstantiation,
  507. diag::err_implicit_instantiate_member_undefined)
  508. << InstantiationTy;
  509. Note = diag::note_member_declared_at;
  510. }
  511. } else {
  512. if (isa<FunctionDecl>(Instantiation)) {
  513. Diag(PointOfInstantiation,
  514. diag::err_explicit_instantiation_undefined_func_template)
  515. << Pattern;
  516. Note = diag::note_explicit_instantiation_here;
  517. } else if (isa<TagDecl>(Instantiation)) {
  518. Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
  519. << (TSK != TSK_ImplicitInstantiation)
  520. << InstantiationTy;
  521. Note = diag::note_template_decl_here;
  522. } else {
  523. assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
  524. if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
  525. Diag(PointOfInstantiation,
  526. diag::err_explicit_instantiation_undefined_var_template)
  527. << Instantiation;
  528. Instantiation->setInvalidDecl();
  529. } else
  530. Diag(PointOfInstantiation,
  531. diag::err_explicit_instantiation_undefined_member)
  532. << /*static data member*/ 2 << Instantiation->getDeclName()
  533. << Instantiation->getDeclContext();
  534. Note = diag::note_explicit_instantiation_here;
  535. }
  536. }
  537. if (Note) // Diagnostics were emitted.
  538. Diag(Pattern->getLocation(), Note.getValue());
  539. // In general, Instantiation isn't marked invalid to get more than one
  540. // error for multiple undefined instantiations. But the code that does
  541. // explicit declaration -> explicit definition conversion can't handle
  542. // invalid declarations, so mark as invalid in that case.
  543. if (TSK == TSK_ExplicitInstantiationDeclaration)
  544. Instantiation->setInvalidDecl();
  545. return true;
  546. }
  547. /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
  548. /// that the template parameter 'PrevDecl' is being shadowed by a new
  549. /// declaration at location Loc. Returns true to indicate that this is
  550. /// an error, and false otherwise.
  551. void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
  552. assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
  553. // Microsoft Visual C++ permits template parameters to be shadowed.
  554. if (getLangOpts().MicrosoftExt)
  555. return;
  556. // C++ [temp.local]p4:
  557. // A template-parameter shall not be redeclared within its
  558. // scope (including nested scopes).
  559. Diag(Loc, diag::err_template_param_shadow)
  560. << cast<NamedDecl>(PrevDecl)->getDeclName();
  561. Diag(PrevDecl->getLocation(), diag::note_template_param_here);
  562. }
  563. /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
  564. /// the parameter D to reference the templated declaration and return a pointer
  565. /// to the template declaration. Otherwise, do nothing to D and return null.
  566. TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
  567. if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
  568. D = Temp->getTemplatedDecl();
  569. return Temp;
  570. }
  571. return nullptr;
  572. }
  573. ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
  574. SourceLocation EllipsisLoc) const {
  575. assert(Kind == Template &&
  576. "Only template template arguments can be pack expansions here");
  577. assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
  578. "Template template argument pack expansion without packs");
  579. ParsedTemplateArgument Result(*this);
  580. Result.EllipsisLoc = EllipsisLoc;
  581. return Result;
  582. }
  583. static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
  584. const ParsedTemplateArgument &Arg) {
  585. switch (Arg.getKind()) {
  586. case ParsedTemplateArgument::Type: {
  587. TypeSourceInfo *DI;
  588. QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
  589. if (!DI)
  590. DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
  591. return TemplateArgumentLoc(TemplateArgument(T), DI);
  592. }
  593. case ParsedTemplateArgument::NonType: {
  594. Expr *E = static_cast<Expr *>(Arg.getAsExpr());
  595. return TemplateArgumentLoc(TemplateArgument(E), E);
  596. }
  597. case ParsedTemplateArgument::Template: {
  598. TemplateName Template = Arg.getAsTemplate().get();
  599. TemplateArgument TArg;
  600. if (Arg.getEllipsisLoc().isValid())
  601. TArg = TemplateArgument(Template, Optional<unsigned int>());
  602. else
  603. TArg = Template;
  604. return TemplateArgumentLoc(TArg,
  605. Arg.getScopeSpec().getWithLocInContext(
  606. SemaRef.Context),
  607. Arg.getLocation(),
  608. Arg.getEllipsisLoc());
  609. }
  610. }
  611. llvm_unreachable("Unhandled parsed template argument");
  612. }
  613. /// \brief Translates template arguments as provided by the parser
  614. /// into template arguments used by semantic analysis.
  615. void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
  616. TemplateArgumentListInfo &TemplateArgs) {
  617. for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
  618. TemplateArgs.addArgument(translateTemplateArgument(*this,
  619. TemplateArgsIn[I]));
  620. }
  621. static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
  622. SourceLocation Loc,
  623. IdentifierInfo *Name) {
  624. NamedDecl *PrevDecl = SemaRef.LookupSingleName(
  625. S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  626. if (PrevDecl && PrevDecl->isTemplateParameter())
  627. SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
  628. }
  629. /// ActOnTypeParameter - Called when a C++ template type parameter
  630. /// (e.g., "typename T") has been parsed. Typename specifies whether
  631. /// the keyword "typename" was used to declare the type parameter
  632. /// (otherwise, "class" was used), and KeyLoc is the location of the
  633. /// "class" or "typename" keyword. ParamName is the name of the
  634. /// parameter (NULL indicates an unnamed template parameter) and
  635. /// ParamNameLoc is the location of the parameter name (if any).
  636. /// If the type parameter has a default argument, it will be added
  637. /// later via ActOnTypeParameterDefault.
  638. Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
  639. SourceLocation EllipsisLoc,
  640. SourceLocation KeyLoc,
  641. IdentifierInfo *ParamName,
  642. SourceLocation ParamNameLoc,
  643. unsigned Depth, unsigned Position,
  644. SourceLocation EqualLoc,
  645. ParsedType DefaultArg) {
  646. assert(S->isTemplateParamScope() &&
  647. "Template type parameter not in template parameter scope!");
  648. SourceLocation Loc = ParamNameLoc;
  649. if (!ParamName)
  650. Loc = KeyLoc;
  651. bool IsParameterPack = EllipsisLoc.isValid();
  652. TemplateTypeParmDecl *Param
  653. = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  654. KeyLoc, Loc, Depth, Position, ParamName,
  655. Typename, IsParameterPack);
  656. Param->setAccess(AS_public);
  657. if (ParamName) {
  658. maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
  659. // Add the template parameter into the current scope.
  660. S->AddDecl(Param);
  661. IdResolver.AddDecl(Param);
  662. }
  663. // C++0x [temp.param]p9:
  664. // A default template-argument may be specified for any kind of
  665. // template-parameter that is not a template parameter pack.
  666. if (DefaultArg && IsParameterPack) {
  667. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  668. DefaultArg = nullptr;
  669. }
  670. // Handle the default argument, if provided.
  671. if (DefaultArg) {
  672. TypeSourceInfo *DefaultTInfo;
  673. GetTypeFromParser(DefaultArg, &DefaultTInfo);
  674. assert(DefaultTInfo && "expected source information for type");
  675. // Check for unexpanded parameter packs.
  676. if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
  677. UPPC_DefaultArgument))
  678. return Param;
  679. // Check the template argument itself.
  680. if (CheckTemplateArgument(Param, DefaultTInfo)) {
  681. Param->setInvalidDecl();
  682. return Param;
  683. }
  684. Param->setDefaultArgument(DefaultTInfo);
  685. }
  686. return Param;
  687. }
  688. /// \brief Check that the type of a non-type template parameter is
  689. /// well-formed.
  690. ///
  691. /// \returns the (possibly-promoted) parameter type if valid;
  692. /// otherwise, produces a diagnostic and returns a NULL type.
  693. QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
  694. SourceLocation Loc) {
  695. if (TSI->getType()->isUndeducedType()) {
  696. // C++1z [temp.dep.expr]p3:
  697. // An id-expression is type-dependent if it contains
  698. // - an identifier associated by name lookup with a non-type
  699. // template-parameter declared with a type that contains a
  700. // placeholder type (7.1.7.4),
  701. TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
  702. }
  703. return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
  704. }
  705. QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
  706. SourceLocation Loc) {
  707. // We don't allow variably-modified types as the type of non-type template
  708. // parameters.
  709. if (T->isVariablyModifiedType()) {
  710. Diag(Loc, diag::err_variably_modified_nontype_template_param)
  711. << T;
  712. return QualType();
  713. }
  714. // C++ [temp.param]p4:
  715. //
  716. // A non-type template-parameter shall have one of the following
  717. // (optionally cv-qualified) types:
  718. //
  719. // -- integral or enumeration type,
  720. if (T->isIntegralOrEnumerationType() ||
  721. // -- pointer to object or pointer to function,
  722. T->isPointerType() ||
  723. // -- reference to object or reference to function,
  724. T->isReferenceType() ||
  725. // -- pointer to member,
  726. T->isMemberPointerType() ||
  727. // -- std::nullptr_t.
  728. T->isNullPtrType() ||
  729. // If T is a dependent type, we can't do the check now, so we
  730. // assume that it is well-formed.
  731. T->isDependentType() ||
  732. // Allow use of auto in template parameter declarations.
  733. T->isUndeducedType()) {
  734. // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
  735. // are ignored when determining its type.
  736. return T.getUnqualifiedType();
  737. }
  738. // C++ [temp.param]p8:
  739. //
  740. // A non-type template-parameter of type "array of T" or
  741. // "function returning T" is adjusted to be of type "pointer to
  742. // T" or "pointer to function returning T", respectively.
  743. else if (T->isArrayType() || T->isFunctionType())
  744. return Context.getDecayedType(T);
  745. Diag(Loc, diag::err_template_nontype_parm_bad_type)
  746. << T;
  747. return QualType();
  748. }
  749. Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
  750. unsigned Depth,
  751. unsigned Position,
  752. SourceLocation EqualLoc,
  753. Expr *Default) {
  754. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  755. if (TInfo->getType()->isUndeducedType()) {
  756. Diag(D.getIdentifierLoc(),
  757. diag::warn_cxx14_compat_template_nontype_parm_auto_type)
  758. << QualType(TInfo->getType()->getContainedAutoType(), 0);
  759. }
  760. assert(S->isTemplateParamScope() &&
  761. "Non-type template parameter not in template parameter scope!");
  762. bool Invalid = false;
  763. QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
  764. if (T.isNull()) {
  765. T = Context.IntTy; // Recover with an 'int' type.
  766. Invalid = true;
  767. }
  768. IdentifierInfo *ParamName = D.getIdentifier();
  769. bool IsParameterPack = D.hasEllipsis();
  770. NonTypeTemplateParmDecl *Param
  771. = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  772. D.getLocStart(),
  773. D.getIdentifierLoc(),
  774. Depth, Position, ParamName, T,
  775. IsParameterPack, TInfo);
  776. Param->setAccess(AS_public);
  777. if (Invalid)
  778. Param->setInvalidDecl();
  779. if (ParamName) {
  780. maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
  781. ParamName);
  782. // Add the template parameter into the current scope.
  783. S->AddDecl(Param);
  784. IdResolver.AddDecl(Param);
  785. }
  786. // C++0x [temp.param]p9:
  787. // A default template-argument may be specified for any kind of
  788. // template-parameter that is not a template parameter pack.
  789. if (Default && IsParameterPack) {
  790. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  791. Default = nullptr;
  792. }
  793. // Check the well-formedness of the default template argument, if provided.
  794. if (Default) {
  795. // Check for unexpanded parameter packs.
  796. if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
  797. return Param;
  798. TemplateArgument Converted;
  799. ExprResult DefaultRes =
  800. CheckTemplateArgument(Param, Param->getType(), Default, Converted);
  801. if (DefaultRes.isInvalid()) {
  802. Param->setInvalidDecl();
  803. return Param;
  804. }
  805. Default = DefaultRes.get();
  806. Param->setDefaultArgument(Default);
  807. }
  808. return Param;
  809. }
  810. /// ActOnTemplateTemplateParameter - Called when a C++ template template
  811. /// parameter (e.g. T in template <template \<typename> class T> class array)
  812. /// has been parsed. S is the current scope.
  813. Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
  814. SourceLocation TmpLoc,
  815. TemplateParameterList *Params,
  816. SourceLocation EllipsisLoc,
  817. IdentifierInfo *Name,
  818. SourceLocation NameLoc,
  819. unsigned Depth,
  820. unsigned Position,
  821. SourceLocation EqualLoc,
  822. ParsedTemplateArgument Default) {
  823. assert(S->isTemplateParamScope() &&
  824. "Template template parameter not in template parameter scope!");
  825. // Construct the parameter object.
  826. bool IsParameterPack = EllipsisLoc.isValid();
  827. TemplateTemplateParmDecl *Param =
  828. TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  829. NameLoc.isInvalid()? TmpLoc : NameLoc,
  830. Depth, Position, IsParameterPack,
  831. Name, Params);
  832. Param->setAccess(AS_public);
  833. // If the template template parameter has a name, then link the identifier
  834. // into the scope and lookup mechanisms.
  835. if (Name) {
  836. maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
  837. S->AddDecl(Param);
  838. IdResolver.AddDecl(Param);
  839. }
  840. if (Params->size() == 0) {
  841. Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
  842. << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
  843. Param->setInvalidDecl();
  844. }
  845. // C++0x [temp.param]p9:
  846. // A default template-argument may be specified for any kind of
  847. // template-parameter that is not a template parameter pack.
  848. if (IsParameterPack && !Default.isInvalid()) {
  849. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  850. Default = ParsedTemplateArgument();
  851. }
  852. if (!Default.isInvalid()) {
  853. // Check only that we have a template template argument. We don't want to
  854. // try to check well-formedness now, because our template template parameter
  855. // might have dependent types in its template parameters, which we wouldn't
  856. // be able to match now.
  857. //
  858. // If none of the template template parameter's template arguments mention
  859. // other template parameters, we could actually perform more checking here.
  860. // However, it isn't worth doing.
  861. TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
  862. if (DefaultArg.getArgument().getAsTemplate().isNull()) {
  863. Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
  864. << DefaultArg.getSourceRange();
  865. return Param;
  866. }
  867. // Check for unexpanded parameter packs.
  868. if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
  869. DefaultArg.getArgument().getAsTemplate(),
  870. UPPC_DefaultArgument))
  871. return Param;
  872. Param->setDefaultArgument(Context, DefaultArg);
  873. }
  874. return Param;
  875. }
  876. /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
  877. /// constrained by RequiresClause, that contains the template parameters in
  878. /// Params.
  879. TemplateParameterList *
  880. Sema::ActOnTemplateParameterList(unsigned Depth,
  881. SourceLocation ExportLoc,
  882. SourceLocation TemplateLoc,
  883. SourceLocation LAngleLoc,
  884. ArrayRef<Decl *> Params,
  885. SourceLocation RAngleLoc,
  886. Expr *RequiresClause) {
  887. if (ExportLoc.isValid())
  888. Diag(ExportLoc, diag::warn_template_export_unsupported);
  889. return TemplateParameterList::Create(
  890. Context, TemplateLoc, LAngleLoc,
  891. llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
  892. RAngleLoc, RequiresClause);
  893. }
  894. static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
  895. if (SS.isSet())
  896. T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
  897. }
  898. DeclResult
  899. Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
  900. SourceLocation KWLoc, CXXScopeSpec &SS,
  901. IdentifierInfo *Name, SourceLocation NameLoc,
  902. AttributeList *Attr,
  903. TemplateParameterList *TemplateParams,
  904. AccessSpecifier AS, SourceLocation ModulePrivateLoc,
  905. SourceLocation FriendLoc,
  906. unsigned NumOuterTemplateParamLists,
  907. TemplateParameterList** OuterTemplateParamLists,
  908. SkipBodyInfo *SkipBody) {
  909. assert(TemplateParams && TemplateParams->size() > 0 &&
  910. "No template parameters");
  911. assert(TUK != TUK_Reference && "Can only declare or define class templates");
  912. bool Invalid = false;
  913. // Check that we can declare a template here.
  914. if (CheckTemplateDeclScope(S, TemplateParams))
  915. return true;
  916. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  917. assert(Kind != TTK_Enum && "can't build template of enumerated type");
  918. // There is no such thing as an unnamed class template.
  919. if (!Name) {
  920. Diag(KWLoc, diag::err_template_unnamed_class);
  921. return true;
  922. }
  923. // Find any previous declaration with this name. For a friend with no
  924. // scope explicitly specified, we only look for tag declarations (per
  925. // C++11 [basic.lookup.elab]p2).
  926. DeclContext *SemanticContext;
  927. LookupResult Previous(*this, Name, NameLoc,
  928. (SS.isEmpty() && TUK == TUK_Friend)
  929. ? LookupTagName : LookupOrdinaryName,
  930. ForRedeclaration);
  931. if (SS.isNotEmpty() && !SS.isInvalid()) {
  932. SemanticContext = computeDeclContext(SS, true);
  933. if (!SemanticContext) {
  934. // FIXME: Horrible, horrible hack! We can't currently represent this
  935. // in the AST, and historically we have just ignored such friend
  936. // class templates, so don't complain here.
  937. Diag(NameLoc, TUK == TUK_Friend
  938. ? diag::warn_template_qualified_friend_ignored
  939. : diag::err_template_qualified_declarator_no_match)
  940. << SS.getScopeRep() << SS.getRange();
  941. return TUK != TUK_Friend;
  942. }
  943. if (RequireCompleteDeclContext(SS, SemanticContext))
  944. return true;
  945. // If we're adding a template to a dependent context, we may need to
  946. // rebuilding some of the types used within the template parameter list,
  947. // now that we know what the current instantiation is.
  948. if (SemanticContext->isDependentContext()) {
  949. ContextRAII SavedContext(*this, SemanticContext);
  950. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  951. Invalid = true;
  952. } else if (TUK != TUK_Friend && TUK != TUK_Reference)
  953. diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
  954. LookupQualifiedName(Previous, SemanticContext);
  955. } else {
  956. SemanticContext = CurContext;
  957. // C++14 [class.mem]p14:
  958. // If T is the name of a class, then each of the following shall have a
  959. // name different from T:
  960. // -- every member template of class T
  961. if (TUK != TUK_Friend &&
  962. DiagnoseClassNameShadow(SemanticContext,
  963. DeclarationNameInfo(Name, NameLoc)))
  964. return true;
  965. LookupName(Previous, S);
  966. }
  967. if (Previous.isAmbiguous())
  968. return true;
  969. NamedDecl *PrevDecl = nullptr;
  970. if (Previous.begin() != Previous.end())
  971. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  972. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  973. // Maybe we will complain about the shadowed template parameter.
  974. DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
  975. // Just pretend that we didn't see the previous declaration.
  976. PrevDecl = nullptr;
  977. }
  978. // If there is a previous declaration with the same name, check
  979. // whether this is a valid redeclaration.
  980. ClassTemplateDecl *PrevClassTemplate
  981. = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
  982. // We may have found the injected-class-name of a class template,
  983. // class template partial specialization, or class template specialization.
  984. // In these cases, grab the template that is being defined or specialized.
  985. if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
  986. cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
  987. PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
  988. PrevClassTemplate
  989. = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
  990. if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
  991. PrevClassTemplate
  992. = cast<ClassTemplateSpecializationDecl>(PrevDecl)
  993. ->getSpecializedTemplate();
  994. }
  995. }
  996. if (TUK == TUK_Friend) {
  997. // C++ [namespace.memdef]p3:
  998. // [...] When looking for a prior declaration of a class or a function
  999. // declared as a friend, and when the name of the friend class or
  1000. // function is neither a qualified name nor a template-id, scopes outside
  1001. // the innermost enclosing namespace scope are not considered.
  1002. if (!SS.isSet()) {
  1003. DeclContext *OutermostContext = CurContext;
  1004. while (!OutermostContext->isFileContext())
  1005. OutermostContext = OutermostContext->getLookupParent();
  1006. if (PrevDecl &&
  1007. (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
  1008. OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
  1009. SemanticContext = PrevDecl->getDeclContext();
  1010. } else {
  1011. // Declarations in outer scopes don't matter. However, the outermost
  1012. // context we computed is the semantic context for our new
  1013. // declaration.
  1014. PrevDecl = PrevClassTemplate = nullptr;
  1015. SemanticContext = OutermostContext;
  1016. // Check that the chosen semantic context doesn't already contain a
  1017. // declaration of this name as a non-tag type.
  1018. Previous.clear(LookupOrdinaryName);
  1019. DeclContext *LookupContext = SemanticContext;
  1020. while (LookupContext->isTransparentContext())
  1021. LookupContext = LookupContext->getLookupParent();
  1022. LookupQualifiedName(Previous, LookupContext);
  1023. if (Previous.isAmbiguous())
  1024. return true;
  1025. if (Previous.begin() != Previous.end())
  1026. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1027. }
  1028. }
  1029. } else if (PrevDecl &&
  1030. !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
  1031. S, SS.isValid()))
  1032. PrevDecl = PrevClassTemplate = nullptr;
  1033. if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
  1034. PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
  1035. if (SS.isEmpty() &&
  1036. !(PrevClassTemplate &&
  1037. PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
  1038. SemanticContext->getRedeclContext()))) {
  1039. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  1040. Diag(Shadow->getTargetDecl()->getLocation(),
  1041. diag::note_using_decl_target);
  1042. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  1043. // Recover by ignoring the old declaration.
  1044. PrevDecl = PrevClassTemplate = nullptr;
  1045. }
  1046. }
  1047. // TODO Memory management; associated constraints are not always stored.
  1048. Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
  1049. if (PrevClassTemplate) {
  1050. // Ensure that the template parameter lists are compatible. Skip this check
  1051. // for a friend in a dependent context: the template parameter list itself
  1052. // could be dependent.
  1053. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1054. !TemplateParameterListsAreEqual(TemplateParams,
  1055. PrevClassTemplate->getTemplateParameters(),
  1056. /*Complain=*/true,
  1057. TPL_TemplateMatch))
  1058. return true;
  1059. // Check for matching associated constraints on redeclarations.
  1060. const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
  1061. const bool RedeclACMismatch = [&] {
  1062. if (!(CurAC || PrevAC))
  1063. return false; // Nothing to check; no mismatch.
  1064. if (CurAC && PrevAC) {
  1065. llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
  1066. CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
  1067. PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
  1068. if (CurACInfo == PrevACInfo)
  1069. return false; // All good; no mismatch.
  1070. }
  1071. return true;
  1072. }();
  1073. if (RedeclACMismatch) {
  1074. Diag(CurAC ? CurAC->getLocStart() : NameLoc,
  1075. diag::err_template_different_associated_constraints);
  1076. Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
  1077. diag::note_template_prev_declaration) << /*declaration*/0;
  1078. return true;
  1079. }
  1080. // C++ [temp.class]p4:
  1081. // In a redeclaration, partial specialization, explicit
  1082. // specialization or explicit instantiation of a class template,
  1083. // the class-key shall agree in kind with the original class
  1084. // template declaration (7.1.5.3).
  1085. RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
  1086. if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
  1087. TUK == TUK_Definition, KWLoc, Name)) {
  1088. Diag(KWLoc, diag::err_use_with_wrong_tag)
  1089. << Name
  1090. << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
  1091. Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
  1092. Kind = PrevRecordDecl->getTagKind();
  1093. }
  1094. // Check for redefinition of this class template.
  1095. if (TUK == TUK_Definition) {
  1096. if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
  1097. // If we have a prior definition that is not visible, treat this as
  1098. // simply making that previous definition visible.
  1099. NamedDecl *Hidden = nullptr;
  1100. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  1101. SkipBody->ShouldSkip = true;
  1102. auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
  1103. assert(Tmpl && "original definition of a class template is not a "
  1104. "class template?");
  1105. makeMergedDefinitionVisible(Hidden, KWLoc);
  1106. makeMergedDefinitionVisible(Tmpl, KWLoc);
  1107. return Def;
  1108. }
  1109. Diag(NameLoc, diag::err_redefinition) << Name;
  1110. Diag(Def->getLocation(), diag::note_previous_definition);
  1111. // FIXME: Would it make sense to try to "forget" the previous
  1112. // definition, as part of error recovery?
  1113. return true;
  1114. }
  1115. }
  1116. } else if (PrevDecl) {
  1117. // C++ [temp]p5:
  1118. // A class template shall not have the same name as any other
  1119. // template, class, function, object, enumeration, enumerator,
  1120. // namespace, or type in the same scope (3.3), except as specified
  1121. // in (14.5.4).
  1122. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  1123. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1124. return true;
  1125. }
  1126. // Check the template parameter list of this declaration, possibly
  1127. // merging in the template parameter list from the previous class
  1128. // template declaration. Skip this check for a friend in a dependent
  1129. // context, because the template parameter list might be dependent.
  1130. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1131. CheckTemplateParameterList(
  1132. TemplateParams,
  1133. PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
  1134. : nullptr,
  1135. (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
  1136. SemanticContext->isDependentContext())
  1137. ? TPC_ClassTemplateMember
  1138. : TUK == TUK_Friend ? TPC_FriendClassTemplate
  1139. : TPC_ClassTemplate))
  1140. Invalid = true;
  1141. if (SS.isSet()) {
  1142. // If the name of the template was qualified, we must be defining the
  1143. // template out-of-line.
  1144. if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
  1145. Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
  1146. : diag::err_member_decl_does_not_match)
  1147. << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
  1148. Invalid = true;
  1149. }
  1150. }
  1151. // If this is a templated friend in a dependent context we should not put it
  1152. // on the redecl chain. In some cases, the templated friend can be the most
  1153. // recent declaration tricking the template instantiator to make substitutions
  1154. // there.
  1155. // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
  1156. bool ShouldAddRedecl
  1157. = !(TUK == TUK_Friend && CurContext->isDependentContext());
  1158. CXXRecordDecl *NewClass =
  1159. CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
  1160. PrevClassTemplate && ShouldAddRedecl ?
  1161. PrevClassTemplate->getTemplatedDecl() : nullptr,
  1162. /*DelayTypeCreation=*/true);
  1163. SetNestedNameSpecifier(NewClass, SS);
  1164. if (NumOuterTemplateParamLists > 0)
  1165. NewClass->setTemplateParameterListsInfo(
  1166. Context, llvm::makeArrayRef(OuterTemplateParamLists,
  1167. NumOuterTemplateParamLists));
  1168. // Add alignment attributes if necessary; these attributes are checked when
  1169. // the ASTContext lays out the structure.
  1170. if (TUK == TUK_Definition) {
  1171. AddAlignmentAttributesForRecord(NewClass);
  1172. AddMsStructLayoutForRecord(NewClass);
  1173. }
  1174. // Attach the associated constraints when the declaration will not be part of
  1175. // a decl chain.
  1176. Expr *const ACtoAttach =
  1177. PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
  1178. ClassTemplateDecl *NewTemplate
  1179. = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
  1180. DeclarationName(Name), TemplateParams,
  1181. NewClass, ACtoAttach);
  1182. if (ShouldAddRedecl)
  1183. NewTemplate->setPreviousDecl(PrevClassTemplate);
  1184. NewClass->setDescribedClassTemplate(NewTemplate);
  1185. if (ModulePrivateLoc.isValid())
  1186. NewTemplate->setModulePrivate();
  1187. // Build the type for the class template declaration now.
  1188. QualType T = NewTemplate->getInjectedClassNameSpecialization();
  1189. T = Context.getInjectedClassNameType(NewClass, T);
  1190. assert(T->isDependentType() && "Class template type is not dependent?");
  1191. (void)T;
  1192. // If we are providing an explicit specialization of a member that is a
  1193. // class template, make a note of that.
  1194. if (PrevClassTemplate &&
  1195. PrevClassTemplate->getInstantiatedFromMemberTemplate())
  1196. PrevClassTemplate->setMemberSpecialization();
  1197. // Set the access specifier.
  1198. if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
  1199. SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
  1200. // Set the lexical context of these templates
  1201. NewClass->setLexicalDeclContext(CurContext);
  1202. NewTemplate->setLexicalDeclContext(CurContext);
  1203. if (TUK == TUK_Definition)
  1204. NewClass->startDefinition();
  1205. if (Attr)
  1206. ProcessDeclAttributeList(S, NewClass, Attr);
  1207. if (PrevClassTemplate)
  1208. mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
  1209. AddPushedVisibilityAttribute(NewClass);
  1210. if (TUK != TUK_Friend) {
  1211. // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
  1212. Scope *Outer = S;
  1213. while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
  1214. Outer = Outer->getParent();
  1215. PushOnScopeChains(NewTemplate, Outer);
  1216. } else {
  1217. if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
  1218. NewTemplate->setAccess(PrevClassTemplate->getAccess());
  1219. NewClass->setAccess(PrevClassTemplate->getAccess());
  1220. }
  1221. NewTemplate->setObjectOfFriendDecl();
  1222. // Friend templates are visible in fairly strange ways.
  1223. if (!CurContext->isDependentContext()) {
  1224. DeclContext *DC = SemanticContext->getRedeclContext();
  1225. DC->makeDeclVisibleInContext(NewTemplate);
  1226. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  1227. PushOnScopeChains(NewTemplate, EnclosingScope,
  1228. /* AddToContext = */ false);
  1229. }
  1230. FriendDecl *Friend = FriendDecl::Create(
  1231. Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
  1232. Friend->setAccess(AS_public);
  1233. CurContext->addDecl(Friend);
  1234. }
  1235. if (Invalid) {
  1236. NewTemplate->setInvalidDecl();
  1237. NewClass->setInvalidDecl();
  1238. }
  1239. ActOnDocumentableDecl(NewTemplate);
  1240. return NewTemplate;
  1241. }
  1242. namespace {
  1243. /// Transform to convert portions of a constructor declaration into the
  1244. /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
  1245. struct ConvertConstructorToDeductionGuideTransform {
  1246. ConvertConstructorToDeductionGuideTransform(Sema &S,
  1247. ClassTemplateDecl *Template)
  1248. : SemaRef(S), Template(Template) {}
  1249. Sema &SemaRef;
  1250. ClassTemplateDecl *Template;
  1251. DeclContext *DC = Template->getDeclContext();
  1252. CXXRecordDecl *Primary = Template->getTemplatedDecl();
  1253. DeclarationName DeductionGuideName =
  1254. SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
  1255. QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
  1256. // Index adjustment to apply to convert depth-1 template parameters into
  1257. // depth-0 template parameters.
  1258. unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
  1259. /// Transform a constructor declaration into a deduction guide.
  1260. NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
  1261. CXXConstructorDecl *CD) {
  1262. SmallVector<TemplateArgument, 16> SubstArgs;
  1263. // C++ [over.match.class.deduct]p1:
  1264. // -- For each constructor of the class template designated by the
  1265. // template-name, a function template with the following properties:
  1266. // -- The template parameters are the template parameters of the class
  1267. // template followed by the template parameters (including default
  1268. // template arguments) of the constructor, if any.
  1269. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  1270. if (FTD) {
  1271. TemplateParameterList *InnerParams = FTD->getTemplateParameters();
  1272. SmallVector<NamedDecl *, 16> AllParams;
  1273. AllParams.reserve(TemplateParams->size() + InnerParams->size());
  1274. AllParams.insert(AllParams.begin(),
  1275. TemplateParams->begin(), TemplateParams->end());
  1276. SubstArgs.reserve(InnerParams->size());
  1277. // Later template parameters could refer to earlier ones, so build up
  1278. // a list of substituted template arguments as we go.
  1279. for (NamedDecl *Param : *InnerParams) {
  1280. MultiLevelTemplateArgumentList Args;
  1281. Args.addOuterTemplateArguments(SubstArgs);
  1282. Args.addOuterTemplateArguments(None);
  1283. NamedDecl *NewParam = transformTemplateParameter(Param, Args);
  1284. if (!NewParam)
  1285. return nullptr;
  1286. AllParams.push_back(NewParam);
  1287. SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
  1288. SemaRef.Context.getInjectedTemplateArg(NewParam)));
  1289. }
  1290. TemplateParams = TemplateParameterList::Create(
  1291. SemaRef.Context, InnerParams->getTemplateLoc(),
  1292. InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
  1293. /*FIXME: RequiresClause*/ nullptr);
  1294. }
  1295. // If we built a new template-parameter-list, track that we need to
  1296. // substitute references to the old parameters into references to the
  1297. // new ones.
  1298. MultiLevelTemplateArgumentList Args;
  1299. if (FTD) {
  1300. Args.addOuterTemplateArguments(SubstArgs);
  1301. Args.addOuterTemplateArguments(None);
  1302. }
  1303. FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
  1304. .getAsAdjusted<FunctionProtoTypeLoc>();
  1305. assert(FPTL && "no prototype for constructor declaration");
  1306. // Transform the type of the function, adjusting the return type and
  1307. // replacing references to the old parameters with references to the
  1308. // new ones.
  1309. TypeLocBuilder TLB;
  1310. SmallVector<ParmVarDecl*, 8> Params;
  1311. QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
  1312. if (NewType.isNull())
  1313. return nullptr;
  1314. TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
  1315. return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
  1316. CD->getLocStart(), CD->getLocation(),
  1317. CD->getLocEnd());
  1318. }
  1319. /// Build a deduction guide with the specified parameter types.
  1320. NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
  1321. SourceLocation Loc = Template->getLocation();
  1322. // Build the requested type.
  1323. FunctionProtoType::ExtProtoInfo EPI;
  1324. EPI.HasTrailingReturn = true;
  1325. QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
  1326. DeductionGuideName, EPI);
  1327. TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
  1328. FunctionProtoTypeLoc FPTL =
  1329. TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
  1330. // Build the parameters, needed during deduction / substitution.
  1331. SmallVector<ParmVarDecl*, 4> Params;
  1332. for (auto T : ParamTypes) {
  1333. ParmVarDecl *NewParam = ParmVarDecl::Create(
  1334. SemaRef.Context, DC, Loc, Loc, nullptr, T,
  1335. SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
  1336. NewParam->setScopeInfo(0, Params.size());
  1337. FPTL.setParam(Params.size(), NewParam);
  1338. Params.push_back(NewParam);
  1339. }
  1340. return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
  1341. Loc, Loc, Loc);
  1342. }
  1343. private:
  1344. /// Transform a constructor template parameter into a deduction guide template
  1345. /// parameter, rebuilding any internal references to earlier parameters and
  1346. /// renumbering as we go.
  1347. NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
  1348. MultiLevelTemplateArgumentList &Args) {
  1349. if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
  1350. // TemplateTypeParmDecl's index cannot be changed after creation, so
  1351. // substitute it directly.
  1352. auto *NewTTP = TemplateTypeParmDecl::Create(
  1353. SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
  1354. /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
  1355. TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
  1356. TTP->isParameterPack());
  1357. if (TTP->hasDefaultArgument()) {
  1358. TypeSourceInfo *InstantiatedDefaultArg =
  1359. SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
  1360. TTP->getDefaultArgumentLoc(), TTP->getDeclName());
  1361. if (InstantiatedDefaultArg)
  1362. NewTTP->setDefaultArgument(InstantiatedDefaultArg);
  1363. }
  1364. return NewTTP;
  1365. }
  1366. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
  1367. return transformTemplateParameterImpl(TTP, Args);
  1368. return transformTemplateParameterImpl(
  1369. cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
  1370. }
  1371. template<typename TemplateParmDecl>
  1372. TemplateParmDecl *
  1373. transformTemplateParameterImpl(TemplateParmDecl *OldParam,
  1374. MultiLevelTemplateArgumentList &Args) {
  1375. // Ask the template instantiator to do the heavy lifting for us, then adjust
  1376. // the index of the parameter once it's done.
  1377. auto *NewParam =
  1378. cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
  1379. assert(NewParam->getDepth() == 0 && "unexpected template param depth");
  1380. NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
  1381. return NewParam;
  1382. }
  1383. QualType transformFunctionProtoType(TypeLocBuilder &TLB,
  1384. FunctionProtoTypeLoc TL,
  1385. SmallVectorImpl<ParmVarDecl*> &Params,
  1386. MultiLevelTemplateArgumentList &Args) {
  1387. SmallVector<QualType, 4> ParamTypes;
  1388. const FunctionProtoType *T = TL.getTypePtr();
  1389. // -- The types of the function parameters are those of the constructor.
  1390. for (auto *OldParam : TL.getParams()) {
  1391. ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
  1392. if (!NewParam)
  1393. return QualType();
  1394. ParamTypes.push_back(NewParam->getType());
  1395. Params.push_back(NewParam);
  1396. }
  1397. // -- The return type is the class template specialization designated by
  1398. // the template-name and template arguments corresponding to the
  1399. // template parameters obtained from the class template.
  1400. //
  1401. // We use the injected-class-name type of the primary template instead.
  1402. // This has the convenient property that it is different from any type that
  1403. // the user can write in a deduction-guide (because they cannot enter the
  1404. // context of the template), so implicit deduction guides can never collide
  1405. // with explicit ones.
  1406. QualType ReturnType = DeducedType;
  1407. TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
  1408. // Resolving a wording defect, we also inherit the variadicness of the
  1409. // constructor.
  1410. FunctionProtoType::ExtProtoInfo EPI;
  1411. EPI.Variadic = T->isVariadic();
  1412. EPI.HasTrailingReturn = true;
  1413. QualType Result = SemaRef.BuildFunctionType(
  1414. ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
  1415. if (Result.isNull())
  1416. return QualType();
  1417. FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
  1418. NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
  1419. NewTL.setLParenLoc(TL.getLParenLoc());
  1420. NewTL.setRParenLoc(TL.getRParenLoc());
  1421. NewTL.setExceptionSpecRange(SourceRange());
  1422. NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
  1423. for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
  1424. NewTL.setParam(I, Params[I]);
  1425. return Result;
  1426. }
  1427. ParmVarDecl *
  1428. transformFunctionTypeParam(ParmVarDecl *OldParam,
  1429. MultiLevelTemplateArgumentList &Args) {
  1430. TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
  1431. TypeSourceInfo *NewDI =
  1432. Args.getNumLevels()
  1433. ? SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
  1434. OldParam->getDeclName())
  1435. : OldDI;
  1436. if (!NewDI)
  1437. return nullptr;
  1438. // Canonicalize the type. This (for instance) replaces references to
  1439. // typedef members of the current instantiations with the definitions of
  1440. // those typedefs, avoiding triggering instantiation of the deduced type
  1441. // during deduction.
  1442. // FIXME: It would be preferable to retain type sugar and source
  1443. // information here (and handle this in substitution instead).
  1444. NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
  1445. SemaRef.Context.getCanonicalType(NewDI->getType()),
  1446. OldParam->getLocation());
  1447. // Resolving a wording defect, we also inherit default arguments from the
  1448. // constructor.
  1449. ExprResult NewDefArg;
  1450. if (OldParam->hasDefaultArg()) {
  1451. NewDefArg = Args.getNumLevels()
  1452. ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
  1453. : OldParam->getDefaultArg();
  1454. if (NewDefArg.isInvalid())
  1455. return nullptr;
  1456. }
  1457. ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
  1458. OldParam->getInnerLocStart(),
  1459. OldParam->getLocation(),
  1460. OldParam->getIdentifier(),
  1461. NewDI->getType(),
  1462. NewDI,
  1463. OldParam->getStorageClass(),
  1464. NewDefArg.get());
  1465. NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
  1466. OldParam->getFunctionScopeIndex());
  1467. return NewParam;
  1468. }
  1469. NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
  1470. bool Explicit, TypeSourceInfo *TInfo,
  1471. SourceLocation LocStart, SourceLocation Loc,
  1472. SourceLocation LocEnd) {
  1473. DeclarationNameInfo Name(DeductionGuideName, Loc);
  1474. ArrayRef<ParmVarDecl *> Params =
  1475. TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
  1476. // Build the implicit deduction guide template.
  1477. auto *Guide =
  1478. CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
  1479. Name, TInfo->getType(), TInfo, LocEnd);
  1480. Guide->setImplicit();
  1481. Guide->setParams(Params);
  1482. for (auto *Param : Params)
  1483. Param->setDeclContext(Guide);
  1484. auto *GuideTemplate = FunctionTemplateDecl::Create(
  1485. SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
  1486. GuideTemplate->setImplicit();
  1487. Guide->setDescribedFunctionTemplate(GuideTemplate);
  1488. if (isa<CXXRecordDecl>(DC)) {
  1489. Guide->setAccess(AS_public);
  1490. GuideTemplate->setAccess(AS_public);
  1491. }
  1492. DC->addDecl(GuideTemplate);
  1493. return GuideTemplate;
  1494. }
  1495. };
  1496. }
  1497. void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
  1498. SourceLocation Loc) {
  1499. DeclContext *DC = Template->getDeclContext();
  1500. if (DC->isDependentContext())
  1501. return;
  1502. ConvertConstructorToDeductionGuideTransform Transform(
  1503. *this, cast<ClassTemplateDecl>(Template));
  1504. if (!isCompleteType(Loc, Transform.DeducedType))
  1505. return;
  1506. // Check whether we've already declared deduction guides for this template.
  1507. // FIXME: Consider storing a flag on the template to indicate this.
  1508. auto Existing = DC->lookup(Transform.DeductionGuideName);
  1509. for (auto *D : Existing)
  1510. if (D->isImplicit())
  1511. return;
  1512. // In case we were expanding a pack when we attempted to declare deduction
  1513. // guides, turn off pack expansion for everything we're about to do.
  1514. ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  1515. // Create a template instantiation record to track the "instantiation" of
  1516. // constructors into deduction guides.
  1517. // FIXME: Add a kind for this to give more meaningful diagnostics. But can
  1518. // this substitution process actually fail?
  1519. InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
  1520. // Convert declared constructors into deduction guide templates.
  1521. // FIXME: Skip constructors for which deduction must necessarily fail (those
  1522. // for which some class template parameter without a default argument never
  1523. // appears in a deduced context).
  1524. bool AddedAny = false;
  1525. bool AddedCopyOrMove = false;
  1526. for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
  1527. D = D->getUnderlyingDecl();
  1528. if (D->isInvalidDecl() || D->isImplicit())
  1529. continue;
  1530. D = cast<NamedDecl>(D->getCanonicalDecl());
  1531. auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
  1532. auto *CD =
  1533. dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
  1534. // Class-scope explicit specializations (MS extension) do not result in
  1535. // deduction guides.
  1536. if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
  1537. continue;
  1538. Transform.transformConstructor(FTD, CD);
  1539. AddedAny = true;
  1540. AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
  1541. }
  1542. // Synthesize an X() -> X<...> guide if there were no declared constructors.
  1543. // FIXME: The standard doesn't say (how) to do this.
  1544. if (!AddedAny)
  1545. Transform.buildSimpleDeductionGuide(None);
  1546. // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
  1547. // resembling a copy or move constructor.
  1548. // FIXME: The standard doesn't say (how) to do this.
  1549. if (!AddedCopyOrMove)
  1550. Transform.buildSimpleDeductionGuide(Transform.DeducedType);
  1551. }
  1552. /// \brief Diagnose the presence of a default template argument on a
  1553. /// template parameter, which is ill-formed in certain contexts.
  1554. ///
  1555. /// \returns true if the default template argument should be dropped.
  1556. static bool DiagnoseDefaultTemplateArgument(Sema &S,
  1557. Sema::TemplateParamListContext TPC,
  1558. SourceLocation ParamLoc,
  1559. SourceRange DefArgRange) {
  1560. switch (TPC) {
  1561. case Sema::TPC_ClassTemplate:
  1562. case Sema::TPC_VarTemplate:
  1563. case Sema::TPC_TypeAliasTemplate:
  1564. return false;
  1565. case Sema::TPC_FunctionTemplate:
  1566. case Sema::TPC_FriendFunctionTemplateDefinition:
  1567. // C++ [temp.param]p9:
  1568. // A default template-argument shall not be specified in a
  1569. // function template declaration or a function template
  1570. // definition [...]
  1571. // If a friend function template declaration specifies a default
  1572. // template-argument, that declaration shall be a definition and shall be
  1573. // the only declaration of the function template in the translation unit.
  1574. // (C++98/03 doesn't have this wording; see DR226).
  1575. S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
  1576. diag::warn_cxx98_compat_template_parameter_default_in_function_template
  1577. : diag::ext_template_parameter_default_in_function_template)
  1578. << DefArgRange;
  1579. return false;
  1580. case Sema::TPC_ClassTemplateMember:
  1581. // C++0x [temp.param]p9:
  1582. // A default template-argument shall not be specified in the
  1583. // template-parameter-lists of the definition of a member of a
  1584. // class template that appears outside of the member's class.
  1585. S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
  1586. << DefArgRange;
  1587. return true;
  1588. case Sema::TPC_FriendClassTemplate:
  1589. case Sema::TPC_FriendFunctionTemplate:
  1590. // C++ [temp.param]p9:
  1591. // A default template-argument shall not be specified in a
  1592. // friend template declaration.
  1593. S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
  1594. << DefArgRange;
  1595. return true;
  1596. // FIXME: C++0x [temp.param]p9 allows default template-arguments
  1597. // for friend function templates if there is only a single
  1598. // declaration (and it is a definition). Strange!
  1599. }
  1600. llvm_unreachable("Invalid TemplateParamListContext!");
  1601. }
  1602. /// \brief Check for unexpanded parameter packs within the template parameters
  1603. /// of a template template parameter, recursively.
  1604. static bool DiagnoseUnexpandedParameterPacks(Sema &S,
  1605. TemplateTemplateParmDecl *TTP) {
  1606. // A template template parameter which is a parameter pack is also a pack
  1607. // expansion.
  1608. if (TTP->isParameterPack())
  1609. return false;
  1610. TemplateParameterList *Params = TTP->getTemplateParameters();
  1611. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  1612. NamedDecl *P = Params->getParam(I);
  1613. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
  1614. if (!NTTP->isParameterPack() &&
  1615. S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
  1616. NTTP->getTypeSourceInfo(),
  1617. Sema::UPPC_NonTypeTemplateParameterType))
  1618. return true;
  1619. continue;
  1620. }
  1621. if (TemplateTemplateParmDecl *InnerTTP
  1622. = dyn_cast<TemplateTemplateParmDecl>(P))
  1623. if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
  1624. return true;
  1625. }
  1626. return false;
  1627. }
  1628. /// \brief Checks the validity of a template parameter list, possibly
  1629. /// considering the template parameter list from a previous
  1630. /// declaration.
  1631. ///
  1632. /// If an "old" template parameter list is provided, it must be
  1633. /// equivalent (per TemplateParameterListsAreEqual) to the "new"
  1634. /// template parameter list.
  1635. ///
  1636. /// \param NewParams Template parameter list for a new template
  1637. /// declaration. This template parameter list will be updated with any
  1638. /// default arguments that are carried through from the previous
  1639. /// template parameter list.
  1640. ///
  1641. /// \param OldParams If provided, template parameter list from a
  1642. /// previous declaration of the same template. Default template
  1643. /// arguments will be merged from the old template parameter list to
  1644. /// the new template parameter list.
  1645. ///
  1646. /// \param TPC Describes the context in which we are checking the given
  1647. /// template parameter list.
  1648. ///
  1649. /// \returns true if an error occurred, false otherwise.
  1650. bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
  1651. TemplateParameterList *OldParams,
  1652. TemplateParamListContext TPC) {
  1653. bool Invalid = false;
  1654. // C++ [temp.param]p10:
  1655. // The set of default template-arguments available for use with a
  1656. // template declaration or definition is obtained by merging the
  1657. // default arguments from the definition (if in scope) and all
  1658. // declarations in scope in the same way default function
  1659. // arguments are (8.3.6).
  1660. bool SawDefaultArgument = false;
  1661. SourceLocation PreviousDefaultArgLoc;
  1662. // Dummy initialization to avoid warnings.
  1663. TemplateParameterList::iterator OldParam = NewParams->end();
  1664. if (OldParams)
  1665. OldParam = OldParams->begin();
  1666. bool RemoveDefaultArguments = false;
  1667. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  1668. NewParamEnd = NewParams->end();
  1669. NewParam != NewParamEnd; ++NewParam) {
  1670. // Variables used to diagnose redundant default arguments
  1671. bool RedundantDefaultArg = false;
  1672. SourceLocation OldDefaultLoc;
  1673. SourceLocation NewDefaultLoc;
  1674. // Variable used to diagnose missing default arguments
  1675. bool MissingDefaultArg = false;
  1676. // Variable used to diagnose non-final parameter packs
  1677. bool SawParameterPack = false;
  1678. if (TemplateTypeParmDecl *NewTypeParm
  1679. = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
  1680. // Check the presence of a default argument here.
  1681. if (NewTypeParm->hasDefaultArgument() &&
  1682. DiagnoseDefaultTemplateArgument(*this, TPC,
  1683. NewTypeParm->getLocation(),
  1684. NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
  1685. .getSourceRange()))
  1686. NewTypeParm->removeDefaultArgument();
  1687. // Merge default arguments for template type parameters.
  1688. TemplateTypeParmDecl *OldTypeParm
  1689. = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
  1690. if (NewTypeParm->isParameterPack()) {
  1691. assert(!NewTypeParm->hasDefaultArgument() &&
  1692. "Parameter packs can't have a default argument!");
  1693. SawParameterPack = true;
  1694. } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
  1695. NewTypeParm->hasDefaultArgument()) {
  1696. OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
  1697. NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
  1698. SawDefaultArgument = true;
  1699. RedundantDefaultArg = true;
  1700. PreviousDefaultArgLoc = NewDefaultLoc;
  1701. } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
  1702. // Merge the default argument from the old declaration to the
  1703. // new declaration.
  1704. NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
  1705. PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
  1706. } else if (NewTypeParm->hasDefaultArgument()) {
  1707. SawDefaultArgument = true;
  1708. PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
  1709. } else if (SawDefaultArgument)
  1710. MissingDefaultArg = true;
  1711. } else if (NonTypeTemplateParmDecl *NewNonTypeParm
  1712. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
  1713. // Check for unexpanded parameter packs.
  1714. if (!NewNonTypeParm->isParameterPack() &&
  1715. DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
  1716. NewNonTypeParm->getTypeSourceInfo(),
  1717. UPPC_NonTypeTemplateParameterType)) {
  1718. Invalid = true;
  1719. continue;
  1720. }
  1721. // Check the presence of a default argument here.
  1722. if (NewNonTypeParm->hasDefaultArgument() &&
  1723. DiagnoseDefaultTemplateArgument(*this, TPC,
  1724. NewNonTypeParm->getLocation(),
  1725. NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
  1726. NewNonTypeParm->removeDefaultArgument();
  1727. }
  1728. // Merge default arguments for non-type template parameters
  1729. NonTypeTemplateParmDecl *OldNonTypeParm
  1730. = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
  1731. if (NewNonTypeParm->isParameterPack()) {
  1732. assert(!NewNonTypeParm->hasDefaultArgument() &&
  1733. "Parameter packs can't have a default argument!");
  1734. if (!NewNonTypeParm->isPackExpansion())
  1735. SawParameterPack = true;
  1736. } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
  1737. NewNonTypeParm->hasDefaultArgument()) {
  1738. OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
  1739. NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
  1740. SawDefaultArgument = true;
  1741. RedundantDefaultArg = true;
  1742. PreviousDefaultArgLoc = NewDefaultLoc;
  1743. } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
  1744. // Merge the default argument from the old declaration to the
  1745. // new declaration.
  1746. NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
  1747. PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
  1748. } else if (NewNonTypeParm->hasDefaultArgument()) {
  1749. SawDefaultArgument = true;
  1750. PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
  1751. } else if (SawDefaultArgument)
  1752. MissingDefaultArg = true;
  1753. } else {
  1754. TemplateTemplateParmDecl *NewTemplateParm
  1755. = cast<TemplateTemplateParmDecl>(*NewParam);
  1756. // Check for unexpanded parameter packs, recursively.
  1757. if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
  1758. Invalid = true;
  1759. continue;
  1760. }
  1761. // Check the presence of a default argument here.
  1762. if (NewTemplateParm->hasDefaultArgument() &&
  1763. DiagnoseDefaultTemplateArgument(*this, TPC,
  1764. NewTemplateParm->getLocation(),
  1765. NewTemplateParm->getDefaultArgument().getSourceRange()))
  1766. NewTemplateParm->removeDefaultArgument();
  1767. // Merge default arguments for template template parameters
  1768. TemplateTemplateParmDecl *OldTemplateParm
  1769. = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
  1770. if (NewTemplateParm->isParameterPack()) {
  1771. assert(!NewTemplateParm->hasDefaultArgument() &&
  1772. "Parameter packs can't have a default argument!");
  1773. if (!NewTemplateParm->isPackExpansion())
  1774. SawParameterPack = true;
  1775. } else if (OldTemplateParm &&
  1776. hasVisibleDefaultArgument(OldTemplateParm) &&
  1777. NewTemplateParm->hasDefaultArgument()) {
  1778. OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
  1779. NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
  1780. SawDefaultArgument = true;
  1781. RedundantDefaultArg = true;
  1782. PreviousDefaultArgLoc = NewDefaultLoc;
  1783. } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
  1784. // Merge the default argument from the old declaration to the
  1785. // new declaration.
  1786. NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
  1787. PreviousDefaultArgLoc
  1788. = OldTemplateParm->getDefaultArgument().getLocation();
  1789. } else if (NewTemplateParm->hasDefaultArgument()) {
  1790. SawDefaultArgument = true;
  1791. PreviousDefaultArgLoc
  1792. = NewTemplateParm->getDefaultArgument().getLocation();
  1793. } else if (SawDefaultArgument)
  1794. MissingDefaultArg = true;
  1795. }
  1796. // C++11 [temp.param]p11:
  1797. // If a template parameter of a primary class template or alias template
  1798. // is a template parameter pack, it shall be the last template parameter.
  1799. if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
  1800. (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
  1801. TPC == TPC_TypeAliasTemplate)) {
  1802. Diag((*NewParam)->getLocation(),
  1803. diag::err_template_param_pack_must_be_last_template_parameter);
  1804. Invalid = true;
  1805. }
  1806. if (RedundantDefaultArg) {
  1807. // C++ [temp.param]p12:
  1808. // A template-parameter shall not be given default arguments
  1809. // by two different declarations in the same scope.
  1810. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
  1811. Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
  1812. Invalid = true;
  1813. } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
  1814. // C++ [temp.param]p11:
  1815. // If a template-parameter of a class template has a default
  1816. // template-argument, each subsequent template-parameter shall either
  1817. // have a default template-argument supplied or be a template parameter
  1818. // pack.
  1819. Diag((*NewParam)->getLocation(),
  1820. diag::err_template_param_default_arg_missing);
  1821. Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
  1822. Invalid = true;
  1823. RemoveDefaultArguments = true;
  1824. }
  1825. // If we have an old template parameter list that we're merging
  1826. // in, move on to the next parameter.
  1827. if (OldParams)
  1828. ++OldParam;
  1829. }
  1830. // We were missing some default arguments at the end of the list, so remove
  1831. // all of the default arguments.
  1832. if (RemoveDefaultArguments) {
  1833. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  1834. NewParamEnd = NewParams->end();
  1835. NewParam != NewParamEnd; ++NewParam) {
  1836. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
  1837. TTP->removeDefaultArgument();
  1838. else if (NonTypeTemplateParmDecl *NTTP
  1839. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
  1840. NTTP->removeDefaultArgument();
  1841. else
  1842. cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
  1843. }
  1844. }
  1845. return Invalid;
  1846. }
  1847. namespace {
  1848. /// A class which looks for a use of a certain level of template
  1849. /// parameter.
  1850. struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
  1851. typedef RecursiveASTVisitor<DependencyChecker> super;
  1852. unsigned Depth;
  1853. bool FindLessThanDepth;
  1854. // Whether we're looking for a use of a template parameter that makes the
  1855. // overall construct type-dependent / a dependent type. This is strictly
  1856. // best-effort for now; we may fail to match at all for a dependent type
  1857. // in some cases if this is set.
  1858. bool IgnoreNonTypeDependent;
  1859. bool Match;
  1860. SourceLocation MatchLoc;
  1861. DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
  1862. bool FindLessThanDepth = false)
  1863. : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
  1864. IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
  1865. DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
  1866. : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
  1867. bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
  1868. if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
  1869. Match = true;
  1870. MatchLoc = Loc;
  1871. return true;
  1872. }
  1873. return false;
  1874. }
  1875. bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
  1876. // Prune out non-type-dependent expressions if requested. This can
  1877. // sometimes result in us failing to find a template parameter reference
  1878. // (if a value-dependent expression creates a dependent type), but this
  1879. // mode is best-effort only.
  1880. if (auto *E = dyn_cast_or_null<Expr>(S))
  1881. if (IgnoreNonTypeDependent && !E->isTypeDependent())
  1882. return true;
  1883. return super::TraverseStmt(S, Q);
  1884. }
  1885. bool TraverseTypeLoc(TypeLoc TL) {
  1886. if (IgnoreNonTypeDependent && !TL.isNull() &&
  1887. !TL.getType()->isDependentType())
  1888. return true;
  1889. return super::TraverseTypeLoc(TL);
  1890. }
  1891. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  1892. return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
  1893. }
  1894. bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  1895. // For a best-effort search, keep looking until we find a location.
  1896. return IgnoreNonTypeDependent || !Matches(T->getDepth());
  1897. }
  1898. bool TraverseTemplateName(TemplateName N) {
  1899. if (TemplateTemplateParmDecl *PD =
  1900. dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
  1901. if (Matches(PD->getDepth()))
  1902. return false;
  1903. return super::TraverseTemplateName(N);
  1904. }
  1905. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1906. if (NonTypeTemplateParmDecl *PD =
  1907. dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
  1908. if (Matches(PD->getDepth(), E->getExprLoc()))
  1909. return false;
  1910. return super::VisitDeclRefExpr(E);
  1911. }
  1912. bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
  1913. return TraverseType(T->getReplacementType());
  1914. }
  1915. bool
  1916. VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
  1917. return TraverseTemplateArgument(T->getArgumentPack());
  1918. }
  1919. bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
  1920. return TraverseType(T->getInjectedSpecializationType());
  1921. }
  1922. };
  1923. } // end anonymous namespace
  1924. /// Determines whether a given type depends on the given parameter
  1925. /// list.
  1926. static bool
  1927. DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
  1928. DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
  1929. Checker.TraverseType(T);
  1930. return Checker.Match;
  1931. }
  1932. // Find the source range corresponding to the named type in the given
  1933. // nested-name-specifier, if any.
  1934. static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
  1935. QualType T,
  1936. const CXXScopeSpec &SS) {
  1937. NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
  1938. while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
  1939. if (const Type *CurType = NNS->getAsType()) {
  1940. if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
  1941. return NNSLoc.getTypeLoc().getSourceRange();
  1942. } else
  1943. break;
  1944. NNSLoc = NNSLoc.getPrefix();
  1945. }
  1946. return SourceRange();
  1947. }
  1948. /// \brief Match the given template parameter lists to the given scope
  1949. /// specifier, returning the template parameter list that applies to the
  1950. /// name.
  1951. ///
  1952. /// \param DeclStartLoc the start of the declaration that has a scope
  1953. /// specifier or a template parameter list.
  1954. ///
  1955. /// \param DeclLoc The location of the declaration itself.
  1956. ///
  1957. /// \param SS the scope specifier that will be matched to the given template
  1958. /// parameter lists. This scope specifier precedes a qualified name that is
  1959. /// being declared.
  1960. ///
  1961. /// \param TemplateId The template-id following the scope specifier, if there
  1962. /// is one. Used to check for a missing 'template<>'.
  1963. ///
  1964. /// \param ParamLists the template parameter lists, from the outermost to the
  1965. /// innermost template parameter lists.
  1966. ///
  1967. /// \param IsFriend Whether to apply the slightly different rules for
  1968. /// matching template parameters to scope specifiers in friend
  1969. /// declarations.
  1970. ///
  1971. /// \param IsMemberSpecialization will be set true if the scope specifier
  1972. /// denotes a fully-specialized type, and therefore this is a declaration of
  1973. /// a member specialization.
  1974. ///
  1975. /// \returns the template parameter list, if any, that corresponds to the
  1976. /// name that is preceded by the scope specifier @p SS. This template
  1977. /// parameter list may have template parameters (if we're declaring a
  1978. /// template) or may have no template parameters (if we're declaring a
  1979. /// template specialization), or may be NULL (if what we're declaring isn't
  1980. /// itself a template).
  1981. TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
  1982. SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
  1983. TemplateIdAnnotation *TemplateId,
  1984. ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
  1985. bool &IsMemberSpecialization, bool &Invalid) {
  1986. IsMemberSpecialization = false;
  1987. Invalid = false;
  1988. // The sequence of nested types to which we will match up the template
  1989. // parameter lists. We first build this list by starting with the type named
  1990. // by the nested-name-specifier and walking out until we run out of types.
  1991. SmallVector<QualType, 4> NestedTypes;
  1992. QualType T;
  1993. if (SS.getScopeRep()) {
  1994. if (CXXRecordDecl *Record
  1995. = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
  1996. T = Context.getTypeDeclType(Record);
  1997. else
  1998. T = QualType(SS.getScopeRep()->getAsType(), 0);
  1999. }
  2000. // If we found an explicit specialization that prevents us from needing
  2001. // 'template<>' headers, this will be set to the location of that
  2002. // explicit specialization.
  2003. SourceLocation ExplicitSpecLoc;
  2004. while (!T.isNull()) {
  2005. NestedTypes.push_back(T);
  2006. // Retrieve the parent of a record type.
  2007. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2008. // If this type is an explicit specialization, we're done.
  2009. if (ClassTemplateSpecializationDecl *Spec
  2010. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2011. if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
  2012. Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
  2013. ExplicitSpecLoc = Spec->getLocation();
  2014. break;
  2015. }
  2016. } else if (Record->getTemplateSpecializationKind()
  2017. == TSK_ExplicitSpecialization) {
  2018. ExplicitSpecLoc = Record->getLocation();
  2019. break;
  2020. }
  2021. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
  2022. T = Context.getTypeDeclType(Parent);
  2023. else
  2024. T = QualType();
  2025. continue;
  2026. }
  2027. if (const TemplateSpecializationType *TST
  2028. = T->getAs<TemplateSpecializationType>()) {
  2029. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2030. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
  2031. T = Context.getTypeDeclType(Parent);
  2032. else
  2033. T = QualType();
  2034. continue;
  2035. }
  2036. }
  2037. // Look one step prior in a dependent template specialization type.
  2038. if (const DependentTemplateSpecializationType *DependentTST
  2039. = T->getAs<DependentTemplateSpecializationType>()) {
  2040. if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
  2041. T = QualType(NNS->getAsType(), 0);
  2042. else
  2043. T = QualType();
  2044. continue;
  2045. }
  2046. // Look one step prior in a dependent name type.
  2047. if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
  2048. if (NestedNameSpecifier *NNS = DependentName->getQualifier())
  2049. T = QualType(NNS->getAsType(), 0);
  2050. else
  2051. T = QualType();
  2052. continue;
  2053. }
  2054. // Retrieve the parent of an enumeration type.
  2055. if (const EnumType *EnumT = T->getAs<EnumType>()) {
  2056. // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
  2057. // check here.
  2058. EnumDecl *Enum = EnumT->getDecl();
  2059. // Get to the parent type.
  2060. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
  2061. T = Context.getTypeDeclType(Parent);
  2062. else
  2063. T = QualType();
  2064. continue;
  2065. }
  2066. T = QualType();
  2067. }
  2068. // Reverse the nested types list, since we want to traverse from the outermost
  2069. // to the innermost while checking template-parameter-lists.
  2070. std::reverse(NestedTypes.begin(), NestedTypes.end());
  2071. // C++0x [temp.expl.spec]p17:
  2072. // A member or a member template may be nested within many
  2073. // enclosing class templates. In an explicit specialization for
  2074. // such a member, the member declaration shall be preceded by a
  2075. // template<> for each enclosing class template that is
  2076. // explicitly specialized.
  2077. bool SawNonEmptyTemplateParameterList = false;
  2078. auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
  2079. if (SawNonEmptyTemplateParameterList) {
  2080. Diag(DeclLoc, diag::err_specialize_member_of_template)
  2081. << !Recovery << Range;
  2082. Invalid = true;
  2083. IsMemberSpecialization = false;
  2084. return true;
  2085. }
  2086. return false;
  2087. };
  2088. auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
  2089. // Check that we can have an explicit specialization here.
  2090. if (CheckExplicitSpecialization(Range, true))
  2091. return true;
  2092. // We don't have a template header, but we should.
  2093. SourceLocation ExpectedTemplateLoc;
  2094. if (!ParamLists.empty())
  2095. ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
  2096. else
  2097. ExpectedTemplateLoc = DeclStartLoc;
  2098. Diag(DeclLoc, diag::err_template_spec_needs_header)
  2099. << Range
  2100. << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
  2101. return false;
  2102. };
  2103. unsigned ParamIdx = 0;
  2104. for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
  2105. ++TypeIdx) {
  2106. T = NestedTypes[TypeIdx];
  2107. // Whether we expect a 'template<>' header.
  2108. bool NeedEmptyTemplateHeader = false;
  2109. // Whether we expect a template header with parameters.
  2110. bool NeedNonemptyTemplateHeader = false;
  2111. // For a dependent type, the set of template parameters that we
  2112. // expect to see.
  2113. TemplateParameterList *ExpectedTemplateParams = nullptr;
  2114. // C++0x [temp.expl.spec]p15:
  2115. // A member or a member template may be nested within many enclosing
  2116. // class templates. In an explicit specialization for such a member, the
  2117. // member declaration shall be preceded by a template<> for each
  2118. // enclosing class template that is explicitly specialized.
  2119. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2120. if (ClassTemplatePartialSpecializationDecl *Partial
  2121. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
  2122. ExpectedTemplateParams = Partial->getTemplateParameters();
  2123. NeedNonemptyTemplateHeader = true;
  2124. } else if (Record->isDependentType()) {
  2125. if (Record->getDescribedClassTemplate()) {
  2126. ExpectedTemplateParams = Record->getDescribedClassTemplate()
  2127. ->getTemplateParameters();
  2128. NeedNonemptyTemplateHeader = true;
  2129. }
  2130. } else if (ClassTemplateSpecializationDecl *Spec
  2131. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2132. // C++0x [temp.expl.spec]p4:
  2133. // Members of an explicitly specialized class template are defined
  2134. // in the same manner as members of normal classes, and not using
  2135. // the template<> syntax.
  2136. if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
  2137. NeedEmptyTemplateHeader = true;
  2138. else
  2139. continue;
  2140. } else if (Record->getTemplateSpecializationKind()) {
  2141. if (Record->getTemplateSpecializationKind()
  2142. != TSK_ExplicitSpecialization &&
  2143. TypeIdx == NumTypes - 1)
  2144. IsMemberSpecialization = true;
  2145. continue;
  2146. }
  2147. } else if (const TemplateSpecializationType *TST
  2148. = T->getAs<TemplateSpecializationType>()) {
  2149. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2150. ExpectedTemplateParams = Template->getTemplateParameters();
  2151. NeedNonemptyTemplateHeader = true;
  2152. }
  2153. } else if (T->getAs<DependentTemplateSpecializationType>()) {
  2154. // FIXME: We actually could/should check the template arguments here
  2155. // against the corresponding template parameter list.
  2156. NeedNonemptyTemplateHeader = false;
  2157. }
  2158. // C++ [temp.expl.spec]p16:
  2159. // In an explicit specialization declaration for a member of a class
  2160. // template or a member template that ap- pears in namespace scope, the
  2161. // member template and some of its enclosing class templates may remain
  2162. // unspecialized, except that the declaration shall not explicitly
  2163. // specialize a class member template if its en- closing class templates
  2164. // are not explicitly specialized as well.
  2165. if (ParamIdx < ParamLists.size()) {
  2166. if (ParamLists[ParamIdx]->size() == 0) {
  2167. if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  2168. false))
  2169. return nullptr;
  2170. } else
  2171. SawNonEmptyTemplateParameterList = true;
  2172. }
  2173. if (NeedEmptyTemplateHeader) {
  2174. // If we're on the last of the types, and we need a 'template<>' header
  2175. // here, then it's a member specialization.
  2176. if (TypeIdx == NumTypes - 1)
  2177. IsMemberSpecialization = true;
  2178. if (ParamIdx < ParamLists.size()) {
  2179. if (ParamLists[ParamIdx]->size() > 0) {
  2180. // The header has template parameters when it shouldn't. Complain.
  2181. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  2182. diag::err_template_param_list_matches_nontemplate)
  2183. << T
  2184. << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
  2185. ParamLists[ParamIdx]->getRAngleLoc())
  2186. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  2187. Invalid = true;
  2188. return nullptr;
  2189. }
  2190. // Consume this template header.
  2191. ++ParamIdx;
  2192. continue;
  2193. }
  2194. if (!IsFriend)
  2195. if (DiagnoseMissingExplicitSpecialization(
  2196. getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
  2197. return nullptr;
  2198. continue;
  2199. }
  2200. if (NeedNonemptyTemplateHeader) {
  2201. // In friend declarations we can have template-ids which don't
  2202. // depend on the corresponding template parameter lists. But
  2203. // assume that empty parameter lists are supposed to match this
  2204. // template-id.
  2205. if (IsFriend && T->isDependentType()) {
  2206. if (ParamIdx < ParamLists.size() &&
  2207. DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
  2208. ExpectedTemplateParams = nullptr;
  2209. else
  2210. continue;
  2211. }
  2212. if (ParamIdx < ParamLists.size()) {
  2213. // Check the template parameter list, if we can.
  2214. if (ExpectedTemplateParams &&
  2215. !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
  2216. ExpectedTemplateParams,
  2217. true, TPL_TemplateMatch))
  2218. Invalid = true;
  2219. if (!Invalid &&
  2220. CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
  2221. TPC_ClassTemplateMember))
  2222. Invalid = true;
  2223. ++ParamIdx;
  2224. continue;
  2225. }
  2226. Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
  2227. << T
  2228. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  2229. Invalid = true;
  2230. continue;
  2231. }
  2232. }
  2233. // If there were at least as many template-ids as there were template
  2234. // parameter lists, then there are no template parameter lists remaining for
  2235. // the declaration itself.
  2236. if (ParamIdx >= ParamLists.size()) {
  2237. if (TemplateId && !IsFriend) {
  2238. // We don't have a template header for the declaration itself, but we
  2239. // should.
  2240. DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
  2241. TemplateId->RAngleLoc));
  2242. // Fabricate an empty template parameter list for the invented header.
  2243. return TemplateParameterList::Create(Context, SourceLocation(),
  2244. SourceLocation(), None,
  2245. SourceLocation(), nullptr);
  2246. }
  2247. return nullptr;
  2248. }
  2249. // If there were too many template parameter lists, complain about that now.
  2250. if (ParamIdx < ParamLists.size() - 1) {
  2251. bool HasAnyExplicitSpecHeader = false;
  2252. bool AllExplicitSpecHeaders = true;
  2253. for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
  2254. if (ParamLists[I]->size() == 0)
  2255. HasAnyExplicitSpecHeader = true;
  2256. else
  2257. AllExplicitSpecHeaders = false;
  2258. }
  2259. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  2260. AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
  2261. : diag::err_template_spec_extra_headers)
  2262. << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  2263. ParamLists[ParamLists.size() - 2]->getRAngleLoc());
  2264. // If there was a specialization somewhere, such that 'template<>' is
  2265. // not required, and there were any 'template<>' headers, note where the
  2266. // specialization occurred.
  2267. if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
  2268. Diag(ExplicitSpecLoc,
  2269. diag::note_explicit_template_spec_does_not_need_header)
  2270. << NestedTypes.back();
  2271. // We have a template parameter list with no corresponding scope, which
  2272. // means that the resulting template declaration can't be instantiated
  2273. // properly (we'll end up with dependent nodes when we shouldn't).
  2274. if (!AllExplicitSpecHeaders)
  2275. Invalid = true;
  2276. }
  2277. // C++ [temp.expl.spec]p16:
  2278. // In an explicit specialization declaration for a member of a class
  2279. // template or a member template that ap- pears in namespace scope, the
  2280. // member template and some of its enclosing class templates may remain
  2281. // unspecialized, except that the declaration shall not explicitly
  2282. // specialize a class member template if its en- closing class templates
  2283. // are not explicitly specialized as well.
  2284. if (ParamLists.back()->size() == 0 &&
  2285. CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  2286. false))
  2287. return nullptr;
  2288. // Return the last template parameter list, which corresponds to the
  2289. // entity being declared.
  2290. return ParamLists.back();
  2291. }
  2292. void Sema::NoteAllFoundTemplates(TemplateName Name) {
  2293. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  2294. Diag(Template->getLocation(), diag::note_template_declared_here)
  2295. << (isa<FunctionTemplateDecl>(Template)
  2296. ? 0
  2297. : isa<ClassTemplateDecl>(Template)
  2298. ? 1
  2299. : isa<VarTemplateDecl>(Template)
  2300. ? 2
  2301. : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
  2302. << Template->getDeclName();
  2303. return;
  2304. }
  2305. if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
  2306. for (OverloadedTemplateStorage::iterator I = OST->begin(),
  2307. IEnd = OST->end();
  2308. I != IEnd; ++I)
  2309. Diag((*I)->getLocation(), diag::note_template_declared_here)
  2310. << 0 << (*I)->getDeclName();
  2311. return;
  2312. }
  2313. }
  2314. static QualType
  2315. checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
  2316. const SmallVectorImpl<TemplateArgument> &Converted,
  2317. SourceLocation TemplateLoc,
  2318. TemplateArgumentListInfo &TemplateArgs) {
  2319. ASTContext &Context = SemaRef.getASTContext();
  2320. switch (BTD->getBuiltinTemplateKind()) {
  2321. case BTK__make_integer_seq: {
  2322. // Specializations of __make_integer_seq<S, T, N> are treated like
  2323. // S<T, 0, ..., N-1>.
  2324. // C++14 [inteseq.intseq]p1:
  2325. // T shall be an integer type.
  2326. if (!Converted[1].getAsType()->isIntegralType(Context)) {
  2327. SemaRef.Diag(TemplateArgs[1].getLocation(),
  2328. diag::err_integer_sequence_integral_element_type);
  2329. return QualType();
  2330. }
  2331. // C++14 [inteseq.make]p1:
  2332. // If N is negative the program is ill-formed.
  2333. TemplateArgument NumArgsArg = Converted[2];
  2334. llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
  2335. if (NumArgs < 0) {
  2336. SemaRef.Diag(TemplateArgs[2].getLocation(),
  2337. diag::err_integer_sequence_negative_length);
  2338. return QualType();
  2339. }
  2340. QualType ArgTy = NumArgsArg.getIntegralType();
  2341. TemplateArgumentListInfo SyntheticTemplateArgs;
  2342. // The type argument gets reused as the first template argument in the
  2343. // synthetic template argument list.
  2344. SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
  2345. // Expand N into 0 ... N-1.
  2346. for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
  2347. I < NumArgs; ++I) {
  2348. TemplateArgument TA(Context, I, ArgTy);
  2349. SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
  2350. TA, ArgTy, TemplateArgs[2].getLocation()));
  2351. }
  2352. // The first template argument will be reused as the template decl that
  2353. // our synthetic template arguments will be applied to.
  2354. return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
  2355. TemplateLoc, SyntheticTemplateArgs);
  2356. }
  2357. case BTK__type_pack_element:
  2358. // Specializations of
  2359. // __type_pack_element<Index, T_1, ..., T_N>
  2360. // are treated like T_Index.
  2361. assert(Converted.size() == 2 &&
  2362. "__type_pack_element should be given an index and a parameter pack");
  2363. // If the Index is out of bounds, the program is ill-formed.
  2364. TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
  2365. llvm::APSInt Index = IndexArg.getAsIntegral();
  2366. assert(Index >= 0 && "the index used with __type_pack_element should be of "
  2367. "type std::size_t, and hence be non-negative");
  2368. if (Index >= Ts.pack_size()) {
  2369. SemaRef.Diag(TemplateArgs[0].getLocation(),
  2370. diag::err_type_pack_element_out_of_bounds);
  2371. return QualType();
  2372. }
  2373. // We simply return the type at index `Index`.
  2374. auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
  2375. return Nth->getAsType();
  2376. }
  2377. llvm_unreachable("unexpected BuiltinTemplateDecl!");
  2378. }
  2379. QualType Sema::CheckTemplateIdType(TemplateName Name,
  2380. SourceLocation TemplateLoc,
  2381. TemplateArgumentListInfo &TemplateArgs) {
  2382. DependentTemplateName *DTN
  2383. = Name.getUnderlying().getAsDependentTemplateName();
  2384. if (DTN && DTN->isIdentifier())
  2385. // When building a template-id where the template-name is dependent,
  2386. // assume the template is a type template. Either our assumption is
  2387. // correct, or the code is ill-formed and will be diagnosed when the
  2388. // dependent name is substituted.
  2389. return Context.getDependentTemplateSpecializationType(ETK_None,
  2390. DTN->getQualifier(),
  2391. DTN->getIdentifier(),
  2392. TemplateArgs);
  2393. TemplateDecl *Template = Name.getAsTemplateDecl();
  2394. if (!Template || isa<FunctionTemplateDecl>(Template) ||
  2395. isa<VarTemplateDecl>(Template)) {
  2396. // We might have a substituted template template parameter pack. If so,
  2397. // build a template specialization type for it.
  2398. if (Name.getAsSubstTemplateTemplateParmPack())
  2399. return Context.getTemplateSpecializationType(Name, TemplateArgs);
  2400. Diag(TemplateLoc, diag::err_template_id_not_a_type)
  2401. << Name;
  2402. NoteAllFoundTemplates(Name);
  2403. return QualType();
  2404. }
  2405. // Check that the template argument list is well-formed for this
  2406. // template.
  2407. SmallVector<TemplateArgument, 4> Converted;
  2408. if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
  2409. false, Converted))
  2410. return QualType();
  2411. QualType CanonType;
  2412. bool InstantiationDependent = false;
  2413. if (TypeAliasTemplateDecl *AliasTemplate =
  2414. dyn_cast<TypeAliasTemplateDecl>(Template)) {
  2415. // Find the canonical type for this type alias template specialization.
  2416. TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
  2417. if (Pattern->isInvalidDecl())
  2418. return QualType();
  2419. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
  2420. Converted);
  2421. // Only substitute for the innermost template argument list.
  2422. MultiLevelTemplateArgumentList TemplateArgLists;
  2423. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  2424. unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
  2425. for (unsigned I = 0; I < Depth; ++I)
  2426. TemplateArgLists.addOuterTemplateArguments(None);
  2427. LocalInstantiationScope Scope(*this);
  2428. InstantiatingTemplate Inst(*this, TemplateLoc, Template);
  2429. if (Inst.isInvalid())
  2430. return QualType();
  2431. CanonType = SubstType(Pattern->getUnderlyingType(),
  2432. TemplateArgLists, AliasTemplate->getLocation(),
  2433. AliasTemplate->getDeclName());
  2434. if (CanonType.isNull())
  2435. return QualType();
  2436. } else if (Name.isDependent() ||
  2437. TemplateSpecializationType::anyDependentTemplateArguments(
  2438. TemplateArgs, InstantiationDependent)) {
  2439. // This class template specialization is a dependent
  2440. // type. Therefore, its canonical type is another class template
  2441. // specialization type that contains all of the converted
  2442. // arguments in canonical form. This ensures that, e.g., A<T> and
  2443. // A<T, T> have identical types when A is declared as:
  2444. //
  2445. // template<typename T, typename U = T> struct A;
  2446. CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
  2447. // This might work out to be a current instantiation, in which
  2448. // case the canonical type needs to be the InjectedClassNameType.
  2449. //
  2450. // TODO: in theory this could be a simple hashtable lookup; most
  2451. // changes to CurContext don't change the set of current
  2452. // instantiations.
  2453. if (isa<ClassTemplateDecl>(Template)) {
  2454. for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
  2455. // If we get out to a namespace, we're done.
  2456. if (Ctx->isFileContext()) break;
  2457. // If this isn't a record, keep looking.
  2458. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
  2459. if (!Record) continue;
  2460. // Look for one of the two cases with InjectedClassNameTypes
  2461. // and check whether it's the same template.
  2462. if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
  2463. !Record->getDescribedClassTemplate())
  2464. continue;
  2465. // Fetch the injected class name type and check whether its
  2466. // injected type is equal to the type we just built.
  2467. QualType ICNT = Context.getTypeDeclType(Record);
  2468. QualType Injected = cast<InjectedClassNameType>(ICNT)
  2469. ->getInjectedSpecializationType();
  2470. if (CanonType != Injected->getCanonicalTypeInternal())
  2471. continue;
  2472. // If so, the canonical type of this TST is the injected
  2473. // class name type of the record we just found.
  2474. assert(ICNT.isCanonical());
  2475. CanonType = ICNT;
  2476. break;
  2477. }
  2478. }
  2479. } else if (ClassTemplateDecl *ClassTemplate
  2480. = dyn_cast<ClassTemplateDecl>(Template)) {
  2481. // Find the class template specialization declaration that
  2482. // corresponds to these arguments.
  2483. void *InsertPos = nullptr;
  2484. ClassTemplateSpecializationDecl *Decl
  2485. = ClassTemplate->findSpecialization(Converted, InsertPos);
  2486. if (!Decl) {
  2487. // This is the first time we have referenced this class template
  2488. // specialization. Create the canonical declaration and add it to
  2489. // the set of specializations.
  2490. Decl = ClassTemplateSpecializationDecl::Create(Context,
  2491. ClassTemplate->getTemplatedDecl()->getTagKind(),
  2492. ClassTemplate->getDeclContext(),
  2493. ClassTemplate->getTemplatedDecl()->getLocStart(),
  2494. ClassTemplate->getLocation(),
  2495. ClassTemplate,
  2496. Converted, nullptr);
  2497. ClassTemplate->AddSpecialization(Decl, InsertPos);
  2498. if (ClassTemplate->isOutOfLine())
  2499. Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
  2500. }
  2501. // Diagnose uses of this specialization.
  2502. (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
  2503. CanonType = Context.getTypeDeclType(Decl);
  2504. assert(isa<RecordType>(CanonType) &&
  2505. "type of non-dependent specialization is not a RecordType");
  2506. } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
  2507. CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
  2508. TemplateArgs);
  2509. }
  2510. // Build the fully-sugared type for this class template
  2511. // specialization, which refers back to the class template
  2512. // specialization we created or found.
  2513. return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
  2514. }
  2515. TypeResult
  2516. Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
  2517. TemplateTy TemplateD, IdentifierInfo *TemplateII,
  2518. SourceLocation TemplateIILoc,
  2519. SourceLocation LAngleLoc,
  2520. ASTTemplateArgsPtr TemplateArgsIn,
  2521. SourceLocation RAngleLoc,
  2522. bool IsCtorOrDtorName, bool IsClassName) {
  2523. if (SS.isInvalid())
  2524. return true;
  2525. if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
  2526. DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
  2527. // C++ [temp.res]p3:
  2528. // A qualified-id that refers to a type and in which the
  2529. // nested-name-specifier depends on a template-parameter (14.6.2)
  2530. // shall be prefixed by the keyword typename to indicate that the
  2531. // qualified-id denotes a type, forming an
  2532. // elaborated-type-specifier (7.1.5.3).
  2533. if (!LookupCtx && isDependentScopeSpecifier(SS)) {
  2534. Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
  2535. << SS.getScopeRep() << TemplateII->getName();
  2536. // Recover as if 'typename' were specified.
  2537. // FIXME: This is not quite correct recovery as we don't transform SS
  2538. // into the corresponding dependent form (and we don't diagnose missing
  2539. // 'template' keywords within SS as a result).
  2540. return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
  2541. TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
  2542. TemplateArgsIn, RAngleLoc);
  2543. }
  2544. // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
  2545. // it's not actually allowed to be used as a type in most cases. Because
  2546. // we annotate it before we know whether it's valid, we have to check for
  2547. // this case here.
  2548. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  2549. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  2550. Diag(TemplateIILoc,
  2551. TemplateKWLoc.isInvalid()
  2552. ? diag::err_out_of_line_qualified_id_type_names_constructor
  2553. : diag::ext_out_of_line_qualified_id_type_names_constructor)
  2554. << TemplateII << 0 /*injected-class-name used as template name*/
  2555. << 1 /*if any keyword was present, it was 'template'*/;
  2556. }
  2557. }
  2558. TemplateName Template = TemplateD.get();
  2559. // Translate the parser's template argument list in our AST format.
  2560. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  2561. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  2562. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  2563. QualType T
  2564. = Context.getDependentTemplateSpecializationType(ETK_None,
  2565. DTN->getQualifier(),
  2566. DTN->getIdentifier(),
  2567. TemplateArgs);
  2568. // Build type-source information.
  2569. TypeLocBuilder TLB;
  2570. DependentTemplateSpecializationTypeLoc SpecTL
  2571. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  2572. SpecTL.setElaboratedKeywordLoc(SourceLocation());
  2573. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2574. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  2575. SpecTL.setTemplateNameLoc(TemplateIILoc);
  2576. SpecTL.setLAngleLoc(LAngleLoc);
  2577. SpecTL.setRAngleLoc(RAngleLoc);
  2578. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  2579. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  2580. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  2581. }
  2582. QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  2583. if (Result.isNull())
  2584. return true;
  2585. // Build type-source information.
  2586. TypeLocBuilder TLB;
  2587. TemplateSpecializationTypeLoc SpecTL
  2588. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  2589. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  2590. SpecTL.setTemplateNameLoc(TemplateIILoc);
  2591. SpecTL.setLAngleLoc(LAngleLoc);
  2592. SpecTL.setRAngleLoc(RAngleLoc);
  2593. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  2594. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  2595. // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
  2596. // constructor or destructor name (in such a case, the scope specifier
  2597. // will be attached to the enclosing Decl or Expr node).
  2598. if (SS.isNotEmpty() && !IsCtorOrDtorName) {
  2599. // Create an elaborated-type-specifier containing the nested-name-specifier.
  2600. Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
  2601. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  2602. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  2603. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2604. }
  2605. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  2606. }
  2607. TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
  2608. TypeSpecifierType TagSpec,
  2609. SourceLocation TagLoc,
  2610. CXXScopeSpec &SS,
  2611. SourceLocation TemplateKWLoc,
  2612. TemplateTy TemplateD,
  2613. SourceLocation TemplateLoc,
  2614. SourceLocation LAngleLoc,
  2615. ASTTemplateArgsPtr TemplateArgsIn,
  2616. SourceLocation RAngleLoc) {
  2617. TemplateName Template = TemplateD.get();
  2618. // Translate the parser's template argument list in our AST format.
  2619. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  2620. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  2621. // Determine the tag kind
  2622. TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  2623. ElaboratedTypeKeyword Keyword
  2624. = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
  2625. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  2626. QualType T = Context.getDependentTemplateSpecializationType(Keyword,
  2627. DTN->getQualifier(),
  2628. DTN->getIdentifier(),
  2629. TemplateArgs);
  2630. // Build type-source information.
  2631. TypeLocBuilder TLB;
  2632. DependentTemplateSpecializationTypeLoc SpecTL
  2633. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  2634. SpecTL.setElaboratedKeywordLoc(TagLoc);
  2635. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2636. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  2637. SpecTL.setTemplateNameLoc(TemplateLoc);
  2638. SpecTL.setLAngleLoc(LAngleLoc);
  2639. SpecTL.setRAngleLoc(RAngleLoc);
  2640. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  2641. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  2642. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  2643. }
  2644. if (TypeAliasTemplateDecl *TAT =
  2645. dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
  2646. // C++0x [dcl.type.elab]p2:
  2647. // If the identifier resolves to a typedef-name or the simple-template-id
  2648. // resolves to an alias template specialization, the
  2649. // elaborated-type-specifier is ill-formed.
  2650. Diag(TemplateLoc, diag::err_tag_reference_non_tag)
  2651. << TAT << NTK_TypeAliasTemplate << TagKind;
  2652. Diag(TAT->getLocation(), diag::note_declared_at);
  2653. }
  2654. QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
  2655. if (Result.isNull())
  2656. return TypeResult(true);
  2657. // Check the tag kind
  2658. if (const RecordType *RT = Result->getAs<RecordType>()) {
  2659. RecordDecl *D = RT->getDecl();
  2660. IdentifierInfo *Id = D->getIdentifier();
  2661. assert(Id && "templated class must have an identifier");
  2662. if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
  2663. TagLoc, Id)) {
  2664. Diag(TagLoc, diag::err_use_with_wrong_tag)
  2665. << Result
  2666. << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
  2667. Diag(D->getLocation(), diag::note_previous_use);
  2668. }
  2669. }
  2670. // Provide source-location information for the template specialization.
  2671. TypeLocBuilder TLB;
  2672. TemplateSpecializationTypeLoc SpecTL
  2673. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  2674. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  2675. SpecTL.setTemplateNameLoc(TemplateLoc);
  2676. SpecTL.setLAngleLoc(LAngleLoc);
  2677. SpecTL.setRAngleLoc(RAngleLoc);
  2678. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  2679. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  2680. // Construct an elaborated type containing the nested-name-specifier (if any)
  2681. // and tag keyword.
  2682. Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
  2683. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  2684. ElabTL.setElaboratedKeywordLoc(TagLoc);
  2685. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2686. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  2687. }
  2688. static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
  2689. NamedDecl *PrevDecl,
  2690. SourceLocation Loc,
  2691. bool IsPartialSpecialization);
  2692. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
  2693. static bool isTemplateArgumentTemplateParameter(
  2694. const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
  2695. switch (Arg.getKind()) {
  2696. case TemplateArgument::Null:
  2697. case TemplateArgument::NullPtr:
  2698. case TemplateArgument::Integral:
  2699. case TemplateArgument::Declaration:
  2700. case TemplateArgument::Pack:
  2701. case TemplateArgument::TemplateExpansion:
  2702. return false;
  2703. case TemplateArgument::Type: {
  2704. QualType Type = Arg.getAsType();
  2705. const TemplateTypeParmType *TPT =
  2706. Arg.getAsType()->getAs<TemplateTypeParmType>();
  2707. return TPT && !Type.hasQualifiers() &&
  2708. TPT->getDepth() == Depth && TPT->getIndex() == Index;
  2709. }
  2710. case TemplateArgument::Expression: {
  2711. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
  2712. if (!DRE || !DRE->getDecl())
  2713. return false;
  2714. const NonTypeTemplateParmDecl *NTTP =
  2715. dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
  2716. return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
  2717. }
  2718. case TemplateArgument::Template:
  2719. const TemplateTemplateParmDecl *TTP =
  2720. dyn_cast_or_null<TemplateTemplateParmDecl>(
  2721. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
  2722. return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
  2723. }
  2724. llvm_unreachable("unexpected kind of template argument");
  2725. }
  2726. static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
  2727. ArrayRef<TemplateArgument> Args) {
  2728. if (Params->size() != Args.size())
  2729. return false;
  2730. unsigned Depth = Params->getDepth();
  2731. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  2732. TemplateArgument Arg = Args[I];
  2733. // If the parameter is a pack expansion, the argument must be a pack
  2734. // whose only element is a pack expansion.
  2735. if (Params->getParam(I)->isParameterPack()) {
  2736. if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
  2737. !Arg.pack_begin()->isPackExpansion())
  2738. return false;
  2739. Arg = Arg.pack_begin()->getPackExpansionPattern();
  2740. }
  2741. if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
  2742. return false;
  2743. }
  2744. return true;
  2745. }
  2746. /// Convert the parser's template argument list representation into our form.
  2747. static TemplateArgumentListInfo
  2748. makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
  2749. TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
  2750. TemplateId.RAngleLoc);
  2751. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
  2752. TemplateId.NumArgs);
  2753. S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
  2754. return TemplateArgs;
  2755. }
  2756. template<typename PartialSpecDecl>
  2757. static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
  2758. if (Partial->getDeclContext()->isDependentContext())
  2759. return;
  2760. // FIXME: Get the TDK from deduction in order to provide better diagnostics
  2761. // for non-substitution-failure issues?
  2762. TemplateDeductionInfo Info(Partial->getLocation());
  2763. if (S.isMoreSpecializedThanPrimary(Partial, Info))
  2764. return;
  2765. auto *Template = Partial->getSpecializedTemplate();
  2766. S.Diag(Partial->getLocation(),
  2767. diag::ext_partial_spec_not_more_specialized_than_primary)
  2768. << isa<VarTemplateDecl>(Template);
  2769. if (Info.hasSFINAEDiagnostic()) {
  2770. PartialDiagnosticAt Diag = {SourceLocation(),
  2771. PartialDiagnostic::NullDiagnostic()};
  2772. Info.takeSFINAEDiagnostic(Diag);
  2773. SmallString<128> SFINAEArgString;
  2774. Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  2775. S.Diag(Diag.first,
  2776. diag::note_partial_spec_not_more_specialized_than_primary)
  2777. << SFINAEArgString;
  2778. }
  2779. S.Diag(Template->getLocation(), diag::note_template_decl_here);
  2780. }
  2781. static void
  2782. noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
  2783. const llvm::SmallBitVector &DeducibleParams) {
  2784. for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
  2785. if (!DeducibleParams[I]) {
  2786. NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
  2787. if (Param->getDeclName())
  2788. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  2789. << Param->getDeclName();
  2790. else
  2791. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  2792. << "(anonymous)";
  2793. }
  2794. }
  2795. }
  2796. template<typename PartialSpecDecl>
  2797. static void checkTemplatePartialSpecialization(Sema &S,
  2798. PartialSpecDecl *Partial) {
  2799. // C++1z [temp.class.spec]p8: (DR1495)
  2800. // - The specialization shall be more specialized than the primary
  2801. // template (14.5.5.2).
  2802. checkMoreSpecializedThanPrimary(S, Partial);
  2803. // C++ [temp.class.spec]p8: (DR1315)
  2804. // - Each template-parameter shall appear at least once in the
  2805. // template-id outside a non-deduced context.
  2806. // C++1z [temp.class.spec.match]p3 (P0127R2)
  2807. // If the template arguments of a partial specialization cannot be
  2808. // deduced because of the structure of its template-parameter-list
  2809. // and the template-id, the program is ill-formed.
  2810. auto *TemplateParams = Partial->getTemplateParameters();
  2811. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  2812. S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
  2813. TemplateParams->getDepth(), DeducibleParams);
  2814. if (!DeducibleParams.all()) {
  2815. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  2816. S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
  2817. << isa<VarTemplatePartialSpecializationDecl>(Partial)
  2818. << (NumNonDeducible > 1)
  2819. << SourceRange(Partial->getLocation(),
  2820. Partial->getTemplateArgsAsWritten()->RAngleLoc);
  2821. noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
  2822. }
  2823. }
  2824. void Sema::CheckTemplatePartialSpecialization(
  2825. ClassTemplatePartialSpecializationDecl *Partial) {
  2826. checkTemplatePartialSpecialization(*this, Partial);
  2827. }
  2828. void Sema::CheckTemplatePartialSpecialization(
  2829. VarTemplatePartialSpecializationDecl *Partial) {
  2830. checkTemplatePartialSpecialization(*this, Partial);
  2831. }
  2832. void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
  2833. // C++1z [temp.param]p11:
  2834. // A template parameter of a deduction guide template that does not have a
  2835. // default-argument shall be deducible from the parameter-type-list of the
  2836. // deduction guide template.
  2837. auto *TemplateParams = TD->getTemplateParameters();
  2838. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  2839. MarkDeducedTemplateParameters(TD, DeducibleParams);
  2840. for (unsigned I = 0; I != TemplateParams->size(); ++I) {
  2841. // A parameter pack is deducible (to an empty pack).
  2842. auto *Param = TemplateParams->getParam(I);
  2843. if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
  2844. DeducibleParams[I] = true;
  2845. }
  2846. if (!DeducibleParams.all()) {
  2847. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  2848. Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
  2849. << (NumNonDeducible > 1);
  2850. noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
  2851. }
  2852. }
  2853. DeclResult Sema::ActOnVarTemplateSpecialization(
  2854. Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
  2855. TemplateParameterList *TemplateParams, StorageClass SC,
  2856. bool IsPartialSpecialization) {
  2857. // D must be variable template id.
  2858. assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
  2859. "Variable template specialization is declared with a template it.");
  2860. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  2861. TemplateArgumentListInfo TemplateArgs =
  2862. makeTemplateArgumentListInfo(*this, *TemplateId);
  2863. SourceLocation TemplateNameLoc = D.getIdentifierLoc();
  2864. SourceLocation LAngleLoc = TemplateId->LAngleLoc;
  2865. SourceLocation RAngleLoc = TemplateId->RAngleLoc;
  2866. TemplateName Name = TemplateId->Template.get();
  2867. // The template-id must name a variable template.
  2868. VarTemplateDecl *VarTemplate =
  2869. dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
  2870. if (!VarTemplate) {
  2871. NamedDecl *FnTemplate;
  2872. if (auto *OTS = Name.getAsOverloadedTemplate())
  2873. FnTemplate = *OTS->begin();
  2874. else
  2875. FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
  2876. if (FnTemplate)
  2877. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
  2878. << FnTemplate->getDeclName();
  2879. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
  2880. << IsPartialSpecialization;
  2881. }
  2882. // Check for unexpanded parameter packs in any of the template arguments.
  2883. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  2884. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  2885. UPPC_PartialSpecialization))
  2886. return true;
  2887. // Check that the template argument list is well-formed for this
  2888. // template.
  2889. SmallVector<TemplateArgument, 4> Converted;
  2890. if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
  2891. false, Converted))
  2892. return true;
  2893. // Find the variable template (partial) specialization declaration that
  2894. // corresponds to these arguments.
  2895. if (IsPartialSpecialization) {
  2896. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
  2897. TemplateArgs.size(), Converted))
  2898. return true;
  2899. // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
  2900. // also do them during instantiation.
  2901. bool InstantiationDependent;
  2902. if (!Name.isDependent() &&
  2903. !TemplateSpecializationType::anyDependentTemplateArguments(
  2904. TemplateArgs.arguments(),
  2905. InstantiationDependent)) {
  2906. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  2907. << VarTemplate->getDeclName();
  2908. IsPartialSpecialization = false;
  2909. }
  2910. if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
  2911. Converted)) {
  2912. // C++ [temp.class.spec]p9b3:
  2913. //
  2914. // -- The argument list of the specialization shall not be identical
  2915. // to the implicit argument list of the primary template.
  2916. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  2917. << /*variable template*/ 1
  2918. << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
  2919. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  2920. // FIXME: Recover from this by treating the declaration as a redeclaration
  2921. // of the primary template.
  2922. return true;
  2923. }
  2924. }
  2925. void *InsertPos = nullptr;
  2926. VarTemplateSpecializationDecl *PrevDecl = nullptr;
  2927. if (IsPartialSpecialization)
  2928. // FIXME: Template parameter list matters too
  2929. PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
  2930. else
  2931. PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
  2932. VarTemplateSpecializationDecl *Specialization = nullptr;
  2933. // Check whether we can declare a variable template specialization in
  2934. // the current scope.
  2935. if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
  2936. TemplateNameLoc,
  2937. IsPartialSpecialization))
  2938. return true;
  2939. if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
  2940. // Since the only prior variable template specialization with these
  2941. // arguments was referenced but not declared, reuse that
  2942. // declaration node as our own, updating its source location and
  2943. // the list of outer template parameters to reflect our new declaration.
  2944. Specialization = PrevDecl;
  2945. Specialization->setLocation(TemplateNameLoc);
  2946. PrevDecl = nullptr;
  2947. } else if (IsPartialSpecialization) {
  2948. // Create a new class template partial specialization declaration node.
  2949. VarTemplatePartialSpecializationDecl *PrevPartial =
  2950. cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
  2951. VarTemplatePartialSpecializationDecl *Partial =
  2952. VarTemplatePartialSpecializationDecl::Create(
  2953. Context, VarTemplate->getDeclContext(), TemplateKWLoc,
  2954. TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
  2955. Converted, TemplateArgs);
  2956. if (!PrevPartial)
  2957. VarTemplate->AddPartialSpecialization(Partial, InsertPos);
  2958. Specialization = Partial;
  2959. // If we are providing an explicit specialization of a member variable
  2960. // template specialization, make a note of that.
  2961. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  2962. PrevPartial->setMemberSpecialization();
  2963. CheckTemplatePartialSpecialization(Partial);
  2964. } else {
  2965. // Create a new class template specialization declaration node for
  2966. // this explicit specialization or friend declaration.
  2967. Specialization = VarTemplateSpecializationDecl::Create(
  2968. Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
  2969. VarTemplate, DI->getType(), DI, SC, Converted);
  2970. Specialization->setTemplateArgsInfo(TemplateArgs);
  2971. if (!PrevDecl)
  2972. VarTemplate->AddSpecialization(Specialization, InsertPos);
  2973. }
  2974. // C++ [temp.expl.spec]p6:
  2975. // If a template, a member template or the member of a class template is
  2976. // explicitly specialized then that specialization shall be declared
  2977. // before the first use of that specialization that would cause an implicit
  2978. // instantiation to take place, in every translation unit in which such a
  2979. // use occurs; no diagnostic is required.
  2980. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  2981. bool Okay = false;
  2982. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  2983. // Is there any previous explicit specialization declaration?
  2984. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  2985. Okay = true;
  2986. break;
  2987. }
  2988. }
  2989. if (!Okay) {
  2990. SourceRange Range(TemplateNameLoc, RAngleLoc);
  2991. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  2992. << Name << Range;
  2993. Diag(PrevDecl->getPointOfInstantiation(),
  2994. diag::note_instantiation_required_here)
  2995. << (PrevDecl->getTemplateSpecializationKind() !=
  2996. TSK_ImplicitInstantiation);
  2997. return true;
  2998. }
  2999. }
  3000. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  3001. Specialization->setLexicalDeclContext(CurContext);
  3002. // Add the specialization into its lexical context, so that it can
  3003. // be seen when iterating through the list of declarations in that
  3004. // context. However, specializations are not found by name lookup.
  3005. CurContext->addDecl(Specialization);
  3006. // Note that this is an explicit specialization.
  3007. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  3008. if (PrevDecl) {
  3009. // Check that this isn't a redefinition of this specialization,
  3010. // merging with previous declarations.
  3011. LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
  3012. ForRedeclaration);
  3013. PrevSpec.addDecl(PrevDecl);
  3014. D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
  3015. } else if (Specialization->isStaticDataMember() &&
  3016. Specialization->isOutOfLine()) {
  3017. Specialization->setAccess(VarTemplate->getAccess());
  3018. }
  3019. // Link instantiations of static data members back to the template from
  3020. // which they were instantiated.
  3021. if (Specialization->isStaticDataMember())
  3022. Specialization->setInstantiationOfStaticDataMember(
  3023. VarTemplate->getTemplatedDecl(),
  3024. Specialization->getSpecializationKind());
  3025. return Specialization;
  3026. }
  3027. namespace {
  3028. /// \brief A partial specialization whose template arguments have matched
  3029. /// a given template-id.
  3030. struct PartialSpecMatchResult {
  3031. VarTemplatePartialSpecializationDecl *Partial;
  3032. TemplateArgumentList *Args;
  3033. };
  3034. } // end anonymous namespace
  3035. DeclResult
  3036. Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
  3037. SourceLocation TemplateNameLoc,
  3038. const TemplateArgumentListInfo &TemplateArgs) {
  3039. assert(Template && "A variable template id without template?");
  3040. // Check that the template argument list is well-formed for this template.
  3041. SmallVector<TemplateArgument, 4> Converted;
  3042. if (CheckTemplateArgumentList(
  3043. Template, TemplateNameLoc,
  3044. const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
  3045. Converted))
  3046. return true;
  3047. // Find the variable template specialization declaration that
  3048. // corresponds to these arguments.
  3049. void *InsertPos = nullptr;
  3050. if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
  3051. Converted, InsertPos)) {
  3052. checkSpecializationVisibility(TemplateNameLoc, Spec);
  3053. // If we already have a variable template specialization, return it.
  3054. return Spec;
  3055. }
  3056. // This is the first time we have referenced this variable template
  3057. // specialization. Create the canonical declaration and add it to
  3058. // the set of specializations, based on the closest partial specialization
  3059. // that it represents. That is,
  3060. VarDecl *InstantiationPattern = Template->getTemplatedDecl();
  3061. TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
  3062. Converted);
  3063. TemplateArgumentList *InstantiationArgs = &TemplateArgList;
  3064. bool AmbiguousPartialSpec = false;
  3065. typedef PartialSpecMatchResult MatchResult;
  3066. SmallVector<MatchResult, 4> Matched;
  3067. SourceLocation PointOfInstantiation = TemplateNameLoc;
  3068. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
  3069. /*ForTakingAddress=*/false);
  3070. // 1. Attempt to find the closest partial specialization that this
  3071. // specializes, if any.
  3072. // If any of the template arguments is dependent, then this is probably
  3073. // a placeholder for an incomplete declarative context; which must be
  3074. // complete by instantiation time. Thus, do not search through the partial
  3075. // specializations yet.
  3076. // TODO: Unify with InstantiateClassTemplateSpecialization()?
  3077. // Perhaps better after unification of DeduceTemplateArguments() and
  3078. // getMoreSpecializedPartialSpecialization().
  3079. bool InstantiationDependent = false;
  3080. if (!TemplateSpecializationType::anyDependentTemplateArguments(
  3081. TemplateArgs, InstantiationDependent)) {
  3082. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  3083. Template->getPartialSpecializations(PartialSpecs);
  3084. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  3085. VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  3086. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  3087. if (TemplateDeductionResult Result =
  3088. DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
  3089. // Store the failed-deduction information for use in diagnostics, later.
  3090. // TODO: Actually use the failed-deduction info?
  3091. FailedCandidates.addCandidate().set(
  3092. DeclAccessPair::make(Template, AS_public), Partial,
  3093. MakeDeductionFailureInfo(Context, Result, Info));
  3094. (void)Result;
  3095. } else {
  3096. Matched.push_back(PartialSpecMatchResult());
  3097. Matched.back().Partial = Partial;
  3098. Matched.back().Args = Info.take();
  3099. }
  3100. }
  3101. if (Matched.size() >= 1) {
  3102. SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
  3103. if (Matched.size() == 1) {
  3104. // -- If exactly one matching specialization is found, the
  3105. // instantiation is generated from that specialization.
  3106. // We don't need to do anything for this.
  3107. } else {
  3108. // -- If more than one matching specialization is found, the
  3109. // partial order rules (14.5.4.2) are used to determine
  3110. // whether one of the specializations is more specialized
  3111. // than the others. If none of the specializations is more
  3112. // specialized than all of the other matching
  3113. // specializations, then the use of the variable template is
  3114. // ambiguous and the program is ill-formed.
  3115. for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
  3116. PEnd = Matched.end();
  3117. P != PEnd; ++P) {
  3118. if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
  3119. PointOfInstantiation) ==
  3120. P->Partial)
  3121. Best = P;
  3122. }
  3123. // Determine if the best partial specialization is more specialized than
  3124. // the others.
  3125. for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
  3126. PEnd = Matched.end();
  3127. P != PEnd; ++P) {
  3128. if (P != Best && getMoreSpecializedPartialSpecialization(
  3129. P->Partial, Best->Partial,
  3130. PointOfInstantiation) != Best->Partial) {
  3131. AmbiguousPartialSpec = true;
  3132. break;
  3133. }
  3134. }
  3135. }
  3136. // Instantiate using the best variable template partial specialization.
  3137. InstantiationPattern = Best->Partial;
  3138. InstantiationArgs = Best->Args;
  3139. } else {
  3140. // -- If no match is found, the instantiation is generated
  3141. // from the primary template.
  3142. // InstantiationPattern = Template->getTemplatedDecl();
  3143. }
  3144. }
  3145. // 2. Create the canonical declaration.
  3146. // Note that we do not instantiate a definition until we see an odr-use
  3147. // in DoMarkVarDeclReferenced().
  3148. // FIXME: LateAttrs et al.?
  3149. VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
  3150. Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
  3151. Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
  3152. if (!Decl)
  3153. return true;
  3154. if (AmbiguousPartialSpec) {
  3155. // Partial ordering did not produce a clear winner. Complain.
  3156. Decl->setInvalidDecl();
  3157. Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
  3158. << Decl;
  3159. // Print the matching partial specializations.
  3160. for (MatchResult P : Matched)
  3161. Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
  3162. << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
  3163. *P.Args);
  3164. return true;
  3165. }
  3166. if (VarTemplatePartialSpecializationDecl *D =
  3167. dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
  3168. Decl->setInstantiationOf(D, InstantiationArgs);
  3169. checkSpecializationVisibility(TemplateNameLoc, Decl);
  3170. assert(Decl && "No variable template specialization?");
  3171. return Decl;
  3172. }
  3173. ExprResult
  3174. Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
  3175. const DeclarationNameInfo &NameInfo,
  3176. VarTemplateDecl *Template, SourceLocation TemplateLoc,
  3177. const TemplateArgumentListInfo *TemplateArgs) {
  3178. DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
  3179. *TemplateArgs);
  3180. if (Decl.isInvalid())
  3181. return ExprError();
  3182. VarDecl *Var = cast<VarDecl>(Decl.get());
  3183. if (!Var->getTemplateSpecializationKind())
  3184. Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
  3185. NameInfo.getLoc());
  3186. // Build an ordinary singleton decl ref.
  3187. return BuildDeclarationNameExpr(SS, NameInfo, Var,
  3188. /*FoundD=*/nullptr, TemplateArgs);
  3189. }
  3190. ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
  3191. SourceLocation TemplateKWLoc,
  3192. LookupResult &R,
  3193. bool RequiresADL,
  3194. const TemplateArgumentListInfo *TemplateArgs) {
  3195. // FIXME: Can we do any checking at this point? I guess we could check the
  3196. // template arguments that we have against the template name, if the template
  3197. // name refers to a single template. That's not a terribly common case,
  3198. // though.
  3199. // foo<int> could identify a single function unambiguously
  3200. // This approach does NOT work, since f<int>(1);
  3201. // gets resolved prior to resorting to overload resolution
  3202. // i.e., template<class T> void f(double);
  3203. // vs template<class T, class U> void f(U);
  3204. // These should be filtered out by our callers.
  3205. assert(!R.empty() && "empty lookup results when building templateid");
  3206. assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
  3207. // In C++1y, check variable template ids.
  3208. bool InstantiationDependent;
  3209. if (R.getAsSingle<VarTemplateDecl>() &&
  3210. !TemplateSpecializationType::anyDependentTemplateArguments(
  3211. *TemplateArgs, InstantiationDependent)) {
  3212. return CheckVarTemplateId(SS, R.getLookupNameInfo(),
  3213. R.getAsSingle<VarTemplateDecl>(),
  3214. TemplateKWLoc, TemplateArgs);
  3215. }
  3216. // We don't want lookup warnings at this point.
  3217. R.suppressDiagnostics();
  3218. UnresolvedLookupExpr *ULE
  3219. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  3220. SS.getWithLocInContext(Context),
  3221. TemplateKWLoc,
  3222. R.getLookupNameInfo(),
  3223. RequiresADL, TemplateArgs,
  3224. R.begin(), R.end());
  3225. return ULE;
  3226. }
  3227. // We actually only call this from template instantiation.
  3228. ExprResult
  3229. Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
  3230. SourceLocation TemplateKWLoc,
  3231. const DeclarationNameInfo &NameInfo,
  3232. const TemplateArgumentListInfo *TemplateArgs) {
  3233. assert(TemplateArgs || TemplateKWLoc.isValid());
  3234. DeclContext *DC;
  3235. if (!(DC = computeDeclContext(SS, false)) ||
  3236. DC->isDependentContext() ||
  3237. RequireCompleteDeclContext(SS, DC))
  3238. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  3239. bool MemberOfUnknownSpecialization;
  3240. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  3241. LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
  3242. MemberOfUnknownSpecialization);
  3243. if (R.isAmbiguous())
  3244. return ExprError();
  3245. if (R.empty()) {
  3246. Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
  3247. << NameInfo.getName() << SS.getRange();
  3248. return ExprError();
  3249. }
  3250. if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
  3251. Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
  3252. << SS.getScopeRep()
  3253. << NameInfo.getName().getAsString() << SS.getRange();
  3254. Diag(Temp->getLocation(), diag::note_referenced_class_template);
  3255. return ExprError();
  3256. }
  3257. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
  3258. }
  3259. /// \brief Form a dependent template name.
  3260. ///
  3261. /// This action forms a dependent template name given the template
  3262. /// name and its (presumably dependent) scope specifier. For
  3263. /// example, given "MetaFun::template apply", the scope specifier \p
  3264. /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
  3265. /// of the "template" keyword, and "apply" is the \p Name.
  3266. TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
  3267. CXXScopeSpec &SS,
  3268. SourceLocation TemplateKWLoc,
  3269. UnqualifiedId &Name,
  3270. ParsedType ObjectType,
  3271. bool EnteringContext,
  3272. TemplateTy &Result,
  3273. bool AllowInjectedClassName) {
  3274. if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
  3275. Diag(TemplateKWLoc,
  3276. getLangOpts().CPlusPlus11 ?
  3277. diag::warn_cxx98_compat_template_outside_of_template :
  3278. diag::ext_template_outside_of_template)
  3279. << FixItHint::CreateRemoval(TemplateKWLoc);
  3280. DeclContext *LookupCtx = nullptr;
  3281. if (SS.isSet())
  3282. LookupCtx = computeDeclContext(SS, EnteringContext);
  3283. if (!LookupCtx && ObjectType)
  3284. LookupCtx = computeDeclContext(ObjectType.get());
  3285. if (LookupCtx) {
  3286. // C++0x [temp.names]p5:
  3287. // If a name prefixed by the keyword template is not the name of
  3288. // a template, the program is ill-formed. [Note: the keyword
  3289. // template may not be applied to non-template members of class
  3290. // templates. -end note ] [ Note: as is the case with the
  3291. // typename prefix, the template prefix is allowed in cases
  3292. // where it is not strictly necessary; i.e., when the
  3293. // nested-name-specifier or the expression on the left of the ->
  3294. // or . is not dependent on a template-parameter, or the use
  3295. // does not appear in the scope of a template. -end note]
  3296. //
  3297. // Note: C++03 was more strict here, because it banned the use of
  3298. // the "template" keyword prior to a template-name that was not a
  3299. // dependent name. C++ DR468 relaxed this requirement (the
  3300. // "template" keyword is now permitted). We follow the C++0x
  3301. // rules, even in C++03 mode with a warning, retroactively applying the DR.
  3302. bool MemberOfUnknownSpecialization;
  3303. TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
  3304. ObjectType, EnteringContext, Result,
  3305. MemberOfUnknownSpecialization);
  3306. if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
  3307. isa<CXXRecordDecl>(LookupCtx) &&
  3308. (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
  3309. cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
  3310. // This is a dependent template. Handle it below.
  3311. } else if (TNK == TNK_Non_template) {
  3312. Diag(Name.getLocStart(),
  3313. diag::err_template_kw_refers_to_non_template)
  3314. << GetNameFromUnqualifiedId(Name).getName()
  3315. << Name.getSourceRange()
  3316. << TemplateKWLoc;
  3317. return TNK_Non_template;
  3318. } else {
  3319. // We found something; return it.
  3320. auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
  3321. if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
  3322. Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
  3323. LookupRD->getIdentifier() == Name.Identifier) {
  3324. // C++14 [class.qual]p2:
  3325. // In a lookup in which function names are not ignored and the
  3326. // nested-name-specifier nominates a class C, if the name specified
  3327. // [...] is the injected-class-name of C, [...] the name is instead
  3328. // considered to name the constructor
  3329. //
  3330. // We don't get here if naming the constructor would be valid, so we
  3331. // just reject immediately and recover by treating the
  3332. // injected-class-name as naming the template.
  3333. Diag(Name.getLocStart(),
  3334. diag::ext_out_of_line_qualified_id_type_names_constructor)
  3335. << Name.Identifier << 0 /*injected-class-name used as template name*/
  3336. << 1 /*'template' keyword was used*/;
  3337. }
  3338. return TNK;
  3339. }
  3340. }
  3341. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  3342. switch (Name.getKind()) {
  3343. case UnqualifiedId::IK_Identifier:
  3344. Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
  3345. Name.Identifier));
  3346. return TNK_Dependent_template_name;
  3347. case UnqualifiedId::IK_OperatorFunctionId:
  3348. Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
  3349. Name.OperatorFunctionId.Operator));
  3350. return TNK_Function_template;
  3351. case UnqualifiedId::IK_LiteralOperatorId:
  3352. llvm_unreachable("literal operator id cannot have a dependent scope");
  3353. default:
  3354. break;
  3355. }
  3356. Diag(Name.getLocStart(),
  3357. diag::err_template_kw_refers_to_non_template)
  3358. << GetNameFromUnqualifiedId(Name).getName()
  3359. << Name.getSourceRange()
  3360. << TemplateKWLoc;
  3361. return TNK_Non_template;
  3362. }
  3363. bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
  3364. TemplateArgumentLoc &AL,
  3365. SmallVectorImpl<TemplateArgument> &Converted) {
  3366. const TemplateArgument &Arg = AL.getArgument();
  3367. QualType ArgType;
  3368. TypeSourceInfo *TSI = nullptr;
  3369. // Check template type parameter.
  3370. switch(Arg.getKind()) {
  3371. case TemplateArgument::Type:
  3372. // C++ [temp.arg.type]p1:
  3373. // A template-argument for a template-parameter which is a
  3374. // type shall be a type-id.
  3375. ArgType = Arg.getAsType();
  3376. TSI = AL.getTypeSourceInfo();
  3377. break;
  3378. case TemplateArgument::Template: {
  3379. // We have a template type parameter but the template argument
  3380. // is a template without any arguments.
  3381. SourceRange SR = AL.getSourceRange();
  3382. TemplateName Name = Arg.getAsTemplate();
  3383. Diag(SR.getBegin(), diag::err_template_missing_args)
  3384. << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
  3385. if (TemplateDecl *Decl = Name.getAsTemplateDecl())
  3386. Diag(Decl->getLocation(), diag::note_template_decl_here);
  3387. return true;
  3388. }
  3389. case TemplateArgument::Expression: {
  3390. // We have a template type parameter but the template argument is an
  3391. // expression; see if maybe it is missing the "typename" keyword.
  3392. CXXScopeSpec SS;
  3393. DeclarationNameInfo NameInfo;
  3394. if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
  3395. SS.Adopt(ArgExpr->getQualifierLoc());
  3396. NameInfo = ArgExpr->getNameInfo();
  3397. } else if (DependentScopeDeclRefExpr *ArgExpr =
  3398. dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
  3399. SS.Adopt(ArgExpr->getQualifierLoc());
  3400. NameInfo = ArgExpr->getNameInfo();
  3401. } else if (CXXDependentScopeMemberExpr *ArgExpr =
  3402. dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
  3403. if (ArgExpr->isImplicitAccess()) {
  3404. SS.Adopt(ArgExpr->getQualifierLoc());
  3405. NameInfo = ArgExpr->getMemberNameInfo();
  3406. }
  3407. }
  3408. if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
  3409. LookupResult Result(*this, NameInfo, LookupOrdinaryName);
  3410. LookupParsedName(Result, CurScope, &SS);
  3411. if (Result.getAsSingle<TypeDecl>() ||
  3412. Result.getResultKind() ==
  3413. LookupResult::NotFoundInCurrentInstantiation) {
  3414. // Suggest that the user add 'typename' before the NNS.
  3415. SourceLocation Loc = AL.getSourceRange().getBegin();
  3416. Diag(Loc, getLangOpts().MSVCCompat
  3417. ? diag::ext_ms_template_type_arg_missing_typename
  3418. : diag::err_template_arg_must_be_type_suggest)
  3419. << FixItHint::CreateInsertion(Loc, "typename ");
  3420. Diag(Param->getLocation(), diag::note_template_param_here);
  3421. // Recover by synthesizing a type using the location information that we
  3422. // already have.
  3423. ArgType =
  3424. Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
  3425. TypeLocBuilder TLB;
  3426. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
  3427. TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
  3428. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3429. TL.setNameLoc(NameInfo.getLoc());
  3430. TSI = TLB.getTypeSourceInfo(Context, ArgType);
  3431. // Overwrite our input TemplateArgumentLoc so that we can recover
  3432. // properly.
  3433. AL = TemplateArgumentLoc(TemplateArgument(ArgType),
  3434. TemplateArgumentLocInfo(TSI));
  3435. break;
  3436. }
  3437. }
  3438. // fallthrough
  3439. }
  3440. default: {
  3441. // We have a template type parameter but the template argument
  3442. // is not a type.
  3443. SourceRange SR = AL.getSourceRange();
  3444. Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
  3445. Diag(Param->getLocation(), diag::note_template_param_here);
  3446. return true;
  3447. }
  3448. }
  3449. if (CheckTemplateArgument(Param, TSI))
  3450. return true;
  3451. // Add the converted template type argument.
  3452. ArgType = Context.getCanonicalType(ArgType);
  3453. // Objective-C ARC:
  3454. // If an explicitly-specified template argument type is a lifetime type
  3455. // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
  3456. if (getLangOpts().ObjCAutoRefCount &&
  3457. ArgType->isObjCLifetimeType() &&
  3458. !ArgType.getObjCLifetime()) {
  3459. Qualifiers Qs;
  3460. Qs.setObjCLifetime(Qualifiers::OCL_Strong);
  3461. ArgType = Context.getQualifiedType(ArgType, Qs);
  3462. }
  3463. Converted.push_back(TemplateArgument(ArgType));
  3464. return false;
  3465. }
  3466. /// \brief Substitute template arguments into the default template argument for
  3467. /// the given template type parameter.
  3468. ///
  3469. /// \param SemaRef the semantic analysis object for which we are performing
  3470. /// the substitution.
  3471. ///
  3472. /// \param Template the template that we are synthesizing template arguments
  3473. /// for.
  3474. ///
  3475. /// \param TemplateLoc the location of the template name that started the
  3476. /// template-id we are checking.
  3477. ///
  3478. /// \param RAngleLoc the location of the right angle bracket ('>') that
  3479. /// terminates the template-id.
  3480. ///
  3481. /// \param Param the template template parameter whose default we are
  3482. /// substituting into.
  3483. ///
  3484. /// \param Converted the list of template arguments provided for template
  3485. /// parameters that precede \p Param in the template parameter list.
  3486. /// \returns the substituted template argument, or NULL if an error occurred.
  3487. static TypeSourceInfo *
  3488. SubstDefaultTemplateArgument(Sema &SemaRef,
  3489. TemplateDecl *Template,
  3490. SourceLocation TemplateLoc,
  3491. SourceLocation RAngleLoc,
  3492. TemplateTypeParmDecl *Param,
  3493. SmallVectorImpl<TemplateArgument> &Converted) {
  3494. TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
  3495. // If the argument type is dependent, instantiate it now based
  3496. // on the previously-computed template arguments.
  3497. if (ArgType->getType()->isDependentType()) {
  3498. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
  3499. Param, Template, Converted,
  3500. SourceRange(TemplateLoc, RAngleLoc));
  3501. if (Inst.isInvalid())
  3502. return nullptr;
  3503. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  3504. // Only substitute for the innermost template argument list.
  3505. MultiLevelTemplateArgumentList TemplateArgLists;
  3506. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  3507. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  3508. TemplateArgLists.addOuterTemplateArguments(None);
  3509. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  3510. ArgType =
  3511. SemaRef.SubstType(ArgType, TemplateArgLists,
  3512. Param->getDefaultArgumentLoc(), Param->getDeclName());
  3513. }
  3514. return ArgType;
  3515. }
  3516. /// \brief Substitute template arguments into the default template argument for
  3517. /// the given non-type template parameter.
  3518. ///
  3519. /// \param SemaRef the semantic analysis object for which we are performing
  3520. /// the substitution.
  3521. ///
  3522. /// \param Template the template that we are synthesizing template arguments
  3523. /// for.
  3524. ///
  3525. /// \param TemplateLoc the location of the template name that started the
  3526. /// template-id we are checking.
  3527. ///
  3528. /// \param RAngleLoc the location of the right angle bracket ('>') that
  3529. /// terminates the template-id.
  3530. ///
  3531. /// \param Param the non-type template parameter whose default we are
  3532. /// substituting into.
  3533. ///
  3534. /// \param Converted the list of template arguments provided for template
  3535. /// parameters that precede \p Param in the template parameter list.
  3536. ///
  3537. /// \returns the substituted template argument, or NULL if an error occurred.
  3538. static ExprResult
  3539. SubstDefaultTemplateArgument(Sema &SemaRef,
  3540. TemplateDecl *Template,
  3541. SourceLocation TemplateLoc,
  3542. SourceLocation RAngleLoc,
  3543. NonTypeTemplateParmDecl *Param,
  3544. SmallVectorImpl<TemplateArgument> &Converted) {
  3545. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
  3546. Param, Template, Converted,
  3547. SourceRange(TemplateLoc, RAngleLoc));
  3548. if (Inst.isInvalid())
  3549. return ExprError();
  3550. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  3551. // Only substitute for the innermost template argument list.
  3552. MultiLevelTemplateArgumentList TemplateArgLists;
  3553. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  3554. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  3555. TemplateArgLists.addOuterTemplateArguments(None);
  3556. EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
  3557. Sema::ConstantEvaluated);
  3558. return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
  3559. }
  3560. /// \brief Substitute template arguments into the default template argument for
  3561. /// the given template template parameter.
  3562. ///
  3563. /// \param SemaRef the semantic analysis object for which we are performing
  3564. /// the substitution.
  3565. ///
  3566. /// \param Template the template that we are synthesizing template arguments
  3567. /// for.
  3568. ///
  3569. /// \param TemplateLoc the location of the template name that started the
  3570. /// template-id we are checking.
  3571. ///
  3572. /// \param RAngleLoc the location of the right angle bracket ('>') that
  3573. /// terminates the template-id.
  3574. ///
  3575. /// \param Param the template template parameter whose default we are
  3576. /// substituting into.
  3577. ///
  3578. /// \param Converted the list of template arguments provided for template
  3579. /// parameters that precede \p Param in the template parameter list.
  3580. ///
  3581. /// \param QualifierLoc Will be set to the nested-name-specifier (with
  3582. /// source-location information) that precedes the template name.
  3583. ///
  3584. /// \returns the substituted template argument, or NULL if an error occurred.
  3585. static TemplateName
  3586. SubstDefaultTemplateArgument(Sema &SemaRef,
  3587. TemplateDecl *Template,
  3588. SourceLocation TemplateLoc,
  3589. SourceLocation RAngleLoc,
  3590. TemplateTemplateParmDecl *Param,
  3591. SmallVectorImpl<TemplateArgument> &Converted,
  3592. NestedNameSpecifierLoc &QualifierLoc) {
  3593. Sema::InstantiatingTemplate Inst(
  3594. SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
  3595. SourceRange(TemplateLoc, RAngleLoc));
  3596. if (Inst.isInvalid())
  3597. return TemplateName();
  3598. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  3599. // Only substitute for the innermost template argument list.
  3600. MultiLevelTemplateArgumentList TemplateArgLists;
  3601. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  3602. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  3603. TemplateArgLists.addOuterTemplateArguments(None);
  3604. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  3605. // Substitute into the nested-name-specifier first,
  3606. QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
  3607. if (QualifierLoc) {
  3608. QualifierLoc =
  3609. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
  3610. if (!QualifierLoc)
  3611. return TemplateName();
  3612. }
  3613. return SemaRef.SubstTemplateName(
  3614. QualifierLoc,
  3615. Param->getDefaultArgument().getArgument().getAsTemplate(),
  3616. Param->getDefaultArgument().getTemplateNameLoc(),
  3617. TemplateArgLists);
  3618. }
  3619. /// \brief If the given template parameter has a default template
  3620. /// argument, substitute into that default template argument and
  3621. /// return the corresponding template argument.
  3622. TemplateArgumentLoc
  3623. Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
  3624. SourceLocation TemplateLoc,
  3625. SourceLocation RAngleLoc,
  3626. Decl *Param,
  3627. SmallVectorImpl<TemplateArgument>
  3628. &Converted,
  3629. bool &HasDefaultArg) {
  3630. HasDefaultArg = false;
  3631. if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
  3632. if (!hasVisibleDefaultArgument(TypeParm))
  3633. return TemplateArgumentLoc();
  3634. HasDefaultArg = true;
  3635. TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
  3636. TemplateLoc,
  3637. RAngleLoc,
  3638. TypeParm,
  3639. Converted);
  3640. if (DI)
  3641. return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
  3642. return TemplateArgumentLoc();
  3643. }
  3644. if (NonTypeTemplateParmDecl *NonTypeParm
  3645. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  3646. if (!hasVisibleDefaultArgument(NonTypeParm))
  3647. return TemplateArgumentLoc();
  3648. HasDefaultArg = true;
  3649. ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
  3650. TemplateLoc,
  3651. RAngleLoc,
  3652. NonTypeParm,
  3653. Converted);
  3654. if (Arg.isInvalid())
  3655. return TemplateArgumentLoc();
  3656. Expr *ArgE = Arg.getAs<Expr>();
  3657. return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
  3658. }
  3659. TemplateTemplateParmDecl *TempTempParm
  3660. = cast<TemplateTemplateParmDecl>(Param);
  3661. if (!hasVisibleDefaultArgument(TempTempParm))
  3662. return TemplateArgumentLoc();
  3663. HasDefaultArg = true;
  3664. NestedNameSpecifierLoc QualifierLoc;
  3665. TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
  3666. TemplateLoc,
  3667. RAngleLoc,
  3668. TempTempParm,
  3669. Converted,
  3670. QualifierLoc);
  3671. if (TName.isNull())
  3672. return TemplateArgumentLoc();
  3673. return TemplateArgumentLoc(TemplateArgument(TName),
  3674. TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
  3675. TempTempParm->getDefaultArgument().getTemplateNameLoc());
  3676. }
  3677. /// Convert a template-argument that we parsed as a type into a template, if
  3678. /// possible. C++ permits injected-class-names to perform dual service as
  3679. /// template template arguments and as template type arguments.
  3680. static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
  3681. // Extract and step over any surrounding nested-name-specifier.
  3682. NestedNameSpecifierLoc QualLoc;
  3683. if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
  3684. if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
  3685. return TemplateArgumentLoc();
  3686. QualLoc = ETLoc.getQualifierLoc();
  3687. TLoc = ETLoc.getNamedTypeLoc();
  3688. }
  3689. // If this type was written as an injected-class-name, it can be used as a
  3690. // template template argument.
  3691. if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
  3692. return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
  3693. QualLoc, InjLoc.getNameLoc());
  3694. // If this type was written as an injected-class-name, it may have been
  3695. // converted to a RecordType during instantiation. If the RecordType is
  3696. // *not* wrapped in a TemplateSpecializationType and denotes a class
  3697. // template specialization, it must have come from an injected-class-name.
  3698. if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
  3699. if (auto *CTSD =
  3700. dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
  3701. return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
  3702. QualLoc, RecLoc.getNameLoc());
  3703. return TemplateArgumentLoc();
  3704. }
  3705. /// \brief Check that the given template argument corresponds to the given
  3706. /// template parameter.
  3707. ///
  3708. /// \param Param The template parameter against which the argument will be
  3709. /// checked.
  3710. ///
  3711. /// \param Arg The template argument, which may be updated due to conversions.
  3712. ///
  3713. /// \param Template The template in which the template argument resides.
  3714. ///
  3715. /// \param TemplateLoc The location of the template name for the template
  3716. /// whose argument list we're matching.
  3717. ///
  3718. /// \param RAngleLoc The location of the right angle bracket ('>') that closes
  3719. /// the template argument list.
  3720. ///
  3721. /// \param ArgumentPackIndex The index into the argument pack where this
  3722. /// argument will be placed. Only valid if the parameter is a parameter pack.
  3723. ///
  3724. /// \param Converted The checked, converted argument will be added to the
  3725. /// end of this small vector.
  3726. ///
  3727. /// \param CTAK Describes how we arrived at this particular template argument:
  3728. /// explicitly written, deduced, etc.
  3729. ///
  3730. /// \returns true on error, false otherwise.
  3731. bool Sema::CheckTemplateArgument(NamedDecl *Param,
  3732. TemplateArgumentLoc &Arg,
  3733. NamedDecl *Template,
  3734. SourceLocation TemplateLoc,
  3735. SourceLocation RAngleLoc,
  3736. unsigned ArgumentPackIndex,
  3737. SmallVectorImpl<TemplateArgument> &Converted,
  3738. CheckTemplateArgumentKind CTAK) {
  3739. // Check template type parameters.
  3740. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  3741. return CheckTemplateTypeArgument(TTP, Arg, Converted);
  3742. // Check non-type template parameters.
  3743. if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  3744. // Do substitution on the type of the non-type template parameter
  3745. // with the template arguments we've seen thus far. But if the
  3746. // template has a dependent context then we cannot substitute yet.
  3747. QualType NTTPType = NTTP->getType();
  3748. if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
  3749. NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
  3750. if (NTTPType->isDependentType() &&
  3751. !isa<TemplateTemplateParmDecl>(Template) &&
  3752. !Template->getDeclContext()->isDependentContext()) {
  3753. // Do substitution on the type of the non-type template parameter.
  3754. InstantiatingTemplate Inst(*this, TemplateLoc, Template,
  3755. NTTP, Converted,
  3756. SourceRange(TemplateLoc, RAngleLoc));
  3757. if (Inst.isInvalid())
  3758. return true;
  3759. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
  3760. Converted);
  3761. NTTPType = SubstType(NTTPType,
  3762. MultiLevelTemplateArgumentList(TemplateArgs),
  3763. NTTP->getLocation(),
  3764. NTTP->getDeclName());
  3765. // If that worked, check the non-type template parameter type
  3766. // for validity.
  3767. if (!NTTPType.isNull())
  3768. NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
  3769. NTTP->getLocation());
  3770. if (NTTPType.isNull())
  3771. return true;
  3772. }
  3773. switch (Arg.getArgument().getKind()) {
  3774. case TemplateArgument::Null:
  3775. llvm_unreachable("Should never see a NULL template argument here");
  3776. case TemplateArgument::Expression: {
  3777. TemplateArgument Result;
  3778. ExprResult Res =
  3779. CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
  3780. Result, CTAK);
  3781. if (Res.isInvalid())
  3782. return true;
  3783. // If the resulting expression is new, then use it in place of the
  3784. // old expression in the template argument.
  3785. if (Res.get() != Arg.getArgument().getAsExpr()) {
  3786. TemplateArgument TA(Res.get());
  3787. Arg = TemplateArgumentLoc(TA, Res.get());
  3788. }
  3789. Converted.push_back(Result);
  3790. break;
  3791. }
  3792. case TemplateArgument::Declaration:
  3793. case TemplateArgument::Integral:
  3794. case TemplateArgument::NullPtr:
  3795. // We've already checked this template argument, so just copy
  3796. // it to the list of converted arguments.
  3797. Converted.push_back(Arg.getArgument());
  3798. break;
  3799. case TemplateArgument::Template:
  3800. case TemplateArgument::TemplateExpansion:
  3801. // We were given a template template argument. It may not be ill-formed;
  3802. // see below.
  3803. if (DependentTemplateName *DTN
  3804. = Arg.getArgument().getAsTemplateOrTemplatePattern()
  3805. .getAsDependentTemplateName()) {
  3806. // We have a template argument such as \c T::template X, which we
  3807. // parsed as a template template argument. However, since we now
  3808. // know that we need a non-type template argument, convert this
  3809. // template name into an expression.
  3810. DeclarationNameInfo NameInfo(DTN->getIdentifier(),
  3811. Arg.getTemplateNameLoc());
  3812. CXXScopeSpec SS;
  3813. SS.Adopt(Arg.getTemplateQualifierLoc());
  3814. // FIXME: the template-template arg was a DependentTemplateName,
  3815. // so it was provided with a template keyword. However, its source
  3816. // location is not stored in the template argument structure.
  3817. SourceLocation TemplateKWLoc;
  3818. ExprResult E = DependentScopeDeclRefExpr::Create(
  3819. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  3820. nullptr);
  3821. // If we parsed the template argument as a pack expansion, create a
  3822. // pack expansion expression.
  3823. if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
  3824. E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
  3825. if (E.isInvalid())
  3826. return true;
  3827. }
  3828. TemplateArgument Result;
  3829. E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
  3830. if (E.isInvalid())
  3831. return true;
  3832. Converted.push_back(Result);
  3833. break;
  3834. }
  3835. // We have a template argument that actually does refer to a class
  3836. // template, alias template, or template template parameter, and
  3837. // therefore cannot be a non-type template argument.
  3838. Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
  3839. << Arg.getSourceRange();
  3840. Diag(Param->getLocation(), diag::note_template_param_here);
  3841. return true;
  3842. case TemplateArgument::Type: {
  3843. // We have a non-type template parameter but the template
  3844. // argument is a type.
  3845. // C++ [temp.arg]p2:
  3846. // In a template-argument, an ambiguity between a type-id and
  3847. // an expression is resolved to a type-id, regardless of the
  3848. // form of the corresponding template-parameter.
  3849. //
  3850. // We warn specifically about this case, since it can be rather
  3851. // confusing for users.
  3852. QualType T = Arg.getArgument().getAsType();
  3853. SourceRange SR = Arg.getSourceRange();
  3854. if (T->isFunctionType())
  3855. Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
  3856. else
  3857. Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
  3858. Diag(Param->getLocation(), diag::note_template_param_here);
  3859. return true;
  3860. }
  3861. case TemplateArgument::Pack:
  3862. llvm_unreachable("Caller must expand template argument packs");
  3863. }
  3864. return false;
  3865. }
  3866. // Check template template parameters.
  3867. TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
  3868. // Substitute into the template parameter list of the template
  3869. // template parameter, since previously-supplied template arguments
  3870. // may appear within the template template parameter.
  3871. {
  3872. // Set up a template instantiation context.
  3873. LocalInstantiationScope Scope(*this);
  3874. InstantiatingTemplate Inst(*this, TemplateLoc, Template,
  3875. TempParm, Converted,
  3876. SourceRange(TemplateLoc, RAngleLoc));
  3877. if (Inst.isInvalid())
  3878. return true;
  3879. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  3880. TempParm = cast_or_null<TemplateTemplateParmDecl>(
  3881. SubstDecl(TempParm, CurContext,
  3882. MultiLevelTemplateArgumentList(TemplateArgs)));
  3883. if (!TempParm)
  3884. return true;
  3885. }
  3886. // C++1z [temp.local]p1: (DR1004)
  3887. // When [the injected-class-name] is used [...] as a template-argument for
  3888. // a template template-parameter [...] it refers to the class template
  3889. // itself.
  3890. if (Arg.getArgument().getKind() == TemplateArgument::Type) {
  3891. TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
  3892. Arg.getTypeSourceInfo()->getTypeLoc());
  3893. if (!ConvertedArg.getArgument().isNull())
  3894. Arg = ConvertedArg;
  3895. }
  3896. switch (Arg.getArgument().getKind()) {
  3897. case TemplateArgument::Null:
  3898. llvm_unreachable("Should never see a NULL template argument here");
  3899. case TemplateArgument::Template:
  3900. case TemplateArgument::TemplateExpansion:
  3901. if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
  3902. return true;
  3903. Converted.push_back(Arg.getArgument());
  3904. break;
  3905. case TemplateArgument::Expression:
  3906. case TemplateArgument::Type:
  3907. // We have a template template parameter but the template
  3908. // argument does not refer to a template.
  3909. Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
  3910. << getLangOpts().CPlusPlus11;
  3911. return true;
  3912. case TemplateArgument::Declaration:
  3913. llvm_unreachable("Declaration argument with template template parameter");
  3914. case TemplateArgument::Integral:
  3915. llvm_unreachable("Integral argument with template template parameter");
  3916. case TemplateArgument::NullPtr:
  3917. llvm_unreachable("Null pointer argument with template template parameter");
  3918. case TemplateArgument::Pack:
  3919. llvm_unreachable("Caller must expand template argument packs");
  3920. }
  3921. return false;
  3922. }
  3923. /// \brief Diagnose an arity mismatch in the
  3924. static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
  3925. SourceLocation TemplateLoc,
  3926. TemplateArgumentListInfo &TemplateArgs) {
  3927. TemplateParameterList *Params = Template->getTemplateParameters();
  3928. unsigned NumParams = Params->size();
  3929. unsigned NumArgs = TemplateArgs.size();
  3930. SourceRange Range;
  3931. if (NumArgs > NumParams)
  3932. Range = SourceRange(TemplateArgs[NumParams].getLocation(),
  3933. TemplateArgs.getRAngleLoc());
  3934. S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  3935. << (NumArgs > NumParams)
  3936. << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
  3937. << Template << Range;
  3938. S.Diag(Template->getLocation(), diag::note_template_decl_here)
  3939. << Params->getSourceRange();
  3940. return true;
  3941. }
  3942. /// \brief Check whether the template parameter is a pack expansion, and if so,
  3943. /// determine the number of parameters produced by that expansion. For instance:
  3944. ///
  3945. /// \code
  3946. /// template<typename ...Ts> struct A {
  3947. /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
  3948. /// };
  3949. /// \endcode
  3950. ///
  3951. /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
  3952. /// is not a pack expansion, so returns an empty Optional.
  3953. static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
  3954. if (NonTypeTemplateParmDecl *NTTP
  3955. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  3956. if (NTTP->isExpandedParameterPack())
  3957. return NTTP->getNumExpansionTypes();
  3958. }
  3959. if (TemplateTemplateParmDecl *TTP
  3960. = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  3961. if (TTP->isExpandedParameterPack())
  3962. return TTP->getNumExpansionTemplateParameters();
  3963. }
  3964. return None;
  3965. }
  3966. /// Diagnose a missing template argument.
  3967. template<typename TemplateParmDecl>
  3968. static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
  3969. TemplateDecl *TD,
  3970. const TemplateParmDecl *D,
  3971. TemplateArgumentListInfo &Args) {
  3972. // Dig out the most recent declaration of the template parameter; there may be
  3973. // declarations of the template that are more recent than TD.
  3974. D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
  3975. ->getTemplateParameters()
  3976. ->getParam(D->getIndex()));
  3977. // If there's a default argument that's not visible, diagnose that we're
  3978. // missing a module import.
  3979. llvm::SmallVector<Module*, 8> Modules;
  3980. if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
  3981. S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
  3982. D->getDefaultArgumentLoc(), Modules,
  3983. Sema::MissingImportKind::DefaultArgument,
  3984. /*Recover*/true);
  3985. return true;
  3986. }
  3987. // FIXME: If there's a more recent default argument that *is* visible,
  3988. // diagnose that it was declared too late.
  3989. return diagnoseArityMismatch(S, TD, Loc, Args);
  3990. }
  3991. /// \brief Check that the given template argument list is well-formed
  3992. /// for specializing the given template.
  3993. bool Sema::CheckTemplateArgumentList(
  3994. TemplateDecl *Template, SourceLocation TemplateLoc,
  3995. TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
  3996. SmallVectorImpl<TemplateArgument> &Converted,
  3997. bool UpdateArgsWithConversions) {
  3998. // Make a copy of the template arguments for processing. Only make the
  3999. // changes at the end when successful in matching the arguments to the
  4000. // template.
  4001. TemplateArgumentListInfo NewArgs = TemplateArgs;
  4002. TemplateParameterList *Params = Template->getTemplateParameters();
  4003. SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
  4004. // C++ [temp.arg]p1:
  4005. // [...] The type and form of each template-argument specified in
  4006. // a template-id shall match the type and form specified for the
  4007. // corresponding parameter declared by the template in its
  4008. // template-parameter-list.
  4009. bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
  4010. SmallVector<TemplateArgument, 2> ArgumentPack;
  4011. unsigned ArgIdx = 0, NumArgs = NewArgs.size();
  4012. LocalInstantiationScope InstScope(*this, true);
  4013. for (TemplateParameterList::iterator Param = Params->begin(),
  4014. ParamEnd = Params->end();
  4015. Param != ParamEnd; /* increment in loop */) {
  4016. // If we have an expanded parameter pack, make sure we don't have too
  4017. // many arguments.
  4018. if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
  4019. if (*Expansions == ArgumentPack.size()) {
  4020. // We're done with this parameter pack. Pack up its arguments and add
  4021. // them to the list.
  4022. Converted.push_back(
  4023. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4024. ArgumentPack.clear();
  4025. // This argument is assigned to the next parameter.
  4026. ++Param;
  4027. continue;
  4028. } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
  4029. // Not enough arguments for this parameter pack.
  4030. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  4031. << false
  4032. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  4033. << Template;
  4034. Diag(Template->getLocation(), diag::note_template_decl_here)
  4035. << Params->getSourceRange();
  4036. return true;
  4037. }
  4038. }
  4039. if (ArgIdx < NumArgs) {
  4040. // Check the template argument we were given.
  4041. if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
  4042. TemplateLoc, RAngleLoc,
  4043. ArgumentPack.size(), Converted))
  4044. return true;
  4045. bool PackExpansionIntoNonPack =
  4046. NewArgs[ArgIdx].getArgument().isPackExpansion() &&
  4047. (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
  4048. if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
  4049. // Core issue 1430: we have a pack expansion as an argument to an
  4050. // alias template, and it's not part of a parameter pack. This
  4051. // can't be canonicalized, so reject it now.
  4052. Diag(NewArgs[ArgIdx].getLocation(),
  4053. diag::err_alias_template_expansion_into_fixed_list)
  4054. << NewArgs[ArgIdx].getSourceRange();
  4055. Diag((*Param)->getLocation(), diag::note_template_param_here);
  4056. return true;
  4057. }
  4058. // We're now done with this argument.
  4059. ++ArgIdx;
  4060. if ((*Param)->isTemplateParameterPack()) {
  4061. // The template parameter was a template parameter pack, so take the
  4062. // deduced argument and place it on the argument pack. Note that we
  4063. // stay on the same template parameter so that we can deduce more
  4064. // arguments.
  4065. ArgumentPack.push_back(Converted.pop_back_val());
  4066. } else {
  4067. // Move to the next template parameter.
  4068. ++Param;
  4069. }
  4070. // If we just saw a pack expansion into a non-pack, then directly convert
  4071. // the remaining arguments, because we don't know what parameters they'll
  4072. // match up with.
  4073. if (PackExpansionIntoNonPack) {
  4074. if (!ArgumentPack.empty()) {
  4075. // If we were part way through filling in an expanded parameter pack,
  4076. // fall back to just producing individual arguments.
  4077. Converted.insert(Converted.end(),
  4078. ArgumentPack.begin(), ArgumentPack.end());
  4079. ArgumentPack.clear();
  4080. }
  4081. while (ArgIdx < NumArgs) {
  4082. Converted.push_back(NewArgs[ArgIdx].getArgument());
  4083. ++ArgIdx;
  4084. }
  4085. return false;
  4086. }
  4087. continue;
  4088. }
  4089. // If we're checking a partial template argument list, we're done.
  4090. if (PartialTemplateArgs) {
  4091. if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
  4092. Converted.push_back(
  4093. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4094. return false;
  4095. }
  4096. // If we have a template parameter pack with no more corresponding
  4097. // arguments, just break out now and we'll fill in the argument pack below.
  4098. if ((*Param)->isTemplateParameterPack()) {
  4099. assert(!getExpandedPackSize(*Param) &&
  4100. "Should have dealt with this already");
  4101. // A non-expanded parameter pack before the end of the parameter list
  4102. // only occurs for an ill-formed template parameter list, unless we've
  4103. // got a partial argument list for a function template, so just bail out.
  4104. if (Param + 1 != ParamEnd)
  4105. return true;
  4106. Converted.push_back(
  4107. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4108. ArgumentPack.clear();
  4109. ++Param;
  4110. continue;
  4111. }
  4112. // Check whether we have a default argument.
  4113. TemplateArgumentLoc Arg;
  4114. // Retrieve the default template argument from the template
  4115. // parameter. For each kind of template parameter, we substitute the
  4116. // template arguments provided thus far and any "outer" template arguments
  4117. // (when the template parameter was part of a nested template) into
  4118. // the default argument.
  4119. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
  4120. if (!hasVisibleDefaultArgument(TTP))
  4121. return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
  4122. NewArgs);
  4123. TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
  4124. Template,
  4125. TemplateLoc,
  4126. RAngleLoc,
  4127. TTP,
  4128. Converted);
  4129. if (!ArgType)
  4130. return true;
  4131. Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
  4132. ArgType);
  4133. } else if (NonTypeTemplateParmDecl *NTTP
  4134. = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
  4135. if (!hasVisibleDefaultArgument(NTTP))
  4136. return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
  4137. NewArgs);
  4138. ExprResult E = SubstDefaultTemplateArgument(*this, Template,
  4139. TemplateLoc,
  4140. RAngleLoc,
  4141. NTTP,
  4142. Converted);
  4143. if (E.isInvalid())
  4144. return true;
  4145. Expr *Ex = E.getAs<Expr>();
  4146. Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
  4147. } else {
  4148. TemplateTemplateParmDecl *TempParm
  4149. = cast<TemplateTemplateParmDecl>(*Param);
  4150. if (!hasVisibleDefaultArgument(TempParm))
  4151. return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
  4152. NewArgs);
  4153. NestedNameSpecifierLoc QualifierLoc;
  4154. TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
  4155. TemplateLoc,
  4156. RAngleLoc,
  4157. TempParm,
  4158. Converted,
  4159. QualifierLoc);
  4160. if (Name.isNull())
  4161. return true;
  4162. Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
  4163. TempParm->getDefaultArgument().getTemplateNameLoc());
  4164. }
  4165. // Introduce an instantiation record that describes where we are using
  4166. // the default template argument. We're not actually instantiating a
  4167. // template here, we just create this object to put a note into the
  4168. // context stack.
  4169. InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
  4170. SourceRange(TemplateLoc, RAngleLoc));
  4171. if (Inst.isInvalid())
  4172. return true;
  4173. // Check the default template argument.
  4174. if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
  4175. RAngleLoc, 0, Converted))
  4176. return true;
  4177. // Core issue 150 (assumed resolution): if this is a template template
  4178. // parameter, keep track of the default template arguments from the
  4179. // template definition.
  4180. if (isTemplateTemplateParameter)
  4181. NewArgs.addArgument(Arg);
  4182. // Move to the next template parameter and argument.
  4183. ++Param;
  4184. ++ArgIdx;
  4185. }
  4186. // If we're performing a partial argument substitution, allow any trailing
  4187. // pack expansions; they might be empty. This can happen even if
  4188. // PartialTemplateArgs is false (the list of arguments is complete but
  4189. // still dependent).
  4190. if (ArgIdx < NumArgs && CurrentInstantiationScope &&
  4191. CurrentInstantiationScope->getPartiallySubstitutedPack()) {
  4192. while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
  4193. Converted.push_back(NewArgs[ArgIdx++].getArgument());
  4194. }
  4195. // If we have any leftover arguments, then there were too many arguments.
  4196. // Complain and fail.
  4197. if (ArgIdx < NumArgs)
  4198. return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
  4199. // No problems found with the new argument list, propagate changes back
  4200. // to caller.
  4201. if (UpdateArgsWithConversions)
  4202. TemplateArgs = std::move(NewArgs);
  4203. return false;
  4204. }
  4205. namespace {
  4206. class UnnamedLocalNoLinkageFinder
  4207. : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
  4208. {
  4209. Sema &S;
  4210. SourceRange SR;
  4211. typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
  4212. public:
  4213. UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
  4214. bool Visit(QualType T) {
  4215. return T.isNull() ? false : inherited::Visit(T.getTypePtr());
  4216. }
  4217. #define TYPE(Class, Parent) \
  4218. bool Visit##Class##Type(const Class##Type *);
  4219. #define ABSTRACT_TYPE(Class, Parent) \
  4220. bool Visit##Class##Type(const Class##Type *) { return false; }
  4221. #define NON_CANONICAL_TYPE(Class, Parent) \
  4222. bool Visit##Class##Type(const Class##Type *) { return false; }
  4223. #include "clang/AST/TypeNodes.def"
  4224. bool VisitTagDecl(const TagDecl *Tag);
  4225. bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
  4226. };
  4227. } // end anonymous namespace
  4228. bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
  4229. return false;
  4230. }
  4231. bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
  4232. return Visit(T->getElementType());
  4233. }
  4234. bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
  4235. return Visit(T->getPointeeType());
  4236. }
  4237. bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
  4238. const BlockPointerType* T) {
  4239. return Visit(T->getPointeeType());
  4240. }
  4241. bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
  4242. const LValueReferenceType* T) {
  4243. return Visit(T->getPointeeType());
  4244. }
  4245. bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
  4246. const RValueReferenceType* T) {
  4247. return Visit(T->getPointeeType());
  4248. }
  4249. bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
  4250. const MemberPointerType* T) {
  4251. return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
  4252. }
  4253. bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
  4254. const ConstantArrayType* T) {
  4255. return Visit(T->getElementType());
  4256. }
  4257. bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
  4258. const IncompleteArrayType* T) {
  4259. return Visit(T->getElementType());
  4260. }
  4261. bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
  4262. const VariableArrayType* T) {
  4263. return Visit(T->getElementType());
  4264. }
  4265. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
  4266. const DependentSizedArrayType* T) {
  4267. return Visit(T->getElementType());
  4268. }
  4269. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
  4270. const DependentSizedExtVectorType* T) {
  4271. return Visit(T->getElementType());
  4272. }
  4273. bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
  4274. return Visit(T->getElementType());
  4275. }
  4276. bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
  4277. return Visit(T->getElementType());
  4278. }
  4279. bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
  4280. const FunctionProtoType* T) {
  4281. for (const auto &A : T->param_types()) {
  4282. if (Visit(A))
  4283. return true;
  4284. }
  4285. return Visit(T->getReturnType());
  4286. }
  4287. bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
  4288. const FunctionNoProtoType* T) {
  4289. return Visit(T->getReturnType());
  4290. }
  4291. bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
  4292. const UnresolvedUsingType*) {
  4293. return false;
  4294. }
  4295. bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
  4296. return false;
  4297. }
  4298. bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
  4299. return Visit(T->getUnderlyingType());
  4300. }
  4301. bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
  4302. return false;
  4303. }
  4304. bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
  4305. const UnaryTransformType*) {
  4306. return false;
  4307. }
  4308. bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
  4309. return Visit(T->getDeducedType());
  4310. }
  4311. bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
  4312. const DeducedTemplateSpecializationType *T) {
  4313. return Visit(T->getDeducedType());
  4314. }
  4315. bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
  4316. return VisitTagDecl(T->getDecl());
  4317. }
  4318. bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
  4319. return VisitTagDecl(T->getDecl());
  4320. }
  4321. bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
  4322. const TemplateTypeParmType*) {
  4323. return false;
  4324. }
  4325. bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
  4326. const SubstTemplateTypeParmPackType *) {
  4327. return false;
  4328. }
  4329. bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
  4330. const TemplateSpecializationType*) {
  4331. return false;
  4332. }
  4333. bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
  4334. const InjectedClassNameType* T) {
  4335. return VisitTagDecl(T->getDecl());
  4336. }
  4337. bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
  4338. const DependentNameType* T) {
  4339. return VisitNestedNameSpecifier(T->getQualifier());
  4340. }
  4341. bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
  4342. const DependentTemplateSpecializationType* T) {
  4343. return VisitNestedNameSpecifier(T->getQualifier());
  4344. }
  4345. bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
  4346. const PackExpansionType* T) {
  4347. return Visit(T->getPattern());
  4348. }
  4349. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
  4350. return false;
  4351. }
  4352. bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
  4353. const ObjCInterfaceType *) {
  4354. return false;
  4355. }
  4356. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
  4357. const ObjCObjectPointerType *) {
  4358. return false;
  4359. }
  4360. bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
  4361. return Visit(T->getValueType());
  4362. }
  4363. bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
  4364. return false;
  4365. }
  4366. bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
  4367. if (Tag->getDeclContext()->isFunctionOrMethod()) {
  4368. S.Diag(SR.getBegin(),
  4369. S.getLangOpts().CPlusPlus11 ?
  4370. diag::warn_cxx98_compat_template_arg_local_type :
  4371. diag::ext_template_arg_local_type)
  4372. << S.Context.getTypeDeclType(Tag) << SR;
  4373. return true;
  4374. }
  4375. if (!Tag->hasNameForLinkage()) {
  4376. S.Diag(SR.getBegin(),
  4377. S.getLangOpts().CPlusPlus11 ?
  4378. diag::warn_cxx98_compat_template_arg_unnamed_type :
  4379. diag::ext_template_arg_unnamed_type) << SR;
  4380. S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
  4381. return true;
  4382. }
  4383. return false;
  4384. }
  4385. bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
  4386. NestedNameSpecifier *NNS) {
  4387. if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
  4388. return true;
  4389. switch (NNS->getKind()) {
  4390. case NestedNameSpecifier::Identifier:
  4391. case NestedNameSpecifier::Namespace:
  4392. case NestedNameSpecifier::NamespaceAlias:
  4393. case NestedNameSpecifier::Global:
  4394. case NestedNameSpecifier::Super:
  4395. return false;
  4396. case NestedNameSpecifier::TypeSpec:
  4397. case NestedNameSpecifier::TypeSpecWithTemplate:
  4398. return Visit(QualType(NNS->getAsType(), 0));
  4399. }
  4400. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  4401. }
  4402. /// \brief Check a template argument against its corresponding
  4403. /// template type parameter.
  4404. ///
  4405. /// This routine implements the semantics of C++ [temp.arg.type]. It
  4406. /// returns true if an error occurred, and false otherwise.
  4407. bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
  4408. TypeSourceInfo *ArgInfo) {
  4409. assert(ArgInfo && "invalid TypeSourceInfo");
  4410. QualType Arg = ArgInfo->getType();
  4411. SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
  4412. if (Arg->isVariablyModifiedType()) {
  4413. return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
  4414. } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
  4415. return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
  4416. }
  4417. // C++03 [temp.arg.type]p2:
  4418. // A local type, a type with no linkage, an unnamed type or a type
  4419. // compounded from any of these types shall not be used as a
  4420. // template-argument for a template type-parameter.
  4421. //
  4422. // C++11 allows these, and even in C++03 we allow them as an extension with
  4423. // a warning.
  4424. if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
  4425. UnnamedLocalNoLinkageFinder Finder(*this, SR);
  4426. (void)Finder.Visit(Context.getCanonicalType(Arg));
  4427. }
  4428. return false;
  4429. }
  4430. enum NullPointerValueKind {
  4431. NPV_NotNullPointer,
  4432. NPV_NullPointer,
  4433. NPV_Error
  4434. };
  4435. /// \brief Determine whether the given template argument is a null pointer
  4436. /// value of the appropriate type.
  4437. static NullPointerValueKind
  4438. isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
  4439. QualType ParamType, Expr *Arg) {
  4440. if (Arg->isValueDependent() || Arg->isTypeDependent())
  4441. return NPV_NotNullPointer;
  4442. if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
  4443. llvm_unreachable(
  4444. "Incomplete parameter type in isNullPointerValueTemplateArgument!");
  4445. if (!S.getLangOpts().CPlusPlus11)
  4446. return NPV_NotNullPointer;
  4447. // Determine whether we have a constant expression.
  4448. ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
  4449. if (ArgRV.isInvalid())
  4450. return NPV_Error;
  4451. Arg = ArgRV.get();
  4452. Expr::EvalResult EvalResult;
  4453. SmallVector<PartialDiagnosticAt, 8> Notes;
  4454. EvalResult.Diag = &Notes;
  4455. if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
  4456. EvalResult.HasSideEffects) {
  4457. SourceLocation DiagLoc = Arg->getExprLoc();
  4458. // If our only note is the usual "invalid subexpression" note, just point
  4459. // the caret at its location rather than producing an essentially
  4460. // redundant note.
  4461. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  4462. diag::note_invalid_subexpr_in_const_expr) {
  4463. DiagLoc = Notes[0].first;
  4464. Notes.clear();
  4465. }
  4466. S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
  4467. << Arg->getType() << Arg->getSourceRange();
  4468. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  4469. S.Diag(Notes[I].first, Notes[I].second);
  4470. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4471. return NPV_Error;
  4472. }
  4473. // C++11 [temp.arg.nontype]p1:
  4474. // - an address constant expression of type std::nullptr_t
  4475. if (Arg->getType()->isNullPtrType())
  4476. return NPV_NullPointer;
  4477. // - a constant expression that evaluates to a null pointer value (4.10); or
  4478. // - a constant expression that evaluates to a null member pointer value
  4479. // (4.11); or
  4480. if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
  4481. (EvalResult.Val.isMemberPointer() &&
  4482. !EvalResult.Val.getMemberPointerDecl())) {
  4483. // If our expression has an appropriate type, we've succeeded.
  4484. bool ObjCLifetimeConversion;
  4485. if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
  4486. S.IsQualificationConversion(Arg->getType(), ParamType, false,
  4487. ObjCLifetimeConversion))
  4488. return NPV_NullPointer;
  4489. // The types didn't match, but we know we got a null pointer; complain,
  4490. // then recover as if the types were correct.
  4491. S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
  4492. << Arg->getType() << ParamType << Arg->getSourceRange();
  4493. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4494. return NPV_NullPointer;
  4495. }
  4496. // If we don't have a null pointer value, but we do have a NULL pointer
  4497. // constant, suggest a cast to the appropriate type.
  4498. if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
  4499. std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
  4500. S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
  4501. << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
  4502. << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
  4503. ")");
  4504. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4505. return NPV_NullPointer;
  4506. }
  4507. // FIXME: If we ever want to support general, address-constant expressions
  4508. // as non-type template arguments, we should return the ExprResult here to
  4509. // be interpreted by the caller.
  4510. return NPV_NotNullPointer;
  4511. }
  4512. /// \brief Checks whether the given template argument is compatible with its
  4513. /// template parameter.
  4514. static bool CheckTemplateArgumentIsCompatibleWithParameter(
  4515. Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
  4516. Expr *Arg, QualType ArgType) {
  4517. bool ObjCLifetimeConversion;
  4518. if (ParamType->isPointerType() &&
  4519. !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
  4520. S.IsQualificationConversion(ArgType, ParamType, false,
  4521. ObjCLifetimeConversion)) {
  4522. // For pointer-to-object types, qualification conversions are
  4523. // permitted.
  4524. } else {
  4525. if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
  4526. if (!ParamRef->getPointeeType()->isFunctionType()) {
  4527. // C++ [temp.arg.nontype]p5b3:
  4528. // For a non-type template-parameter of type reference to
  4529. // object, no conversions apply. The type referred to by the
  4530. // reference may be more cv-qualified than the (otherwise
  4531. // identical) type of the template- argument. The
  4532. // template-parameter is bound directly to the
  4533. // template-argument, which shall be an lvalue.
  4534. // FIXME: Other qualifiers?
  4535. unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
  4536. unsigned ArgQuals = ArgType.getCVRQualifiers();
  4537. if ((ParamQuals | ArgQuals) != ParamQuals) {
  4538. S.Diag(Arg->getLocStart(),
  4539. diag::err_template_arg_ref_bind_ignores_quals)
  4540. << ParamType << Arg->getType() << Arg->getSourceRange();
  4541. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4542. return true;
  4543. }
  4544. }
  4545. }
  4546. // At this point, the template argument refers to an object or
  4547. // function with external linkage. We now need to check whether the
  4548. // argument and parameter types are compatible.
  4549. if (!S.Context.hasSameUnqualifiedType(ArgType,
  4550. ParamType.getNonReferenceType())) {
  4551. // We can't perform this conversion or binding.
  4552. if (ParamType->isReferenceType())
  4553. S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
  4554. << ParamType << ArgIn->getType() << Arg->getSourceRange();
  4555. else
  4556. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
  4557. << ArgIn->getType() << ParamType << Arg->getSourceRange();
  4558. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4559. return true;
  4560. }
  4561. }
  4562. return false;
  4563. }
  4564. /// \brief Checks whether the given template argument is the address
  4565. /// of an object or function according to C++ [temp.arg.nontype]p1.
  4566. static bool
  4567. CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
  4568. NonTypeTemplateParmDecl *Param,
  4569. QualType ParamType,
  4570. Expr *ArgIn,
  4571. TemplateArgument &Converted) {
  4572. bool Invalid = false;
  4573. Expr *Arg = ArgIn;
  4574. QualType ArgType = Arg->getType();
  4575. bool AddressTaken = false;
  4576. SourceLocation AddrOpLoc;
  4577. if (S.getLangOpts().MicrosoftExt) {
  4578. // Microsoft Visual C++ strips all casts, allows an arbitrary number of
  4579. // dereference and address-of operators.
  4580. Arg = Arg->IgnoreParenCasts();
  4581. bool ExtWarnMSTemplateArg = false;
  4582. UnaryOperatorKind FirstOpKind;
  4583. SourceLocation FirstOpLoc;
  4584. while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  4585. UnaryOperatorKind UnOpKind = UnOp->getOpcode();
  4586. if (UnOpKind == UO_Deref)
  4587. ExtWarnMSTemplateArg = true;
  4588. if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
  4589. Arg = UnOp->getSubExpr()->IgnoreParenCasts();
  4590. if (!AddrOpLoc.isValid()) {
  4591. FirstOpKind = UnOpKind;
  4592. FirstOpLoc = UnOp->getOperatorLoc();
  4593. }
  4594. } else
  4595. break;
  4596. }
  4597. if (FirstOpLoc.isValid()) {
  4598. if (ExtWarnMSTemplateArg)
  4599. S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
  4600. << ArgIn->getSourceRange();
  4601. if (FirstOpKind == UO_AddrOf)
  4602. AddressTaken = true;
  4603. else if (Arg->getType()->isPointerType()) {
  4604. // We cannot let pointers get dereferenced here, that is obviously not a
  4605. // constant expression.
  4606. assert(FirstOpKind == UO_Deref);
  4607. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
  4608. << Arg->getSourceRange();
  4609. }
  4610. }
  4611. } else {
  4612. // See through any implicit casts we added to fix the type.
  4613. Arg = Arg->IgnoreImpCasts();
  4614. // C++ [temp.arg.nontype]p1:
  4615. //
  4616. // A template-argument for a non-type, non-template
  4617. // template-parameter shall be one of: [...]
  4618. //
  4619. // -- the address of an object or function with external
  4620. // linkage, including function templates and function
  4621. // template-ids but excluding non-static class members,
  4622. // expressed as & id-expression where the & is optional if
  4623. // the name refers to a function or array, or if the
  4624. // corresponding template-parameter is a reference; or
  4625. // In C++98/03 mode, give an extension warning on any extra parentheses.
  4626. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  4627. bool ExtraParens = false;
  4628. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  4629. if (!Invalid && !ExtraParens) {
  4630. S.Diag(Arg->getLocStart(),
  4631. S.getLangOpts().CPlusPlus11
  4632. ? diag::warn_cxx98_compat_template_arg_extra_parens
  4633. : diag::ext_template_arg_extra_parens)
  4634. << Arg->getSourceRange();
  4635. ExtraParens = true;
  4636. }
  4637. Arg = Parens->getSubExpr();
  4638. }
  4639. while (SubstNonTypeTemplateParmExpr *subst =
  4640. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  4641. Arg = subst->getReplacement()->IgnoreImpCasts();
  4642. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  4643. if (UnOp->getOpcode() == UO_AddrOf) {
  4644. Arg = UnOp->getSubExpr();
  4645. AddressTaken = true;
  4646. AddrOpLoc = UnOp->getOperatorLoc();
  4647. }
  4648. }
  4649. while (SubstNonTypeTemplateParmExpr *subst =
  4650. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  4651. Arg = subst->getReplacement()->IgnoreImpCasts();
  4652. }
  4653. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
  4654. ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
  4655. // If our parameter has pointer type, check for a null template value.
  4656. if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
  4657. NullPointerValueKind NPV;
  4658. // dllimport'd entities aren't constant but are available inside of template
  4659. // arguments.
  4660. if (Entity && Entity->hasAttr<DLLImportAttr>())
  4661. NPV = NPV_NotNullPointer;
  4662. else
  4663. NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
  4664. switch (NPV) {
  4665. case NPV_NullPointer:
  4666. S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  4667. Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  4668. /*isNullPtr=*/true);
  4669. return false;
  4670. case NPV_Error:
  4671. return true;
  4672. case NPV_NotNullPointer:
  4673. break;
  4674. }
  4675. }
  4676. // Stop checking the precise nature of the argument if it is value dependent,
  4677. // it should be checked when instantiated.
  4678. if (Arg->isValueDependent()) {
  4679. Converted = TemplateArgument(ArgIn);
  4680. return false;
  4681. }
  4682. if (isa<CXXUuidofExpr>(Arg)) {
  4683. if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
  4684. ArgIn, Arg, ArgType))
  4685. return true;
  4686. Converted = TemplateArgument(ArgIn);
  4687. return false;
  4688. }
  4689. if (!DRE) {
  4690. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
  4691. << Arg->getSourceRange();
  4692. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4693. return true;
  4694. }
  4695. // Cannot refer to non-static data members
  4696. if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
  4697. S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
  4698. << Entity << Arg->getSourceRange();
  4699. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4700. return true;
  4701. }
  4702. // Cannot refer to non-static member functions
  4703. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
  4704. if (!Method->isStatic()) {
  4705. S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
  4706. << Method << Arg->getSourceRange();
  4707. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4708. return true;
  4709. }
  4710. }
  4711. FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
  4712. VarDecl *Var = dyn_cast<VarDecl>(Entity);
  4713. // A non-type template argument must refer to an object or function.
  4714. if (!Func && !Var) {
  4715. // We found something, but we don't know specifically what it is.
  4716. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
  4717. << Arg->getSourceRange();
  4718. S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
  4719. return true;
  4720. }
  4721. // Address / reference template args must have external linkage in C++98.
  4722. if (Entity->getFormalLinkage() == InternalLinkage) {
  4723. S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
  4724. diag::warn_cxx98_compat_template_arg_object_internal :
  4725. diag::ext_template_arg_object_internal)
  4726. << !Func << Entity << Arg->getSourceRange();
  4727. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  4728. << !Func;
  4729. } else if (!Entity->hasLinkage()) {
  4730. S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
  4731. << !Func << Entity << Arg->getSourceRange();
  4732. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  4733. << !Func;
  4734. return true;
  4735. }
  4736. if (Func) {
  4737. // If the template parameter has pointer type, the function decays.
  4738. if (ParamType->isPointerType() && !AddressTaken)
  4739. ArgType = S.Context.getPointerType(Func->getType());
  4740. else if (AddressTaken && ParamType->isReferenceType()) {
  4741. // If we originally had an address-of operator, but the
  4742. // parameter has reference type, complain and (if things look
  4743. // like they will work) drop the address-of operator.
  4744. if (!S.Context.hasSameUnqualifiedType(Func->getType(),
  4745. ParamType.getNonReferenceType())) {
  4746. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  4747. << ParamType;
  4748. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4749. return true;
  4750. }
  4751. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  4752. << ParamType
  4753. << FixItHint::CreateRemoval(AddrOpLoc);
  4754. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4755. ArgType = Func->getType();
  4756. }
  4757. } else {
  4758. // A value of reference type is not an object.
  4759. if (Var->getType()->isReferenceType()) {
  4760. S.Diag(Arg->getLocStart(),
  4761. diag::err_template_arg_reference_var)
  4762. << Var->getType() << Arg->getSourceRange();
  4763. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4764. return true;
  4765. }
  4766. // A template argument must have static storage duration.
  4767. if (Var->getTLSKind()) {
  4768. S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
  4769. << Arg->getSourceRange();
  4770. S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
  4771. return true;
  4772. }
  4773. // If the template parameter has pointer type, we must have taken
  4774. // the address of this object.
  4775. if (ParamType->isReferenceType()) {
  4776. if (AddressTaken) {
  4777. // If we originally had an address-of operator, but the
  4778. // parameter has reference type, complain and (if things look
  4779. // like they will work) drop the address-of operator.
  4780. if (!S.Context.hasSameUnqualifiedType(Var->getType(),
  4781. ParamType.getNonReferenceType())) {
  4782. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  4783. << ParamType;
  4784. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4785. return true;
  4786. }
  4787. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  4788. << ParamType
  4789. << FixItHint::CreateRemoval(AddrOpLoc);
  4790. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4791. ArgType = Var->getType();
  4792. }
  4793. } else if (!AddressTaken && ParamType->isPointerType()) {
  4794. if (Var->getType()->isArrayType()) {
  4795. // Array-to-pointer decay.
  4796. ArgType = S.Context.getArrayDecayedType(Var->getType());
  4797. } else {
  4798. // If the template parameter has pointer type but the address of
  4799. // this object was not taken, complain and (possibly) recover by
  4800. // taking the address of the entity.
  4801. ArgType = S.Context.getPointerType(Var->getType());
  4802. if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
  4803. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
  4804. << ParamType;
  4805. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4806. return true;
  4807. }
  4808. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
  4809. << ParamType
  4810. << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
  4811. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4812. }
  4813. }
  4814. }
  4815. if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
  4816. Arg, ArgType))
  4817. return true;
  4818. // Create the template argument.
  4819. Converted =
  4820. TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
  4821. S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
  4822. return false;
  4823. }
  4824. /// \brief Checks whether the given template argument is a pointer to
  4825. /// member constant according to C++ [temp.arg.nontype]p1.
  4826. static bool CheckTemplateArgumentPointerToMember(Sema &S,
  4827. NonTypeTemplateParmDecl *Param,
  4828. QualType ParamType,
  4829. Expr *&ResultArg,
  4830. TemplateArgument &Converted) {
  4831. bool Invalid = false;
  4832. // Check for a null pointer value.
  4833. Expr *Arg = ResultArg;
  4834. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
  4835. case NPV_Error:
  4836. return true;
  4837. case NPV_NullPointer:
  4838. S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  4839. Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  4840. /*isNullPtr*/true);
  4841. return false;
  4842. case NPV_NotNullPointer:
  4843. break;
  4844. }
  4845. bool ObjCLifetimeConversion;
  4846. if (S.IsQualificationConversion(Arg->getType(),
  4847. ParamType.getNonReferenceType(),
  4848. false, ObjCLifetimeConversion)) {
  4849. Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
  4850. Arg->getValueKind()).get();
  4851. ResultArg = Arg;
  4852. } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
  4853. ParamType.getNonReferenceType())) {
  4854. // We can't perform this conversion.
  4855. S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
  4856. << Arg->getType() << ParamType << Arg->getSourceRange();
  4857. S.Diag(Param->getLocation(), diag::note_template_param_here);
  4858. return true;
  4859. }
  4860. // See through any implicit casts we added to fix the type.
  4861. while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
  4862. Arg = Cast->getSubExpr();
  4863. // C++ [temp.arg.nontype]p1:
  4864. //
  4865. // A template-argument for a non-type, non-template
  4866. // template-parameter shall be one of: [...]
  4867. //
  4868. // -- a pointer to member expressed as described in 5.3.1.
  4869. DeclRefExpr *DRE = nullptr;
  4870. // In C++98/03 mode, give an extension warning on any extra parentheses.
  4871. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  4872. bool ExtraParens = false;
  4873. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  4874. if (!Invalid && !ExtraParens) {
  4875. S.Diag(Arg->getLocStart(),
  4876. S.getLangOpts().CPlusPlus11 ?
  4877. diag::warn_cxx98_compat_template_arg_extra_parens :
  4878. diag::ext_template_arg_extra_parens)
  4879. << Arg->getSourceRange();
  4880. ExtraParens = true;
  4881. }
  4882. Arg = Parens->getSubExpr();
  4883. }
  4884. while (SubstNonTypeTemplateParmExpr *subst =
  4885. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  4886. Arg = subst->getReplacement()->IgnoreImpCasts();
  4887. // A pointer-to-member constant written &Class::member.
  4888. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  4889. if (UnOp->getOpcode() == UO_AddrOf) {
  4890. DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
  4891. if (DRE && !DRE->getQualifier())
  4892. DRE = nullptr;
  4893. }
  4894. }
  4895. // A constant of pointer-to-member type.
  4896. else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
  4897. if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
  4898. if (VD->getType()->isMemberPointerType()) {
  4899. if (isa<NonTypeTemplateParmDecl>(VD)) {
  4900. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  4901. Converted = TemplateArgument(Arg);
  4902. } else {
  4903. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  4904. Converted = TemplateArgument(VD, ParamType);
  4905. }
  4906. return Invalid;
  4907. }
  4908. }
  4909. }
  4910. DRE = nullptr;
  4911. }
  4912. if (!DRE)
  4913. return S.Diag(Arg->getLocStart(),
  4914. diag::err_template_arg_not_pointer_to_member_form)
  4915. << Arg->getSourceRange();
  4916. if (isa<FieldDecl>(DRE->getDecl()) ||
  4917. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  4918. isa<CXXMethodDecl>(DRE->getDecl())) {
  4919. assert((isa<FieldDecl>(DRE->getDecl()) ||
  4920. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  4921. !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
  4922. "Only non-static member pointers can make it here");
  4923. // Okay: this is the address of a non-static member, and therefore
  4924. // a member pointer constant.
  4925. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  4926. Converted = TemplateArgument(Arg);
  4927. } else {
  4928. ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
  4929. Converted = TemplateArgument(D, ParamType);
  4930. }
  4931. return Invalid;
  4932. }
  4933. // We found something else, but we don't know specifically what it is.
  4934. S.Diag(Arg->getLocStart(),
  4935. diag::err_template_arg_not_pointer_to_member_form)
  4936. << Arg->getSourceRange();
  4937. S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
  4938. return true;
  4939. }
  4940. /// \brief Check a template argument against its corresponding
  4941. /// non-type template parameter.
  4942. ///
  4943. /// This routine implements the semantics of C++ [temp.arg.nontype].
  4944. /// If an error occurred, it returns ExprError(); otherwise, it
  4945. /// returns the converted template argument. \p ParamType is the
  4946. /// type of the non-type template parameter after it has been instantiated.
  4947. ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
  4948. QualType ParamType, Expr *Arg,
  4949. TemplateArgument &Converted,
  4950. CheckTemplateArgumentKind CTAK) {
  4951. SourceLocation StartLoc = Arg->getLocStart();
  4952. // If the parameter type somehow involves auto, deduce the type now.
  4953. if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
  4954. // When checking a deduced template argument, deduce from its type even if
  4955. // the type is dependent, in order to check the types of non-type template
  4956. // arguments line up properly in partial ordering.
  4957. Optional<unsigned> Depth;
  4958. if (CTAK != CTAK_Specified)
  4959. Depth = Param->getDepth() + 1;
  4960. if (DeduceAutoType(
  4961. Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
  4962. Arg, ParamType, Depth) == DAR_Failed) {
  4963. Diag(Arg->getExprLoc(),
  4964. diag::err_non_type_template_parm_type_deduction_failure)
  4965. << Param->getDeclName() << Param->getType() << Arg->getType()
  4966. << Arg->getSourceRange();
  4967. Diag(Param->getLocation(), diag::note_template_param_here);
  4968. return ExprError();
  4969. }
  4970. // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
  4971. // an error. The error message normally references the parameter
  4972. // declaration, but here we'll pass the argument location because that's
  4973. // where the parameter type is deduced.
  4974. ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
  4975. if (ParamType.isNull()) {
  4976. Diag(Param->getLocation(), diag::note_template_param_here);
  4977. return ExprError();
  4978. }
  4979. }
  4980. // We should have already dropped all cv-qualifiers by now.
  4981. assert(!ParamType.hasQualifiers() &&
  4982. "non-type template parameter type cannot be qualified");
  4983. if (CTAK == CTAK_Deduced &&
  4984. !Context.hasSameType(ParamType.getNonLValueExprType(Context),
  4985. Arg->getType())) {
  4986. // FIXME: If either type is dependent, we skip the check. This isn't
  4987. // correct, since during deduction we're supposed to have replaced each
  4988. // template parameter with some unique (non-dependent) placeholder.
  4989. // FIXME: If the argument type contains 'auto', we carry on and fail the
  4990. // type check in order to force specific types to be more specialized than
  4991. // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
  4992. // work.
  4993. if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
  4994. !Arg->getType()->getContainedAutoType()) {
  4995. Converted = TemplateArgument(Arg);
  4996. return Arg;
  4997. }
  4998. // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
  4999. // we should actually be checking the type of the template argument in P,
  5000. // not the type of the template argument deduced from A, against the
  5001. // template parameter type.
  5002. Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
  5003. << Arg->getType()
  5004. << ParamType.getUnqualifiedType();
  5005. Diag(Param->getLocation(), diag::note_template_param_here);
  5006. return ExprError();
  5007. }
  5008. // If either the parameter has a dependent type or the argument is
  5009. // type-dependent, there's nothing we can check now.
  5010. if (ParamType->isDependentType() || Arg->isTypeDependent()) {
  5011. // FIXME: Produce a cloned, canonical expression?
  5012. Converted = TemplateArgument(Arg);
  5013. return Arg;
  5014. }
  5015. // The initialization of the parameter from the argument is
  5016. // a constant-evaluated context.
  5017. EnterExpressionEvaluationContext ConstantEvaluated(*this,
  5018. Sema::ConstantEvaluated);
  5019. if (getLangOpts().CPlusPlus1z) {
  5020. // C++1z [temp.arg.nontype]p1:
  5021. // A template-argument for a non-type template parameter shall be
  5022. // a converted constant expression of the type of the template-parameter.
  5023. APValue Value;
  5024. ExprResult ArgResult = CheckConvertedConstantExpression(
  5025. Arg, ParamType, Value, CCEK_TemplateArg);
  5026. if (ArgResult.isInvalid())
  5027. return ExprError();
  5028. // For a value-dependent argument, CheckConvertedConstantExpression is
  5029. // permitted (and expected) to be unable to determine a value.
  5030. if (ArgResult.get()->isValueDependent()) {
  5031. Converted = TemplateArgument(ArgResult.get());
  5032. return ArgResult;
  5033. }
  5034. QualType CanonParamType = Context.getCanonicalType(ParamType);
  5035. // Convert the APValue to a TemplateArgument.
  5036. switch (Value.getKind()) {
  5037. case APValue::Uninitialized:
  5038. assert(ParamType->isNullPtrType());
  5039. Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
  5040. break;
  5041. case APValue::Int:
  5042. assert(ParamType->isIntegralOrEnumerationType());
  5043. Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
  5044. break;
  5045. case APValue::MemberPointer: {
  5046. assert(ParamType->isMemberPointerType());
  5047. // FIXME: We need TemplateArgument representation and mangling for these.
  5048. if (!Value.getMemberPointerPath().empty()) {
  5049. Diag(Arg->getLocStart(),
  5050. diag::err_template_arg_member_ptr_base_derived_not_supported)
  5051. << Value.getMemberPointerDecl() << ParamType
  5052. << Arg->getSourceRange();
  5053. return ExprError();
  5054. }
  5055. auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
  5056. Converted = VD ? TemplateArgument(VD, CanonParamType)
  5057. : TemplateArgument(CanonParamType, /*isNullPtr*/true);
  5058. break;
  5059. }
  5060. case APValue::LValue: {
  5061. // For a non-type template-parameter of pointer or reference type,
  5062. // the value of the constant expression shall not refer to
  5063. assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
  5064. ParamType->isNullPtrType());
  5065. // -- a temporary object
  5066. // -- a string literal
  5067. // -- the result of a typeid expression, or
  5068. // -- a predefind __func__ variable
  5069. if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
  5070. if (isa<CXXUuidofExpr>(E)) {
  5071. Converted = TemplateArgument(const_cast<Expr*>(E));
  5072. break;
  5073. }
  5074. Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
  5075. << Arg->getSourceRange();
  5076. return ExprError();
  5077. }
  5078. auto *VD = const_cast<ValueDecl *>(
  5079. Value.getLValueBase().dyn_cast<const ValueDecl *>());
  5080. // -- a subobject
  5081. if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
  5082. VD && VD->getType()->isArrayType() &&
  5083. Value.getLValuePath()[0].ArrayIndex == 0 &&
  5084. !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
  5085. // Per defect report (no number yet):
  5086. // ... other than a pointer to the first element of a complete array
  5087. // object.
  5088. } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
  5089. Value.isLValueOnePastTheEnd()) {
  5090. Diag(StartLoc, diag::err_non_type_template_arg_subobject)
  5091. << Value.getAsString(Context, ParamType);
  5092. return ExprError();
  5093. }
  5094. assert((VD || !ParamType->isReferenceType()) &&
  5095. "null reference should not be a constant expression");
  5096. assert((!VD || !ParamType->isNullPtrType()) &&
  5097. "non-null value of type nullptr_t?");
  5098. Converted = VD ? TemplateArgument(VD, CanonParamType)
  5099. : TemplateArgument(CanonParamType, /*isNullPtr*/true);
  5100. break;
  5101. }
  5102. case APValue::AddrLabelDiff:
  5103. return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
  5104. case APValue::Float:
  5105. case APValue::ComplexInt:
  5106. case APValue::ComplexFloat:
  5107. case APValue::Vector:
  5108. case APValue::Array:
  5109. case APValue::Struct:
  5110. case APValue::Union:
  5111. llvm_unreachable("invalid kind for template argument");
  5112. }
  5113. return ArgResult.get();
  5114. }
  5115. // C++ [temp.arg.nontype]p5:
  5116. // The following conversions are performed on each expression used
  5117. // as a non-type template-argument. If a non-type
  5118. // template-argument cannot be converted to the type of the
  5119. // corresponding template-parameter then the program is
  5120. // ill-formed.
  5121. if (ParamType->isIntegralOrEnumerationType()) {
  5122. // C++11:
  5123. // -- for a non-type template-parameter of integral or
  5124. // enumeration type, conversions permitted in a converted
  5125. // constant expression are applied.
  5126. //
  5127. // C++98:
  5128. // -- for a non-type template-parameter of integral or
  5129. // enumeration type, integral promotions (4.5) and integral
  5130. // conversions (4.7) are applied.
  5131. if (getLangOpts().CPlusPlus11) {
  5132. // C++ [temp.arg.nontype]p1:
  5133. // A template-argument for a non-type, non-template template-parameter
  5134. // shall be one of:
  5135. //
  5136. // -- for a non-type template-parameter of integral or enumeration
  5137. // type, a converted constant expression of the type of the
  5138. // template-parameter; or
  5139. llvm::APSInt Value;
  5140. ExprResult ArgResult =
  5141. CheckConvertedConstantExpression(Arg, ParamType, Value,
  5142. CCEK_TemplateArg);
  5143. if (ArgResult.isInvalid())
  5144. return ExprError();
  5145. // We can't check arbitrary value-dependent arguments.
  5146. if (ArgResult.get()->isValueDependent()) {
  5147. Converted = TemplateArgument(ArgResult.get());
  5148. return ArgResult;
  5149. }
  5150. // Widen the argument value to sizeof(parameter type). This is almost
  5151. // always a no-op, except when the parameter type is bool. In
  5152. // that case, this may extend the argument from 1 bit to 8 bits.
  5153. QualType IntegerType = ParamType;
  5154. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  5155. IntegerType = Enum->getDecl()->getIntegerType();
  5156. Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
  5157. Converted = TemplateArgument(Context, Value,
  5158. Context.getCanonicalType(ParamType));
  5159. return ArgResult;
  5160. }
  5161. ExprResult ArgResult = DefaultLvalueConversion(Arg);
  5162. if (ArgResult.isInvalid())
  5163. return ExprError();
  5164. Arg = ArgResult.get();
  5165. QualType ArgType = Arg->getType();
  5166. // C++ [temp.arg.nontype]p1:
  5167. // A template-argument for a non-type, non-template
  5168. // template-parameter shall be one of:
  5169. //
  5170. // -- an integral constant-expression of integral or enumeration
  5171. // type; or
  5172. // -- the name of a non-type template-parameter; or
  5173. SourceLocation NonConstantLoc;
  5174. llvm::APSInt Value;
  5175. if (!ArgType->isIntegralOrEnumerationType()) {
  5176. Diag(Arg->getLocStart(),
  5177. diag::err_template_arg_not_integral_or_enumeral)
  5178. << ArgType << Arg->getSourceRange();
  5179. Diag(Param->getLocation(), diag::note_template_param_here);
  5180. return ExprError();
  5181. } else if (!Arg->isValueDependent()) {
  5182. class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
  5183. QualType T;
  5184. public:
  5185. TmplArgICEDiagnoser(QualType T) : T(T) { }
  5186. void diagnoseNotICE(Sema &S, SourceLocation Loc,
  5187. SourceRange SR) override {
  5188. S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
  5189. }
  5190. } Diagnoser(ArgType);
  5191. Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
  5192. false).get();
  5193. if (!Arg)
  5194. return ExprError();
  5195. }
  5196. // From here on out, all we care about is the unqualified form
  5197. // of the argument type.
  5198. ArgType = ArgType.getUnqualifiedType();
  5199. // Try to convert the argument to the parameter's type.
  5200. if (Context.hasSameType(ParamType, ArgType)) {
  5201. // Okay: no conversion necessary
  5202. } else if (ParamType->isBooleanType()) {
  5203. // This is an integral-to-boolean conversion.
  5204. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
  5205. } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
  5206. !ParamType->isEnumeralType()) {
  5207. // This is an integral promotion or conversion.
  5208. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
  5209. } else {
  5210. // We can't perform this conversion.
  5211. Diag(Arg->getLocStart(),
  5212. diag::err_template_arg_not_convertible)
  5213. << Arg->getType() << ParamType << Arg->getSourceRange();
  5214. Diag(Param->getLocation(), diag::note_template_param_here);
  5215. return ExprError();
  5216. }
  5217. // Add the value of this argument to the list of converted
  5218. // arguments. We use the bitwidth and signedness of the template
  5219. // parameter.
  5220. if (Arg->isValueDependent()) {
  5221. // The argument is value-dependent. Create a new
  5222. // TemplateArgument with the converted expression.
  5223. Converted = TemplateArgument(Arg);
  5224. return Arg;
  5225. }
  5226. QualType IntegerType = Context.getCanonicalType(ParamType);
  5227. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  5228. IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
  5229. if (ParamType->isBooleanType()) {
  5230. // Value must be zero or one.
  5231. Value = Value != 0;
  5232. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  5233. if (Value.getBitWidth() != AllowedBits)
  5234. Value = Value.extOrTrunc(AllowedBits);
  5235. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  5236. } else {
  5237. llvm::APSInt OldValue = Value;
  5238. // Coerce the template argument's value to the value it will have
  5239. // based on the template parameter's type.
  5240. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  5241. if (Value.getBitWidth() != AllowedBits)
  5242. Value = Value.extOrTrunc(AllowedBits);
  5243. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  5244. // Complain if an unsigned parameter received a negative value.
  5245. if (IntegerType->isUnsignedIntegerOrEnumerationType()
  5246. && (OldValue.isSigned() && OldValue.isNegative())) {
  5247. Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
  5248. << OldValue.toString(10) << Value.toString(10) << Param->getType()
  5249. << Arg->getSourceRange();
  5250. Diag(Param->getLocation(), diag::note_template_param_here);
  5251. }
  5252. // Complain if we overflowed the template parameter's type.
  5253. unsigned RequiredBits;
  5254. if (IntegerType->isUnsignedIntegerOrEnumerationType())
  5255. RequiredBits = OldValue.getActiveBits();
  5256. else if (OldValue.isUnsigned())
  5257. RequiredBits = OldValue.getActiveBits() + 1;
  5258. else
  5259. RequiredBits = OldValue.getMinSignedBits();
  5260. if (RequiredBits > AllowedBits) {
  5261. Diag(Arg->getLocStart(),
  5262. diag::warn_template_arg_too_large)
  5263. << OldValue.toString(10) << Value.toString(10) << Param->getType()
  5264. << Arg->getSourceRange();
  5265. Diag(Param->getLocation(), diag::note_template_param_here);
  5266. }
  5267. }
  5268. Converted = TemplateArgument(Context, Value,
  5269. ParamType->isEnumeralType()
  5270. ? Context.getCanonicalType(ParamType)
  5271. : IntegerType);
  5272. return Arg;
  5273. }
  5274. QualType ArgType = Arg->getType();
  5275. DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
  5276. // Handle pointer-to-function, reference-to-function, and
  5277. // pointer-to-member-function all in (roughly) the same way.
  5278. if (// -- For a non-type template-parameter of type pointer to
  5279. // function, only the function-to-pointer conversion (4.3) is
  5280. // applied. If the template-argument represents a set of
  5281. // overloaded functions (or a pointer to such), the matching
  5282. // function is selected from the set (13.4).
  5283. (ParamType->isPointerType() &&
  5284. ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
  5285. // -- For a non-type template-parameter of type reference to
  5286. // function, no conversions apply. If the template-argument
  5287. // represents a set of overloaded functions, the matching
  5288. // function is selected from the set (13.4).
  5289. (ParamType->isReferenceType() &&
  5290. ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
  5291. // -- For a non-type template-parameter of type pointer to
  5292. // member function, no conversions apply. If the
  5293. // template-argument represents a set of overloaded member
  5294. // functions, the matching member function is selected from
  5295. // the set (13.4).
  5296. (ParamType->isMemberPointerType() &&
  5297. ParamType->getAs<MemberPointerType>()->getPointeeType()
  5298. ->isFunctionType())) {
  5299. if (Arg->getType() == Context.OverloadTy) {
  5300. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
  5301. true,
  5302. FoundResult)) {
  5303. if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
  5304. return ExprError();
  5305. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  5306. ArgType = Arg->getType();
  5307. } else
  5308. return ExprError();
  5309. }
  5310. if (!ParamType->isMemberPointerType()) {
  5311. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  5312. ParamType,
  5313. Arg, Converted))
  5314. return ExprError();
  5315. return Arg;
  5316. }
  5317. if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
  5318. Converted))
  5319. return ExprError();
  5320. return Arg;
  5321. }
  5322. if (ParamType->isPointerType()) {
  5323. // -- for a non-type template-parameter of type pointer to
  5324. // object, qualification conversions (4.4) and the
  5325. // array-to-pointer conversion (4.2) are applied.
  5326. // C++0x also allows a value of std::nullptr_t.
  5327. assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
  5328. "Only object pointers allowed here");
  5329. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  5330. ParamType,
  5331. Arg, Converted))
  5332. return ExprError();
  5333. return Arg;
  5334. }
  5335. if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
  5336. // -- For a non-type template-parameter of type reference to
  5337. // object, no conversions apply. The type referred to by the
  5338. // reference may be more cv-qualified than the (otherwise
  5339. // identical) type of the template-argument. The
  5340. // template-parameter is bound directly to the
  5341. // template-argument, which must be an lvalue.
  5342. assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
  5343. "Only object references allowed here");
  5344. if (Arg->getType() == Context.OverloadTy) {
  5345. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
  5346. ParamRefType->getPointeeType(),
  5347. true,
  5348. FoundResult)) {
  5349. if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
  5350. return ExprError();
  5351. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  5352. ArgType = Arg->getType();
  5353. } else
  5354. return ExprError();
  5355. }
  5356. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  5357. ParamType,
  5358. Arg, Converted))
  5359. return ExprError();
  5360. return Arg;
  5361. }
  5362. // Deal with parameters of type std::nullptr_t.
  5363. if (ParamType->isNullPtrType()) {
  5364. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  5365. Converted = TemplateArgument(Arg);
  5366. return Arg;
  5367. }
  5368. switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
  5369. case NPV_NotNullPointer:
  5370. Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
  5371. << Arg->getType() << ParamType;
  5372. Diag(Param->getLocation(), diag::note_template_param_here);
  5373. return ExprError();
  5374. case NPV_Error:
  5375. return ExprError();
  5376. case NPV_NullPointer:
  5377. Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5378. Converted = TemplateArgument(Context.getCanonicalType(ParamType),
  5379. /*isNullPtr*/true);
  5380. return Arg;
  5381. }
  5382. }
  5383. // -- For a non-type template-parameter of type pointer to data
  5384. // member, qualification conversions (4.4) are applied.
  5385. assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
  5386. if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
  5387. Converted))
  5388. return ExprError();
  5389. return Arg;
  5390. }
  5391. static void DiagnoseTemplateParameterListArityMismatch(
  5392. Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
  5393. Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
  5394. /// \brief Check a template argument against its corresponding
  5395. /// template template parameter.
  5396. ///
  5397. /// This routine implements the semantics of C++ [temp.arg.template].
  5398. /// It returns true if an error occurred, and false otherwise.
  5399. bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
  5400. TemplateArgumentLoc &Arg,
  5401. unsigned ArgumentPackIndex) {
  5402. TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
  5403. TemplateDecl *Template = Name.getAsTemplateDecl();
  5404. if (!Template) {
  5405. // Any dependent template name is fine.
  5406. assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
  5407. return false;
  5408. }
  5409. if (Template->isInvalidDecl())
  5410. return true;
  5411. // C++0x [temp.arg.template]p1:
  5412. // A template-argument for a template template-parameter shall be
  5413. // the name of a class template or an alias template, expressed as an
  5414. // id-expression. When the template-argument names a class template, only
  5415. // primary class templates are considered when matching the
  5416. // template template argument with the corresponding parameter;
  5417. // partial specializations are not considered even if their
  5418. // parameter lists match that of the template template parameter.
  5419. //
  5420. // Note that we also allow template template parameters here, which
  5421. // will happen when we are dealing with, e.g., class template
  5422. // partial specializations.
  5423. if (!isa<ClassTemplateDecl>(Template) &&
  5424. !isa<TemplateTemplateParmDecl>(Template) &&
  5425. !isa<TypeAliasTemplateDecl>(Template) &&
  5426. !isa<BuiltinTemplateDecl>(Template)) {
  5427. assert(isa<FunctionTemplateDecl>(Template) &&
  5428. "Only function templates are possible here");
  5429. Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
  5430. Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
  5431. << Template;
  5432. }
  5433. TemplateParameterList *Params = Param->getTemplateParameters();
  5434. if (Param->isExpandedParameterPack())
  5435. Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
  5436. // C++1z [temp.arg.template]p3: (DR 150)
  5437. // A template-argument matches a template template-parameter P when P
  5438. // is at least as specialized as the template-argument A.
  5439. if (getLangOpts().RelaxedTemplateTemplateArgs) {
  5440. // Quick check for the common case:
  5441. // If P contains a parameter pack, then A [...] matches P if each of A's
  5442. // template parameters matches the corresponding template parameter in
  5443. // the template-parameter-list of P.
  5444. if (TemplateParameterListsAreEqual(
  5445. Template->getTemplateParameters(), Params, false,
  5446. TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
  5447. return false;
  5448. if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
  5449. Arg.getLocation()))
  5450. return false;
  5451. // FIXME: Produce better diagnostics for deduction failures.
  5452. }
  5453. return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
  5454. Params,
  5455. true,
  5456. TPL_TemplateTemplateArgumentMatch,
  5457. Arg.getLocation());
  5458. }
  5459. /// \brief Given a non-type template argument that refers to a
  5460. /// declaration and the type of its corresponding non-type template
  5461. /// parameter, produce an expression that properly refers to that
  5462. /// declaration.
  5463. ExprResult
  5464. Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
  5465. QualType ParamType,
  5466. SourceLocation Loc) {
  5467. // C++ [temp.param]p8:
  5468. //
  5469. // A non-type template-parameter of type "array of T" or
  5470. // "function returning T" is adjusted to be of type "pointer to
  5471. // T" or "pointer to function returning T", respectively.
  5472. if (ParamType->isArrayType())
  5473. ParamType = Context.getArrayDecayedType(ParamType);
  5474. else if (ParamType->isFunctionType())
  5475. ParamType = Context.getPointerType(ParamType);
  5476. // For a NULL non-type template argument, return nullptr casted to the
  5477. // parameter's type.
  5478. if (Arg.getKind() == TemplateArgument::NullPtr) {
  5479. return ImpCastExprToType(
  5480. new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
  5481. ParamType,
  5482. ParamType->getAs<MemberPointerType>()
  5483. ? CK_NullToMemberPointer
  5484. : CK_NullToPointer);
  5485. }
  5486. assert(Arg.getKind() == TemplateArgument::Declaration &&
  5487. "Only declaration template arguments permitted here");
  5488. ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
  5489. if (VD->getDeclContext()->isRecord() &&
  5490. (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
  5491. isa<IndirectFieldDecl>(VD))) {
  5492. // If the value is a class member, we might have a pointer-to-member.
  5493. // Determine whether the non-type template template parameter is of
  5494. // pointer-to-member type. If so, we need to build an appropriate
  5495. // expression for a pointer-to-member, since a "normal" DeclRefExpr
  5496. // would refer to the member itself.
  5497. if (ParamType->isMemberPointerType()) {
  5498. QualType ClassType
  5499. = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
  5500. NestedNameSpecifier *Qualifier
  5501. = NestedNameSpecifier::Create(Context, nullptr, false,
  5502. ClassType.getTypePtr());
  5503. CXXScopeSpec SS;
  5504. SS.MakeTrivial(Context, Qualifier, Loc);
  5505. // The actual value-ness of this is unimportant, but for
  5506. // internal consistency's sake, references to instance methods
  5507. // are r-values.
  5508. ExprValueKind VK = VK_LValue;
  5509. if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
  5510. VK = VK_RValue;
  5511. ExprResult RefExpr = BuildDeclRefExpr(VD,
  5512. VD->getType().getNonReferenceType(),
  5513. VK,
  5514. Loc,
  5515. &SS);
  5516. if (RefExpr.isInvalid())
  5517. return ExprError();
  5518. RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
  5519. // We might need to perform a trailing qualification conversion, since
  5520. // the element type on the parameter could be more qualified than the
  5521. // element type in the expression we constructed.
  5522. bool ObjCLifetimeConversion;
  5523. if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
  5524. ParamType.getUnqualifiedType(), false,
  5525. ObjCLifetimeConversion))
  5526. RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
  5527. assert(!RefExpr.isInvalid() &&
  5528. Context.hasSameType(((Expr*) RefExpr.get())->getType(),
  5529. ParamType.getUnqualifiedType()));
  5530. return RefExpr;
  5531. }
  5532. }
  5533. QualType T = VD->getType().getNonReferenceType();
  5534. if (ParamType->isPointerType()) {
  5535. // When the non-type template parameter is a pointer, take the
  5536. // address of the declaration.
  5537. ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
  5538. if (RefExpr.isInvalid())
  5539. return ExprError();
  5540. if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
  5541. (T->isFunctionType() || T->isArrayType())) {
  5542. // Decay functions and arrays unless we're forming a pointer to array.
  5543. RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
  5544. if (RefExpr.isInvalid())
  5545. return ExprError();
  5546. return RefExpr;
  5547. }
  5548. // Take the address of everything else
  5549. return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
  5550. }
  5551. ExprValueKind VK = VK_RValue;
  5552. // If the non-type template parameter has reference type, qualify the
  5553. // resulting declaration reference with the extra qualifiers on the
  5554. // type that the reference refers to.
  5555. if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
  5556. VK = VK_LValue;
  5557. T = Context.getQualifiedType(T,
  5558. TargetRef->getPointeeType().getQualifiers());
  5559. } else if (isa<FunctionDecl>(VD)) {
  5560. // References to functions are always lvalues.
  5561. VK = VK_LValue;
  5562. }
  5563. return BuildDeclRefExpr(VD, T, VK, Loc);
  5564. }
  5565. /// \brief Construct a new expression that refers to the given
  5566. /// integral template argument with the given source-location
  5567. /// information.
  5568. ///
  5569. /// This routine takes care of the mapping from an integral template
  5570. /// argument (which may have any integral type) to the appropriate
  5571. /// literal value.
  5572. ExprResult
  5573. Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
  5574. SourceLocation Loc) {
  5575. assert(Arg.getKind() == TemplateArgument::Integral &&
  5576. "Operation is only valid for integral template arguments");
  5577. QualType OrigT = Arg.getIntegralType();
  5578. // If this is an enum type that we're instantiating, we need to use an integer
  5579. // type the same size as the enumerator. We don't want to build an
  5580. // IntegerLiteral with enum type. The integer type of an enum type can be of
  5581. // any integral type with C++11 enum classes, make sure we create the right
  5582. // type of literal for it.
  5583. QualType T = OrigT;
  5584. if (const EnumType *ET = OrigT->getAs<EnumType>())
  5585. T = ET->getDecl()->getIntegerType();
  5586. Expr *E;
  5587. if (T->isAnyCharacterType()) {
  5588. // This does not need to handle u8 character literals because those are
  5589. // of type char, and so can also be covered by an ASCII character literal.
  5590. CharacterLiteral::CharacterKind Kind;
  5591. if (T->isWideCharType())
  5592. Kind = CharacterLiteral::Wide;
  5593. else if (T->isChar16Type())
  5594. Kind = CharacterLiteral::UTF16;
  5595. else if (T->isChar32Type())
  5596. Kind = CharacterLiteral::UTF32;
  5597. else
  5598. Kind = CharacterLiteral::Ascii;
  5599. E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
  5600. Kind, T, Loc);
  5601. } else if (T->isBooleanType()) {
  5602. E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
  5603. T, Loc);
  5604. } else if (T->isNullPtrType()) {
  5605. E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  5606. } else {
  5607. E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
  5608. }
  5609. if (OrigT->isEnumeralType()) {
  5610. // FIXME: This is a hack. We need a better way to handle substituted
  5611. // non-type template parameters.
  5612. E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
  5613. nullptr,
  5614. Context.getTrivialTypeSourceInfo(OrigT, Loc),
  5615. Loc, Loc);
  5616. }
  5617. return E;
  5618. }
  5619. static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
  5620. if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
  5621. return false;
  5622. DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
  5623. /*FindLessThanDepth*/ true);
  5624. Checker.TraverseType(NTTP->getType());
  5625. return Checker.Match;
  5626. }
  5627. /// \brief Match two template parameters within template parameter lists.
  5628. static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
  5629. bool Complain,
  5630. Sema::TemplateParameterListEqualKind Kind,
  5631. SourceLocation TemplateArgLoc) {
  5632. // Check the actual kind (type, non-type, template).
  5633. if (Old->getKind() != New->getKind()) {
  5634. if (Complain) {
  5635. unsigned NextDiag = diag::err_template_param_different_kind;
  5636. if (TemplateArgLoc.isValid()) {
  5637. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  5638. NextDiag = diag::note_template_param_different_kind;
  5639. }
  5640. S.Diag(New->getLocation(), NextDiag)
  5641. << (Kind != Sema::TPL_TemplateMatch);
  5642. S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
  5643. << (Kind != Sema::TPL_TemplateMatch);
  5644. }
  5645. return false;
  5646. }
  5647. // Check that both are parameter packs or neither are parameter packs.
  5648. // However, if we are matching a template template argument to a
  5649. // template template parameter, the template template parameter can have
  5650. // a parameter pack where the template template argument does not.
  5651. if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
  5652. !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
  5653. Old->isTemplateParameterPack())) {
  5654. if (Complain) {
  5655. unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
  5656. if (TemplateArgLoc.isValid()) {
  5657. S.Diag(TemplateArgLoc,
  5658. diag::err_template_arg_template_params_mismatch);
  5659. NextDiag = diag::note_template_parameter_pack_non_pack;
  5660. }
  5661. unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
  5662. : isa<NonTypeTemplateParmDecl>(New)? 1
  5663. : 2;
  5664. S.Diag(New->getLocation(), NextDiag)
  5665. << ParamKind << New->isParameterPack();
  5666. S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
  5667. << ParamKind << Old->isParameterPack();
  5668. }
  5669. return false;
  5670. }
  5671. // For non-type template parameters, check the type of the parameter.
  5672. if (NonTypeTemplateParmDecl *OldNTTP
  5673. = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
  5674. NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
  5675. // If we are matching a template template argument to a template
  5676. // template parameter and one of the non-type template parameter types
  5677. // is dependent on an outer template's parameter, then we must wait until
  5678. // template instantiation time to actually compare the arguments.
  5679. if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
  5680. (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
  5681. return true;
  5682. if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
  5683. if (Complain) {
  5684. unsigned NextDiag = diag::err_template_nontype_parm_different_type;
  5685. if (TemplateArgLoc.isValid()) {
  5686. S.Diag(TemplateArgLoc,
  5687. diag::err_template_arg_template_params_mismatch);
  5688. NextDiag = diag::note_template_nontype_parm_different_type;
  5689. }
  5690. S.Diag(NewNTTP->getLocation(), NextDiag)
  5691. << NewNTTP->getType()
  5692. << (Kind != Sema::TPL_TemplateMatch);
  5693. S.Diag(OldNTTP->getLocation(),
  5694. diag::note_template_nontype_parm_prev_declaration)
  5695. << OldNTTP->getType();
  5696. }
  5697. return false;
  5698. }
  5699. return true;
  5700. }
  5701. // For template template parameters, check the template parameter types.
  5702. // The template parameter lists of template template
  5703. // parameters must agree.
  5704. if (TemplateTemplateParmDecl *OldTTP
  5705. = dyn_cast<TemplateTemplateParmDecl>(Old)) {
  5706. TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
  5707. return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
  5708. OldTTP->getTemplateParameters(),
  5709. Complain,
  5710. (Kind == Sema::TPL_TemplateMatch
  5711. ? Sema::TPL_TemplateTemplateParmMatch
  5712. : Kind),
  5713. TemplateArgLoc);
  5714. }
  5715. return true;
  5716. }
  5717. /// \brief Diagnose a known arity mismatch when comparing template argument
  5718. /// lists.
  5719. static
  5720. void DiagnoseTemplateParameterListArityMismatch(Sema &S,
  5721. TemplateParameterList *New,
  5722. TemplateParameterList *Old,
  5723. Sema::TemplateParameterListEqualKind Kind,
  5724. SourceLocation TemplateArgLoc) {
  5725. unsigned NextDiag = diag::err_template_param_list_different_arity;
  5726. if (TemplateArgLoc.isValid()) {
  5727. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  5728. NextDiag = diag::note_template_param_list_different_arity;
  5729. }
  5730. S.Diag(New->getTemplateLoc(), NextDiag)
  5731. << (New->size() > Old->size())
  5732. << (Kind != Sema::TPL_TemplateMatch)
  5733. << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
  5734. S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
  5735. << (Kind != Sema::TPL_TemplateMatch)
  5736. << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
  5737. }
  5738. /// \brief Determine whether the given template parameter lists are
  5739. /// equivalent.
  5740. ///
  5741. /// \param New The new template parameter list, typically written in the
  5742. /// source code as part of a new template declaration.
  5743. ///
  5744. /// \param Old The old template parameter list, typically found via
  5745. /// name lookup of the template declared with this template parameter
  5746. /// list.
  5747. ///
  5748. /// \param Complain If true, this routine will produce a diagnostic if
  5749. /// the template parameter lists are not equivalent.
  5750. ///
  5751. /// \param Kind describes how we are to match the template parameter lists.
  5752. ///
  5753. /// \param TemplateArgLoc If this source location is valid, then we
  5754. /// are actually checking the template parameter list of a template
  5755. /// argument (New) against the template parameter list of its
  5756. /// corresponding template template parameter (Old). We produce
  5757. /// slightly different diagnostics in this scenario.
  5758. ///
  5759. /// \returns True if the template parameter lists are equal, false
  5760. /// otherwise.
  5761. bool
  5762. Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
  5763. TemplateParameterList *Old,
  5764. bool Complain,
  5765. TemplateParameterListEqualKind Kind,
  5766. SourceLocation TemplateArgLoc) {
  5767. if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
  5768. if (Complain)
  5769. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  5770. TemplateArgLoc);
  5771. return false;
  5772. }
  5773. // C++0x [temp.arg.template]p3:
  5774. // A template-argument matches a template template-parameter (call it P)
  5775. // when each of the template parameters in the template-parameter-list of
  5776. // the template-argument's corresponding class template or alias template
  5777. // (call it A) matches the corresponding template parameter in the
  5778. // template-parameter-list of P. [...]
  5779. TemplateParameterList::iterator NewParm = New->begin();
  5780. TemplateParameterList::iterator NewParmEnd = New->end();
  5781. for (TemplateParameterList::iterator OldParm = Old->begin(),
  5782. OldParmEnd = Old->end();
  5783. OldParm != OldParmEnd; ++OldParm) {
  5784. if (Kind != TPL_TemplateTemplateArgumentMatch ||
  5785. !(*OldParm)->isTemplateParameterPack()) {
  5786. if (NewParm == NewParmEnd) {
  5787. if (Complain)
  5788. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  5789. TemplateArgLoc);
  5790. return false;
  5791. }
  5792. if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
  5793. Kind, TemplateArgLoc))
  5794. return false;
  5795. ++NewParm;
  5796. continue;
  5797. }
  5798. // C++0x [temp.arg.template]p3:
  5799. // [...] When P's template- parameter-list contains a template parameter
  5800. // pack (14.5.3), the template parameter pack will match zero or more
  5801. // template parameters or template parameter packs in the
  5802. // template-parameter-list of A with the same type and form as the
  5803. // template parameter pack in P (ignoring whether those template
  5804. // parameters are template parameter packs).
  5805. for (; NewParm != NewParmEnd; ++NewParm) {
  5806. if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
  5807. Kind, TemplateArgLoc))
  5808. return false;
  5809. }
  5810. }
  5811. // Make sure we exhausted all of the arguments.
  5812. if (NewParm != NewParmEnd) {
  5813. if (Complain)
  5814. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  5815. TemplateArgLoc);
  5816. return false;
  5817. }
  5818. return true;
  5819. }
  5820. /// \brief Check whether a template can be declared within this scope.
  5821. ///
  5822. /// If the template declaration is valid in this scope, returns
  5823. /// false. Otherwise, issues a diagnostic and returns true.
  5824. bool
  5825. Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
  5826. if (!S)
  5827. return false;
  5828. // Find the nearest enclosing declaration scope.
  5829. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  5830. (S->getFlags() & Scope::TemplateParamScope) != 0)
  5831. S = S->getParent();
  5832. // C++ [temp]p4:
  5833. // A template [...] shall not have C linkage.
  5834. DeclContext *Ctx = S->getEntity();
  5835. if (Ctx && Ctx->isExternCContext()) {
  5836. Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
  5837. << TemplateParams->getSourceRange();
  5838. if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
  5839. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  5840. return true;
  5841. }
  5842. Ctx = Ctx->getRedeclContext();
  5843. // C++ [temp]p2:
  5844. // A template-declaration can appear only as a namespace scope or
  5845. // class scope declaration.
  5846. if (Ctx) {
  5847. if (Ctx->isFileContext())
  5848. return false;
  5849. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
  5850. // C++ [temp.mem]p2:
  5851. // A local class shall not have member templates.
  5852. if (RD->isLocalClass())
  5853. return Diag(TemplateParams->getTemplateLoc(),
  5854. diag::err_template_inside_local_class)
  5855. << TemplateParams->getSourceRange();
  5856. else
  5857. return false;
  5858. }
  5859. }
  5860. return Diag(TemplateParams->getTemplateLoc(),
  5861. diag::err_template_outside_namespace_or_class_scope)
  5862. << TemplateParams->getSourceRange();
  5863. }
  5864. /// \brief Determine what kind of template specialization the given declaration
  5865. /// is.
  5866. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
  5867. if (!D)
  5868. return TSK_Undeclared;
  5869. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
  5870. return Record->getTemplateSpecializationKind();
  5871. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  5872. return Function->getTemplateSpecializationKind();
  5873. if (VarDecl *Var = dyn_cast<VarDecl>(D))
  5874. return Var->getTemplateSpecializationKind();
  5875. return TSK_Undeclared;
  5876. }
  5877. /// \brief Check whether a specialization is well-formed in the current
  5878. /// context.
  5879. ///
  5880. /// This routine determines whether a template specialization can be declared
  5881. /// in the current context (C++ [temp.expl.spec]p2).
  5882. ///
  5883. /// \param S the semantic analysis object for which this check is being
  5884. /// performed.
  5885. ///
  5886. /// \param Specialized the entity being specialized or instantiated, which
  5887. /// may be a kind of template (class template, function template, etc.) or
  5888. /// a member of a class template (member function, static data member,
  5889. /// member class).
  5890. ///
  5891. /// \param PrevDecl the previous declaration of this entity, if any.
  5892. ///
  5893. /// \param Loc the location of the explicit specialization or instantiation of
  5894. /// this entity.
  5895. ///
  5896. /// \param IsPartialSpecialization whether this is a partial specialization of
  5897. /// a class template.
  5898. ///
  5899. /// \returns true if there was an error that we cannot recover from, false
  5900. /// otherwise.
  5901. static bool CheckTemplateSpecializationScope(Sema &S,
  5902. NamedDecl *Specialized,
  5903. NamedDecl *PrevDecl,
  5904. SourceLocation Loc,
  5905. bool IsPartialSpecialization) {
  5906. // Keep these "kind" numbers in sync with the %select statements in the
  5907. // various diagnostics emitted by this routine.
  5908. int EntityKind = 0;
  5909. if (isa<ClassTemplateDecl>(Specialized))
  5910. EntityKind = IsPartialSpecialization? 1 : 0;
  5911. else if (isa<VarTemplateDecl>(Specialized))
  5912. EntityKind = IsPartialSpecialization ? 3 : 2;
  5913. else if (isa<FunctionTemplateDecl>(Specialized))
  5914. EntityKind = 4;
  5915. else if (isa<CXXMethodDecl>(Specialized))
  5916. EntityKind = 5;
  5917. else if (isa<VarDecl>(Specialized))
  5918. EntityKind = 6;
  5919. else if (isa<RecordDecl>(Specialized))
  5920. EntityKind = 7;
  5921. else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
  5922. EntityKind = 8;
  5923. else {
  5924. S.Diag(Loc, diag::err_template_spec_unknown_kind)
  5925. << S.getLangOpts().CPlusPlus11;
  5926. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  5927. return true;
  5928. }
  5929. // C++ [temp.expl.spec]p2:
  5930. // An explicit specialization shall be declared in the namespace
  5931. // of which the template is a member, or, for member templates, in
  5932. // the namespace of which the enclosing class or enclosing class
  5933. // template is a member. An explicit specialization of a member
  5934. // function, member class or static data member of a class
  5935. // template shall be declared in the namespace of which the class
  5936. // template is a member. Such a declaration may also be a
  5937. // definition. If the declaration is not a definition, the
  5938. // specialization may be defined later in the name- space in which
  5939. // the explicit specialization was declared, or in a namespace
  5940. // that encloses the one in which the explicit specialization was
  5941. // declared.
  5942. if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  5943. S.Diag(Loc, diag::err_template_spec_decl_function_scope)
  5944. << Specialized;
  5945. return true;
  5946. }
  5947. if (S.CurContext->isRecord() && !IsPartialSpecialization) {
  5948. if (S.getLangOpts().MicrosoftExt) {
  5949. // Do not warn for class scope explicit specialization during
  5950. // instantiation, warning was already emitted during pattern
  5951. // semantic analysis.
  5952. if (!S.ActiveTemplateInstantiations.size())
  5953. S.Diag(Loc, diag::ext_function_specialization_in_class)
  5954. << Specialized;
  5955. } else {
  5956. S.Diag(Loc, diag::err_template_spec_decl_class_scope)
  5957. << Specialized;
  5958. return true;
  5959. }
  5960. }
  5961. if (S.CurContext->isRecord() &&
  5962. !S.CurContext->Equals(Specialized->getDeclContext())) {
  5963. // Make sure that we're specializing in the right record context.
  5964. // Otherwise, things can go horribly wrong.
  5965. S.Diag(Loc, diag::err_template_spec_decl_class_scope)
  5966. << Specialized;
  5967. return true;
  5968. }
  5969. // C++ [temp.class.spec]p6:
  5970. // A class template partial specialization may be declared or redeclared
  5971. // in any namespace scope in which its definition may be defined (14.5.1
  5972. // and 14.5.2).
  5973. DeclContext *SpecializedContext
  5974. = Specialized->getDeclContext()->getEnclosingNamespaceContext();
  5975. DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
  5976. // Make sure that this redeclaration (or definition) occurs in an enclosing
  5977. // namespace.
  5978. // Note that HandleDeclarator() performs this check for explicit
  5979. // specializations of function templates, static data members, and member
  5980. // functions, so we skip the check here for those kinds of entities.
  5981. // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
  5982. // Should we refactor that check, so that it occurs later?
  5983. if (!DC->Encloses(SpecializedContext) &&
  5984. !(isa<FunctionTemplateDecl>(Specialized) ||
  5985. isa<FunctionDecl>(Specialized) ||
  5986. isa<VarTemplateDecl>(Specialized) ||
  5987. isa<VarDecl>(Specialized))) {
  5988. if (isa<TranslationUnitDecl>(SpecializedContext))
  5989. S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
  5990. << EntityKind << Specialized;
  5991. else if (isa<NamespaceDecl>(SpecializedContext)) {
  5992. int Diag = diag::err_template_spec_redecl_out_of_scope;
  5993. if (S.getLangOpts().MicrosoftExt)
  5994. Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
  5995. S.Diag(Loc, Diag) << EntityKind << Specialized
  5996. << cast<NamedDecl>(SpecializedContext);
  5997. } else
  5998. llvm_unreachable("unexpected namespace context for specialization");
  5999. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  6000. } else if ((!PrevDecl ||
  6001. getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
  6002. getTemplateSpecializationKind(PrevDecl) ==
  6003. TSK_ImplicitInstantiation)) {
  6004. // C++ [temp.exp.spec]p2:
  6005. // An explicit specialization shall be declared in the namespace of which
  6006. // the template is a member, or, for member templates, in the namespace
  6007. // of which the enclosing class or enclosing class template is a member.
  6008. // An explicit specialization of a member function, member class or
  6009. // static data member of a class template shall be declared in the
  6010. // namespace of which the class template is a member.
  6011. //
  6012. // C++11 [temp.expl.spec]p2:
  6013. // An explicit specialization shall be declared in a namespace enclosing
  6014. // the specialized template.
  6015. // C++11 [temp.explicit]p3:
  6016. // An explicit instantiation shall appear in an enclosing namespace of its
  6017. // template.
  6018. if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
  6019. bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
  6020. if (isa<TranslationUnitDecl>(SpecializedContext)) {
  6021. assert(!IsCPlusPlus11Extension &&
  6022. "DC encloses TU but isn't in enclosing namespace set");
  6023. S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
  6024. << EntityKind << Specialized;
  6025. } else if (isa<NamespaceDecl>(SpecializedContext)) {
  6026. int Diag;
  6027. if (!IsCPlusPlus11Extension)
  6028. Diag = diag::err_template_spec_decl_out_of_scope;
  6029. else if (!S.getLangOpts().CPlusPlus11)
  6030. Diag = diag::ext_template_spec_decl_out_of_scope;
  6031. else
  6032. Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
  6033. S.Diag(Loc, Diag)
  6034. << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
  6035. }
  6036. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  6037. }
  6038. }
  6039. return false;
  6040. }
  6041. static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
  6042. if (!E->isTypeDependent())
  6043. return SourceLocation();
  6044. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  6045. Checker.TraverseStmt(E);
  6046. if (Checker.MatchLoc.isInvalid())
  6047. return E->getSourceRange();
  6048. return Checker.MatchLoc;
  6049. }
  6050. static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
  6051. if (!TL.getType()->isDependentType())
  6052. return SourceLocation();
  6053. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  6054. Checker.TraverseTypeLoc(TL);
  6055. if (Checker.MatchLoc.isInvalid())
  6056. return TL.getSourceRange();
  6057. return Checker.MatchLoc;
  6058. }
  6059. /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
  6060. /// that checks non-type template partial specialization arguments.
  6061. static bool CheckNonTypeTemplatePartialSpecializationArgs(
  6062. Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
  6063. const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
  6064. for (unsigned I = 0; I != NumArgs; ++I) {
  6065. if (Args[I].getKind() == TemplateArgument::Pack) {
  6066. if (CheckNonTypeTemplatePartialSpecializationArgs(
  6067. S, TemplateNameLoc, Param, Args[I].pack_begin(),
  6068. Args[I].pack_size(), IsDefaultArgument))
  6069. return true;
  6070. continue;
  6071. }
  6072. if (Args[I].getKind() != TemplateArgument::Expression)
  6073. continue;
  6074. Expr *ArgExpr = Args[I].getAsExpr();
  6075. // We can have a pack expansion of any of the bullets below.
  6076. if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
  6077. ArgExpr = Expansion->getPattern();
  6078. // Strip off any implicit casts we added as part of type checking.
  6079. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  6080. ArgExpr = ICE->getSubExpr();
  6081. // C++ [temp.class.spec]p8:
  6082. // A non-type argument is non-specialized if it is the name of a
  6083. // non-type parameter. All other non-type arguments are
  6084. // specialized.
  6085. //
  6086. // Below, we check the two conditions that only apply to
  6087. // specialized non-type arguments, so skip any non-specialized
  6088. // arguments.
  6089. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
  6090. if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
  6091. continue;
  6092. // C++ [temp.class.spec]p9:
  6093. // Within the argument list of a class template partial
  6094. // specialization, the following restrictions apply:
  6095. // -- A partially specialized non-type argument expression
  6096. // shall not involve a template parameter of the partial
  6097. // specialization except when the argument expression is a
  6098. // simple identifier.
  6099. // -- The type of a template parameter corresponding to a
  6100. // specialized non-type argument shall not be dependent on a
  6101. // parameter of the specialization.
  6102. // DR1315 removes the first bullet, leaving an incoherent set of rules.
  6103. // We implement a compromise between the original rules and DR1315:
  6104. // -- A specialized non-type template argument shall not be
  6105. // type-dependent and the corresponding template parameter
  6106. // shall have a non-dependent type.
  6107. SourceRange ParamUseRange =
  6108. findTemplateParameterInType(Param->getDepth(), ArgExpr);
  6109. if (ParamUseRange.isValid()) {
  6110. if (IsDefaultArgument) {
  6111. S.Diag(TemplateNameLoc,
  6112. diag::err_dependent_non_type_arg_in_partial_spec);
  6113. S.Diag(ParamUseRange.getBegin(),
  6114. diag::note_dependent_non_type_default_arg_in_partial_spec)
  6115. << ParamUseRange;
  6116. } else {
  6117. S.Diag(ParamUseRange.getBegin(),
  6118. diag::err_dependent_non_type_arg_in_partial_spec)
  6119. << ParamUseRange;
  6120. }
  6121. return true;
  6122. }
  6123. ParamUseRange = findTemplateParameter(
  6124. Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
  6125. if (ParamUseRange.isValid()) {
  6126. S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
  6127. diag::err_dependent_typed_non_type_arg_in_partial_spec)
  6128. << Param->getType();
  6129. S.Diag(Param->getLocation(), diag::note_template_param_here)
  6130. << (IsDefaultArgument ? ParamUseRange : SourceRange())
  6131. << ParamUseRange;
  6132. return true;
  6133. }
  6134. }
  6135. return false;
  6136. }
  6137. /// \brief Check the non-type template arguments of a class template
  6138. /// partial specialization according to C++ [temp.class.spec]p9.
  6139. ///
  6140. /// \param TemplateNameLoc the location of the template name.
  6141. /// \param PrimaryTemplate the template parameters of the primary class
  6142. /// template.
  6143. /// \param NumExplicit the number of explicitly-specified template arguments.
  6144. /// \param TemplateArgs the template arguments of the class template
  6145. /// partial specialization.
  6146. ///
  6147. /// \returns \c true if there was an error, \c false otherwise.
  6148. bool Sema::CheckTemplatePartialSpecializationArgs(
  6149. SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
  6150. unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
  6151. // We have to be conservative when checking a template in a dependent
  6152. // context.
  6153. if (PrimaryTemplate->getDeclContext()->isDependentContext())
  6154. return false;
  6155. TemplateParameterList *TemplateParams =
  6156. PrimaryTemplate->getTemplateParameters();
  6157. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  6158. NonTypeTemplateParmDecl *Param
  6159. = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
  6160. if (!Param)
  6161. continue;
  6162. if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
  6163. Param, &TemplateArgs[I],
  6164. 1, I >= NumExplicit))
  6165. return true;
  6166. }
  6167. return false;
  6168. }
  6169. DeclResult
  6170. Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
  6171. TagUseKind TUK,
  6172. SourceLocation KWLoc,
  6173. SourceLocation ModulePrivateLoc,
  6174. TemplateIdAnnotation &TemplateId,
  6175. AttributeList *Attr,
  6176. MultiTemplateParamsArg
  6177. TemplateParameterLists,
  6178. SkipBodyInfo *SkipBody) {
  6179. assert(TUK != TUK_Reference && "References are not specializations");
  6180. CXXScopeSpec &SS = TemplateId.SS;
  6181. // NOTE: KWLoc is the location of the tag keyword. This will instead
  6182. // store the location of the outermost template keyword in the declaration.
  6183. SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
  6184. ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
  6185. SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
  6186. SourceLocation LAngleLoc = TemplateId.LAngleLoc;
  6187. SourceLocation RAngleLoc = TemplateId.RAngleLoc;
  6188. // Find the class template we're specializing
  6189. TemplateName Name = TemplateId.Template.get();
  6190. ClassTemplateDecl *ClassTemplate
  6191. = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
  6192. if (!ClassTemplate) {
  6193. Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
  6194. << (Name.getAsTemplateDecl() &&
  6195. isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
  6196. return true;
  6197. }
  6198. bool isMemberSpecialization = false;
  6199. bool isPartialSpecialization = false;
  6200. // Check the validity of the template headers that introduce this
  6201. // template.
  6202. // FIXME: We probably shouldn't complain about these headers for
  6203. // friend declarations.
  6204. bool Invalid = false;
  6205. TemplateParameterList *TemplateParams =
  6206. MatchTemplateParametersToScopeSpecifier(
  6207. KWLoc, TemplateNameLoc, SS, &TemplateId,
  6208. TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
  6209. Invalid);
  6210. if (Invalid)
  6211. return true;
  6212. if (TemplateParams && TemplateParams->size() > 0) {
  6213. isPartialSpecialization = true;
  6214. if (TUK == TUK_Friend) {
  6215. Diag(KWLoc, diag::err_partial_specialization_friend)
  6216. << SourceRange(LAngleLoc, RAngleLoc);
  6217. return true;
  6218. }
  6219. // C++ [temp.class.spec]p10:
  6220. // The template parameter list of a specialization shall not
  6221. // contain default template argument values.
  6222. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  6223. Decl *Param = TemplateParams->getParam(I);
  6224. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  6225. if (TTP->hasDefaultArgument()) {
  6226. Diag(TTP->getDefaultArgumentLoc(),
  6227. diag::err_default_arg_in_partial_spec);
  6228. TTP->removeDefaultArgument();
  6229. }
  6230. } else if (NonTypeTemplateParmDecl *NTTP
  6231. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  6232. if (Expr *DefArg = NTTP->getDefaultArgument()) {
  6233. Diag(NTTP->getDefaultArgumentLoc(),
  6234. diag::err_default_arg_in_partial_spec)
  6235. << DefArg->getSourceRange();
  6236. NTTP->removeDefaultArgument();
  6237. }
  6238. } else {
  6239. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
  6240. if (TTP->hasDefaultArgument()) {
  6241. Diag(TTP->getDefaultArgument().getLocation(),
  6242. diag::err_default_arg_in_partial_spec)
  6243. << TTP->getDefaultArgument().getSourceRange();
  6244. TTP->removeDefaultArgument();
  6245. }
  6246. }
  6247. }
  6248. } else if (TemplateParams) {
  6249. if (TUK == TUK_Friend)
  6250. Diag(KWLoc, diag::err_template_spec_friend)
  6251. << FixItHint::CreateRemoval(
  6252. SourceRange(TemplateParams->getTemplateLoc(),
  6253. TemplateParams->getRAngleLoc()))
  6254. << SourceRange(LAngleLoc, RAngleLoc);
  6255. } else {
  6256. assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
  6257. }
  6258. // Check that the specialization uses the same tag kind as the
  6259. // original template.
  6260. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  6261. assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
  6262. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  6263. Kind, TUK == TUK_Definition, KWLoc,
  6264. ClassTemplate->getIdentifier())) {
  6265. Diag(KWLoc, diag::err_use_with_wrong_tag)
  6266. << ClassTemplate
  6267. << FixItHint::CreateReplacement(KWLoc,
  6268. ClassTemplate->getTemplatedDecl()->getKindName());
  6269. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  6270. diag::note_previous_use);
  6271. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  6272. }
  6273. // Translate the parser's template argument list in our AST format.
  6274. TemplateArgumentListInfo TemplateArgs =
  6275. makeTemplateArgumentListInfo(*this, TemplateId);
  6276. // Check for unexpanded parameter packs in any of the template arguments.
  6277. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  6278. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  6279. UPPC_PartialSpecialization))
  6280. return true;
  6281. // Check that the template argument list is well-formed for this
  6282. // template.
  6283. SmallVector<TemplateArgument, 4> Converted;
  6284. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
  6285. TemplateArgs, false, Converted))
  6286. return true;
  6287. // Find the class template (partial) specialization declaration that
  6288. // corresponds to these arguments.
  6289. if (isPartialSpecialization) {
  6290. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
  6291. TemplateArgs.size(), Converted))
  6292. return true;
  6293. // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
  6294. // also do it during instantiation.
  6295. bool InstantiationDependent;
  6296. if (!Name.isDependent() &&
  6297. !TemplateSpecializationType::anyDependentTemplateArguments(
  6298. TemplateArgs.arguments(), InstantiationDependent)) {
  6299. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  6300. << ClassTemplate->getDeclName();
  6301. isPartialSpecialization = false;
  6302. }
  6303. }
  6304. void *InsertPos = nullptr;
  6305. ClassTemplateSpecializationDecl *PrevDecl = nullptr;
  6306. if (isPartialSpecialization)
  6307. // FIXME: Template parameter list matters, too
  6308. PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
  6309. else
  6310. PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
  6311. ClassTemplateSpecializationDecl *Specialization = nullptr;
  6312. // Check whether we can declare a class template specialization in
  6313. // the current scope.
  6314. if (TUK != TUK_Friend &&
  6315. CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
  6316. TemplateNameLoc,
  6317. isPartialSpecialization))
  6318. return true;
  6319. // The canonical type
  6320. QualType CanonType;
  6321. if (isPartialSpecialization) {
  6322. // Build the canonical type that describes the converted template
  6323. // arguments of the class template partial specialization.
  6324. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  6325. CanonType = Context.getTemplateSpecializationType(CanonTemplate,
  6326. Converted);
  6327. if (Context.hasSameType(CanonType,
  6328. ClassTemplate->getInjectedClassNameSpecialization())) {
  6329. // C++ [temp.class.spec]p9b3:
  6330. //
  6331. // -- The argument list of the specialization shall not be identical
  6332. // to the implicit argument list of the primary template.
  6333. //
  6334. // This rule has since been removed, because it's redundant given DR1495,
  6335. // but we keep it because it produces better diagnostics and recovery.
  6336. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  6337. << /*class template*/0 << (TUK == TUK_Definition)
  6338. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  6339. return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
  6340. ClassTemplate->getIdentifier(),
  6341. TemplateNameLoc,
  6342. Attr,
  6343. TemplateParams,
  6344. AS_none, /*ModulePrivateLoc=*/SourceLocation(),
  6345. /*FriendLoc*/SourceLocation(),
  6346. TemplateParameterLists.size() - 1,
  6347. TemplateParameterLists.data());
  6348. }
  6349. // Create a new class template partial specialization declaration node.
  6350. ClassTemplatePartialSpecializationDecl *PrevPartial
  6351. = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
  6352. ClassTemplatePartialSpecializationDecl *Partial
  6353. = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
  6354. ClassTemplate->getDeclContext(),
  6355. KWLoc, TemplateNameLoc,
  6356. TemplateParams,
  6357. ClassTemplate,
  6358. Converted,
  6359. TemplateArgs,
  6360. CanonType,
  6361. PrevPartial);
  6362. SetNestedNameSpecifier(Partial, SS);
  6363. if (TemplateParameterLists.size() > 1 && SS.isSet()) {
  6364. Partial->setTemplateParameterListsInfo(
  6365. Context, TemplateParameterLists.drop_back(1));
  6366. }
  6367. if (!PrevPartial)
  6368. ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
  6369. Specialization = Partial;
  6370. // If we are providing an explicit specialization of a member class
  6371. // template specialization, make a note of that.
  6372. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  6373. PrevPartial->setMemberSpecialization();
  6374. CheckTemplatePartialSpecialization(Partial);
  6375. } else {
  6376. // Create a new class template specialization declaration node for
  6377. // this explicit specialization or friend declaration.
  6378. Specialization
  6379. = ClassTemplateSpecializationDecl::Create(Context, Kind,
  6380. ClassTemplate->getDeclContext(),
  6381. KWLoc, TemplateNameLoc,
  6382. ClassTemplate,
  6383. Converted,
  6384. PrevDecl);
  6385. SetNestedNameSpecifier(Specialization, SS);
  6386. if (TemplateParameterLists.size() > 0) {
  6387. Specialization->setTemplateParameterListsInfo(Context,
  6388. TemplateParameterLists);
  6389. }
  6390. if (!PrevDecl)
  6391. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  6392. if (CurContext->isDependentContext()) {
  6393. // -fms-extensions permits specialization of nested classes without
  6394. // fully specializing the outer class(es).
  6395. assert(getLangOpts().MicrosoftExt &&
  6396. "Only possible with -fms-extensions!");
  6397. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  6398. CanonType = Context.getTemplateSpecializationType(
  6399. CanonTemplate, Converted);
  6400. } else {
  6401. CanonType = Context.getTypeDeclType(Specialization);
  6402. }
  6403. }
  6404. // C++ [temp.expl.spec]p6:
  6405. // If a template, a member template or the member of a class template is
  6406. // explicitly specialized then that specialization shall be declared
  6407. // before the first use of that specialization that would cause an implicit
  6408. // instantiation to take place, in every translation unit in which such a
  6409. // use occurs; no diagnostic is required.
  6410. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  6411. bool Okay = false;
  6412. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  6413. // Is there any previous explicit specialization declaration?
  6414. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  6415. Okay = true;
  6416. break;
  6417. }
  6418. }
  6419. if (!Okay) {
  6420. SourceRange Range(TemplateNameLoc, RAngleLoc);
  6421. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  6422. << Context.getTypeDeclType(Specialization) << Range;
  6423. Diag(PrevDecl->getPointOfInstantiation(),
  6424. diag::note_instantiation_required_here)
  6425. << (PrevDecl->getTemplateSpecializationKind()
  6426. != TSK_ImplicitInstantiation);
  6427. return true;
  6428. }
  6429. }
  6430. // If this is not a friend, note that this is an explicit specialization.
  6431. if (TUK != TUK_Friend)
  6432. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  6433. // Check that this isn't a redefinition of this specialization.
  6434. if (TUK == TUK_Definition) {
  6435. RecordDecl *Def = Specialization->getDefinition();
  6436. NamedDecl *Hidden = nullptr;
  6437. if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  6438. SkipBody->ShouldSkip = true;
  6439. makeMergedDefinitionVisible(Hidden, KWLoc);
  6440. // From here on out, treat this as just a redeclaration.
  6441. TUK = TUK_Declaration;
  6442. } else if (Def) {
  6443. SourceRange Range(TemplateNameLoc, RAngleLoc);
  6444. Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
  6445. Diag(Def->getLocation(), diag::note_previous_definition);
  6446. Specialization->setInvalidDecl();
  6447. return true;
  6448. }
  6449. }
  6450. if (Attr)
  6451. ProcessDeclAttributeList(S, Specialization, Attr);
  6452. // Add alignment attributes if necessary; these attributes are checked when
  6453. // the ASTContext lays out the structure.
  6454. if (TUK == TUK_Definition) {
  6455. AddAlignmentAttributesForRecord(Specialization);
  6456. AddMsStructLayoutForRecord(Specialization);
  6457. }
  6458. if (ModulePrivateLoc.isValid())
  6459. Diag(Specialization->getLocation(), diag::err_module_private_specialization)
  6460. << (isPartialSpecialization? 1 : 0)
  6461. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6462. // Build the fully-sugared type for this class template
  6463. // specialization as the user wrote in the specialization
  6464. // itself. This means that we'll pretty-print the type retrieved
  6465. // from the specialization's declaration the way that the user
  6466. // actually wrote the specialization, rather than formatting the
  6467. // name based on the "canonical" representation used to store the
  6468. // template arguments in the specialization.
  6469. TypeSourceInfo *WrittenTy
  6470. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  6471. TemplateArgs, CanonType);
  6472. if (TUK != TUK_Friend) {
  6473. Specialization->setTypeAsWritten(WrittenTy);
  6474. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  6475. }
  6476. // C++ [temp.expl.spec]p9:
  6477. // A template explicit specialization is in the scope of the
  6478. // namespace in which the template was defined.
  6479. //
  6480. // We actually implement this paragraph where we set the semantic
  6481. // context (in the creation of the ClassTemplateSpecializationDecl),
  6482. // but we also maintain the lexical context where the actual
  6483. // definition occurs.
  6484. Specialization->setLexicalDeclContext(CurContext);
  6485. // We may be starting the definition of this specialization.
  6486. if (TUK == TUK_Definition)
  6487. Specialization->startDefinition();
  6488. if (TUK == TUK_Friend) {
  6489. FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
  6490. TemplateNameLoc,
  6491. WrittenTy,
  6492. /*FIXME:*/KWLoc);
  6493. Friend->setAccess(AS_public);
  6494. CurContext->addDecl(Friend);
  6495. } else {
  6496. // Add the specialization into its lexical context, so that it can
  6497. // be seen when iterating through the list of declarations in that
  6498. // context. However, specializations are not found by name lookup.
  6499. CurContext->addDecl(Specialization);
  6500. }
  6501. return Specialization;
  6502. }
  6503. Decl *Sema::ActOnTemplateDeclarator(Scope *S,
  6504. MultiTemplateParamsArg TemplateParameterLists,
  6505. Declarator &D) {
  6506. Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
  6507. ActOnDocumentableDecl(NewDecl);
  6508. return NewDecl;
  6509. }
  6510. /// \brief Strips various properties off an implicit instantiation
  6511. /// that has just been explicitly specialized.
  6512. static void StripImplicitInstantiation(NamedDecl *D) {
  6513. D->dropAttr<DLLImportAttr>();
  6514. D->dropAttr<DLLExportAttr>();
  6515. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  6516. FD->setInlineSpecified(false);
  6517. }
  6518. /// \brief Compute the diagnostic location for an explicit instantiation
  6519. // declaration or definition.
  6520. static SourceLocation DiagLocForExplicitInstantiation(
  6521. NamedDecl* D, SourceLocation PointOfInstantiation) {
  6522. // Explicit instantiations following a specialization have no effect and
  6523. // hence no PointOfInstantiation. In that case, walk decl backwards
  6524. // until a valid name loc is found.
  6525. SourceLocation PrevDiagLoc = PointOfInstantiation;
  6526. for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
  6527. Prev = Prev->getPreviousDecl()) {
  6528. PrevDiagLoc = Prev->getLocation();
  6529. }
  6530. assert(PrevDiagLoc.isValid() &&
  6531. "Explicit instantiation without point of instantiation?");
  6532. return PrevDiagLoc;
  6533. }
  6534. /// \brief Diagnose cases where we have an explicit template specialization
  6535. /// before/after an explicit template instantiation, producing diagnostics
  6536. /// for those cases where they are required and determining whether the
  6537. /// new specialization/instantiation will have any effect.
  6538. ///
  6539. /// \param NewLoc the location of the new explicit specialization or
  6540. /// instantiation.
  6541. ///
  6542. /// \param NewTSK the kind of the new explicit specialization or instantiation.
  6543. ///
  6544. /// \param PrevDecl the previous declaration of the entity.
  6545. ///
  6546. /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
  6547. ///
  6548. /// \param PrevPointOfInstantiation if valid, indicates where the previus
  6549. /// declaration was instantiated (either implicitly or explicitly).
  6550. ///
  6551. /// \param HasNoEffect will be set to true to indicate that the new
  6552. /// specialization or instantiation has no effect and should be ignored.
  6553. ///
  6554. /// \returns true if there was an error that should prevent the introduction of
  6555. /// the new declaration into the AST, false otherwise.
  6556. bool
  6557. Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
  6558. TemplateSpecializationKind NewTSK,
  6559. NamedDecl *PrevDecl,
  6560. TemplateSpecializationKind PrevTSK,
  6561. SourceLocation PrevPointOfInstantiation,
  6562. bool &HasNoEffect) {
  6563. HasNoEffect = false;
  6564. switch (NewTSK) {
  6565. case TSK_Undeclared:
  6566. case TSK_ImplicitInstantiation:
  6567. assert(
  6568. (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
  6569. "previous declaration must be implicit!");
  6570. return false;
  6571. case TSK_ExplicitSpecialization:
  6572. switch (PrevTSK) {
  6573. case TSK_Undeclared:
  6574. case TSK_ExplicitSpecialization:
  6575. // Okay, we're just specializing something that is either already
  6576. // explicitly specialized or has merely been mentioned without any
  6577. // instantiation.
  6578. return false;
  6579. case TSK_ImplicitInstantiation:
  6580. if (PrevPointOfInstantiation.isInvalid()) {
  6581. // The declaration itself has not actually been instantiated, so it is
  6582. // still okay to specialize it.
  6583. StripImplicitInstantiation(PrevDecl);
  6584. return false;
  6585. }
  6586. // Fall through
  6587. case TSK_ExplicitInstantiationDeclaration:
  6588. case TSK_ExplicitInstantiationDefinition:
  6589. assert((PrevTSK == TSK_ImplicitInstantiation ||
  6590. PrevPointOfInstantiation.isValid()) &&
  6591. "Explicit instantiation without point of instantiation?");
  6592. // C++ [temp.expl.spec]p6:
  6593. // If a template, a member template or the member of a class template
  6594. // is explicitly specialized then that specialization shall be declared
  6595. // before the first use of that specialization that would cause an
  6596. // implicit instantiation to take place, in every translation unit in
  6597. // which such a use occurs; no diagnostic is required.
  6598. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  6599. // Is there any previous explicit specialization declaration?
  6600. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
  6601. return false;
  6602. }
  6603. Diag(NewLoc, diag::err_specialization_after_instantiation)
  6604. << PrevDecl;
  6605. Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
  6606. << (PrevTSK != TSK_ImplicitInstantiation);
  6607. return true;
  6608. }
  6609. case TSK_ExplicitInstantiationDeclaration:
  6610. switch (PrevTSK) {
  6611. case TSK_ExplicitInstantiationDeclaration:
  6612. // This explicit instantiation declaration is redundant (that's okay).
  6613. HasNoEffect = true;
  6614. return false;
  6615. case TSK_Undeclared:
  6616. case TSK_ImplicitInstantiation:
  6617. // We're explicitly instantiating something that may have already been
  6618. // implicitly instantiated; that's fine.
  6619. return false;
  6620. case TSK_ExplicitSpecialization:
  6621. // C++0x [temp.explicit]p4:
  6622. // For a given set of template parameters, if an explicit instantiation
  6623. // of a template appears after a declaration of an explicit
  6624. // specialization for that template, the explicit instantiation has no
  6625. // effect.
  6626. HasNoEffect = true;
  6627. return false;
  6628. case TSK_ExplicitInstantiationDefinition:
  6629. // C++0x [temp.explicit]p10:
  6630. // If an entity is the subject of both an explicit instantiation
  6631. // declaration and an explicit instantiation definition in the same
  6632. // translation unit, the definition shall follow the declaration.
  6633. Diag(NewLoc,
  6634. diag::err_explicit_instantiation_declaration_after_definition);
  6635. // Explicit instantiations following a specialization have no effect and
  6636. // hence no PrevPointOfInstantiation. In that case, walk decl backwards
  6637. // until a valid name loc is found.
  6638. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  6639. diag::note_explicit_instantiation_definition_here);
  6640. HasNoEffect = true;
  6641. return false;
  6642. }
  6643. case TSK_ExplicitInstantiationDefinition:
  6644. switch (PrevTSK) {
  6645. case TSK_Undeclared:
  6646. case TSK_ImplicitInstantiation:
  6647. // We're explicitly instantiating something that may have already been
  6648. // implicitly instantiated; that's fine.
  6649. return false;
  6650. case TSK_ExplicitSpecialization:
  6651. // C++ DR 259, C++0x [temp.explicit]p4:
  6652. // For a given set of template parameters, if an explicit
  6653. // instantiation of a template appears after a declaration of
  6654. // an explicit specialization for that template, the explicit
  6655. // instantiation has no effect.
  6656. Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
  6657. << PrevDecl;
  6658. Diag(PrevDecl->getLocation(),
  6659. diag::note_previous_template_specialization);
  6660. HasNoEffect = true;
  6661. return false;
  6662. case TSK_ExplicitInstantiationDeclaration:
  6663. // We're explicity instantiating a definition for something for which we
  6664. // were previously asked to suppress instantiations. That's fine.
  6665. // C++0x [temp.explicit]p4:
  6666. // For a given set of template parameters, if an explicit instantiation
  6667. // of a template appears after a declaration of an explicit
  6668. // specialization for that template, the explicit instantiation has no
  6669. // effect.
  6670. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  6671. // Is there any previous explicit specialization declaration?
  6672. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  6673. HasNoEffect = true;
  6674. break;
  6675. }
  6676. }
  6677. return false;
  6678. case TSK_ExplicitInstantiationDefinition:
  6679. // C++0x [temp.spec]p5:
  6680. // For a given template and a given set of template-arguments,
  6681. // - an explicit instantiation definition shall appear at most once
  6682. // in a program,
  6683. // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
  6684. Diag(NewLoc, (getLangOpts().MSVCCompat)
  6685. ? diag::ext_explicit_instantiation_duplicate
  6686. : diag::err_explicit_instantiation_duplicate)
  6687. << PrevDecl;
  6688. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  6689. diag::note_previous_explicit_instantiation);
  6690. HasNoEffect = true;
  6691. return false;
  6692. }
  6693. }
  6694. llvm_unreachable("Missing specialization/instantiation case?");
  6695. }
  6696. /// \brief Perform semantic analysis for the given dependent function
  6697. /// template specialization.
  6698. ///
  6699. /// The only possible way to get a dependent function template specialization
  6700. /// is with a friend declaration, like so:
  6701. ///
  6702. /// \code
  6703. /// template \<class T> void foo(T);
  6704. /// template \<class T> class A {
  6705. /// friend void foo<>(T);
  6706. /// };
  6707. /// \endcode
  6708. ///
  6709. /// There really isn't any useful analysis we can do here, so we
  6710. /// just store the information.
  6711. bool
  6712. Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
  6713. const TemplateArgumentListInfo &ExplicitTemplateArgs,
  6714. LookupResult &Previous) {
  6715. // Remove anything from Previous that isn't a function template in
  6716. // the correct context.
  6717. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  6718. LookupResult::Filter F = Previous.makeFilter();
  6719. while (F.hasNext()) {
  6720. NamedDecl *D = F.next()->getUnderlyingDecl();
  6721. if (!isa<FunctionTemplateDecl>(D) ||
  6722. !FDLookupContext->InEnclosingNamespaceSetOf(
  6723. D->getDeclContext()->getRedeclContext()))
  6724. F.erase();
  6725. }
  6726. F.done();
  6727. // Should this be diagnosed here?
  6728. if (Previous.empty()) return true;
  6729. FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
  6730. ExplicitTemplateArgs);
  6731. return false;
  6732. }
  6733. /// \brief Perform semantic analysis for the given function template
  6734. /// specialization.
  6735. ///
  6736. /// This routine performs all of the semantic analysis required for an
  6737. /// explicit function template specialization. On successful completion,
  6738. /// the function declaration \p FD will become a function template
  6739. /// specialization.
  6740. ///
  6741. /// \param FD the function declaration, which will be updated to become a
  6742. /// function template specialization.
  6743. ///
  6744. /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
  6745. /// if any. Note that this may be valid info even when 0 arguments are
  6746. /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
  6747. /// as it anyway contains info on the angle brackets locations.
  6748. ///
  6749. /// \param Previous the set of declarations that may be specialized by
  6750. /// this function specialization.
  6751. bool Sema::CheckFunctionTemplateSpecialization(
  6752. FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
  6753. LookupResult &Previous) {
  6754. // The set of function template specializations that could match this
  6755. // explicit function template specialization.
  6756. UnresolvedSet<8> Candidates;
  6757. TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
  6758. /*ForTakingAddress=*/false);
  6759. llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
  6760. ConvertedTemplateArgs;
  6761. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  6762. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6763. I != E; ++I) {
  6764. NamedDecl *Ovl = (*I)->getUnderlyingDecl();
  6765. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
  6766. // Only consider templates found within the same semantic lookup scope as
  6767. // FD.
  6768. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  6769. Ovl->getDeclContext()->getRedeclContext()))
  6770. continue;
  6771. // When matching a constexpr member function template specialization
  6772. // against the primary template, we don't yet know whether the
  6773. // specialization has an implicit 'const' (because we don't know whether
  6774. // it will be a static member function until we know which template it
  6775. // specializes), so adjust it now assuming it specializes this template.
  6776. QualType FT = FD->getType();
  6777. if (FD->isConstexpr()) {
  6778. CXXMethodDecl *OldMD =
  6779. dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
  6780. if (OldMD && OldMD->isConst()) {
  6781. const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
  6782. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  6783. EPI.TypeQuals |= Qualifiers::Const;
  6784. FT = Context.getFunctionType(FPT->getReturnType(),
  6785. FPT->getParamTypes(), EPI);
  6786. }
  6787. }
  6788. TemplateArgumentListInfo Args;
  6789. if (ExplicitTemplateArgs)
  6790. Args = *ExplicitTemplateArgs;
  6791. // C++ [temp.expl.spec]p11:
  6792. // A trailing template-argument can be left unspecified in the
  6793. // template-id naming an explicit function template specialization
  6794. // provided it can be deduced from the function argument type.
  6795. // Perform template argument deduction to determine whether we may be
  6796. // specializing this template.
  6797. // FIXME: It is somewhat wasteful to build
  6798. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  6799. FunctionDecl *Specialization = nullptr;
  6800. if (TemplateDeductionResult TDK = DeduceTemplateArguments(
  6801. cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
  6802. ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
  6803. Info)) {
  6804. // Template argument deduction failed; record why it failed, so
  6805. // that we can provide nifty diagnostics.
  6806. FailedCandidates.addCandidate().set(
  6807. I.getPair(), FunTmpl->getTemplatedDecl(),
  6808. MakeDeductionFailureInfo(Context, TDK, Info));
  6809. (void)TDK;
  6810. continue;
  6811. }
  6812. // Target attributes are part of the cuda function signature, so
  6813. // the deduced template's cuda target must match that of the
  6814. // specialization. Given that C++ template deduction does not
  6815. // take target attributes into account, we reject candidates
  6816. // here that have a different target.
  6817. if (LangOpts.CUDA &&
  6818. IdentifyCUDATarget(Specialization,
  6819. /* IgnoreImplicitHDAttributes = */ true) !=
  6820. IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
  6821. FailedCandidates.addCandidate().set(
  6822. I.getPair(), FunTmpl->getTemplatedDecl(),
  6823. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  6824. continue;
  6825. }
  6826. // Record this candidate.
  6827. if (ExplicitTemplateArgs)
  6828. ConvertedTemplateArgs[Specialization] = std::move(Args);
  6829. Candidates.addDecl(Specialization, I.getAccess());
  6830. }
  6831. }
  6832. // Find the most specialized function template.
  6833. UnresolvedSetIterator Result = getMostSpecialized(
  6834. Candidates.begin(), Candidates.end(), FailedCandidates,
  6835. FD->getLocation(),
  6836. PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
  6837. PDiag(diag::err_function_template_spec_ambiguous)
  6838. << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
  6839. PDiag(diag::note_function_template_spec_matched));
  6840. if (Result == Candidates.end())
  6841. return true;
  6842. // Ignore access information; it doesn't figure into redeclaration checking.
  6843. FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
  6844. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
  6845. // an explicit specialization (14.8.3) [...] of a concept definition.
  6846. if (Specialization->getPrimaryTemplate()->isConcept()) {
  6847. Diag(FD->getLocation(), diag::err_concept_specialized)
  6848. << 0 /*function*/ << 1 /*explicitly specialized*/;
  6849. Diag(Specialization->getLocation(), diag::note_previous_declaration);
  6850. return true;
  6851. }
  6852. FunctionTemplateSpecializationInfo *SpecInfo
  6853. = Specialization->getTemplateSpecializationInfo();
  6854. assert(SpecInfo && "Function template specialization info missing?");
  6855. // Note: do not overwrite location info if previous template
  6856. // specialization kind was explicit.
  6857. TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
  6858. if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
  6859. Specialization->setLocation(FD->getLocation());
  6860. // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
  6861. // function can differ from the template declaration with respect to
  6862. // the constexpr specifier.
  6863. Specialization->setConstexpr(FD->isConstexpr());
  6864. }
  6865. // FIXME: Check if the prior specialization has a point of instantiation.
  6866. // If so, we have run afoul of .
  6867. // If this is a friend declaration, then we're not really declaring
  6868. // an explicit specialization.
  6869. bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
  6870. // Check the scope of this explicit specialization.
  6871. if (!isFriend &&
  6872. CheckTemplateSpecializationScope(*this,
  6873. Specialization->getPrimaryTemplate(),
  6874. Specialization, FD->getLocation(),
  6875. false))
  6876. return true;
  6877. // C++ [temp.expl.spec]p6:
  6878. // If a template, a member template or the member of a class template is
  6879. // explicitly specialized then that specialization shall be declared
  6880. // before the first use of that specialization that would cause an implicit
  6881. // instantiation to take place, in every translation unit in which such a
  6882. // use occurs; no diagnostic is required.
  6883. bool HasNoEffect = false;
  6884. if (!isFriend &&
  6885. CheckSpecializationInstantiationRedecl(FD->getLocation(),
  6886. TSK_ExplicitSpecialization,
  6887. Specialization,
  6888. SpecInfo->getTemplateSpecializationKind(),
  6889. SpecInfo->getPointOfInstantiation(),
  6890. HasNoEffect))
  6891. return true;
  6892. // Mark the prior declaration as an explicit specialization, so that later
  6893. // clients know that this is an explicit specialization.
  6894. if (!isFriend) {
  6895. // Since explicit specializations do not inherit '=delete' from their
  6896. // primary function template - check if the 'specialization' that was
  6897. // implicitly generated (during template argument deduction for partial
  6898. // ordering) from the most specialized of all the function templates that
  6899. // 'FD' could have been specializing, has a 'deleted' definition. If so,
  6900. // first check that it was implicitly generated during template argument
  6901. // deduction by making sure it wasn't referenced, and then reset the deleted
  6902. // flag to not-deleted, so that we can inherit that information from 'FD'.
  6903. if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
  6904. !Specialization->getCanonicalDecl()->isReferenced()) {
  6905. assert(
  6906. Specialization->getCanonicalDecl() == Specialization &&
  6907. "This must be the only existing declaration of this specialization");
  6908. Specialization->setDeletedAsWritten(false);
  6909. }
  6910. SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  6911. MarkUnusedFileScopedDecl(Specialization);
  6912. }
  6913. // Turn the given function declaration into a function template
  6914. // specialization, with the template arguments from the previous
  6915. // specialization.
  6916. // Take copies of (semantic and syntactic) template argument lists.
  6917. const TemplateArgumentList* TemplArgs = new (Context)
  6918. TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
  6919. FD->setFunctionTemplateSpecialization(
  6920. Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
  6921. SpecInfo->getTemplateSpecializationKind(),
  6922. ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
  6923. // A function template specialization inherits the target attributes
  6924. // of its template. (We require the attributes explicitly in the
  6925. // code to match, but a template may have implicit attributes by
  6926. // virtue e.g. of being constexpr, and it passes these implicit
  6927. // attributes on to its specializations.)
  6928. if (LangOpts.CUDA)
  6929. inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
  6930. // The "previous declaration" for this function template specialization is
  6931. // the prior function template specialization.
  6932. Previous.clear();
  6933. Previous.addDecl(Specialization);
  6934. return false;
  6935. }
  6936. /// \brief Perform semantic analysis for the given non-template member
  6937. /// specialization.
  6938. ///
  6939. /// This routine performs all of the semantic analysis required for an
  6940. /// explicit member function specialization. On successful completion,
  6941. /// the function declaration \p FD will become a member function
  6942. /// specialization.
  6943. ///
  6944. /// \param Member the member declaration, which will be updated to become a
  6945. /// specialization.
  6946. ///
  6947. /// \param Previous the set of declarations, one of which may be specialized
  6948. /// by this function specialization; the set will be modified to contain the
  6949. /// redeclared member.
  6950. bool
  6951. Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
  6952. assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
  6953. // Try to find the member we are instantiating.
  6954. NamedDecl *FoundInstantiation = nullptr;
  6955. NamedDecl *Instantiation = nullptr;
  6956. NamedDecl *InstantiatedFrom = nullptr;
  6957. MemberSpecializationInfo *MSInfo = nullptr;
  6958. if (Previous.empty()) {
  6959. // Nowhere to look anyway.
  6960. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
  6961. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6962. I != E; ++I) {
  6963. NamedDecl *D = (*I)->getUnderlyingDecl();
  6964. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  6965. QualType Adjusted = Function->getType();
  6966. if (!hasExplicitCallingConv(Adjusted))
  6967. Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
  6968. if (Context.hasSameType(Adjusted, Method->getType())) {
  6969. FoundInstantiation = *I;
  6970. Instantiation = Method;
  6971. InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
  6972. MSInfo = Method->getMemberSpecializationInfo();
  6973. break;
  6974. }
  6975. }
  6976. }
  6977. } else if (isa<VarDecl>(Member)) {
  6978. VarDecl *PrevVar;
  6979. if (Previous.isSingleResult() &&
  6980. (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
  6981. if (PrevVar->isStaticDataMember()) {
  6982. FoundInstantiation = Previous.getRepresentativeDecl();
  6983. Instantiation = PrevVar;
  6984. InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
  6985. MSInfo = PrevVar->getMemberSpecializationInfo();
  6986. }
  6987. } else if (isa<RecordDecl>(Member)) {
  6988. CXXRecordDecl *PrevRecord;
  6989. if (Previous.isSingleResult() &&
  6990. (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
  6991. FoundInstantiation = Previous.getRepresentativeDecl();
  6992. Instantiation = PrevRecord;
  6993. InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
  6994. MSInfo = PrevRecord->getMemberSpecializationInfo();
  6995. }
  6996. } else if (isa<EnumDecl>(Member)) {
  6997. EnumDecl *PrevEnum;
  6998. if (Previous.isSingleResult() &&
  6999. (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
  7000. FoundInstantiation = Previous.getRepresentativeDecl();
  7001. Instantiation = PrevEnum;
  7002. InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
  7003. MSInfo = PrevEnum->getMemberSpecializationInfo();
  7004. }
  7005. }
  7006. if (!Instantiation) {
  7007. // There is no previous declaration that matches. Since member
  7008. // specializations are always out-of-line, the caller will complain about
  7009. // this mismatch later.
  7010. return false;
  7011. }
  7012. // If this is a friend, just bail out here before we start turning
  7013. // things into explicit specializations.
  7014. if (Member->getFriendObjectKind() != Decl::FOK_None) {
  7015. // Preserve instantiation information.
  7016. if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
  7017. cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
  7018. cast<CXXMethodDecl>(InstantiatedFrom),
  7019. cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
  7020. } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
  7021. cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
  7022. cast<CXXRecordDecl>(InstantiatedFrom),
  7023. cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
  7024. }
  7025. Previous.clear();
  7026. Previous.addDecl(FoundInstantiation);
  7027. return false;
  7028. }
  7029. // Make sure that this is a specialization of a member.
  7030. if (!InstantiatedFrom) {
  7031. Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
  7032. << Member;
  7033. Diag(Instantiation->getLocation(), diag::note_specialized_decl);
  7034. return true;
  7035. }
  7036. // C++ [temp.expl.spec]p6:
  7037. // If a template, a member template or the member of a class template is
  7038. // explicitly specialized then that specialization shall be declared
  7039. // before the first use of that specialization that would cause an implicit
  7040. // instantiation to take place, in every translation unit in which such a
  7041. // use occurs; no diagnostic is required.
  7042. assert(MSInfo && "Member specialization info missing?");
  7043. bool HasNoEffect = false;
  7044. if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
  7045. TSK_ExplicitSpecialization,
  7046. Instantiation,
  7047. MSInfo->getTemplateSpecializationKind(),
  7048. MSInfo->getPointOfInstantiation(),
  7049. HasNoEffect))
  7050. return true;
  7051. // Check the scope of this explicit specialization.
  7052. if (CheckTemplateSpecializationScope(*this,
  7053. InstantiatedFrom,
  7054. Instantiation, Member->getLocation(),
  7055. false))
  7056. return true;
  7057. // Note that this is an explicit instantiation of a member.
  7058. // the original declaration to note that it is an explicit specialization
  7059. // (if it was previously an implicit instantiation). This latter step
  7060. // makes bookkeeping easier.
  7061. if (isa<FunctionDecl>(Member)) {
  7062. FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
  7063. if (InstantiationFunction->getTemplateSpecializationKind() ==
  7064. TSK_ImplicitInstantiation) {
  7065. InstantiationFunction->setTemplateSpecializationKind(
  7066. TSK_ExplicitSpecialization);
  7067. InstantiationFunction->setLocation(Member->getLocation());
  7068. // Explicit specializations of member functions of class templates do not
  7069. // inherit '=delete' from the member function they are specializing.
  7070. if (InstantiationFunction->isDeleted()) {
  7071. assert(InstantiationFunction->getCanonicalDecl() ==
  7072. InstantiationFunction);
  7073. InstantiationFunction->setDeletedAsWritten(false);
  7074. }
  7075. }
  7076. cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
  7077. cast<CXXMethodDecl>(InstantiatedFrom),
  7078. TSK_ExplicitSpecialization);
  7079. MarkUnusedFileScopedDecl(InstantiationFunction);
  7080. } else if (isa<VarDecl>(Member)) {
  7081. VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
  7082. if (InstantiationVar->getTemplateSpecializationKind() ==
  7083. TSK_ImplicitInstantiation) {
  7084. InstantiationVar->setTemplateSpecializationKind(
  7085. TSK_ExplicitSpecialization);
  7086. InstantiationVar->setLocation(Member->getLocation());
  7087. }
  7088. cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
  7089. cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  7090. MarkUnusedFileScopedDecl(InstantiationVar);
  7091. } else if (isa<CXXRecordDecl>(Member)) {
  7092. CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
  7093. if (InstantiationClass->getTemplateSpecializationKind() ==
  7094. TSK_ImplicitInstantiation) {
  7095. InstantiationClass->setTemplateSpecializationKind(
  7096. TSK_ExplicitSpecialization);
  7097. InstantiationClass->setLocation(Member->getLocation());
  7098. }
  7099. cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
  7100. cast<CXXRecordDecl>(InstantiatedFrom),
  7101. TSK_ExplicitSpecialization);
  7102. } else {
  7103. assert(isa<EnumDecl>(Member) && "Only member enums remain");
  7104. EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
  7105. if (InstantiationEnum->getTemplateSpecializationKind() ==
  7106. TSK_ImplicitInstantiation) {
  7107. InstantiationEnum->setTemplateSpecializationKind(
  7108. TSK_ExplicitSpecialization);
  7109. InstantiationEnum->setLocation(Member->getLocation());
  7110. }
  7111. cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
  7112. cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  7113. }
  7114. // Save the caller the trouble of having to figure out which declaration
  7115. // this specialization matches.
  7116. Previous.clear();
  7117. Previous.addDecl(FoundInstantiation);
  7118. return false;
  7119. }
  7120. /// \brief Check the scope of an explicit instantiation.
  7121. ///
  7122. /// \returns true if a serious error occurs, false otherwise.
  7123. static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
  7124. SourceLocation InstLoc,
  7125. bool WasQualifiedName) {
  7126. DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
  7127. DeclContext *CurContext = S.CurContext->getRedeclContext();
  7128. if (CurContext->isRecord()) {
  7129. S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
  7130. << D;
  7131. return true;
  7132. }
  7133. // C++11 [temp.explicit]p3:
  7134. // An explicit instantiation shall appear in an enclosing namespace of its
  7135. // template. If the name declared in the explicit instantiation is an
  7136. // unqualified name, the explicit instantiation shall appear in the
  7137. // namespace where its template is declared or, if that namespace is inline
  7138. // (7.3.1), any namespace from its enclosing namespace set.
  7139. //
  7140. // This is DR275, which we do not retroactively apply to C++98/03.
  7141. if (WasQualifiedName) {
  7142. if (CurContext->Encloses(OrigContext))
  7143. return false;
  7144. } else {
  7145. if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
  7146. return false;
  7147. }
  7148. if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
  7149. if (WasQualifiedName)
  7150. S.Diag(InstLoc,
  7151. S.getLangOpts().CPlusPlus11?
  7152. diag::err_explicit_instantiation_out_of_scope :
  7153. diag::warn_explicit_instantiation_out_of_scope_0x)
  7154. << D << NS;
  7155. else
  7156. S.Diag(InstLoc,
  7157. S.getLangOpts().CPlusPlus11?
  7158. diag::err_explicit_instantiation_unqualified_wrong_namespace :
  7159. diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
  7160. << D << NS;
  7161. } else
  7162. S.Diag(InstLoc,
  7163. S.getLangOpts().CPlusPlus11?
  7164. diag::err_explicit_instantiation_must_be_global :
  7165. diag::warn_explicit_instantiation_must_be_global_0x)
  7166. << D;
  7167. S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
  7168. return false;
  7169. }
  7170. /// \brief Determine whether the given scope specifier has a template-id in it.
  7171. static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
  7172. if (!SS.isSet())
  7173. return false;
  7174. // C++11 [temp.explicit]p3:
  7175. // If the explicit instantiation is for a member function, a member class
  7176. // or a static data member of a class template specialization, the name of
  7177. // the class template specialization in the qualified-id for the member
  7178. // name shall be a simple-template-id.
  7179. //
  7180. // C++98 has the same restriction, just worded differently.
  7181. for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
  7182. NNS = NNS->getPrefix())
  7183. if (const Type *T = NNS->getAsType())
  7184. if (isa<TemplateSpecializationType>(T))
  7185. return true;
  7186. return false;
  7187. }
  7188. /// Make a dllexport or dllimport attr on a class template specialization take
  7189. /// effect.
  7190. static void dllExportImportClassTemplateSpecialization(
  7191. Sema &S, ClassTemplateSpecializationDecl *Def) {
  7192. auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
  7193. assert(A && "dllExportImportClassTemplateSpecialization called "
  7194. "on Def without dllexport or dllimport");
  7195. // We reject explicit instantiations in class scope, so there should
  7196. // never be any delayed exported classes to worry about.
  7197. assert(S.DelayedDllExportClasses.empty() &&
  7198. "delayed exports present at explicit instantiation");
  7199. S.checkClassLevelDLLAttribute(Def);
  7200. // Propagate attribute to base class templates.
  7201. for (auto &B : Def->bases()) {
  7202. if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  7203. B.getType()->getAsCXXRecordDecl()))
  7204. S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
  7205. }
  7206. S.referenceDLLExportedClassMethods();
  7207. }
  7208. // Explicit instantiation of a class template specialization
  7209. DeclResult
  7210. Sema::ActOnExplicitInstantiation(Scope *S,
  7211. SourceLocation ExternLoc,
  7212. SourceLocation TemplateLoc,
  7213. unsigned TagSpec,
  7214. SourceLocation KWLoc,
  7215. const CXXScopeSpec &SS,
  7216. TemplateTy TemplateD,
  7217. SourceLocation TemplateNameLoc,
  7218. SourceLocation LAngleLoc,
  7219. ASTTemplateArgsPtr TemplateArgsIn,
  7220. SourceLocation RAngleLoc,
  7221. AttributeList *Attr) {
  7222. // Find the class template we're specializing
  7223. TemplateName Name = TemplateD.get();
  7224. TemplateDecl *TD = Name.getAsTemplateDecl();
  7225. // Check that the specialization uses the same tag kind as the
  7226. // original template.
  7227. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7228. assert(Kind != TTK_Enum &&
  7229. "Invalid enum tag in class template explicit instantiation!");
  7230. ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
  7231. if (!ClassTemplate) {
  7232. NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
  7233. Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
  7234. Diag(TD->getLocation(), diag::note_previous_use);
  7235. return true;
  7236. }
  7237. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  7238. Kind, /*isDefinition*/false, KWLoc,
  7239. ClassTemplate->getIdentifier())) {
  7240. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7241. << ClassTemplate
  7242. << FixItHint::CreateReplacement(KWLoc,
  7243. ClassTemplate->getTemplatedDecl()->getKindName());
  7244. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  7245. diag::note_previous_use);
  7246. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  7247. }
  7248. // C++0x [temp.explicit]p2:
  7249. // There are two forms of explicit instantiation: an explicit instantiation
  7250. // definition and an explicit instantiation declaration. An explicit
  7251. // instantiation declaration begins with the extern keyword. [...]
  7252. TemplateSpecializationKind TSK = ExternLoc.isInvalid()
  7253. ? TSK_ExplicitInstantiationDefinition
  7254. : TSK_ExplicitInstantiationDeclaration;
  7255. if (TSK == TSK_ExplicitInstantiationDeclaration) {
  7256. // Check for dllexport class template instantiation declarations.
  7257. for (AttributeList *A = Attr; A; A = A->getNext()) {
  7258. if (A->getKind() == AttributeList::AT_DLLExport) {
  7259. Diag(ExternLoc,
  7260. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  7261. Diag(A->getLoc(), diag::note_attribute);
  7262. break;
  7263. }
  7264. }
  7265. if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
  7266. Diag(ExternLoc,
  7267. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  7268. Diag(A->getLocation(), diag::note_attribute);
  7269. }
  7270. }
  7271. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  7272. // instantiation declarations for most purposes.
  7273. bool DLLImportExplicitInstantiationDef = false;
  7274. if (TSK == TSK_ExplicitInstantiationDefinition &&
  7275. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  7276. // Check for dllimport class template instantiation definitions.
  7277. bool DLLImport =
  7278. ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
  7279. for (AttributeList *A = Attr; A; A = A->getNext()) {
  7280. if (A->getKind() == AttributeList::AT_DLLImport)
  7281. DLLImport = true;
  7282. if (A->getKind() == AttributeList::AT_DLLExport) {
  7283. // dllexport trumps dllimport here.
  7284. DLLImport = false;
  7285. break;
  7286. }
  7287. }
  7288. if (DLLImport) {
  7289. TSK = TSK_ExplicitInstantiationDeclaration;
  7290. DLLImportExplicitInstantiationDef = true;
  7291. }
  7292. }
  7293. // Translate the parser's template argument list in our AST format.
  7294. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  7295. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  7296. // Check that the template argument list is well-formed for this
  7297. // template.
  7298. SmallVector<TemplateArgument, 4> Converted;
  7299. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
  7300. TemplateArgs, false, Converted))
  7301. return true;
  7302. // Find the class template specialization declaration that
  7303. // corresponds to these arguments.
  7304. void *InsertPos = nullptr;
  7305. ClassTemplateSpecializationDecl *PrevDecl
  7306. = ClassTemplate->findSpecialization(Converted, InsertPos);
  7307. TemplateSpecializationKind PrevDecl_TSK
  7308. = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
  7309. // C++0x [temp.explicit]p2:
  7310. // [...] An explicit instantiation shall appear in an enclosing
  7311. // namespace of its template. [...]
  7312. //
  7313. // This is C++ DR 275.
  7314. if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
  7315. SS.isSet()))
  7316. return true;
  7317. ClassTemplateSpecializationDecl *Specialization = nullptr;
  7318. bool HasNoEffect = false;
  7319. if (PrevDecl) {
  7320. if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
  7321. PrevDecl, PrevDecl_TSK,
  7322. PrevDecl->getPointOfInstantiation(),
  7323. HasNoEffect))
  7324. return PrevDecl;
  7325. // Even though HasNoEffect == true means that this explicit instantiation
  7326. // has no effect on semantics, we go on to put its syntax in the AST.
  7327. if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
  7328. PrevDecl_TSK == TSK_Undeclared) {
  7329. // Since the only prior class template specialization with these
  7330. // arguments was referenced but not declared, reuse that
  7331. // declaration node as our own, updating the source location
  7332. // for the template name to reflect our new declaration.
  7333. // (Other source locations will be updated later.)
  7334. Specialization = PrevDecl;
  7335. Specialization->setLocation(TemplateNameLoc);
  7336. PrevDecl = nullptr;
  7337. }
  7338. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  7339. DLLImportExplicitInstantiationDef) {
  7340. // The new specialization might add a dllimport attribute.
  7341. HasNoEffect = false;
  7342. }
  7343. }
  7344. if (!Specialization) {
  7345. // Create a new class template specialization declaration node for
  7346. // this explicit specialization.
  7347. Specialization
  7348. = ClassTemplateSpecializationDecl::Create(Context, Kind,
  7349. ClassTemplate->getDeclContext(),
  7350. KWLoc, TemplateNameLoc,
  7351. ClassTemplate,
  7352. Converted,
  7353. PrevDecl);
  7354. SetNestedNameSpecifier(Specialization, SS);
  7355. if (!HasNoEffect && !PrevDecl) {
  7356. // Insert the new specialization.
  7357. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  7358. }
  7359. }
  7360. // Build the fully-sugared type for this explicit instantiation as
  7361. // the user wrote in the explicit instantiation itself. This means
  7362. // that we'll pretty-print the type retrieved from the
  7363. // specialization's declaration the way that the user actually wrote
  7364. // the explicit instantiation, rather than formatting the name based
  7365. // on the "canonical" representation used to store the template
  7366. // arguments in the specialization.
  7367. TypeSourceInfo *WrittenTy
  7368. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  7369. TemplateArgs,
  7370. Context.getTypeDeclType(Specialization));
  7371. Specialization->setTypeAsWritten(WrittenTy);
  7372. // Set source locations for keywords.
  7373. Specialization->setExternLoc(ExternLoc);
  7374. Specialization->setTemplateKeywordLoc(TemplateLoc);
  7375. Specialization->setBraceRange(SourceRange());
  7376. bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
  7377. if (Attr)
  7378. ProcessDeclAttributeList(S, Specialization, Attr);
  7379. // Add the explicit instantiation into its lexical context. However,
  7380. // since explicit instantiations are never found by name lookup, we
  7381. // just put it into the declaration context directly.
  7382. Specialization->setLexicalDeclContext(CurContext);
  7383. CurContext->addDecl(Specialization);
  7384. // Syntax is now OK, so return if it has no other effect on semantics.
  7385. if (HasNoEffect) {
  7386. // Set the template specialization kind.
  7387. Specialization->setTemplateSpecializationKind(TSK);
  7388. return Specialization;
  7389. }
  7390. // C++ [temp.explicit]p3:
  7391. // A definition of a class template or class member template
  7392. // shall be in scope at the point of the explicit instantiation of
  7393. // the class template or class member template.
  7394. //
  7395. // This check comes when we actually try to perform the
  7396. // instantiation.
  7397. ClassTemplateSpecializationDecl *Def
  7398. = cast_or_null<ClassTemplateSpecializationDecl>(
  7399. Specialization->getDefinition());
  7400. if (!Def)
  7401. InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
  7402. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  7403. MarkVTableUsed(TemplateNameLoc, Specialization, true);
  7404. Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
  7405. }
  7406. // Instantiate the members of this class template specialization.
  7407. Def = cast_or_null<ClassTemplateSpecializationDecl>(
  7408. Specialization->getDefinition());
  7409. if (Def) {
  7410. TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
  7411. // Fix a TSK_ExplicitInstantiationDeclaration followed by a
  7412. // TSK_ExplicitInstantiationDefinition
  7413. if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
  7414. (TSK == TSK_ExplicitInstantiationDefinition ||
  7415. DLLImportExplicitInstantiationDef)) {
  7416. // FIXME: Need to notify the ASTMutationListener that we did this.
  7417. Def->setTemplateSpecializationKind(TSK);
  7418. if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
  7419. (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  7420. Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
  7421. // In the MS ABI, an explicit instantiation definition can add a dll
  7422. // attribute to a template with a previous instantiation declaration.
  7423. // MinGW doesn't allow this.
  7424. auto *A = cast<InheritableAttr>(
  7425. getDLLAttr(Specialization)->clone(getASTContext()));
  7426. A->setInherited(true);
  7427. Def->addAttr(A);
  7428. dllExportImportClassTemplateSpecialization(*this, Def);
  7429. }
  7430. }
  7431. // Fix a TSK_ImplicitInstantiation followed by a
  7432. // TSK_ExplicitInstantiationDefinition
  7433. bool NewlyDLLExported =
  7434. !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
  7435. if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
  7436. (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  7437. Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
  7438. // In the MS ABI, an explicit instantiation definition can add a dll
  7439. // attribute to a template with a previous implicit instantiation.
  7440. // MinGW doesn't allow this. We limit clang to only adding dllexport, to
  7441. // avoid potentially strange codegen behavior. For example, if we extend
  7442. // this conditional to dllimport, and we have a source file calling a
  7443. // method on an implicitly instantiated template class instance and then
  7444. // declaring a dllimport explicit instantiation definition for the same
  7445. // template class, the codegen for the method call will not respect the
  7446. // dllimport, while it will with cl. The Def will already have the DLL
  7447. // attribute, since the Def and Specialization will be the same in the
  7448. // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
  7449. // attribute to the Specialization; we just need to make it take effect.
  7450. assert(Def == Specialization &&
  7451. "Def and Specialization should match for implicit instantiation");
  7452. dllExportImportClassTemplateSpecialization(*this, Def);
  7453. }
  7454. // Set the template specialization kind. Make sure it is set before
  7455. // instantiating the members which will trigger ASTConsumer callbacks.
  7456. Specialization->setTemplateSpecializationKind(TSK);
  7457. InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
  7458. } else {
  7459. // Set the template specialization kind.
  7460. Specialization->setTemplateSpecializationKind(TSK);
  7461. }
  7462. return Specialization;
  7463. }
  7464. // Explicit instantiation of a member class of a class template.
  7465. DeclResult
  7466. Sema::ActOnExplicitInstantiation(Scope *S,
  7467. SourceLocation ExternLoc,
  7468. SourceLocation TemplateLoc,
  7469. unsigned TagSpec,
  7470. SourceLocation KWLoc,
  7471. CXXScopeSpec &SS,
  7472. IdentifierInfo *Name,
  7473. SourceLocation NameLoc,
  7474. AttributeList *Attr) {
  7475. bool Owned = false;
  7476. bool IsDependent = false;
  7477. Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
  7478. KWLoc, SS, Name, NameLoc, Attr, AS_none,
  7479. /*ModulePrivateLoc=*/SourceLocation(),
  7480. MultiTemplateParamsArg(), Owned, IsDependent,
  7481. SourceLocation(), false, TypeResult(),
  7482. /*IsTypeSpecifier*/false);
  7483. assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
  7484. if (!TagD)
  7485. return true;
  7486. TagDecl *Tag = cast<TagDecl>(TagD);
  7487. assert(!Tag->isEnum() && "shouldn't see enumerations here");
  7488. if (Tag->isInvalidDecl())
  7489. return true;
  7490. CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
  7491. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  7492. if (!Pattern) {
  7493. Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
  7494. << Context.getTypeDeclType(Record);
  7495. Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
  7496. return true;
  7497. }
  7498. // C++0x [temp.explicit]p2:
  7499. // If the explicit instantiation is for a class or member class, the
  7500. // elaborated-type-specifier in the declaration shall include a
  7501. // simple-template-id.
  7502. //
  7503. // C++98 has the same restriction, just worded differently.
  7504. if (!ScopeSpecifierHasTemplateId(SS))
  7505. Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
  7506. << Record << SS.getRange();
  7507. // C++0x [temp.explicit]p2:
  7508. // There are two forms of explicit instantiation: an explicit instantiation
  7509. // definition and an explicit instantiation declaration. An explicit
  7510. // instantiation declaration begins with the extern keyword. [...]
  7511. TemplateSpecializationKind TSK
  7512. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  7513. : TSK_ExplicitInstantiationDeclaration;
  7514. // C++0x [temp.explicit]p2:
  7515. // [...] An explicit instantiation shall appear in an enclosing
  7516. // namespace of its template. [...]
  7517. //
  7518. // This is C++ DR 275.
  7519. CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
  7520. // Verify that it is okay to explicitly instantiate here.
  7521. CXXRecordDecl *PrevDecl
  7522. = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
  7523. if (!PrevDecl && Record->getDefinition())
  7524. PrevDecl = Record;
  7525. if (PrevDecl) {
  7526. MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
  7527. bool HasNoEffect = false;
  7528. assert(MSInfo && "No member specialization information?");
  7529. if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
  7530. PrevDecl,
  7531. MSInfo->getTemplateSpecializationKind(),
  7532. MSInfo->getPointOfInstantiation(),
  7533. HasNoEffect))
  7534. return true;
  7535. if (HasNoEffect)
  7536. return TagD;
  7537. }
  7538. CXXRecordDecl *RecordDef
  7539. = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  7540. if (!RecordDef) {
  7541. // C++ [temp.explicit]p3:
  7542. // A definition of a member class of a class template shall be in scope
  7543. // at the point of an explicit instantiation of the member class.
  7544. CXXRecordDecl *Def
  7545. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  7546. if (!Def) {
  7547. Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
  7548. << 0 << Record->getDeclName() << Record->getDeclContext();
  7549. Diag(Pattern->getLocation(), diag::note_forward_declaration)
  7550. << Pattern;
  7551. return true;
  7552. } else {
  7553. if (InstantiateClass(NameLoc, Record, Def,
  7554. getTemplateInstantiationArgs(Record),
  7555. TSK))
  7556. return true;
  7557. RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  7558. if (!RecordDef)
  7559. return true;
  7560. }
  7561. }
  7562. // Instantiate all of the members of the class.
  7563. InstantiateClassMembers(NameLoc, RecordDef,
  7564. getTemplateInstantiationArgs(Record), TSK);
  7565. if (TSK == TSK_ExplicitInstantiationDefinition)
  7566. MarkVTableUsed(NameLoc, RecordDef, true);
  7567. // FIXME: We don't have any representation for explicit instantiations of
  7568. // member classes. Such a representation is not needed for compilation, but it
  7569. // should be available for clients that want to see all of the declarations in
  7570. // the source code.
  7571. return TagD;
  7572. }
  7573. DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
  7574. SourceLocation ExternLoc,
  7575. SourceLocation TemplateLoc,
  7576. Declarator &D) {
  7577. // Explicit instantiations always require a name.
  7578. // TODO: check if/when DNInfo should replace Name.
  7579. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7580. DeclarationName Name = NameInfo.getName();
  7581. if (!Name) {
  7582. if (!D.isInvalidType())
  7583. Diag(D.getDeclSpec().getLocStart(),
  7584. diag::err_explicit_instantiation_requires_name)
  7585. << D.getDeclSpec().getSourceRange()
  7586. << D.getSourceRange();
  7587. return true;
  7588. }
  7589. // The scope passed in may not be a decl scope. Zip up the scope tree until
  7590. // we find one that is.
  7591. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  7592. (S->getFlags() & Scope::TemplateParamScope) != 0)
  7593. S = S->getParent();
  7594. // Determine the type of the declaration.
  7595. TypeSourceInfo *T = GetTypeForDeclarator(D, S);
  7596. QualType R = T->getType();
  7597. if (R.isNull())
  7598. return true;
  7599. // C++ [dcl.stc]p1:
  7600. // A storage-class-specifier shall not be specified in [...] an explicit
  7601. // instantiation (14.7.2) directive.
  7602. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  7603. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
  7604. << Name;
  7605. return true;
  7606. } else if (D.getDeclSpec().getStorageClassSpec()
  7607. != DeclSpec::SCS_unspecified) {
  7608. // Complain about then remove the storage class specifier.
  7609. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
  7610. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7611. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7612. }
  7613. // C++0x [temp.explicit]p1:
  7614. // [...] An explicit instantiation of a function template shall not use the
  7615. // inline or constexpr specifiers.
  7616. // Presumably, this also applies to member functions of class templates as
  7617. // well.
  7618. if (D.getDeclSpec().isInlineSpecified())
  7619. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7620. getLangOpts().CPlusPlus11 ?
  7621. diag::err_explicit_instantiation_inline :
  7622. diag::warn_explicit_instantiation_inline_0x)
  7623. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7624. if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
  7625. // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
  7626. // not already specified.
  7627. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7628. diag::err_explicit_instantiation_constexpr);
  7629. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7630. // applied only to the definition of a function template or variable template,
  7631. // declared in namespace scope.
  7632. if (D.getDeclSpec().isConceptSpecified()) {
  7633. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7634. diag::err_concept_specified_specialization) << 0;
  7635. return true;
  7636. }
  7637. // A deduction guide is not on the list of entities that can be explicitly
  7638. // instantiated.
  7639. if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7640. Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
  7641. << /*explicit instantiation*/ 0;
  7642. return true;
  7643. }
  7644. // C++0x [temp.explicit]p2:
  7645. // There are two forms of explicit instantiation: an explicit instantiation
  7646. // definition and an explicit instantiation declaration. An explicit
  7647. // instantiation declaration begins with the extern keyword. [...]
  7648. TemplateSpecializationKind TSK
  7649. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  7650. : TSK_ExplicitInstantiationDeclaration;
  7651. LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
  7652. LookupParsedName(Previous, S, &D.getCXXScopeSpec());
  7653. if (!R->isFunctionType()) {
  7654. // C++ [temp.explicit]p1:
  7655. // A [...] static data member of a class template can be explicitly
  7656. // instantiated from the member definition associated with its class
  7657. // template.
  7658. // C++1y [temp.explicit]p1:
  7659. // A [...] variable [...] template specialization can be explicitly
  7660. // instantiated from its template.
  7661. if (Previous.isAmbiguous())
  7662. return true;
  7663. VarDecl *Prev = Previous.getAsSingle<VarDecl>();
  7664. VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
  7665. if (!PrevTemplate) {
  7666. if (!Prev || !Prev->isStaticDataMember()) {
  7667. // We expect to see a data data member here.
  7668. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
  7669. << Name;
  7670. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  7671. P != PEnd; ++P)
  7672. Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
  7673. return true;
  7674. }
  7675. if (!Prev->getInstantiatedFromStaticDataMember()) {
  7676. // FIXME: Check for explicit specialization?
  7677. Diag(D.getIdentifierLoc(),
  7678. diag::err_explicit_instantiation_data_member_not_instantiated)
  7679. << Prev;
  7680. Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
  7681. // FIXME: Can we provide a note showing where this was declared?
  7682. return true;
  7683. }
  7684. } else {
  7685. // Explicitly instantiate a variable template.
  7686. // C++1y [dcl.spec.auto]p6:
  7687. // ... A program that uses auto or decltype(auto) in a context not
  7688. // explicitly allowed in this section is ill-formed.
  7689. //
  7690. // This includes auto-typed variable template instantiations.
  7691. if (R->isUndeducedType()) {
  7692. Diag(T->getTypeLoc().getLocStart(),
  7693. diag::err_auto_not_allowed_var_inst);
  7694. return true;
  7695. }
  7696. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  7697. // C++1y [temp.explicit]p3:
  7698. // If the explicit instantiation is for a variable, the unqualified-id
  7699. // in the declaration shall be a template-id.
  7700. Diag(D.getIdentifierLoc(),
  7701. diag::err_explicit_instantiation_without_template_id)
  7702. << PrevTemplate;
  7703. Diag(PrevTemplate->getLocation(),
  7704. diag::note_explicit_instantiation_here);
  7705. return true;
  7706. }
  7707. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
  7708. // explicit instantiation (14.8.2) [...] of a concept definition.
  7709. if (PrevTemplate->isConcept()) {
  7710. Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
  7711. << 1 /*variable*/ << 0 /*explicitly instantiated*/;
  7712. Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
  7713. return true;
  7714. }
  7715. // Translate the parser's template argument list into our AST format.
  7716. TemplateArgumentListInfo TemplateArgs =
  7717. makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  7718. DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
  7719. D.getIdentifierLoc(), TemplateArgs);
  7720. if (Res.isInvalid())
  7721. return true;
  7722. // Ignore access control bits, we don't need them for redeclaration
  7723. // checking.
  7724. Prev = cast<VarDecl>(Res.get());
  7725. }
  7726. // C++0x [temp.explicit]p2:
  7727. // If the explicit instantiation is for a member function, a member class
  7728. // or a static data member of a class template specialization, the name of
  7729. // the class template specialization in the qualified-id for the member
  7730. // name shall be a simple-template-id.
  7731. //
  7732. // C++98 has the same restriction, just worded differently.
  7733. //
  7734. // This does not apply to variable template specializations, where the
  7735. // template-id is in the unqualified-id instead.
  7736. if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
  7737. Diag(D.getIdentifierLoc(),
  7738. diag::ext_explicit_instantiation_without_qualified_id)
  7739. << Prev << D.getCXXScopeSpec().getRange();
  7740. // Check the scope of this explicit instantiation.
  7741. CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
  7742. // Verify that it is okay to explicitly instantiate here.
  7743. TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
  7744. SourceLocation POI = Prev->getPointOfInstantiation();
  7745. bool HasNoEffect = false;
  7746. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
  7747. PrevTSK, POI, HasNoEffect))
  7748. return true;
  7749. if (!HasNoEffect) {
  7750. // Instantiate static data member or variable template.
  7751. Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  7752. if (PrevTemplate) {
  7753. // Merge attributes.
  7754. if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
  7755. ProcessDeclAttributeList(S, Prev, Attr);
  7756. }
  7757. if (TSK == TSK_ExplicitInstantiationDefinition)
  7758. InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
  7759. }
  7760. // Check the new variable specialization against the parsed input.
  7761. if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
  7762. Diag(T->getTypeLoc().getLocStart(),
  7763. diag::err_invalid_var_template_spec_type)
  7764. << 0 << PrevTemplate << R << Prev->getType();
  7765. Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
  7766. << 2 << PrevTemplate->getDeclName();
  7767. return true;
  7768. }
  7769. // FIXME: Create an ExplicitInstantiation node?
  7770. return (Decl*) nullptr;
  7771. }
  7772. // If the declarator is a template-id, translate the parser's template
  7773. // argument list into our AST format.
  7774. bool HasExplicitTemplateArgs = false;
  7775. TemplateArgumentListInfo TemplateArgs;
  7776. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  7777. TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  7778. HasExplicitTemplateArgs = true;
  7779. }
  7780. // C++ [temp.explicit]p1:
  7781. // A [...] function [...] can be explicitly instantiated from its template.
  7782. // A member function [...] of a class template can be explicitly
  7783. // instantiated from the member definition associated with its class
  7784. // template.
  7785. UnresolvedSet<8> Matches;
  7786. AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
  7787. TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
  7788. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  7789. P != PEnd; ++P) {
  7790. NamedDecl *Prev = *P;
  7791. if (!HasExplicitTemplateArgs) {
  7792. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
  7793. QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
  7794. /*AdjustExceptionSpec*/true);
  7795. if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
  7796. Matches.clear();
  7797. Matches.addDecl(Method, P.getAccess());
  7798. if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
  7804. if (!FunTmpl)
  7805. continue;
  7806. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  7807. FunctionDecl *Specialization = nullptr;
  7808. if (TemplateDeductionResult TDK
  7809. = DeduceTemplateArguments(FunTmpl,
  7810. (HasExplicitTemplateArgs ? &TemplateArgs
  7811. : nullptr),
  7812. R, Specialization, Info)) {
  7813. // Keep track of almost-matches.
  7814. FailedCandidates.addCandidate()
  7815. .set(P.getPair(), FunTmpl->getTemplatedDecl(),
  7816. MakeDeductionFailureInfo(Context, TDK, Info));
  7817. (void)TDK;
  7818. continue;
  7819. }
  7820. // Target attributes are part of the cuda function signature, so
  7821. // the cuda target of the instantiated function must match that of its
  7822. // template. Given that C++ template deduction does not take
  7823. // target attributes into account, we reject candidates here that
  7824. // have a different target.
  7825. if (LangOpts.CUDA &&
  7826. IdentifyCUDATarget(Specialization,
  7827. /* IgnoreImplicitHDAttributes = */ true) !=
  7828. IdentifyCUDATarget(Attr)) {
  7829. FailedCandidates.addCandidate().set(
  7830. P.getPair(), FunTmpl->getTemplatedDecl(),
  7831. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  7832. continue;
  7833. }
  7834. Matches.addDecl(Specialization, P.getAccess());
  7835. }
  7836. // Find the most specialized function template specialization.
  7837. UnresolvedSetIterator Result = getMostSpecialized(
  7838. Matches.begin(), Matches.end(), FailedCandidates,
  7839. D.getIdentifierLoc(),
  7840. PDiag(diag::err_explicit_instantiation_not_known) << Name,
  7841. PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
  7842. PDiag(diag::note_explicit_instantiation_candidate));
  7843. if (Result == Matches.end())
  7844. return true;
  7845. // Ignore access control bits, we don't need them for redeclaration checking.
  7846. FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
  7847. // C++11 [except.spec]p4
  7848. // In an explicit instantiation an exception-specification may be specified,
  7849. // but is not required.
  7850. // If an exception-specification is specified in an explicit instantiation
  7851. // directive, it shall be compatible with the exception-specifications of
  7852. // other declarations of that function.
  7853. if (auto *FPT = R->getAs<FunctionProtoType>())
  7854. if (FPT->hasExceptionSpec()) {
  7855. unsigned DiagID =
  7856. diag::err_mismatched_exception_spec_explicit_instantiation;
  7857. if (getLangOpts().MicrosoftExt)
  7858. DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
  7859. bool Result = CheckEquivalentExceptionSpec(
  7860. PDiag(DiagID) << Specialization->getType(),
  7861. PDiag(diag::note_explicit_instantiation_here),
  7862. Specialization->getType()->getAs<FunctionProtoType>(),
  7863. Specialization->getLocation(), FPT, D.getLocStart());
  7864. // In Microsoft mode, mismatching exception specifications just cause a
  7865. // warning.
  7866. if (!getLangOpts().MicrosoftExt && Result)
  7867. return true;
  7868. }
  7869. if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
  7870. Diag(D.getIdentifierLoc(),
  7871. diag::err_explicit_instantiation_member_function_not_instantiated)
  7872. << Specialization
  7873. << (Specialization->getTemplateSpecializationKind() ==
  7874. TSK_ExplicitSpecialization);
  7875. Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
  7876. return true;
  7877. }
  7878. FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
  7879. if (!PrevDecl && Specialization->isThisDeclarationADefinition())
  7880. PrevDecl = Specialization;
  7881. if (PrevDecl) {
  7882. bool HasNoEffect = false;
  7883. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
  7884. PrevDecl,
  7885. PrevDecl->getTemplateSpecializationKind(),
  7886. PrevDecl->getPointOfInstantiation(),
  7887. HasNoEffect))
  7888. return true;
  7889. // FIXME: We may still want to build some representation of this
  7890. // explicit specialization.
  7891. if (HasNoEffect)
  7892. return (Decl*) nullptr;
  7893. }
  7894. Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  7895. if (Attr)
  7896. ProcessDeclAttributeList(S, Specialization, Attr);
  7897. if (Specialization->isDefined()) {
  7898. // Let the ASTConsumer know that this function has been explicitly
  7899. // instantiated now, and its linkage might have changed.
  7900. Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
  7901. } else if (TSK == TSK_ExplicitInstantiationDefinition)
  7902. InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
  7903. // C++0x [temp.explicit]p2:
  7904. // If the explicit instantiation is for a member function, a member class
  7905. // or a static data member of a class template specialization, the name of
  7906. // the class template specialization in the qualified-id for the member
  7907. // name shall be a simple-template-id.
  7908. //
  7909. // C++98 has the same restriction, just worded differently.
  7910. FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
  7911. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
  7912. D.getCXXScopeSpec().isSet() &&
  7913. !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
  7914. Diag(D.getIdentifierLoc(),
  7915. diag::ext_explicit_instantiation_without_qualified_id)
  7916. << Specialization << D.getCXXScopeSpec().getRange();
  7917. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
  7918. // explicit instantiation (14.8.2) [...] of a concept definition.
  7919. if (FunTmpl && FunTmpl->isConcept() &&
  7920. !D.getDeclSpec().isConceptSpecified()) {
  7921. Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
  7922. << 0 /*function*/ << 0 /*explicitly instantiated*/;
  7923. Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
  7924. return true;
  7925. }
  7926. CheckExplicitInstantiationScope(*this,
  7927. FunTmpl? (NamedDecl *)FunTmpl
  7928. : Specialization->getInstantiatedFromMemberFunction(),
  7929. D.getIdentifierLoc(),
  7930. D.getCXXScopeSpec().isSet());
  7931. // FIXME: Create some kind of ExplicitInstantiationDecl here.
  7932. return (Decl*) nullptr;
  7933. }
  7934. TypeResult
  7935. Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  7936. const CXXScopeSpec &SS, IdentifierInfo *Name,
  7937. SourceLocation TagLoc, SourceLocation NameLoc) {
  7938. // This has to hold, because SS is expected to be defined.
  7939. assert(Name && "Expected a name in a dependent tag");
  7940. NestedNameSpecifier *NNS = SS.getScopeRep();
  7941. if (!NNS)
  7942. return true;
  7943. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7944. if (TUK == TUK_Declaration || TUK == TUK_Definition) {
  7945. Diag(NameLoc, diag::err_dependent_tag_decl)
  7946. << (TUK == TUK_Definition) << Kind << SS.getRange();
  7947. return true;
  7948. }
  7949. // Create the resulting type.
  7950. ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  7951. QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
  7952. // Create type-source location information for this type.
  7953. TypeLocBuilder TLB;
  7954. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
  7955. TL.setElaboratedKeywordLoc(TagLoc);
  7956. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  7957. TL.setNameLoc(NameLoc);
  7958. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  7959. }
  7960. TypeResult
  7961. Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
  7962. const CXXScopeSpec &SS, const IdentifierInfo &II,
  7963. SourceLocation IdLoc) {
  7964. if (SS.isInvalid())
  7965. return true;
  7966. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  7967. Diag(TypenameLoc,
  7968. getLangOpts().CPlusPlus11 ?
  7969. diag::warn_cxx98_compat_typename_outside_of_template :
  7970. diag::ext_typename_outside_of_template)
  7971. << FixItHint::CreateRemoval(TypenameLoc);
  7972. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  7973. QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
  7974. TypenameLoc, QualifierLoc, II, IdLoc);
  7975. if (T.isNull())
  7976. return true;
  7977. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  7978. if (isa<DependentNameType>(T)) {
  7979. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  7980. TL.setElaboratedKeywordLoc(TypenameLoc);
  7981. TL.setQualifierLoc(QualifierLoc);
  7982. TL.setNameLoc(IdLoc);
  7983. } else {
  7984. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  7985. TL.setElaboratedKeywordLoc(TypenameLoc);
  7986. TL.setQualifierLoc(QualifierLoc);
  7987. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  7988. }
  7989. return CreateParsedType(T, TSI);
  7990. }
  7991. TypeResult
  7992. Sema::ActOnTypenameType(Scope *S,
  7993. SourceLocation TypenameLoc,
  7994. const CXXScopeSpec &SS,
  7995. SourceLocation TemplateKWLoc,
  7996. TemplateTy TemplateIn,
  7997. IdentifierInfo *TemplateII,
  7998. SourceLocation TemplateIILoc,
  7999. SourceLocation LAngleLoc,
  8000. ASTTemplateArgsPtr TemplateArgsIn,
  8001. SourceLocation RAngleLoc) {
  8002. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  8003. Diag(TypenameLoc,
  8004. getLangOpts().CPlusPlus11 ?
  8005. diag::warn_cxx98_compat_typename_outside_of_template :
  8006. diag::ext_typename_outside_of_template)
  8007. << FixItHint::CreateRemoval(TypenameLoc);
  8008. // Strangely, non-type results are not ignored by this lookup, so the
  8009. // program is ill-formed if it finds an injected-class-name.
  8010. if (TypenameLoc.isValid()) {
  8011. auto *LookupRD =
  8012. dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
  8013. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  8014. Diag(TemplateIILoc,
  8015. diag::ext_out_of_line_qualified_id_type_names_constructor)
  8016. << TemplateII << 0 /*injected-class-name used as template name*/
  8017. << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
  8018. }
  8019. }
  8020. // Translate the parser's template argument list in our AST format.
  8021. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  8022. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  8023. TemplateName Template = TemplateIn.get();
  8024. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  8025. // Construct a dependent template specialization type.
  8026. assert(DTN && "dependent template has non-dependent name?");
  8027. assert(DTN->getQualifier() == SS.getScopeRep());
  8028. QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
  8029. DTN->getQualifier(),
  8030. DTN->getIdentifier(),
  8031. TemplateArgs);
  8032. // Create source-location information for this type.
  8033. TypeLocBuilder Builder;
  8034. DependentTemplateSpecializationTypeLoc SpecTL
  8035. = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
  8036. SpecTL.setElaboratedKeywordLoc(TypenameLoc);
  8037. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  8038. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  8039. SpecTL.setTemplateNameLoc(TemplateIILoc);
  8040. SpecTL.setLAngleLoc(LAngleLoc);
  8041. SpecTL.setRAngleLoc(RAngleLoc);
  8042. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  8043. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  8044. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  8045. }
  8046. QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  8047. if (T.isNull())
  8048. return true;
  8049. // Provide source-location information for the template specialization type.
  8050. TypeLocBuilder Builder;
  8051. TemplateSpecializationTypeLoc SpecTL
  8052. = Builder.push<TemplateSpecializationTypeLoc>(T);
  8053. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  8054. SpecTL.setTemplateNameLoc(TemplateIILoc);
  8055. SpecTL.setLAngleLoc(LAngleLoc);
  8056. SpecTL.setRAngleLoc(RAngleLoc);
  8057. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  8058. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  8059. T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
  8060. ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
  8061. TL.setElaboratedKeywordLoc(TypenameLoc);
  8062. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  8063. TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
  8064. return CreateParsedType(T, TSI);
  8065. }
  8066. /// Determine whether this failed name lookup should be treated as being
  8067. /// disabled by a usage of std::enable_if.
  8068. static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
  8069. SourceRange &CondRange) {
  8070. // We must be looking for a ::type...
  8071. if (!II.isStr("type"))
  8072. return false;
  8073. // ... within an explicitly-written template specialization...
  8074. if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
  8075. return false;
  8076. TypeLoc EnableIfTy = NNS.getTypeLoc();
  8077. TemplateSpecializationTypeLoc EnableIfTSTLoc =
  8078. EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
  8079. if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
  8080. return false;
  8081. const TemplateSpecializationType *EnableIfTST =
  8082. cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
  8083. // ... which names a complete class template declaration...
  8084. const TemplateDecl *EnableIfDecl =
  8085. EnableIfTST->getTemplateName().getAsTemplateDecl();
  8086. if (!EnableIfDecl || EnableIfTST->isIncompleteType())
  8087. return false;
  8088. // ... called "enable_if".
  8089. const IdentifierInfo *EnableIfII =
  8090. EnableIfDecl->getDeclName().getAsIdentifierInfo();
  8091. if (!EnableIfII || !EnableIfII->isStr("enable_if"))
  8092. return false;
  8093. // Assume the first template argument is the condition.
  8094. CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
  8095. return true;
  8096. }
  8097. /// \brief Build the type that describes a C++ typename specifier,
  8098. /// e.g., "typename T::type".
  8099. QualType
  8100. Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
  8101. SourceLocation KeywordLoc,
  8102. NestedNameSpecifierLoc QualifierLoc,
  8103. const IdentifierInfo &II,
  8104. SourceLocation IILoc) {
  8105. CXXScopeSpec SS;
  8106. SS.Adopt(QualifierLoc);
  8107. DeclContext *Ctx = computeDeclContext(SS);
  8108. if (!Ctx) {
  8109. // If the nested-name-specifier is dependent and couldn't be
  8110. // resolved to a type, build a typename type.
  8111. assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
  8112. return Context.getDependentNameType(Keyword,
  8113. QualifierLoc.getNestedNameSpecifier(),
  8114. &II);
  8115. }
  8116. // If the nested-name-specifier refers to the current instantiation,
  8117. // the "typename" keyword itself is superfluous. In C++03, the
  8118. // program is actually ill-formed. However, DR 382 (in C++0x CD1)
  8119. // allows such extraneous "typename" keywords, and we retroactively
  8120. // apply this DR to C++03 code with only a warning. In any case we continue.
  8121. if (RequireCompleteDeclContext(SS, Ctx))
  8122. return QualType();
  8123. DeclarationName Name(&II);
  8124. LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
  8125. LookupQualifiedName(Result, Ctx, SS);
  8126. unsigned DiagID = 0;
  8127. Decl *Referenced = nullptr;
  8128. switch (Result.getResultKind()) {
  8129. case LookupResult::NotFound: {
  8130. // If we're looking up 'type' within a template named 'enable_if', produce
  8131. // a more specific diagnostic.
  8132. SourceRange CondRange;
  8133. if (isEnableIf(QualifierLoc, II, CondRange)) {
  8134. Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
  8135. << Ctx << CondRange;
  8136. return QualType();
  8137. }
  8138. DiagID = diag::err_typename_nested_not_found;
  8139. break;
  8140. }
  8141. case LookupResult::FoundUnresolvedValue: {
  8142. // We found a using declaration that is a value. Most likely, the using
  8143. // declaration itself is meant to have the 'typename' keyword.
  8144. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  8145. IILoc);
  8146. Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
  8147. << Name << Ctx << FullRange;
  8148. if (UnresolvedUsingValueDecl *Using
  8149. = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
  8150. SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
  8151. Diag(Loc, diag::note_using_value_decl_missing_typename)
  8152. << FixItHint::CreateInsertion(Loc, "typename ");
  8153. }
  8154. }
  8155. // Fall through to create a dependent typename type, from which we can recover
  8156. // better.
  8157. case LookupResult::NotFoundInCurrentInstantiation:
  8158. // Okay, it's a member of an unknown instantiation.
  8159. return Context.getDependentNameType(Keyword,
  8160. QualifierLoc.getNestedNameSpecifier(),
  8161. &II);
  8162. case LookupResult::Found:
  8163. if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
  8164. // C++ [class.qual]p2:
  8165. // In a lookup in which function names are not ignored and the
  8166. // nested-name-specifier nominates a class C, if the name specified
  8167. // after the nested-name-specifier, when looked up in C, is the
  8168. // injected-class-name of C [...] then the name is instead considered
  8169. // to name the constructor of class C.
  8170. //
  8171. // Unlike in an elaborated-type-specifier, function names are not ignored
  8172. // in typename-specifier lookup. However, they are ignored in all the
  8173. // contexts where we form a typename type with no keyword (that is, in
  8174. // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
  8175. //
  8176. // FIXME: That's not strictly true: mem-initializer-id lookup does not
  8177. // ignore functions, but that appears to be an oversight.
  8178. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
  8179. auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
  8180. if (Keyword == ETK_Typename && LookupRD && FoundRD &&
  8181. FoundRD->isInjectedClassName() &&
  8182. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  8183. Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
  8184. << &II << 1 << 0 /*'typename' keyword used*/;
  8185. // We found a type. Build an ElaboratedType, since the
  8186. // typename-specifier was just sugar.
  8187. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  8188. return Context.getElaboratedType(Keyword,
  8189. QualifierLoc.getNestedNameSpecifier(),
  8190. Context.getTypeDeclType(Type));
  8191. }
  8192. // C++ [dcl.type.simple]p2:
  8193. // A type-specifier of the form
  8194. // typename[opt] nested-name-specifier[opt] template-name
  8195. // is a placeholder for a deduced class type [...].
  8196. if (getLangOpts().CPlusPlus1z) {
  8197. if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
  8198. return Context.getElaboratedType(
  8199. Keyword, QualifierLoc.getNestedNameSpecifier(),
  8200. Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  8201. QualType(), false));
  8202. }
  8203. }
  8204. DiagID = diag::err_typename_nested_not_type;
  8205. Referenced = Result.getFoundDecl();
  8206. break;
  8207. case LookupResult::FoundOverloaded:
  8208. DiagID = diag::err_typename_nested_not_type;
  8209. Referenced = *Result.begin();
  8210. break;
  8211. case LookupResult::Ambiguous:
  8212. return QualType();
  8213. }
  8214. // If we get here, it's because name lookup did not find a
  8215. // type. Emit an appropriate diagnostic and return an error.
  8216. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  8217. IILoc);
  8218. Diag(IILoc, DiagID) << FullRange << Name << Ctx;
  8219. if (Referenced)
  8220. Diag(Referenced->getLocation(), diag::note_typename_refers_here)
  8221. << Name;
  8222. return QualType();
  8223. }
  8224. namespace {
  8225. // See Sema::RebuildTypeInCurrentInstantiation
  8226. class CurrentInstantiationRebuilder
  8227. : public TreeTransform<CurrentInstantiationRebuilder> {
  8228. SourceLocation Loc;
  8229. DeclarationName Entity;
  8230. public:
  8231. typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
  8232. CurrentInstantiationRebuilder(Sema &SemaRef,
  8233. SourceLocation Loc,
  8234. DeclarationName Entity)
  8235. : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
  8236. Loc(Loc), Entity(Entity) { }
  8237. /// \brief Determine whether the given type \p T has already been
  8238. /// transformed.
  8239. ///
  8240. /// For the purposes of type reconstruction, a type has already been
  8241. /// transformed if it is NULL or if it is not dependent.
  8242. bool AlreadyTransformed(QualType T) {
  8243. return T.isNull() || !T->isDependentType();
  8244. }
  8245. /// \brief Returns the location of the entity whose type is being
  8246. /// rebuilt.
  8247. SourceLocation getBaseLocation() { return Loc; }
  8248. /// \brief Returns the name of the entity whose type is being rebuilt.
  8249. DeclarationName getBaseEntity() { return Entity; }
  8250. /// \brief Sets the "base" location and entity when that
  8251. /// information is known based on another transformation.
  8252. void setBase(SourceLocation Loc, DeclarationName Entity) {
  8253. this->Loc = Loc;
  8254. this->Entity = Entity;
  8255. }
  8256. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  8257. // Lambdas never need to be transformed.
  8258. return E;
  8259. }
  8260. };
  8261. } // end anonymous namespace
  8262. /// \brief Rebuilds a type within the context of the current instantiation.
  8263. ///
  8264. /// The type \p T is part of the type of an out-of-line member definition of
  8265. /// a class template (or class template partial specialization) that was parsed
  8266. /// and constructed before we entered the scope of the class template (or
  8267. /// partial specialization thereof). This routine will rebuild that type now
  8268. /// that we have entered the declarator's scope, which may produce different
  8269. /// canonical types, e.g.,
  8270. ///
  8271. /// \code
  8272. /// template<typename T>
  8273. /// struct X {
  8274. /// typedef T* pointer;
  8275. /// pointer data();
  8276. /// };
  8277. ///
  8278. /// template<typename T>
  8279. /// typename X<T>::pointer X<T>::data() { ... }
  8280. /// \endcode
  8281. ///
  8282. /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
  8283. /// since we do not know that we can look into X<T> when we parsed the type.
  8284. /// This function will rebuild the type, performing the lookup of "pointer"
  8285. /// in X<T> and returning an ElaboratedType whose canonical type is the same
  8286. /// as the canonical type of T*, allowing the return types of the out-of-line
  8287. /// definition and the declaration to match.
  8288. TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
  8289. SourceLocation Loc,
  8290. DeclarationName Name) {
  8291. if (!T || !T->getType()->isDependentType())
  8292. return T;
  8293. CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
  8294. return Rebuilder.TransformType(T);
  8295. }
  8296. ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
  8297. CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
  8298. DeclarationName());
  8299. return Rebuilder.TransformExpr(E);
  8300. }
  8301. bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
  8302. if (SS.isInvalid())
  8303. return true;
  8304. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8305. CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
  8306. DeclarationName());
  8307. NestedNameSpecifierLoc Rebuilt
  8308. = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
  8309. if (!Rebuilt)
  8310. return true;
  8311. SS.Adopt(Rebuilt);
  8312. return false;
  8313. }
  8314. /// \brief Rebuild the template parameters now that we know we're in a current
  8315. /// instantiation.
  8316. bool Sema::RebuildTemplateParamsInCurrentInstantiation(
  8317. TemplateParameterList *Params) {
  8318. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  8319. Decl *Param = Params->getParam(I);
  8320. // There is nothing to rebuild in a type parameter.
  8321. if (isa<TemplateTypeParmDecl>(Param))
  8322. continue;
  8323. // Rebuild the template parameter list of a template template parameter.
  8324. if (TemplateTemplateParmDecl *TTP
  8325. = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  8326. if (RebuildTemplateParamsInCurrentInstantiation(
  8327. TTP->getTemplateParameters()))
  8328. return true;
  8329. continue;
  8330. }
  8331. // Rebuild the type of a non-type template parameter.
  8332. NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
  8333. TypeSourceInfo *NewTSI
  8334. = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
  8335. NTTP->getLocation(),
  8336. NTTP->getDeclName());
  8337. if (!NewTSI)
  8338. return true;
  8339. if (NewTSI != NTTP->getTypeSourceInfo()) {
  8340. NTTP->setTypeSourceInfo(NewTSI);
  8341. NTTP->setType(NewTSI->getType());
  8342. }
  8343. }
  8344. return false;
  8345. }
  8346. /// \brief Produces a formatted string that describes the binding of
  8347. /// template parameters to template arguments.
  8348. std::string
  8349. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  8350. const TemplateArgumentList &Args) {
  8351. return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
  8352. }
  8353. std::string
  8354. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  8355. const TemplateArgument *Args,
  8356. unsigned NumArgs) {
  8357. SmallString<128> Str;
  8358. llvm::raw_svector_ostream Out(Str);
  8359. if (!Params || Params->size() == 0 || NumArgs == 0)
  8360. return std::string();
  8361. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  8362. if (I >= NumArgs)
  8363. break;
  8364. if (I == 0)
  8365. Out << "[with ";
  8366. else
  8367. Out << ", ";
  8368. if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
  8369. Out << Id->getName();
  8370. } else {
  8371. Out << '$' << I;
  8372. }
  8373. Out << " = ";
  8374. Args[I].print(getPrintingPolicy(), Out);
  8375. }
  8376. Out << ']';
  8377. return Out.str();
  8378. }
  8379. void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
  8380. CachedTokens &Toks) {
  8381. if (!FD)
  8382. return;
  8383. auto LPT = llvm::make_unique<LateParsedTemplate>();
  8384. // Take tokens to avoid allocations
  8385. LPT->Toks.swap(Toks);
  8386. LPT->D = FnD;
  8387. LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
  8388. FD->setLateTemplateParsed(true);
  8389. }
  8390. void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
  8391. if (!FD)
  8392. return;
  8393. FD->setLateTemplateParsed(false);
  8394. }
  8395. bool Sema::IsInsideALocalClassWithinATemplateFunction() {
  8396. DeclContext *DC = CurContext;
  8397. while (DC) {
  8398. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
  8399. const FunctionDecl *FD = RD->isLocalClass();
  8400. return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
  8401. } else if (DC->isTranslationUnit() || DC->isNamespace())
  8402. return false;
  8403. DC = DC->getParent();
  8404. }
  8405. return false;
  8406. }
  8407. namespace {
  8408. /// \brief Walk the path from which a declaration was instantiated, and check
  8409. /// that every explicit specialization along that path is visible. This enforces
  8410. /// C++ [temp.expl.spec]/6:
  8411. ///
  8412. /// If a template, a member template or a member of a class template is
  8413. /// explicitly specialized then that specialization shall be declared before
  8414. /// the first use of that specialization that would cause an implicit
  8415. /// instantiation to take place, in every translation unit in which such a
  8416. /// use occurs; no diagnostic is required.
  8417. ///
  8418. /// and also C++ [temp.class.spec]/1:
  8419. ///
  8420. /// A partial specialization shall be declared before the first use of a
  8421. /// class template specialization that would make use of the partial
  8422. /// specialization as the result of an implicit or explicit instantiation
  8423. /// in every translation unit in which such a use occurs; no diagnostic is
  8424. /// required.
  8425. class ExplicitSpecializationVisibilityChecker {
  8426. Sema &S;
  8427. SourceLocation Loc;
  8428. llvm::SmallVector<Module *, 8> Modules;
  8429. public:
  8430. ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
  8431. : S(S), Loc(Loc) {}
  8432. void check(NamedDecl *ND) {
  8433. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  8434. return checkImpl(FD);
  8435. if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
  8436. return checkImpl(RD);
  8437. if (auto *VD = dyn_cast<VarDecl>(ND))
  8438. return checkImpl(VD);
  8439. if (auto *ED = dyn_cast<EnumDecl>(ND))
  8440. return checkImpl(ED);
  8441. }
  8442. private:
  8443. void diagnose(NamedDecl *D, bool IsPartialSpec) {
  8444. auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
  8445. : Sema::MissingImportKind::ExplicitSpecialization;
  8446. const bool Recover = true;
  8447. // If we got a custom set of modules (because only a subset of the
  8448. // declarations are interesting), use them, otherwise let
  8449. // diagnoseMissingImport intelligently pick some.
  8450. if (Modules.empty())
  8451. S.diagnoseMissingImport(Loc, D, Kind, Recover);
  8452. else
  8453. S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
  8454. }
  8455. // Check a specific declaration. There are three problematic cases:
  8456. //
  8457. // 1) The declaration is an explicit specialization of a template
  8458. // specialization.
  8459. // 2) The declaration is an explicit specialization of a member of an
  8460. // templated class.
  8461. // 3) The declaration is an instantiation of a template, and that template
  8462. // is an explicit specialization of a member of a templated class.
  8463. //
  8464. // We don't need to go any deeper than that, as the instantiation of the
  8465. // surrounding class / etc is not triggered by whatever triggered this
  8466. // instantiation, and thus should be checked elsewhere.
  8467. template<typename SpecDecl>
  8468. void checkImpl(SpecDecl *Spec) {
  8469. bool IsHiddenExplicitSpecialization = false;
  8470. if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
  8471. IsHiddenExplicitSpecialization =
  8472. Spec->getMemberSpecializationInfo()
  8473. ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
  8474. : !S.hasVisibleDeclaration(Spec);
  8475. } else {
  8476. checkInstantiated(Spec);
  8477. }
  8478. if (IsHiddenExplicitSpecialization)
  8479. diagnose(Spec->getMostRecentDecl(), false);
  8480. }
  8481. void checkInstantiated(FunctionDecl *FD) {
  8482. if (auto *TD = FD->getPrimaryTemplate())
  8483. checkTemplate(TD);
  8484. }
  8485. void checkInstantiated(CXXRecordDecl *RD) {
  8486. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
  8487. if (!SD)
  8488. return;
  8489. auto From = SD->getSpecializedTemplateOrPartial();
  8490. if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
  8491. checkTemplate(TD);
  8492. else if (auto *TD =
  8493. From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  8494. if (!S.hasVisibleDeclaration(TD))
  8495. diagnose(TD, true);
  8496. checkTemplate(TD);
  8497. }
  8498. }
  8499. void checkInstantiated(VarDecl *RD) {
  8500. auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
  8501. if (!SD)
  8502. return;
  8503. auto From = SD->getSpecializedTemplateOrPartial();
  8504. if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
  8505. checkTemplate(TD);
  8506. else if (auto *TD =
  8507. From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  8508. if (!S.hasVisibleDeclaration(TD))
  8509. diagnose(TD, true);
  8510. checkTemplate(TD);
  8511. }
  8512. }
  8513. void checkInstantiated(EnumDecl *FD) {}
  8514. template<typename TemplDecl>
  8515. void checkTemplate(TemplDecl *TD) {
  8516. if (TD->isMemberSpecialization()) {
  8517. if (!S.hasVisibleMemberSpecialization(TD, &Modules))
  8518. diagnose(TD->getMostRecentDecl(), false);
  8519. }
  8520. }
  8521. };
  8522. } // end anonymous namespace
  8523. void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
  8524. if (!getLangOpts().Modules)
  8525. return;
  8526. ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
  8527. }
  8528. /// \brief Check whether a template partial specialization that we've discovered
  8529. /// is hidden, and produce suitable diagnostics if so.
  8530. void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
  8531. NamedDecl *Spec) {
  8532. llvm::SmallVector<Module *, 8> Modules;
  8533. if (!hasVisibleDeclaration(Spec, &Modules))
  8534. diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
  8535. MissingImportKind::PartialSpecialization,
  8536. /*Recover*/true);
  8537. }