SemaTemplate.cpp 420 KB

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