SemaTemplate.cpp 338 KB

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