SemaTemplate.cpp 282 KB

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