SemaTemplate.cpp 358 KB

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