SemaTemplate.cpp 419 KB

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