SemaTemplate.cpp 339 KB

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