SemaTemplateInstantiateDecl.cpp 252 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410
  1. //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
  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 C++ template instantiation for declarations.
  9. //
  10. //===----------------------------------------------------------------------===/
  11. #include "TreeTransform.h"
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTMutationListener.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/DeclVisitor.h"
  17. #include "clang/AST/DependentDiagnostic.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/PrettyDeclStackTrace.h"
  21. #include "clang/AST/TypeLoc.h"
  22. #include "clang/Basic/SourceManager.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Sema/Initialization.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/ScopeInfo.h"
  27. #include "clang/Sema/SemaInternal.h"
  28. #include "clang/Sema/Template.h"
  29. #include "clang/Sema/TemplateInstCallback.h"
  30. #include "llvm/Support/TimeProfiler.h"
  31. #include <optional>
  32. using namespace clang;
  33. static bool isDeclWithinFunction(const Decl *D) {
  34. const DeclContext *DC = D->getDeclContext();
  35. if (DC->isFunctionOrMethod())
  36. return true;
  37. if (DC->isRecord())
  38. return cast<CXXRecordDecl>(DC)->isLocalClass();
  39. return false;
  40. }
  41. template<typename DeclT>
  42. static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
  43. const MultiLevelTemplateArgumentList &TemplateArgs) {
  44. if (!OldDecl->getQualifierLoc())
  45. return false;
  46. assert((NewDecl->getFriendObjectKind() ||
  47. !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
  48. "non-friend with qualified name defined in dependent context");
  49. Sema::ContextRAII SavedContext(
  50. SemaRef,
  51. const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
  52. ? NewDecl->getLexicalDeclContext()
  53. : OldDecl->getLexicalDeclContext()));
  54. NestedNameSpecifierLoc NewQualifierLoc
  55. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  56. TemplateArgs);
  57. if (!NewQualifierLoc)
  58. return true;
  59. NewDecl->setQualifierInfo(NewQualifierLoc);
  60. return false;
  61. }
  62. bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
  63. DeclaratorDecl *NewDecl) {
  64. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  65. }
  66. bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
  67. TagDecl *NewDecl) {
  68. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  69. }
  70. // Include attribute instantiation code.
  71. #include "clang/Sema/AttrTemplateInstantiate.inc"
  72. static void instantiateDependentAlignedAttr(
  73. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  74. const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
  75. if (Aligned->isAlignmentExpr()) {
  76. // The alignment expression is a constant expression.
  77. EnterExpressionEvaluationContext Unevaluated(
  78. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  79. ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
  80. if (!Result.isInvalid())
  81. S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
  82. } else {
  83. TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
  84. TemplateArgs, Aligned->getLocation(),
  85. DeclarationName());
  86. if (Result)
  87. S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
  88. }
  89. }
  90. static void instantiateDependentAlignedAttr(
  91. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  92. const AlignedAttr *Aligned, Decl *New) {
  93. if (!Aligned->isPackExpansion()) {
  94. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  95. return;
  96. }
  97. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  98. if (Aligned->isAlignmentExpr())
  99. S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
  100. Unexpanded);
  101. else
  102. S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
  103. Unexpanded);
  104. assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
  105. // Determine whether we can expand this attribute pack yet.
  106. bool Expand = true, RetainExpansion = false;
  107. std::optional<unsigned> NumExpansions;
  108. // FIXME: Use the actual location of the ellipsis.
  109. SourceLocation EllipsisLoc = Aligned->getLocation();
  110. if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
  111. Unexpanded, TemplateArgs, Expand,
  112. RetainExpansion, NumExpansions))
  113. return;
  114. if (!Expand) {
  115. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
  116. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
  117. } else {
  118. for (unsigned I = 0; I != *NumExpansions; ++I) {
  119. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
  120. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  121. }
  122. }
  123. }
  124. static void instantiateDependentAssumeAlignedAttr(
  125. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  126. const AssumeAlignedAttr *Aligned, Decl *New) {
  127. // The alignment expression is a constant expression.
  128. EnterExpressionEvaluationContext Unevaluated(
  129. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  130. Expr *E, *OE = nullptr;
  131. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  132. if (Result.isInvalid())
  133. return;
  134. E = Result.getAs<Expr>();
  135. if (Aligned->getOffset()) {
  136. Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
  137. if (Result.isInvalid())
  138. return;
  139. OE = Result.getAs<Expr>();
  140. }
  141. S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
  142. }
  143. static void instantiateDependentAlignValueAttr(
  144. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  145. const AlignValueAttr *Aligned, Decl *New) {
  146. // The alignment expression is a constant expression.
  147. EnterExpressionEvaluationContext Unevaluated(
  148. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  149. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  150. if (!Result.isInvalid())
  151. S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
  152. }
  153. static void instantiateDependentAllocAlignAttr(
  154. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  155. const AllocAlignAttr *Align, Decl *New) {
  156. Expr *Param = IntegerLiteral::Create(
  157. S.getASTContext(),
  158. llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
  159. S.getASTContext().UnsignedLongLongTy, Align->getLocation());
  160. S.AddAllocAlignAttr(New, *Align, Param);
  161. }
  162. static void instantiateDependentAnnotationAttr(
  163. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  164. const AnnotateAttr *Attr, Decl *New) {
  165. EnterExpressionEvaluationContext Unevaluated(
  166. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  167. // If the attribute has delayed arguments it will have to instantiate those
  168. // and handle them as new arguments for the attribute.
  169. bool HasDelayedArgs = Attr->delayedArgs_size();
  170. ArrayRef<Expr *> ArgsToInstantiate =
  171. HasDelayedArgs
  172. ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
  173. : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
  174. SmallVector<Expr *, 4> Args;
  175. if (S.SubstExprs(ArgsToInstantiate,
  176. /*IsCall=*/false, TemplateArgs, Args))
  177. return;
  178. StringRef Str = Attr->getAnnotation();
  179. if (HasDelayedArgs) {
  180. if (Args.size() < 1) {
  181. S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
  182. << Attr << 1;
  183. return;
  184. }
  185. if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
  186. return;
  187. llvm::SmallVector<Expr *, 4> ActualArgs;
  188. ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
  189. std::swap(Args, ActualArgs);
  190. }
  191. S.AddAnnotationAttr(New, *Attr, Str, Args);
  192. }
  193. static Expr *instantiateDependentFunctionAttrCondition(
  194. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  195. const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
  196. Expr *Cond = nullptr;
  197. {
  198. Sema::ContextRAII SwitchContext(S, New);
  199. EnterExpressionEvaluationContext Unevaluated(
  200. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  201. ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
  202. if (Result.isInvalid())
  203. return nullptr;
  204. Cond = Result.getAs<Expr>();
  205. }
  206. if (!Cond->isTypeDependent()) {
  207. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  208. if (Converted.isInvalid())
  209. return nullptr;
  210. Cond = Converted.get();
  211. }
  212. SmallVector<PartialDiagnosticAt, 8> Diags;
  213. if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
  214. !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
  215. S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
  216. for (const auto &P : Diags)
  217. S.Diag(P.first, P.second);
  218. return nullptr;
  219. }
  220. return Cond;
  221. }
  222. static void instantiateDependentEnableIfAttr(
  223. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  224. const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
  225. Expr *Cond = instantiateDependentFunctionAttrCondition(
  226. S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
  227. if (Cond)
  228. New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
  229. Cond, EIA->getMessage()));
  230. }
  231. static void instantiateDependentDiagnoseIfAttr(
  232. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  233. const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
  234. Expr *Cond = instantiateDependentFunctionAttrCondition(
  235. S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
  236. if (Cond)
  237. New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
  238. S.getASTContext(), *DIA, Cond, DIA->getMessage(),
  239. DIA->getDiagnosticType(), DIA->getArgDependent(), New));
  240. }
  241. // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
  242. // template A as the base and arguments from TemplateArgs.
  243. static void instantiateDependentCUDALaunchBoundsAttr(
  244. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  245. const CUDALaunchBoundsAttr &Attr, Decl *New) {
  246. // The alignment expression is a constant expression.
  247. EnterExpressionEvaluationContext Unevaluated(
  248. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  249. ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
  250. if (Result.isInvalid())
  251. return;
  252. Expr *MaxThreads = Result.getAs<Expr>();
  253. Expr *MinBlocks = nullptr;
  254. if (Attr.getMinBlocks()) {
  255. Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
  256. if (Result.isInvalid())
  257. return;
  258. MinBlocks = Result.getAs<Expr>();
  259. }
  260. S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
  261. }
  262. static void
  263. instantiateDependentModeAttr(Sema &S,
  264. const MultiLevelTemplateArgumentList &TemplateArgs,
  265. const ModeAttr &Attr, Decl *New) {
  266. S.AddModeAttr(New, Attr, Attr.getMode(),
  267. /*InInstantiation=*/true);
  268. }
  269. /// Instantiation of 'declare simd' attribute and its arguments.
  270. static void instantiateOMPDeclareSimdDeclAttr(
  271. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  272. const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
  273. // Allow 'this' in clauses with varlists.
  274. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
  275. New = FTD->getTemplatedDecl();
  276. auto *FD = cast<FunctionDecl>(New);
  277. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
  278. SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
  279. SmallVector<unsigned, 4> LinModifiers;
  280. auto SubstExpr = [&](Expr *E) -> ExprResult {
  281. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  282. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  283. Sema::ContextRAII SavedContext(S, FD);
  284. LocalInstantiationScope Local(S);
  285. if (FD->getNumParams() > PVD->getFunctionScopeIndex())
  286. Local.InstantiatedLocal(
  287. PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
  288. return S.SubstExpr(E, TemplateArgs);
  289. }
  290. Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
  291. FD->isCXXInstanceMember());
  292. return S.SubstExpr(E, TemplateArgs);
  293. };
  294. // Substitute a single OpenMP clause, which is a potentially-evaluated
  295. // full-expression.
  296. auto Subst = [&](Expr *E) -> ExprResult {
  297. EnterExpressionEvaluationContext Evaluated(
  298. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  299. ExprResult Res = SubstExpr(E);
  300. if (Res.isInvalid())
  301. return Res;
  302. return S.ActOnFinishFullExpr(Res.get(), false);
  303. };
  304. ExprResult Simdlen;
  305. if (auto *E = Attr.getSimdlen())
  306. Simdlen = Subst(E);
  307. if (Attr.uniforms_size() > 0) {
  308. for(auto *E : Attr.uniforms()) {
  309. ExprResult Inst = Subst(E);
  310. if (Inst.isInvalid())
  311. continue;
  312. Uniforms.push_back(Inst.get());
  313. }
  314. }
  315. auto AI = Attr.alignments_begin();
  316. for (auto *E : Attr.aligneds()) {
  317. ExprResult Inst = Subst(E);
  318. if (Inst.isInvalid())
  319. continue;
  320. Aligneds.push_back(Inst.get());
  321. Inst = ExprEmpty();
  322. if (*AI)
  323. Inst = S.SubstExpr(*AI, TemplateArgs);
  324. Alignments.push_back(Inst.get());
  325. ++AI;
  326. }
  327. auto SI = Attr.steps_begin();
  328. for (auto *E : Attr.linears()) {
  329. ExprResult Inst = Subst(E);
  330. if (Inst.isInvalid())
  331. continue;
  332. Linears.push_back(Inst.get());
  333. Inst = ExprEmpty();
  334. if (*SI)
  335. Inst = S.SubstExpr(*SI, TemplateArgs);
  336. Steps.push_back(Inst.get());
  337. ++SI;
  338. }
  339. LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
  340. (void)S.ActOnOpenMPDeclareSimdDirective(
  341. S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
  342. Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
  343. Attr.getRange());
  344. }
  345. /// Instantiation of 'declare variant' attribute and its arguments.
  346. static void instantiateOMPDeclareVariantAttr(
  347. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  348. const OMPDeclareVariantAttr &Attr, Decl *New) {
  349. // Allow 'this' in clauses with varlists.
  350. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
  351. New = FTD->getTemplatedDecl();
  352. auto *FD = cast<FunctionDecl>(New);
  353. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
  354. auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
  355. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  356. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  357. Sema::ContextRAII SavedContext(S, FD);
  358. LocalInstantiationScope Local(S);
  359. if (FD->getNumParams() > PVD->getFunctionScopeIndex())
  360. Local.InstantiatedLocal(
  361. PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
  362. return S.SubstExpr(E, TemplateArgs);
  363. }
  364. Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
  365. FD->isCXXInstanceMember());
  366. return S.SubstExpr(E, TemplateArgs);
  367. };
  368. // Substitute a single OpenMP clause, which is a potentially-evaluated
  369. // full-expression.
  370. auto &&Subst = [&SubstExpr, &S](Expr *E) {
  371. EnterExpressionEvaluationContext Evaluated(
  372. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  373. ExprResult Res = SubstExpr(E);
  374. if (Res.isInvalid())
  375. return Res;
  376. return S.ActOnFinishFullExpr(Res.get(), false);
  377. };
  378. ExprResult VariantFuncRef;
  379. if (Expr *E = Attr.getVariantFuncRef()) {
  380. // Do not mark function as is used to prevent its emission if this is the
  381. // only place where it is used.
  382. EnterExpressionEvaluationContext Unevaluated(
  383. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  384. VariantFuncRef = Subst(E);
  385. }
  386. // Copy the template version of the OMPTraitInfo and run substitute on all
  387. // score and condition expressiosn.
  388. OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
  389. TI = *Attr.getTraitInfos();
  390. // Try to substitute template parameters in score and condition expressions.
  391. auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
  392. if (E) {
  393. EnterExpressionEvaluationContext Unevaluated(
  394. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  395. ExprResult ER = Subst(E);
  396. if (ER.isUsable())
  397. E = ER.get();
  398. else
  399. return true;
  400. }
  401. return false;
  402. };
  403. if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
  404. return;
  405. Expr *E = VariantFuncRef.get();
  406. // Check function/variant ref for `omp declare variant` but not for `omp
  407. // begin declare variant` (which use implicit attributes).
  408. std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
  409. S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
  410. Attr.appendArgs_size(),
  411. Attr.getRange());
  412. if (!DeclVarData)
  413. return;
  414. E = DeclVarData->second;
  415. FD = DeclVarData->first;
  416. if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
  417. if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
  418. if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
  419. if (!VariantFTD->isThisDeclarationADefinition())
  420. return;
  421. Sema::TentativeAnalysisScope Trap(S);
  422. const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
  423. S.Context, TemplateArgs.getInnermost());
  424. auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
  425. New->getLocation());
  426. if (!SubstFD)
  427. return;
  428. QualType NewType = S.Context.mergeFunctionTypes(
  429. SubstFD->getType(), FD->getType(),
  430. /* OfBlockPointer */ false,
  431. /* Unqualified */ false, /* AllowCXX */ true);
  432. if (NewType.isNull())
  433. return;
  434. S.InstantiateFunctionDefinition(
  435. New->getLocation(), SubstFD, /* Recursive */ true,
  436. /* DefinitionRequired */ false, /* AtEndOfTU */ false);
  437. SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
  438. E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
  439. SourceLocation(), SubstFD,
  440. /* RefersToEnclosingVariableOrCapture */ false,
  441. /* NameLoc */ SubstFD->getLocation(),
  442. SubstFD->getType(), ExprValueKind::VK_PRValue);
  443. }
  444. }
  445. }
  446. SmallVector<Expr *, 8> NothingExprs;
  447. SmallVector<Expr *, 8> NeedDevicePtrExprs;
  448. SmallVector<OMPInteropInfo, 4> AppendArgs;
  449. for (Expr *E : Attr.adjustArgsNothing()) {
  450. ExprResult ER = Subst(E);
  451. if (ER.isInvalid())
  452. continue;
  453. NothingExprs.push_back(ER.get());
  454. }
  455. for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
  456. ExprResult ER = Subst(E);
  457. if (ER.isInvalid())
  458. continue;
  459. NeedDevicePtrExprs.push_back(ER.get());
  460. }
  461. for (OMPInteropInfo &II : Attr.appendArgs()) {
  462. // When prefer_type is implemented for append_args handle them here too.
  463. AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
  464. }
  465. S.ActOnOpenMPDeclareVariantDirective(
  466. FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
  467. SourceLocation(), Attr.getRange());
  468. }
  469. static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
  470. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  471. const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
  472. // Both min and max expression are constant expressions.
  473. EnterExpressionEvaluationContext Unevaluated(
  474. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  475. ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
  476. if (Result.isInvalid())
  477. return;
  478. Expr *MinExpr = Result.getAs<Expr>();
  479. Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
  480. if (Result.isInvalid())
  481. return;
  482. Expr *MaxExpr = Result.getAs<Expr>();
  483. S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
  484. }
  485. static ExplicitSpecifier
  486. instantiateExplicitSpecifier(Sema &S,
  487. const MultiLevelTemplateArgumentList &TemplateArgs,
  488. ExplicitSpecifier ES, FunctionDecl *New) {
  489. if (!ES.getExpr())
  490. return ES;
  491. Expr *OldCond = ES.getExpr();
  492. Expr *Cond = nullptr;
  493. {
  494. EnterExpressionEvaluationContext Unevaluated(
  495. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  496. ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
  497. if (SubstResult.isInvalid()) {
  498. return ExplicitSpecifier::Invalid();
  499. }
  500. Cond = SubstResult.get();
  501. }
  502. ExplicitSpecifier Result(Cond, ES.getKind());
  503. if (!Cond->isTypeDependent())
  504. S.tryResolveExplicitSpecifier(Result);
  505. return Result;
  506. }
  507. static void instantiateDependentAMDGPUWavesPerEUAttr(
  508. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  509. const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
  510. // Both min and max expression are constant expressions.
  511. EnterExpressionEvaluationContext Unevaluated(
  512. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  513. ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
  514. if (Result.isInvalid())
  515. return;
  516. Expr *MinExpr = Result.getAs<Expr>();
  517. Expr *MaxExpr = nullptr;
  518. if (auto Max = Attr.getMax()) {
  519. Result = S.SubstExpr(Max, TemplateArgs);
  520. if (Result.isInvalid())
  521. return;
  522. MaxExpr = Result.getAs<Expr>();
  523. }
  524. S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
  525. }
  526. // This doesn't take any template parameters, but we have a custom action that
  527. // needs to happen when the kernel itself is instantiated. We need to run the
  528. // ItaniumMangler to mark the names required to name this kernel.
  529. static void instantiateDependentSYCLKernelAttr(
  530. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  531. const SYCLKernelAttr &Attr, Decl *New) {
  532. New->addAttr(Attr.clone(S.getASTContext()));
  533. }
  534. /// Determine whether the attribute A might be relevant to the declaration D.
  535. /// If not, we can skip instantiating it. The attribute may or may not have
  536. /// been instantiated yet.
  537. static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
  538. // 'preferred_name' is only relevant to the matching specialization of the
  539. // template.
  540. if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
  541. QualType T = PNA->getTypedefType();
  542. const auto *RD = cast<CXXRecordDecl>(D);
  543. if (!T->isDependentType() && !RD->isDependentContext() &&
  544. !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
  545. return false;
  546. for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
  547. if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
  548. PNA->getTypedefType()))
  549. return false;
  550. return true;
  551. }
  552. if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
  553. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  554. switch (BA->getID()) {
  555. case Builtin::BIforward:
  556. // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
  557. // type and returns an lvalue reference type. The library implementation
  558. // will produce an error in this case; don't get in its way.
  559. if (FD && FD->getNumParams() >= 1 &&
  560. FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
  561. FD->getReturnType()->isLValueReferenceType()) {
  562. return false;
  563. }
  564. [[fallthrough]];
  565. case Builtin::BImove:
  566. case Builtin::BImove_if_noexcept:
  567. // HACK: Super-old versions of libc++ (3.1 and earlier) provide
  568. // std::forward and std::move overloads that sometimes return by value
  569. // instead of by reference when building in C++98 mode. Don't treat such
  570. // cases as builtins.
  571. if (FD && !FD->getReturnType()->isReferenceType())
  572. return false;
  573. break;
  574. }
  575. }
  576. return true;
  577. }
  578. void Sema::InstantiateAttrsForDecl(
  579. const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
  580. Decl *New, LateInstantiatedAttrVec *LateAttrs,
  581. LocalInstantiationScope *OuterMostScope) {
  582. if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
  583. // FIXME: This function is called multiple times for the same template
  584. // specialization. We should only instantiate attributes that were added
  585. // since the previous instantiation.
  586. for (const auto *TmplAttr : Tmpl->attrs()) {
  587. if (!isRelevantAttr(*this, New, TmplAttr))
  588. continue;
  589. // FIXME: If any of the special case versions from InstantiateAttrs become
  590. // applicable to template declaration, we'll need to add them here.
  591. CXXThisScopeRAII ThisScope(
  592. *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
  593. Qualifiers(), ND->isCXXInstanceMember());
  594. Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
  595. TmplAttr, Context, *this, TemplateArgs);
  596. if (NewAttr && isRelevantAttr(*this, New, NewAttr))
  597. New->addAttr(NewAttr);
  598. }
  599. }
  600. }
  601. static Sema::RetainOwnershipKind
  602. attrToRetainOwnershipKind(const Attr *A) {
  603. switch (A->getKind()) {
  604. case clang::attr::CFConsumed:
  605. return Sema::RetainOwnershipKind::CF;
  606. case clang::attr::OSConsumed:
  607. return Sema::RetainOwnershipKind::OS;
  608. case clang::attr::NSConsumed:
  609. return Sema::RetainOwnershipKind::NS;
  610. default:
  611. llvm_unreachable("Wrong argument supplied");
  612. }
  613. }
  614. void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
  615. const Decl *Tmpl, Decl *New,
  616. LateInstantiatedAttrVec *LateAttrs,
  617. LocalInstantiationScope *OuterMostScope) {
  618. for (const auto *TmplAttr : Tmpl->attrs()) {
  619. if (!isRelevantAttr(*this, New, TmplAttr))
  620. continue;
  621. // FIXME: This should be generalized to more than just the AlignedAttr.
  622. const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
  623. if (Aligned && Aligned->isAlignmentDependent()) {
  624. instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
  625. continue;
  626. }
  627. if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
  628. instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
  629. continue;
  630. }
  631. if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
  632. instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
  633. continue;
  634. }
  635. if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
  636. instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
  637. continue;
  638. }
  639. if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
  640. instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
  641. continue;
  642. }
  643. if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
  644. instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
  645. cast<FunctionDecl>(New));
  646. continue;
  647. }
  648. if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
  649. instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
  650. cast<FunctionDecl>(New));
  651. continue;
  652. }
  653. if (const auto *CUDALaunchBounds =
  654. dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
  655. instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
  656. *CUDALaunchBounds, New);
  657. continue;
  658. }
  659. if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
  660. instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
  661. continue;
  662. }
  663. if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
  664. instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
  665. continue;
  666. }
  667. if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
  668. instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
  669. continue;
  670. }
  671. if (const auto *AMDGPUFlatWorkGroupSize =
  672. dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
  673. instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
  674. *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
  675. }
  676. if (const auto *AMDGPUFlatWorkGroupSize =
  677. dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
  678. instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
  679. *AMDGPUFlatWorkGroupSize, New);
  680. }
  681. // Existing DLL attribute on the instantiation takes precedence.
  682. if (TmplAttr->getKind() == attr::DLLExport ||
  683. TmplAttr->getKind() == attr::DLLImport) {
  684. if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
  685. continue;
  686. }
  687. }
  688. if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
  689. AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
  690. continue;
  691. }
  692. if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
  693. isa<CFConsumedAttr>(TmplAttr)) {
  694. AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
  695. /*template instantiation=*/true);
  696. continue;
  697. }
  698. if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
  699. if (!New->hasAttr<PointerAttr>())
  700. New->addAttr(A->clone(Context));
  701. continue;
  702. }
  703. if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
  704. if (!New->hasAttr<OwnerAttr>())
  705. New->addAttr(A->clone(Context));
  706. continue;
  707. }
  708. if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
  709. instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
  710. continue;
  711. }
  712. assert(!TmplAttr->isPackExpansion());
  713. if (TmplAttr->isLateParsed() && LateAttrs) {
  714. // Late parsed attributes must be instantiated and attached after the
  715. // enclosing class has been instantiated. See Sema::InstantiateClass.
  716. LocalInstantiationScope *Saved = nullptr;
  717. if (CurrentInstantiationScope)
  718. Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
  719. LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
  720. } else {
  721. // Allow 'this' within late-parsed attributes.
  722. auto *ND = cast<NamedDecl>(New);
  723. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  724. CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
  725. ND->isCXXInstanceMember());
  726. Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
  727. *this, TemplateArgs);
  728. if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
  729. New->addAttr(NewAttr);
  730. }
  731. }
  732. }
  733. /// In the MS ABI, we need to instantiate default arguments of dllexported
  734. /// default constructors along with the constructor definition. This allows IR
  735. /// gen to emit a constructor closure which calls the default constructor with
  736. /// its default arguments.
  737. void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
  738. assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  739. Ctor->isDefaultConstructor());
  740. unsigned NumParams = Ctor->getNumParams();
  741. if (NumParams == 0)
  742. return;
  743. DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
  744. if (!Attr)
  745. return;
  746. for (unsigned I = 0; I != NumParams; ++I) {
  747. (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
  748. Ctor->getParamDecl(I));
  749. CleanupVarDeclMarking();
  750. }
  751. }
  752. /// Get the previous declaration of a declaration for the purposes of template
  753. /// instantiation. If this finds a previous declaration, then the previous
  754. /// declaration of the instantiation of D should be an instantiation of the
  755. /// result of this function.
  756. template<typename DeclT>
  757. static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
  758. DeclT *Result = D->getPreviousDecl();
  759. // If the declaration is within a class, and the previous declaration was
  760. // merged from a different definition of that class, then we don't have a
  761. // previous declaration for the purpose of template instantiation.
  762. if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
  763. D->getLexicalDeclContext() != Result->getLexicalDeclContext())
  764. return nullptr;
  765. return Result;
  766. }
  767. Decl *
  768. TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  769. llvm_unreachable("Translation units cannot be instantiated");
  770. }
  771. Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
  772. llvm_unreachable("HLSL buffer declarations cannot be instantiated");
  773. }
  774. Decl *
  775. TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
  776. llvm_unreachable("pragma comment cannot be instantiated");
  777. }
  778. Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
  779. PragmaDetectMismatchDecl *D) {
  780. llvm_unreachable("pragma comment cannot be instantiated");
  781. }
  782. Decl *
  783. TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
  784. llvm_unreachable("extern \"C\" context cannot be instantiated");
  785. }
  786. Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
  787. llvm_unreachable("GUID declaration cannot be instantiated");
  788. }
  789. Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
  790. UnnamedGlobalConstantDecl *D) {
  791. llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
  792. }
  793. Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
  794. TemplateParamObjectDecl *D) {
  795. llvm_unreachable("template parameter objects cannot be instantiated");
  796. }
  797. Decl *
  798. TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
  799. LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  800. D->getIdentifier());
  801. Owner->addDecl(Inst);
  802. return Inst;
  803. }
  804. Decl *
  805. TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
  806. llvm_unreachable("Namespaces cannot be instantiated");
  807. }
  808. Decl *
  809. TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  810. NamespaceAliasDecl *Inst
  811. = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
  812. D->getNamespaceLoc(),
  813. D->getAliasLoc(),
  814. D->getIdentifier(),
  815. D->getQualifierLoc(),
  816. D->getTargetNameLoc(),
  817. D->getNamespace());
  818. Owner->addDecl(Inst);
  819. return Inst;
  820. }
  821. Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
  822. bool IsTypeAlias) {
  823. bool Invalid = false;
  824. TypeSourceInfo *DI = D->getTypeSourceInfo();
  825. if (DI->getType()->isInstantiationDependentType() ||
  826. DI->getType()->isVariablyModifiedType()) {
  827. DI = SemaRef.SubstType(DI, TemplateArgs,
  828. D->getLocation(), D->getDeclName());
  829. if (!DI) {
  830. Invalid = true;
  831. DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
  832. }
  833. } else {
  834. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  835. }
  836. // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
  837. // libstdc++ relies upon this bug in its implementation of common_type. If we
  838. // happen to be processing that implementation, fake up the g++ ?:
  839. // semantics. See LWG issue 2141 for more information on the bug. The bugs
  840. // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
  841. const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
  842. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  843. if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
  844. DT->isReferenceType() &&
  845. RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
  846. RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
  847. D->getIdentifier() && D->getIdentifier()->isStr("type") &&
  848. SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
  849. // Fold it to the (non-reference) type which g++ would have produced.
  850. DI = SemaRef.Context.getTrivialTypeSourceInfo(
  851. DI->getType().getNonReferenceType());
  852. // Create the new typedef
  853. TypedefNameDecl *Typedef;
  854. if (IsTypeAlias)
  855. Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  856. D->getLocation(), D->getIdentifier(), DI);
  857. else
  858. Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  859. D->getLocation(), D->getIdentifier(), DI);
  860. if (Invalid)
  861. Typedef->setInvalidDecl();
  862. // If the old typedef was the name for linkage purposes of an anonymous
  863. // tag decl, re-establish that relationship for the new typedef.
  864. if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
  865. TagDecl *oldTag = oldTagType->getDecl();
  866. if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
  867. TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
  868. assert(!newTag->hasNameForLinkage());
  869. newTag->setTypedefNameForAnonDecl(Typedef);
  870. }
  871. }
  872. if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
  873. NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
  874. TemplateArgs);
  875. if (!InstPrev)
  876. return nullptr;
  877. TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
  878. // If the typedef types are not identical, reject them.
  879. SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
  880. Typedef->setPreviousDecl(InstPrevTypedef);
  881. }
  882. SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
  883. if (D->getUnderlyingType()->getAs<DependentNameType>())
  884. SemaRef.inferGslPointerAttribute(Typedef);
  885. Typedef->setAccess(D->getAccess());
  886. Typedef->setReferenced(D->isReferenced());
  887. return Typedef;
  888. }
  889. Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
  890. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
  891. if (Typedef)
  892. Owner->addDecl(Typedef);
  893. return Typedef;
  894. }
  895. Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
  896. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
  897. if (Typedef)
  898. Owner->addDecl(Typedef);
  899. return Typedef;
  900. }
  901. Decl *
  902. TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  903. // Create a local instantiation scope for this type alias template, which
  904. // will contain the instantiations of the template parameters.
  905. LocalInstantiationScope Scope(SemaRef);
  906. TemplateParameterList *TempParams = D->getTemplateParameters();
  907. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  908. if (!InstParams)
  909. return nullptr;
  910. TypeAliasDecl *Pattern = D->getTemplatedDecl();
  911. TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
  912. if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
  913. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  914. if (!Found.empty()) {
  915. PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
  916. }
  917. }
  918. TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
  919. InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
  920. if (!AliasInst)
  921. return nullptr;
  922. TypeAliasTemplateDecl *Inst
  923. = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  924. D->getDeclName(), InstParams, AliasInst);
  925. AliasInst->setDescribedAliasTemplate(Inst);
  926. if (PrevAliasTemplate)
  927. Inst->setPreviousDecl(PrevAliasTemplate);
  928. Inst->setAccess(D->getAccess());
  929. if (!PrevAliasTemplate)
  930. Inst->setInstantiatedFromMemberTemplate(D);
  931. Owner->addDecl(Inst);
  932. return Inst;
  933. }
  934. Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
  935. auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  936. D->getIdentifier());
  937. NewBD->setReferenced(D->isReferenced());
  938. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
  939. return NewBD;
  940. }
  941. Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
  942. // Transform the bindings first.
  943. SmallVector<BindingDecl*, 16> NewBindings;
  944. for (auto *OldBD : D->bindings())
  945. NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
  946. ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
  947. auto *NewDD = cast_or_null<DecompositionDecl>(
  948. VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
  949. if (!NewDD || NewDD->isInvalidDecl())
  950. for (auto *NewBD : NewBindings)
  951. NewBD->setInvalidDecl();
  952. return NewDD;
  953. }
  954. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
  955. return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
  956. }
  957. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
  958. bool InstantiatingVarTemplate,
  959. ArrayRef<BindingDecl*> *Bindings) {
  960. // Do substitution on the type of the declaration
  961. TypeSourceInfo *DI = SemaRef.SubstType(
  962. D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
  963. D->getDeclName(), /*AllowDeducedTST*/true);
  964. if (!DI)
  965. return nullptr;
  966. if (DI->getType()->isFunctionType()) {
  967. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  968. << D->isStaticDataMember() << DI->getType();
  969. return nullptr;
  970. }
  971. DeclContext *DC = Owner;
  972. if (D->isLocalExternDecl())
  973. SemaRef.adjustContextForLocalExternDecl(DC);
  974. // Build the instantiated declaration.
  975. VarDecl *Var;
  976. if (Bindings)
  977. Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  978. D->getLocation(), DI->getType(), DI,
  979. D->getStorageClass(), *Bindings);
  980. else
  981. Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  982. D->getLocation(), D->getIdentifier(), DI->getType(),
  983. DI, D->getStorageClass());
  984. // In ARC, infer 'retaining' for variables of retainable type.
  985. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  986. SemaRef.inferObjCARCLifetime(Var))
  987. Var->setInvalidDecl();
  988. if (SemaRef.getLangOpts().OpenCL)
  989. SemaRef.deduceOpenCLAddressSpace(Var);
  990. // Substitute the nested name specifier, if any.
  991. if (SubstQualifier(D, Var))
  992. return nullptr;
  993. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  994. StartingScope, InstantiatingVarTemplate);
  995. if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
  996. QualType RT;
  997. if (auto *F = dyn_cast<FunctionDecl>(DC))
  998. RT = F->getReturnType();
  999. else if (isa<BlockDecl>(DC))
  1000. RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
  1001. ->getReturnType();
  1002. else
  1003. llvm_unreachable("Unknown context type");
  1004. // This is the last chance we have of checking copy elision eligibility
  1005. // for functions in dependent contexts. The sema actions for building
  1006. // the return statement during template instantiation will have no effect
  1007. // regarding copy elision, since NRVO propagation runs on the scope exit
  1008. // actions, and these are not run on instantiation.
  1009. // This might run through some VarDecls which were returned from non-taken
  1010. // 'if constexpr' branches, and these will end up being constructed on the
  1011. // return slot even if they will never be returned, as a sort of accidental
  1012. // 'optimization'. Notably, functions with 'auto' return types won't have it
  1013. // deduced by this point. Coupled with the limitation described
  1014. // previously, this makes it very hard to support copy elision for these.
  1015. Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
  1016. bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
  1017. Var->setNRVOVariable(NRVO);
  1018. }
  1019. Var->setImplicit(D->isImplicit());
  1020. if (Var->isStaticLocal())
  1021. SemaRef.CheckStaticLocalForDllExport(Var);
  1022. if (Var->getTLSKind())
  1023. SemaRef.CheckThreadLocalForLargeAlignment(Var);
  1024. return Var;
  1025. }
  1026. Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
  1027. AccessSpecDecl* AD
  1028. = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
  1029. D->getAccessSpecifierLoc(), D->getColonLoc());
  1030. Owner->addHiddenDecl(AD);
  1031. return AD;
  1032. }
  1033. Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
  1034. bool Invalid = false;
  1035. TypeSourceInfo *DI = D->getTypeSourceInfo();
  1036. if (DI->getType()->isInstantiationDependentType() ||
  1037. DI->getType()->isVariablyModifiedType()) {
  1038. DI = SemaRef.SubstType(DI, TemplateArgs,
  1039. D->getLocation(), D->getDeclName());
  1040. if (!DI) {
  1041. DI = D->getTypeSourceInfo();
  1042. Invalid = true;
  1043. } else if (DI->getType()->isFunctionType()) {
  1044. // C++ [temp.arg.type]p3:
  1045. // If a declaration acquires a function type through a type
  1046. // dependent on a template-parameter and this causes a
  1047. // declaration that does not use the syntactic form of a
  1048. // function declarator to have function type, the program is
  1049. // ill-formed.
  1050. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  1051. << DI->getType();
  1052. Invalid = true;
  1053. }
  1054. } else {
  1055. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  1056. }
  1057. Expr *BitWidth = D->getBitWidth();
  1058. if (Invalid)
  1059. BitWidth = nullptr;
  1060. else if (BitWidth) {
  1061. // The bit-width expression is a constant expression.
  1062. EnterExpressionEvaluationContext Unevaluated(
  1063. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  1064. ExprResult InstantiatedBitWidth
  1065. = SemaRef.SubstExpr(BitWidth, TemplateArgs);
  1066. if (InstantiatedBitWidth.isInvalid()) {
  1067. Invalid = true;
  1068. BitWidth = nullptr;
  1069. } else
  1070. BitWidth = InstantiatedBitWidth.getAs<Expr>();
  1071. }
  1072. FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
  1073. DI->getType(), DI,
  1074. cast<RecordDecl>(Owner),
  1075. D->getLocation(),
  1076. D->isMutable(),
  1077. BitWidth,
  1078. D->getInClassInitStyle(),
  1079. D->getInnerLocStart(),
  1080. D->getAccess(),
  1081. nullptr);
  1082. if (!Field) {
  1083. cast<Decl>(Owner)->setInvalidDecl();
  1084. return nullptr;
  1085. }
  1086. SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
  1087. if (Field->hasAttrs())
  1088. SemaRef.CheckAlignasUnderalignment(Field);
  1089. if (Invalid)
  1090. Field->setInvalidDecl();
  1091. if (!Field->getDeclName()) {
  1092. // Keep track of where this decl came from.
  1093. SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
  1094. }
  1095. if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
  1096. if (Parent->isAnonymousStructOrUnion() &&
  1097. Parent->getRedeclContext()->isFunctionOrMethod())
  1098. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
  1099. }
  1100. Field->setImplicit(D->isImplicit());
  1101. Field->setAccess(D->getAccess());
  1102. Owner->addDecl(Field);
  1103. return Field;
  1104. }
  1105. Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
  1106. bool Invalid = false;
  1107. TypeSourceInfo *DI = D->getTypeSourceInfo();
  1108. if (DI->getType()->isVariablyModifiedType()) {
  1109. SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
  1110. << D;
  1111. Invalid = true;
  1112. } else if (DI->getType()->isInstantiationDependentType()) {
  1113. DI = SemaRef.SubstType(DI, TemplateArgs,
  1114. D->getLocation(), D->getDeclName());
  1115. if (!DI) {
  1116. DI = D->getTypeSourceInfo();
  1117. Invalid = true;
  1118. } else if (DI->getType()->isFunctionType()) {
  1119. // C++ [temp.arg.type]p3:
  1120. // If a declaration acquires a function type through a type
  1121. // dependent on a template-parameter and this causes a
  1122. // declaration that does not use the syntactic form of a
  1123. // function declarator to have function type, the program is
  1124. // ill-formed.
  1125. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  1126. << DI->getType();
  1127. Invalid = true;
  1128. }
  1129. } else {
  1130. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  1131. }
  1132. MSPropertyDecl *Property = MSPropertyDecl::Create(
  1133. SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
  1134. DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
  1135. SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
  1136. StartingScope);
  1137. if (Invalid)
  1138. Property->setInvalidDecl();
  1139. Property->setAccess(D->getAccess());
  1140. Owner->addDecl(Property);
  1141. return Property;
  1142. }
  1143. Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  1144. NamedDecl **NamedChain =
  1145. new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
  1146. int i = 0;
  1147. for (auto *PI : D->chain()) {
  1148. NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
  1149. TemplateArgs);
  1150. if (!Next)
  1151. return nullptr;
  1152. NamedChain[i++] = Next;
  1153. }
  1154. QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
  1155. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  1156. SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
  1157. {NamedChain, D->getChainingSize()});
  1158. for (const auto *Attr : D->attrs())
  1159. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  1160. IndirectField->setImplicit(D->isImplicit());
  1161. IndirectField->setAccess(D->getAccess());
  1162. Owner->addDecl(IndirectField);
  1163. return IndirectField;
  1164. }
  1165. Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
  1166. // Handle friend type expressions by simply substituting template
  1167. // parameters into the pattern type and checking the result.
  1168. if (TypeSourceInfo *Ty = D->getFriendType()) {
  1169. TypeSourceInfo *InstTy;
  1170. // If this is an unsupported friend, don't bother substituting template
  1171. // arguments into it. The actual type referred to won't be used by any
  1172. // parts of Clang, and may not be valid for instantiating. Just use the
  1173. // same info for the instantiated friend.
  1174. if (D->isUnsupportedFriend()) {
  1175. InstTy = Ty;
  1176. } else {
  1177. InstTy = SemaRef.SubstType(Ty, TemplateArgs,
  1178. D->getLocation(), DeclarationName());
  1179. }
  1180. if (!InstTy)
  1181. return nullptr;
  1182. FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
  1183. D->getFriendLoc(), InstTy);
  1184. if (!FD)
  1185. return nullptr;
  1186. FD->setAccess(AS_public);
  1187. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  1188. Owner->addDecl(FD);
  1189. return FD;
  1190. }
  1191. NamedDecl *ND = D->getFriendDecl();
  1192. assert(ND && "friend decl must be a decl or a type!");
  1193. // All of the Visit implementations for the various potential friend
  1194. // declarations have to be carefully written to work for friend
  1195. // objects, with the most important detail being that the target
  1196. // decl should almost certainly not be placed in Owner.
  1197. Decl *NewND = Visit(ND);
  1198. if (!NewND) return nullptr;
  1199. FriendDecl *FD =
  1200. FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  1201. cast<NamedDecl>(NewND), D->getFriendLoc());
  1202. FD->setAccess(AS_public);
  1203. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  1204. Owner->addDecl(FD);
  1205. return FD;
  1206. }
  1207. Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
  1208. Expr *AssertExpr = D->getAssertExpr();
  1209. // The expression in a static assertion is a constant expression.
  1210. EnterExpressionEvaluationContext Unevaluated(
  1211. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  1212. ExprResult InstantiatedAssertExpr
  1213. = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
  1214. if (InstantiatedAssertExpr.isInvalid())
  1215. return nullptr;
  1216. return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
  1217. InstantiatedAssertExpr.get(),
  1218. D->getMessage(),
  1219. D->getRParenLoc(),
  1220. D->isFailed());
  1221. }
  1222. Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
  1223. EnumDecl *PrevDecl = nullptr;
  1224. if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  1225. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1226. PatternPrev,
  1227. TemplateArgs);
  1228. if (!Prev) return nullptr;
  1229. PrevDecl = cast<EnumDecl>(Prev);
  1230. }
  1231. EnumDecl *Enum =
  1232. EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  1233. D->getLocation(), D->getIdentifier(), PrevDecl,
  1234. D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
  1235. if (D->isFixed()) {
  1236. if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
  1237. // If we have type source information for the underlying type, it means it
  1238. // has been explicitly set by the user. Perform substitution on it before
  1239. // moving on.
  1240. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  1241. TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
  1242. DeclarationName());
  1243. if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
  1244. Enum->setIntegerType(SemaRef.Context.IntTy);
  1245. else
  1246. Enum->setIntegerTypeSourceInfo(NewTI);
  1247. } else {
  1248. assert(!D->getIntegerType()->isDependentType()
  1249. && "Dependent type without type source info");
  1250. Enum->setIntegerType(D->getIntegerType());
  1251. }
  1252. }
  1253. SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
  1254. Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
  1255. Enum->setAccess(D->getAccess());
  1256. // Forward the mangling number from the template to the instantiated decl.
  1257. SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
  1258. // See if the old tag was defined along with a declarator.
  1259. // If it did, mark the new tag as being associated with that declarator.
  1260. if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
  1261. SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
  1262. // See if the old tag was defined along with a typedef.
  1263. // If it did, mark the new tag as being associated with that typedef.
  1264. if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
  1265. SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
  1266. if (SubstQualifier(D, Enum)) return nullptr;
  1267. Owner->addDecl(Enum);
  1268. EnumDecl *Def = D->getDefinition();
  1269. if (Def && Def != D) {
  1270. // If this is an out-of-line definition of an enum member template, check
  1271. // that the underlying types match in the instantiation of both
  1272. // declarations.
  1273. if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
  1274. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  1275. QualType DefnUnderlying =
  1276. SemaRef.SubstType(TI->getType(), TemplateArgs,
  1277. UnderlyingLoc, DeclarationName());
  1278. SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
  1279. DefnUnderlying, /*IsFixed=*/true, Enum);
  1280. }
  1281. }
  1282. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  1283. // specialization causes the implicit instantiation of the declarations, but
  1284. // not the definitions of scoped member enumerations.
  1285. //
  1286. // DR1484 clarifies that enumeration definitions inside of a template
  1287. // declaration aren't considered entities that can be separately instantiated
  1288. // from the rest of the entity they are declared inside of.
  1289. if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
  1290. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
  1291. InstantiateEnumDefinition(Enum, Def);
  1292. }
  1293. return Enum;
  1294. }
  1295. void TemplateDeclInstantiator::InstantiateEnumDefinition(
  1296. EnumDecl *Enum, EnumDecl *Pattern) {
  1297. Enum->startDefinition();
  1298. // Update the location to refer to the definition.
  1299. Enum->setLocation(Pattern->getLocation());
  1300. SmallVector<Decl*, 4> Enumerators;
  1301. EnumConstantDecl *LastEnumConst = nullptr;
  1302. for (auto *EC : Pattern->enumerators()) {
  1303. // The specified value for the enumerator.
  1304. ExprResult Value((Expr *)nullptr);
  1305. if (Expr *UninstValue = EC->getInitExpr()) {
  1306. // The enumerator's value expression is a constant expression.
  1307. EnterExpressionEvaluationContext Unevaluated(
  1308. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  1309. Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
  1310. }
  1311. // Drop the initial value and continue.
  1312. bool isInvalid = false;
  1313. if (Value.isInvalid()) {
  1314. Value = nullptr;
  1315. isInvalid = true;
  1316. }
  1317. EnumConstantDecl *EnumConst
  1318. = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
  1319. EC->getLocation(), EC->getIdentifier(),
  1320. Value.get());
  1321. if (isInvalid) {
  1322. if (EnumConst)
  1323. EnumConst->setInvalidDecl();
  1324. Enum->setInvalidDecl();
  1325. }
  1326. if (EnumConst) {
  1327. SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
  1328. EnumConst->setAccess(Enum->getAccess());
  1329. Enum->addDecl(EnumConst);
  1330. Enumerators.push_back(EnumConst);
  1331. LastEnumConst = EnumConst;
  1332. if (Pattern->getDeclContext()->isFunctionOrMethod() &&
  1333. !Enum->isScoped()) {
  1334. // If the enumeration is within a function or method, record the enum
  1335. // constant as a local.
  1336. SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
  1337. }
  1338. }
  1339. }
  1340. SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
  1341. Enumerators, nullptr, ParsedAttributesView());
  1342. }
  1343. Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
  1344. llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
  1345. }
  1346. Decl *
  1347. TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
  1348. llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
  1349. }
  1350. Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  1351. bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1352. // Create a local instantiation scope for this class template, which
  1353. // will contain the instantiations of the template parameters.
  1354. LocalInstantiationScope Scope(SemaRef);
  1355. TemplateParameterList *TempParams = D->getTemplateParameters();
  1356. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1357. if (!InstParams)
  1358. return nullptr;
  1359. CXXRecordDecl *Pattern = D->getTemplatedDecl();
  1360. // Instantiate the qualifier. We have to do this first in case
  1361. // we're a friend declaration, because if we are then we need to put
  1362. // the new declaration in the appropriate context.
  1363. NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
  1364. if (QualifierLoc) {
  1365. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1366. TemplateArgs);
  1367. if (!QualifierLoc)
  1368. return nullptr;
  1369. }
  1370. CXXRecordDecl *PrevDecl = nullptr;
  1371. ClassTemplateDecl *PrevClassTemplate = nullptr;
  1372. if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
  1373. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  1374. if (!Found.empty()) {
  1375. PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
  1376. if (PrevClassTemplate)
  1377. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  1378. }
  1379. }
  1380. // If this isn't a friend, then it's a member template, in which
  1381. // case we just want to build the instantiation in the
  1382. // specialization. If it is a friend, we want to build it in
  1383. // the appropriate context.
  1384. DeclContext *DC = Owner;
  1385. if (isFriend) {
  1386. if (QualifierLoc) {
  1387. CXXScopeSpec SS;
  1388. SS.Adopt(QualifierLoc);
  1389. DC = SemaRef.computeDeclContext(SS);
  1390. if (!DC) return nullptr;
  1391. } else {
  1392. DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
  1393. Pattern->getDeclContext(),
  1394. TemplateArgs);
  1395. }
  1396. // Look for a previous declaration of the template in the owning
  1397. // context.
  1398. LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
  1399. Sema::LookupOrdinaryName,
  1400. SemaRef.forRedeclarationInCurContext());
  1401. SemaRef.LookupQualifiedName(R, DC);
  1402. if (R.isSingleResult()) {
  1403. PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
  1404. if (PrevClassTemplate)
  1405. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  1406. }
  1407. if (!PrevClassTemplate && QualifierLoc) {
  1408. SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
  1409. << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
  1410. << QualifierLoc.getSourceRange();
  1411. return nullptr;
  1412. }
  1413. if (PrevClassTemplate) {
  1414. const ClassTemplateDecl *MostRecentPrevCT =
  1415. PrevClassTemplate->getMostRecentDecl();
  1416. TemplateParameterList *PrevParams =
  1417. MostRecentPrevCT->getTemplateParameters();
  1418. // Make sure the parameter lists match.
  1419. if (!SemaRef.TemplateParameterListsAreEqual(
  1420. D->getTemplatedDecl(), InstParams,
  1421. MostRecentPrevCT->getTemplatedDecl(), PrevParams, true,
  1422. Sema::TPL_TemplateMatch))
  1423. return nullptr;
  1424. // Do some additional validation, then merge default arguments
  1425. // from the existing declarations.
  1426. if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
  1427. Sema::TPC_ClassTemplate))
  1428. return nullptr;
  1429. }
  1430. }
  1431. CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
  1432. SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
  1433. Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
  1434. /*DelayTypeCreation=*/true);
  1435. if (QualifierLoc)
  1436. RecordInst->setQualifierInfo(QualifierLoc);
  1437. SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
  1438. StartingScope);
  1439. ClassTemplateDecl *Inst
  1440. = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
  1441. D->getIdentifier(), InstParams, RecordInst);
  1442. assert(!(isFriend && Owner->isDependentContext()));
  1443. Inst->setPreviousDecl(PrevClassTemplate);
  1444. RecordInst->setDescribedClassTemplate(Inst);
  1445. if (isFriend) {
  1446. if (PrevClassTemplate)
  1447. Inst->setAccess(PrevClassTemplate->getAccess());
  1448. else
  1449. Inst->setAccess(D->getAccess());
  1450. Inst->setObjectOfFriendDecl();
  1451. // TODO: do we want to track the instantiation progeny of this
  1452. // friend target decl?
  1453. } else {
  1454. Inst->setAccess(D->getAccess());
  1455. if (!PrevClassTemplate)
  1456. Inst->setInstantiatedFromMemberTemplate(D);
  1457. }
  1458. // Trigger creation of the type for the instantiation.
  1459. SemaRef.Context.getInjectedClassNameType(RecordInst,
  1460. Inst->getInjectedClassNameSpecialization());
  1461. // Finish handling of friends.
  1462. if (isFriend) {
  1463. DC->makeDeclVisibleInContext(Inst);
  1464. Inst->setLexicalDeclContext(Owner);
  1465. RecordInst->setLexicalDeclContext(Owner);
  1466. return Inst;
  1467. }
  1468. if (D->isOutOfLine()) {
  1469. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  1470. RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
  1471. }
  1472. Owner->addDecl(Inst);
  1473. if (!PrevClassTemplate) {
  1474. // Queue up any out-of-line partial specializations of this member
  1475. // class template; the client will force their instantiation once
  1476. // the enclosing class has been instantiated.
  1477. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1478. D->getPartialSpecializations(PartialSpecs);
  1479. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1480. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1481. OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
  1482. }
  1483. return Inst;
  1484. }
  1485. Decl *
  1486. TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
  1487. ClassTemplatePartialSpecializationDecl *D) {
  1488. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  1489. // Lookup the already-instantiated declaration in the instantiation
  1490. // of the class template and return that.
  1491. DeclContext::lookup_result Found
  1492. = Owner->lookup(ClassTemplate->getDeclName());
  1493. if (Found.empty())
  1494. return nullptr;
  1495. ClassTemplateDecl *InstClassTemplate
  1496. = dyn_cast<ClassTemplateDecl>(Found.front());
  1497. if (!InstClassTemplate)
  1498. return nullptr;
  1499. if (ClassTemplatePartialSpecializationDecl *Result
  1500. = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
  1501. return Result;
  1502. return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
  1503. }
  1504. Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
  1505. assert(D->getTemplatedDecl()->isStaticDataMember() &&
  1506. "Only static data member templates are allowed.");
  1507. // Create a local instantiation scope for this variable template, which
  1508. // will contain the instantiations of the template parameters.
  1509. LocalInstantiationScope Scope(SemaRef);
  1510. TemplateParameterList *TempParams = D->getTemplateParameters();
  1511. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1512. if (!InstParams)
  1513. return nullptr;
  1514. VarDecl *Pattern = D->getTemplatedDecl();
  1515. VarTemplateDecl *PrevVarTemplate = nullptr;
  1516. if (getPreviousDeclForInstantiation(Pattern)) {
  1517. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  1518. if (!Found.empty())
  1519. PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1520. }
  1521. VarDecl *VarInst =
  1522. cast_or_null<VarDecl>(VisitVarDecl(Pattern,
  1523. /*InstantiatingVarTemplate=*/true));
  1524. if (!VarInst) return nullptr;
  1525. DeclContext *DC = Owner;
  1526. VarTemplateDecl *Inst = VarTemplateDecl::Create(
  1527. SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
  1528. VarInst);
  1529. VarInst->setDescribedVarTemplate(Inst);
  1530. Inst->setPreviousDecl(PrevVarTemplate);
  1531. Inst->setAccess(D->getAccess());
  1532. if (!PrevVarTemplate)
  1533. Inst->setInstantiatedFromMemberTemplate(D);
  1534. if (D->isOutOfLine()) {
  1535. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  1536. VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
  1537. }
  1538. Owner->addDecl(Inst);
  1539. if (!PrevVarTemplate) {
  1540. // Queue up any out-of-line partial specializations of this member
  1541. // variable template; the client will force their instantiation once
  1542. // the enclosing class has been instantiated.
  1543. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1544. D->getPartialSpecializations(PartialSpecs);
  1545. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1546. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1547. OutOfLineVarPartialSpecs.push_back(
  1548. std::make_pair(Inst, PartialSpecs[I]));
  1549. }
  1550. return Inst;
  1551. }
  1552. Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
  1553. VarTemplatePartialSpecializationDecl *D) {
  1554. assert(D->isStaticDataMember() &&
  1555. "Only static data member templates are allowed.");
  1556. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  1557. // Lookup the already-instantiated declaration and return that.
  1558. DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
  1559. assert(!Found.empty() && "Instantiation found nothing?");
  1560. VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1561. assert(InstVarTemplate && "Instantiation did not find a variable template?");
  1562. if (VarTemplatePartialSpecializationDecl *Result =
  1563. InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
  1564. return Result;
  1565. return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
  1566. }
  1567. Decl *
  1568. TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  1569. // Create a local instantiation scope for this function template, which
  1570. // will contain the instantiations of the template parameters and then get
  1571. // merged with the local instantiation scope for the function template
  1572. // itself.
  1573. LocalInstantiationScope Scope(SemaRef);
  1574. Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
  1575. TemplateParameterList *TempParams = D->getTemplateParameters();
  1576. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1577. if (!InstParams)
  1578. return nullptr;
  1579. FunctionDecl *Instantiated = nullptr;
  1580. if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
  1581. Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
  1582. InstParams));
  1583. else
  1584. Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
  1585. D->getTemplatedDecl(),
  1586. InstParams));
  1587. if (!Instantiated)
  1588. return nullptr;
  1589. // Link the instantiated function template declaration to the function
  1590. // template from which it was instantiated.
  1591. FunctionTemplateDecl *InstTemplate
  1592. = Instantiated->getDescribedFunctionTemplate();
  1593. InstTemplate->setAccess(D->getAccess());
  1594. assert(InstTemplate &&
  1595. "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
  1596. bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
  1597. // Link the instantiation back to the pattern *unless* this is a
  1598. // non-definition friend declaration.
  1599. if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
  1600. !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
  1601. InstTemplate->setInstantiatedFromMemberTemplate(D);
  1602. // Make declarations visible in the appropriate context.
  1603. if (!isFriend) {
  1604. Owner->addDecl(InstTemplate);
  1605. } else if (InstTemplate->getDeclContext()->isRecord() &&
  1606. !getPreviousDeclForInstantiation(D)) {
  1607. SemaRef.CheckFriendAccess(InstTemplate);
  1608. }
  1609. return InstTemplate;
  1610. }
  1611. Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
  1612. CXXRecordDecl *PrevDecl = nullptr;
  1613. if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  1614. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1615. PatternPrev,
  1616. TemplateArgs);
  1617. if (!Prev) return nullptr;
  1618. PrevDecl = cast<CXXRecordDecl>(Prev);
  1619. }
  1620. CXXRecordDecl *Record = nullptr;
  1621. bool IsInjectedClassName = D->isInjectedClassName();
  1622. if (D->isLambda())
  1623. Record = CXXRecordDecl::CreateLambda(
  1624. SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
  1625. D->getLambdaDependencyKind(), D->isGenericLambda(),
  1626. D->getLambdaCaptureDefault());
  1627. else
  1628. Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
  1629. D->getBeginLoc(), D->getLocation(),
  1630. D->getIdentifier(), PrevDecl,
  1631. /*DelayTypeCreation=*/IsInjectedClassName);
  1632. // Link the type of the injected-class-name to that of the outer class.
  1633. if (IsInjectedClassName)
  1634. (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
  1635. // Substitute the nested name specifier, if any.
  1636. if (SubstQualifier(D, Record))
  1637. return nullptr;
  1638. SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
  1639. StartingScope);
  1640. Record->setImplicit(D->isImplicit());
  1641. // FIXME: Check against AS_none is an ugly hack to work around the issue that
  1642. // the tag decls introduced by friend class declarations don't have an access
  1643. // specifier. Remove once this area of the code gets sorted out.
  1644. if (D->getAccess() != AS_none)
  1645. Record->setAccess(D->getAccess());
  1646. if (!IsInjectedClassName)
  1647. Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  1648. // If the original function was part of a friend declaration,
  1649. // inherit its namespace state.
  1650. if (D->getFriendObjectKind())
  1651. Record->setObjectOfFriendDecl();
  1652. // Make sure that anonymous structs and unions are recorded.
  1653. if (D->isAnonymousStructOrUnion())
  1654. Record->setAnonymousStructOrUnion(true);
  1655. if (D->isLocalClass())
  1656. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
  1657. // Forward the mangling number from the template to the instantiated decl.
  1658. SemaRef.Context.setManglingNumber(Record,
  1659. SemaRef.Context.getManglingNumber(D));
  1660. // See if the old tag was defined along with a declarator.
  1661. // If it did, mark the new tag as being associated with that declarator.
  1662. if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
  1663. SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
  1664. // See if the old tag was defined along with a typedef.
  1665. // If it did, mark the new tag as being associated with that typedef.
  1666. if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
  1667. SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
  1668. Owner->addDecl(Record);
  1669. // DR1484 clarifies that the members of a local class are instantiated as part
  1670. // of the instantiation of their enclosing entity.
  1671. if (D->isCompleteDefinition() && D->isLocalClass()) {
  1672. Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
  1673. SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
  1674. TSK_ImplicitInstantiation,
  1675. /*Complain=*/true);
  1676. // For nested local classes, we will instantiate the members when we
  1677. // reach the end of the outermost (non-nested) local class.
  1678. if (!D->isCXXClassMember())
  1679. SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
  1680. TSK_ImplicitInstantiation);
  1681. // This class may have local implicit instantiations that need to be
  1682. // performed within this scope.
  1683. LocalInstantiations.perform();
  1684. }
  1685. SemaRef.DiagnoseUnusedNestedTypedefs(Record);
  1686. if (IsInjectedClassName)
  1687. assert(Record->isInjectedClassName() && "Broken injected-class-name");
  1688. return Record;
  1689. }
  1690. /// Adjust the given function type for an instantiation of the
  1691. /// given declaration, to cope with modifications to the function's type that
  1692. /// aren't reflected in the type-source information.
  1693. ///
  1694. /// \param D The declaration we're instantiating.
  1695. /// \param TInfo The already-instantiated type.
  1696. static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
  1697. FunctionDecl *D,
  1698. TypeSourceInfo *TInfo) {
  1699. const FunctionProtoType *OrigFunc
  1700. = D->getType()->castAs<FunctionProtoType>();
  1701. const FunctionProtoType *NewFunc
  1702. = TInfo->getType()->castAs<FunctionProtoType>();
  1703. if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
  1704. return TInfo->getType();
  1705. FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
  1706. NewEPI.ExtInfo = OrigFunc->getExtInfo();
  1707. return Context.getFunctionType(NewFunc->getReturnType(),
  1708. NewFunc->getParamTypes(), NewEPI);
  1709. }
  1710. /// Normal class members are of more specific types and therefore
  1711. /// don't make it here. This function serves three purposes:
  1712. /// 1) instantiating function templates
  1713. /// 2) substituting friend and local function declarations
  1714. /// 3) substituting deduction guide declarations for nested class templates
  1715. Decl *TemplateDeclInstantiator::VisitFunctionDecl(
  1716. FunctionDecl *D, TemplateParameterList *TemplateParams,
  1717. RewriteKind FunctionRewriteKind) {
  1718. // Check whether there is already a function template specialization for
  1719. // this declaration.
  1720. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1721. if (FunctionTemplate && !TemplateParams) {
  1722. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1723. void *InsertPos = nullptr;
  1724. FunctionDecl *SpecFunc
  1725. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1726. // If we already have a function template specialization, return it.
  1727. if (SpecFunc)
  1728. return SpecFunc;
  1729. }
  1730. bool isFriend;
  1731. if (FunctionTemplate)
  1732. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1733. else
  1734. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1735. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1736. Owner->isFunctionOrMethod() ||
  1737. !(isa<Decl>(Owner) &&
  1738. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1739. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1740. ExplicitSpecifier InstantiatedExplicitSpecifier;
  1741. if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
  1742. InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
  1743. SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
  1744. if (InstantiatedExplicitSpecifier.isInvalid())
  1745. return nullptr;
  1746. }
  1747. SmallVector<ParmVarDecl *, 4> Params;
  1748. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1749. if (!TInfo)
  1750. return nullptr;
  1751. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1752. if (TemplateParams && TemplateParams->size()) {
  1753. auto *LastParam =
  1754. dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
  1755. if (LastParam && LastParam->isImplicit() &&
  1756. LastParam->hasTypeConstraint()) {
  1757. // In abbreviated templates, the type-constraints of invented template
  1758. // type parameters are instantiated with the function type, invalidating
  1759. // the TemplateParameterList which relied on the template type parameter
  1760. // not having a type constraint. Recreate the TemplateParameterList with
  1761. // the updated parameter list.
  1762. TemplateParams = TemplateParameterList::Create(
  1763. SemaRef.Context, TemplateParams->getTemplateLoc(),
  1764. TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
  1765. TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
  1766. }
  1767. }
  1768. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1769. if (QualifierLoc) {
  1770. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1771. TemplateArgs);
  1772. if (!QualifierLoc)
  1773. return nullptr;
  1774. }
  1775. Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
  1776. // If we're instantiating a local function declaration, put the result
  1777. // in the enclosing namespace; otherwise we need to find the instantiated
  1778. // context.
  1779. DeclContext *DC;
  1780. if (D->isLocalExternDecl()) {
  1781. DC = Owner;
  1782. SemaRef.adjustContextForLocalExternDecl(DC);
  1783. } else if (isFriend && QualifierLoc) {
  1784. CXXScopeSpec SS;
  1785. SS.Adopt(QualifierLoc);
  1786. DC = SemaRef.computeDeclContext(SS);
  1787. if (!DC) return nullptr;
  1788. } else {
  1789. DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
  1790. TemplateArgs);
  1791. }
  1792. DeclarationNameInfo NameInfo
  1793. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1794. if (FunctionRewriteKind != RewriteKind::None)
  1795. adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
  1796. FunctionDecl *Function;
  1797. if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
  1798. Function = CXXDeductionGuideDecl::Create(
  1799. SemaRef.Context, DC, D->getInnerLocStart(),
  1800. InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
  1801. D->getSourceRange().getEnd());
  1802. if (DGuide->isCopyDeductionCandidate())
  1803. cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
  1804. Function->setAccess(D->getAccess());
  1805. } else {
  1806. Function = FunctionDecl::Create(
  1807. SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
  1808. D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
  1809. D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
  1810. TrailingRequiresClause);
  1811. Function->setFriendConstraintRefersToEnclosingTemplate(
  1812. D->FriendConstraintRefersToEnclosingTemplate());
  1813. Function->setRangeEnd(D->getSourceRange().getEnd());
  1814. }
  1815. if (D->isInlined())
  1816. Function->setImplicitlyInline();
  1817. if (QualifierLoc)
  1818. Function->setQualifierInfo(QualifierLoc);
  1819. if (D->isLocalExternDecl())
  1820. Function->setLocalExternDecl();
  1821. DeclContext *LexicalDC = Owner;
  1822. if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
  1823. assert(D->getDeclContext()->isFileContext());
  1824. LexicalDC = D->getDeclContext();
  1825. }
  1826. else if (D->isLocalExternDecl()) {
  1827. LexicalDC = SemaRef.CurContext;
  1828. }
  1829. Function->setLexicalDeclContext(LexicalDC);
  1830. // Attach the parameters
  1831. for (unsigned P = 0; P < Params.size(); ++P)
  1832. if (Params[P])
  1833. Params[P]->setOwningFunction(Function);
  1834. Function->setParams(Params);
  1835. if (TrailingRequiresClause)
  1836. Function->setTrailingRequiresClause(TrailingRequiresClause);
  1837. if (TemplateParams) {
  1838. // Our resulting instantiation is actually a function template, since we
  1839. // are substituting only the outer template parameters. For example, given
  1840. //
  1841. // template<typename T>
  1842. // struct X {
  1843. // template<typename U> friend void f(T, U);
  1844. // };
  1845. //
  1846. // X<int> x;
  1847. //
  1848. // We are instantiating the friend function template "f" within X<int>,
  1849. // which means substituting int for T, but leaving "f" as a friend function
  1850. // template.
  1851. // Build the function template itself.
  1852. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
  1853. Function->getLocation(),
  1854. Function->getDeclName(),
  1855. TemplateParams, Function);
  1856. Function->setDescribedFunctionTemplate(FunctionTemplate);
  1857. FunctionTemplate->setLexicalDeclContext(LexicalDC);
  1858. if (isFriend && D->isThisDeclarationADefinition()) {
  1859. FunctionTemplate->setInstantiatedFromMemberTemplate(
  1860. D->getDescribedFunctionTemplate());
  1861. }
  1862. } else if (FunctionTemplate) {
  1863. // Record this function template specialization.
  1864. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1865. Function->setFunctionTemplateSpecialization(FunctionTemplate,
  1866. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1867. Innermost),
  1868. /*InsertPos=*/nullptr);
  1869. } else if (isFriend && D->isThisDeclarationADefinition()) {
  1870. // Do not connect the friend to the template unless it's actually a
  1871. // definition. We don't want non-template functions to be marked as being
  1872. // template instantiations.
  1873. Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1874. } else if (!isFriend) {
  1875. // If this is not a function template, and this is not a friend (that is,
  1876. // this is a locally declared function), save the instantiation relationship
  1877. // for the purposes of constraint instantiation.
  1878. Function->setInstantiatedFromDecl(D);
  1879. }
  1880. if (isFriend) {
  1881. Function->setObjectOfFriendDecl();
  1882. if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
  1883. FT->setObjectOfFriendDecl();
  1884. }
  1885. if (InitFunctionInstantiation(Function, D))
  1886. Function->setInvalidDecl();
  1887. bool IsExplicitSpecialization = false;
  1888. LookupResult Previous(
  1889. SemaRef, Function->getDeclName(), SourceLocation(),
  1890. D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  1891. : Sema::LookupOrdinaryName,
  1892. D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
  1893. : SemaRef.forRedeclarationInCurContext());
  1894. if (DependentFunctionTemplateSpecializationInfo *Info
  1895. = D->getDependentSpecializationInfo()) {
  1896. assert(isFriend && "non-friend has dependent specialization info?");
  1897. // Instantiate the explicit template arguments.
  1898. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1899. Info->getRAngleLoc());
  1900. if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
  1901. ExplicitArgs))
  1902. return nullptr;
  1903. // Map the candidate templates to their instantiations.
  1904. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1905. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1906. Info->getTemplate(I),
  1907. TemplateArgs);
  1908. if (!Temp) return nullptr;
  1909. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1910. }
  1911. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1912. &ExplicitArgs,
  1913. Previous))
  1914. Function->setInvalidDecl();
  1915. IsExplicitSpecialization = true;
  1916. } else if (const ASTTemplateArgumentListInfo *Info =
  1917. D->getTemplateSpecializationArgsAsWritten()) {
  1918. // The name of this function was written as a template-id.
  1919. SemaRef.LookupQualifiedName(Previous, DC);
  1920. // Instantiate the explicit template arguments.
  1921. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1922. Info->getRAngleLoc());
  1923. if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
  1924. ExplicitArgs))
  1925. return nullptr;
  1926. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1927. &ExplicitArgs,
  1928. Previous))
  1929. Function->setInvalidDecl();
  1930. IsExplicitSpecialization = true;
  1931. } else if (TemplateParams || !FunctionTemplate) {
  1932. // Look only into the namespace where the friend would be declared to
  1933. // find a previous declaration. This is the innermost enclosing namespace,
  1934. // as described in ActOnFriendFunctionDecl.
  1935. SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
  1936. // In C++, the previous declaration we find might be a tag type
  1937. // (class or enum). In this case, the new declaration will hide the
  1938. // tag type. Note that this does not apply if we're declaring a
  1939. // typedef (C++ [dcl.typedef]p4).
  1940. if (Previous.isSingleTagDecl())
  1941. Previous.clear();
  1942. // Filter out previous declarations that don't match the scope. The only
  1943. // effect this has is to remove declarations found in inline namespaces
  1944. // for friend declarations with unqualified names.
  1945. if (isFriend && !QualifierLoc && !FunctionTemplate) {
  1946. SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
  1947. /*ConsiderLinkage=*/ true,
  1948. QualifierLoc.hasQualifier());
  1949. }
  1950. }
  1951. // Per [temp.inst], default arguments in function declarations at local scope
  1952. // are instantiated along with the enclosing declaration. For example:
  1953. //
  1954. // template<typename T>
  1955. // void ft() {
  1956. // void f(int = []{ return T::value; }());
  1957. // }
  1958. // template void ft<int>(); // error: type 'int' cannot be used prior
  1959. // to '::' because it has no members
  1960. //
  1961. // The error is issued during instantiation of ft<int>() because substitution
  1962. // into the default argument fails; the default argument is instantiated even
  1963. // though it is never used.
  1964. if (Function->isLocalExternDecl()) {
  1965. for (ParmVarDecl *PVD : Function->parameters()) {
  1966. if (!PVD->hasDefaultArg())
  1967. continue;
  1968. if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
  1969. // If substitution fails, the default argument is set to a
  1970. // RecoveryExpr that wraps the uninstantiated default argument so
  1971. // that downstream diagnostics are omitted.
  1972. Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
  1973. ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
  1974. UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
  1975. { UninstExpr }, UninstExpr->getType());
  1976. if (ErrorResult.isUsable())
  1977. PVD->setDefaultArg(ErrorResult.get());
  1978. }
  1979. }
  1980. }
  1981. SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
  1982. IsExplicitSpecialization,
  1983. Function->isThisDeclarationADefinition());
  1984. // Check the template parameter list against the previous declaration. The
  1985. // goal here is to pick up default arguments added since the friend was
  1986. // declared; we know the template parameter lists match, since otherwise
  1987. // we would not have picked this template as the previous declaration.
  1988. if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
  1989. SemaRef.CheckTemplateParameterList(
  1990. TemplateParams,
  1991. FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
  1992. Function->isThisDeclarationADefinition()
  1993. ? Sema::TPC_FriendFunctionTemplateDefinition
  1994. : Sema::TPC_FriendFunctionTemplate);
  1995. }
  1996. // If we're introducing a friend definition after the first use, trigger
  1997. // instantiation.
  1998. // FIXME: If this is a friend function template definition, we should check
  1999. // to see if any specializations have been used.
  2000. if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
  2001. if (MemberSpecializationInfo *MSInfo =
  2002. Function->getMemberSpecializationInfo()) {
  2003. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  2004. SourceLocation Loc = D->getLocation(); // FIXME
  2005. MSInfo->setPointOfInstantiation(Loc);
  2006. SemaRef.PendingLocalImplicitInstantiations.push_back(
  2007. std::make_pair(Function, Loc));
  2008. }
  2009. }
  2010. }
  2011. if (D->isExplicitlyDefaulted()) {
  2012. if (SubstDefaultedFunction(Function, D))
  2013. return nullptr;
  2014. }
  2015. if (D->isDeleted())
  2016. SemaRef.SetDeclDeleted(Function, D->getLocation());
  2017. NamedDecl *PrincipalDecl =
  2018. (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
  2019. // If this declaration lives in a different context from its lexical context,
  2020. // add it to the corresponding lookup table.
  2021. if (isFriend ||
  2022. (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
  2023. DC->makeDeclVisibleInContext(PrincipalDecl);
  2024. if (Function->isOverloadedOperator() && !DC->isRecord() &&
  2025. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  2026. PrincipalDecl->setNonMemberOperator();
  2027. return Function;
  2028. }
  2029. Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
  2030. CXXMethodDecl *D, TemplateParameterList *TemplateParams,
  2031. std::optional<const ASTTemplateArgumentListInfo *>
  2032. ClassScopeSpecializationArgs,
  2033. RewriteKind FunctionRewriteKind) {
  2034. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  2035. if (FunctionTemplate && !TemplateParams) {
  2036. // We are creating a function template specialization from a function
  2037. // template. Check whether there is already a function template
  2038. // specialization for this particular set of template arguments.
  2039. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  2040. void *InsertPos = nullptr;
  2041. FunctionDecl *SpecFunc
  2042. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  2043. // If we already have a function template specialization, return it.
  2044. if (SpecFunc)
  2045. return SpecFunc;
  2046. }
  2047. bool isFriend;
  2048. if (FunctionTemplate)
  2049. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  2050. else
  2051. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  2052. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  2053. !(isa<Decl>(Owner) &&
  2054. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  2055. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  2056. // Instantiate enclosing template arguments for friends.
  2057. SmallVector<TemplateParameterList *, 4> TempParamLists;
  2058. unsigned NumTempParamLists = 0;
  2059. if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
  2060. TempParamLists.resize(NumTempParamLists);
  2061. for (unsigned I = 0; I != NumTempParamLists; ++I) {
  2062. TemplateParameterList *TempParams = D->getTemplateParameterList(I);
  2063. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  2064. if (!InstParams)
  2065. return nullptr;
  2066. TempParamLists[I] = InstParams;
  2067. }
  2068. }
  2069. ExplicitSpecifier InstantiatedExplicitSpecifier =
  2070. instantiateExplicitSpecifier(SemaRef, TemplateArgs,
  2071. ExplicitSpecifier::getFromDecl(D), D);
  2072. if (InstantiatedExplicitSpecifier.isInvalid())
  2073. return nullptr;
  2074. // Implicit destructors/constructors created for local classes in
  2075. // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
  2076. // Unfortunately there isn't enough context in those functions to
  2077. // conditionally populate the TSI without breaking non-template related use
  2078. // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
  2079. // a proper transformation.
  2080. if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
  2081. !D->getTypeSourceInfo() &&
  2082. isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
  2083. TypeSourceInfo *TSI =
  2084. SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
  2085. D->setTypeSourceInfo(TSI);
  2086. }
  2087. SmallVector<ParmVarDecl *, 4> Params;
  2088. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  2089. if (!TInfo)
  2090. return nullptr;
  2091. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  2092. if (TemplateParams && TemplateParams->size()) {
  2093. auto *LastParam =
  2094. dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
  2095. if (LastParam && LastParam->isImplicit() &&
  2096. LastParam->hasTypeConstraint()) {
  2097. // In abbreviated templates, the type-constraints of invented template
  2098. // type parameters are instantiated with the function type, invalidating
  2099. // the TemplateParameterList which relied on the template type parameter
  2100. // not having a type constraint. Recreate the TemplateParameterList with
  2101. // the updated parameter list.
  2102. TemplateParams = TemplateParameterList::Create(
  2103. SemaRef.Context, TemplateParams->getTemplateLoc(),
  2104. TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
  2105. TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
  2106. }
  2107. }
  2108. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  2109. if (QualifierLoc) {
  2110. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  2111. TemplateArgs);
  2112. if (!QualifierLoc)
  2113. return nullptr;
  2114. }
  2115. DeclContext *DC = Owner;
  2116. if (isFriend) {
  2117. if (QualifierLoc) {
  2118. CXXScopeSpec SS;
  2119. SS.Adopt(QualifierLoc);
  2120. DC = SemaRef.computeDeclContext(SS);
  2121. if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
  2122. return nullptr;
  2123. } else {
  2124. DC = SemaRef.FindInstantiatedContext(D->getLocation(),
  2125. D->getDeclContext(),
  2126. TemplateArgs);
  2127. }
  2128. if (!DC) return nullptr;
  2129. }
  2130. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  2131. Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
  2132. DeclarationNameInfo NameInfo
  2133. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  2134. if (FunctionRewriteKind != RewriteKind::None)
  2135. adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
  2136. // Build the instantiated method declaration.
  2137. CXXMethodDecl *Method = nullptr;
  2138. SourceLocation StartLoc = D->getInnerLocStart();
  2139. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  2140. Method = CXXConstructorDecl::Create(
  2141. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
  2142. InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
  2143. Constructor->isInlineSpecified(), false,
  2144. Constructor->getConstexprKind(), InheritedConstructor(),
  2145. TrailingRequiresClause);
  2146. Method->setRangeEnd(Constructor->getEndLoc());
  2147. if (Constructor->isDefaultConstructor() ||
  2148. Constructor->isCopyOrMoveConstructor())
  2149. Method->setIneligibleOrNotSelected(true);
  2150. } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
  2151. Method = CXXDestructorDecl::Create(
  2152. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
  2153. Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
  2154. Destructor->getConstexprKind(), TrailingRequiresClause);
  2155. Method->setIneligibleOrNotSelected(true);
  2156. Method->setRangeEnd(Destructor->getEndLoc());
  2157. Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
  2158. SemaRef.Context.getCanonicalType(
  2159. SemaRef.Context.getTypeDeclType(Record))));
  2160. } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  2161. Method = CXXConversionDecl::Create(
  2162. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
  2163. Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
  2164. InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
  2165. Conversion->getEndLoc(), TrailingRequiresClause);
  2166. } else {
  2167. StorageClass SC = D->isStatic() ? SC_Static : SC_None;
  2168. Method = CXXMethodDecl::Create(
  2169. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
  2170. D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
  2171. D->getEndLoc(), TrailingRequiresClause);
  2172. if (D->isMoveAssignmentOperator() || D->isCopyAssignmentOperator())
  2173. Method->setIneligibleOrNotSelected(true);
  2174. }
  2175. if (D->isInlined())
  2176. Method->setImplicitlyInline();
  2177. if (QualifierLoc)
  2178. Method->setQualifierInfo(QualifierLoc);
  2179. if (TemplateParams) {
  2180. // Our resulting instantiation is actually a function template, since we
  2181. // are substituting only the outer template parameters. For example, given
  2182. //
  2183. // template<typename T>
  2184. // struct X {
  2185. // template<typename U> void f(T, U);
  2186. // };
  2187. //
  2188. // X<int> x;
  2189. //
  2190. // We are instantiating the member template "f" within X<int>, which means
  2191. // substituting int for T, but leaving "f" as a member function template.
  2192. // Build the function template itself.
  2193. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
  2194. Method->getLocation(),
  2195. Method->getDeclName(),
  2196. TemplateParams, Method);
  2197. if (isFriend) {
  2198. FunctionTemplate->setLexicalDeclContext(Owner);
  2199. FunctionTemplate->setObjectOfFriendDecl();
  2200. } else if (D->isOutOfLine())
  2201. FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
  2202. Method->setDescribedFunctionTemplate(FunctionTemplate);
  2203. } else if (FunctionTemplate) {
  2204. // Record this function template specialization.
  2205. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  2206. Method->setFunctionTemplateSpecialization(FunctionTemplate,
  2207. TemplateArgumentList::CreateCopy(SemaRef.Context,
  2208. Innermost),
  2209. /*InsertPos=*/nullptr);
  2210. } else if (!isFriend) {
  2211. // Record that this is an instantiation of a member function.
  2212. Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  2213. }
  2214. // If we are instantiating a member function defined
  2215. // out-of-line, the instantiation will have the same lexical
  2216. // context (which will be a namespace scope) as the template.
  2217. if (isFriend) {
  2218. if (NumTempParamLists)
  2219. Method->setTemplateParameterListsInfo(
  2220. SemaRef.Context,
  2221. llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
  2222. Method->setLexicalDeclContext(Owner);
  2223. Method->setObjectOfFriendDecl();
  2224. } else if (D->isOutOfLine())
  2225. Method->setLexicalDeclContext(D->getLexicalDeclContext());
  2226. // Attach the parameters
  2227. for (unsigned P = 0; P < Params.size(); ++P)
  2228. Params[P]->setOwningFunction(Method);
  2229. Method->setParams(Params);
  2230. if (InitMethodInstantiation(Method, D))
  2231. Method->setInvalidDecl();
  2232. LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
  2233. Sema::ForExternalRedeclaration);
  2234. bool IsExplicitSpecialization = false;
  2235. // If the name of this function was written as a template-id, instantiate
  2236. // the explicit template arguments.
  2237. if (DependentFunctionTemplateSpecializationInfo *Info
  2238. = D->getDependentSpecializationInfo()) {
  2239. assert(isFriend && "non-friend has dependent specialization info?");
  2240. // Instantiate the explicit template arguments.
  2241. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  2242. Info->getRAngleLoc());
  2243. if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
  2244. ExplicitArgs))
  2245. return nullptr;
  2246. // Map the candidate templates to their instantiations.
  2247. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  2248. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  2249. Info->getTemplate(I),
  2250. TemplateArgs);
  2251. if (!Temp) return nullptr;
  2252. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  2253. }
  2254. if (SemaRef.CheckFunctionTemplateSpecialization(Method,
  2255. &ExplicitArgs,
  2256. Previous))
  2257. Method->setInvalidDecl();
  2258. IsExplicitSpecialization = true;
  2259. } else if (const ASTTemplateArgumentListInfo *Info =
  2260. ClassScopeSpecializationArgs.value_or(
  2261. D->getTemplateSpecializationArgsAsWritten())) {
  2262. SemaRef.LookupQualifiedName(Previous, DC);
  2263. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  2264. Info->getRAngleLoc());
  2265. if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
  2266. ExplicitArgs))
  2267. return nullptr;
  2268. if (SemaRef.CheckFunctionTemplateSpecialization(Method,
  2269. &ExplicitArgs,
  2270. Previous))
  2271. Method->setInvalidDecl();
  2272. IsExplicitSpecialization = true;
  2273. } else if (ClassScopeSpecializationArgs) {
  2274. // Class-scope explicit specialization written without explicit template
  2275. // arguments.
  2276. SemaRef.LookupQualifiedName(Previous, DC);
  2277. if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
  2278. Method->setInvalidDecl();
  2279. IsExplicitSpecialization = true;
  2280. } else if (!FunctionTemplate || TemplateParams || isFriend) {
  2281. SemaRef.LookupQualifiedName(Previous, Record);
  2282. // In C++, the previous declaration we find might be a tag type
  2283. // (class or enum). In this case, the new declaration will hide the
  2284. // tag type. Note that this does not apply if we're declaring a
  2285. // typedef (C++ [dcl.typedef]p4).
  2286. if (Previous.isSingleTagDecl())
  2287. Previous.clear();
  2288. }
  2289. // Per [temp.inst], default arguments in member functions of local classes
  2290. // are instantiated along with the member function declaration. For example:
  2291. //
  2292. // template<typename T>
  2293. // void ft() {
  2294. // struct lc {
  2295. // int operator()(int p = []{ return T::value; }());
  2296. // };
  2297. // }
  2298. // template void ft<int>(); // error: type 'int' cannot be used prior
  2299. // to '::'because it has no members
  2300. //
  2301. // The error is issued during instantiation of ft<int>()::lc::operator()
  2302. // because substitution into the default argument fails; the default argument
  2303. // is instantiated even though it is never used.
  2304. if (D->isInLocalScopeForInstantiation()) {
  2305. for (unsigned P = 0; P < Params.size(); ++P) {
  2306. if (!Params[P]->hasDefaultArg())
  2307. continue;
  2308. if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
  2309. // If substitution fails, the default argument is set to a
  2310. // RecoveryExpr that wraps the uninstantiated default argument so
  2311. // that downstream diagnostics are omitted.
  2312. Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
  2313. ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
  2314. UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
  2315. { UninstExpr }, UninstExpr->getType());
  2316. if (ErrorResult.isUsable())
  2317. Params[P]->setDefaultArg(ErrorResult.get());
  2318. }
  2319. }
  2320. }
  2321. SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
  2322. IsExplicitSpecialization,
  2323. Method->isThisDeclarationADefinition());
  2324. if (D->isPure())
  2325. SemaRef.CheckPureMethod(Method, SourceRange());
  2326. // Propagate access. For a non-friend declaration, the access is
  2327. // whatever we're propagating from. For a friend, it should be the
  2328. // previous declaration we just found.
  2329. if (isFriend && Method->getPreviousDecl())
  2330. Method->setAccess(Method->getPreviousDecl()->getAccess());
  2331. else
  2332. Method->setAccess(D->getAccess());
  2333. if (FunctionTemplate)
  2334. FunctionTemplate->setAccess(Method->getAccess());
  2335. SemaRef.CheckOverrideControl(Method);
  2336. // If a function is defined as defaulted or deleted, mark it as such now.
  2337. if (D->isExplicitlyDefaulted()) {
  2338. if (SubstDefaultedFunction(Method, D))
  2339. return nullptr;
  2340. }
  2341. if (D->isDeletedAsWritten())
  2342. SemaRef.SetDeclDeleted(Method, Method->getLocation());
  2343. // If this is an explicit specialization, mark the implicitly-instantiated
  2344. // template specialization as being an explicit specialization too.
  2345. // FIXME: Is this necessary?
  2346. if (IsExplicitSpecialization && !isFriend)
  2347. SemaRef.CompleteMemberSpecialization(Method, Previous);
  2348. // If there's a function template, let our caller handle it.
  2349. if (FunctionTemplate) {
  2350. // do nothing
  2351. // Don't hide a (potentially) valid declaration with an invalid one.
  2352. } else if (Method->isInvalidDecl() && !Previous.empty()) {
  2353. // do nothing
  2354. // Otherwise, check access to friends and make them visible.
  2355. } else if (isFriend) {
  2356. // We only need to re-check access for methods which we didn't
  2357. // manage to match during parsing.
  2358. if (!D->getPreviousDecl())
  2359. SemaRef.CheckFriendAccess(Method);
  2360. Record->makeDeclVisibleInContext(Method);
  2361. // Otherwise, add the declaration. We don't need to do this for
  2362. // class-scope specializations because we'll have matched them with
  2363. // the appropriate template.
  2364. } else {
  2365. Owner->addDecl(Method);
  2366. }
  2367. // PR17480: Honor the used attribute to instantiate member function
  2368. // definitions
  2369. if (Method->hasAttr<UsedAttr>()) {
  2370. if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
  2371. SourceLocation Loc;
  2372. if (const MemberSpecializationInfo *MSInfo =
  2373. A->getMemberSpecializationInfo())
  2374. Loc = MSInfo->getPointOfInstantiation();
  2375. else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
  2376. Loc = Spec->getPointOfInstantiation();
  2377. SemaRef.MarkFunctionReferenced(Loc, Method);
  2378. }
  2379. }
  2380. return Method;
  2381. }
  2382. Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  2383. return VisitCXXMethodDecl(D);
  2384. }
  2385. Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  2386. return VisitCXXMethodDecl(D);
  2387. }
  2388. Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
  2389. return VisitCXXMethodDecl(D);
  2390. }
  2391. Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
  2392. return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
  2393. std::nullopt,
  2394. /*ExpectParameterPack=*/false);
  2395. }
  2396. Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
  2397. TemplateTypeParmDecl *D) {
  2398. assert(D->getTypeForDecl()->isTemplateTypeParmType());
  2399. std::optional<unsigned> NumExpanded;
  2400. if (const TypeConstraint *TC = D->getTypeConstraint()) {
  2401. if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
  2402. assert(TC->getTemplateArgsAsWritten() &&
  2403. "type parameter can only be an expansion when explicit arguments "
  2404. "are specified");
  2405. // The template type parameter pack's type is a pack expansion of types.
  2406. // Determine whether we need to expand this parameter pack into separate
  2407. // types.
  2408. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2409. for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
  2410. SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
  2411. // Determine whether the set of unexpanded parameter packs can and should
  2412. // be expanded.
  2413. bool Expand = true;
  2414. bool RetainExpansion = false;
  2415. if (SemaRef.CheckParameterPacksForExpansion(
  2416. cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
  2417. ->getEllipsisLoc(),
  2418. SourceRange(TC->getConceptNameLoc(),
  2419. TC->hasExplicitTemplateArgs() ?
  2420. TC->getTemplateArgsAsWritten()->getRAngleLoc() :
  2421. TC->getConceptNameInfo().getEndLoc()),
  2422. Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
  2423. return nullptr;
  2424. }
  2425. }
  2426. TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
  2427. SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
  2428. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
  2429. D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
  2430. D->hasTypeConstraint(), NumExpanded);
  2431. Inst->setAccess(AS_public);
  2432. Inst->setImplicit(D->isImplicit());
  2433. if (auto *TC = D->getTypeConstraint()) {
  2434. if (!D->isImplicit()) {
  2435. // Invented template parameter type constraints will be instantiated
  2436. // with the corresponding auto-typed parameter as it might reference
  2437. // other parameters.
  2438. if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
  2439. EvaluateConstraints))
  2440. return nullptr;
  2441. }
  2442. }
  2443. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  2444. TypeSourceInfo *InstantiatedDefaultArg =
  2445. SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
  2446. D->getDefaultArgumentLoc(), D->getDeclName());
  2447. if (InstantiatedDefaultArg)
  2448. Inst->setDefaultArgument(InstantiatedDefaultArg);
  2449. }
  2450. // Introduce this template parameter's instantiation into the instantiation
  2451. // scope.
  2452. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  2453. return Inst;
  2454. }
  2455. Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
  2456. NonTypeTemplateParmDecl *D) {
  2457. // Substitute into the type of the non-type template parameter.
  2458. TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
  2459. SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
  2460. SmallVector<QualType, 4> ExpandedParameterPackTypes;
  2461. bool IsExpandedParameterPack = false;
  2462. TypeSourceInfo *DI;
  2463. QualType T;
  2464. bool Invalid = false;
  2465. if (D->isExpandedParameterPack()) {
  2466. // The non-type template parameter pack is an already-expanded pack
  2467. // expansion of types. Substitute into each of the expanded types.
  2468. ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
  2469. ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
  2470. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  2471. TypeSourceInfo *NewDI =
  2472. SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
  2473. D->getLocation(), D->getDeclName());
  2474. if (!NewDI)
  2475. return nullptr;
  2476. QualType NewT =
  2477. SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
  2478. if (NewT.isNull())
  2479. return nullptr;
  2480. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  2481. ExpandedParameterPackTypes.push_back(NewT);
  2482. }
  2483. IsExpandedParameterPack = true;
  2484. DI = D->getTypeSourceInfo();
  2485. T = DI->getType();
  2486. } else if (D->isPackExpansion()) {
  2487. // The non-type template parameter pack's type is a pack expansion of types.
  2488. // Determine whether we need to expand this parameter pack into separate
  2489. // types.
  2490. PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
  2491. TypeLoc Pattern = Expansion.getPatternLoc();
  2492. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2493. SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  2494. // Determine whether the set of unexpanded parameter packs can and should
  2495. // be expanded.
  2496. bool Expand = true;
  2497. bool RetainExpansion = false;
  2498. std::optional<unsigned> OrigNumExpansions =
  2499. Expansion.getTypePtr()->getNumExpansions();
  2500. std::optional<unsigned> NumExpansions = OrigNumExpansions;
  2501. if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
  2502. Pattern.getSourceRange(),
  2503. Unexpanded,
  2504. TemplateArgs,
  2505. Expand, RetainExpansion,
  2506. NumExpansions))
  2507. return nullptr;
  2508. if (Expand) {
  2509. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2510. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2511. TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
  2512. D->getLocation(),
  2513. D->getDeclName());
  2514. if (!NewDI)
  2515. return nullptr;
  2516. QualType NewT =
  2517. SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
  2518. if (NewT.isNull())
  2519. return nullptr;
  2520. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  2521. ExpandedParameterPackTypes.push_back(NewT);
  2522. }
  2523. // Note that we have an expanded parameter pack. The "type" of this
  2524. // expanded parameter pack is the original expansion type, but callers
  2525. // will end up using the expanded parameter pack types for type-checking.
  2526. IsExpandedParameterPack = true;
  2527. DI = D->getTypeSourceInfo();
  2528. T = DI->getType();
  2529. } else {
  2530. // We cannot fully expand the pack expansion now, so substitute into the
  2531. // pattern and create a new pack expansion type.
  2532. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2533. TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
  2534. D->getLocation(),
  2535. D->getDeclName());
  2536. if (!NewPattern)
  2537. return nullptr;
  2538. SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
  2539. DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
  2540. NumExpansions);
  2541. if (!DI)
  2542. return nullptr;
  2543. T = DI->getType();
  2544. }
  2545. } else {
  2546. // Simple case: substitution into a parameter that is not a parameter pack.
  2547. DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  2548. D->getLocation(), D->getDeclName());
  2549. if (!DI)
  2550. return nullptr;
  2551. // Check that this type is acceptable for a non-type template parameter.
  2552. T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
  2553. if (T.isNull()) {
  2554. T = SemaRef.Context.IntTy;
  2555. Invalid = true;
  2556. }
  2557. }
  2558. NonTypeTemplateParmDecl *Param;
  2559. if (IsExpandedParameterPack)
  2560. Param = NonTypeTemplateParmDecl::Create(
  2561. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2562. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2563. D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
  2564. ExpandedParameterPackTypesAsWritten);
  2565. else
  2566. Param = NonTypeTemplateParmDecl::Create(
  2567. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2568. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2569. D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
  2570. if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
  2571. if (AutoLoc.isConstrained())
  2572. if (SemaRef.AttachTypeConstraint(
  2573. AutoLoc, Param,
  2574. IsExpandedParameterPack
  2575. ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
  2576. .getEllipsisLoc()
  2577. : SourceLocation()))
  2578. Invalid = true;
  2579. Param->setAccess(AS_public);
  2580. Param->setImplicit(D->isImplicit());
  2581. if (Invalid)
  2582. Param->setInvalidDecl();
  2583. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  2584. EnterExpressionEvaluationContext ConstantEvaluated(
  2585. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  2586. ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
  2587. if (!Value.isInvalid())
  2588. Param->setDefaultArgument(Value.get());
  2589. }
  2590. // Introduce this template parameter's instantiation into the instantiation
  2591. // scope.
  2592. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  2593. return Param;
  2594. }
  2595. static void collectUnexpandedParameterPacks(
  2596. Sema &S,
  2597. TemplateParameterList *Params,
  2598. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  2599. for (const auto &P : *Params) {
  2600. if (P->isTemplateParameterPack())
  2601. continue;
  2602. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
  2603. S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
  2604. Unexpanded);
  2605. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
  2606. collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
  2607. Unexpanded);
  2608. }
  2609. }
  2610. Decl *
  2611. TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
  2612. TemplateTemplateParmDecl *D) {
  2613. // Instantiate the template parameter list of the template template parameter.
  2614. TemplateParameterList *TempParams = D->getTemplateParameters();
  2615. TemplateParameterList *InstParams;
  2616. SmallVector<TemplateParameterList*, 8> ExpandedParams;
  2617. bool IsExpandedParameterPack = false;
  2618. if (D->isExpandedParameterPack()) {
  2619. // The template template parameter pack is an already-expanded pack
  2620. // expansion of template parameters. Substitute into each of the expanded
  2621. // parameters.
  2622. ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
  2623. for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
  2624. I != N; ++I) {
  2625. LocalInstantiationScope Scope(SemaRef);
  2626. TemplateParameterList *Expansion =
  2627. SubstTemplateParams(D->getExpansionTemplateParameters(I));
  2628. if (!Expansion)
  2629. return nullptr;
  2630. ExpandedParams.push_back(Expansion);
  2631. }
  2632. IsExpandedParameterPack = true;
  2633. InstParams = TempParams;
  2634. } else if (D->isPackExpansion()) {
  2635. // The template template parameter pack expands to a pack of template
  2636. // template parameters. Determine whether we need to expand this parameter
  2637. // pack into separate parameters.
  2638. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2639. collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
  2640. Unexpanded);
  2641. // Determine whether the set of unexpanded parameter packs can and should
  2642. // be expanded.
  2643. bool Expand = true;
  2644. bool RetainExpansion = false;
  2645. std::optional<unsigned> NumExpansions;
  2646. if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
  2647. TempParams->getSourceRange(),
  2648. Unexpanded,
  2649. TemplateArgs,
  2650. Expand, RetainExpansion,
  2651. NumExpansions))
  2652. return nullptr;
  2653. if (Expand) {
  2654. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2655. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2656. LocalInstantiationScope Scope(SemaRef);
  2657. TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
  2658. if (!Expansion)
  2659. return nullptr;
  2660. ExpandedParams.push_back(Expansion);
  2661. }
  2662. // Note that we have an expanded parameter pack. The "type" of this
  2663. // expanded parameter pack is the original expansion type, but callers
  2664. // will end up using the expanded parameter pack types for type-checking.
  2665. IsExpandedParameterPack = true;
  2666. InstParams = TempParams;
  2667. } else {
  2668. // We cannot fully expand the pack expansion now, so just substitute
  2669. // into the pattern.
  2670. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2671. LocalInstantiationScope Scope(SemaRef);
  2672. InstParams = SubstTemplateParams(TempParams);
  2673. if (!InstParams)
  2674. return nullptr;
  2675. }
  2676. } else {
  2677. // Perform the actual substitution of template parameters within a new,
  2678. // local instantiation scope.
  2679. LocalInstantiationScope Scope(SemaRef);
  2680. InstParams = SubstTemplateParams(TempParams);
  2681. if (!InstParams)
  2682. return nullptr;
  2683. }
  2684. // Build the template template parameter.
  2685. TemplateTemplateParmDecl *Param;
  2686. if (IsExpandedParameterPack)
  2687. Param = TemplateTemplateParmDecl::Create(
  2688. SemaRef.Context, Owner, D->getLocation(),
  2689. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2690. D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
  2691. else
  2692. Param = TemplateTemplateParmDecl::Create(
  2693. SemaRef.Context, Owner, D->getLocation(),
  2694. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2695. D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
  2696. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  2697. NestedNameSpecifierLoc QualifierLoc =
  2698. D->getDefaultArgument().getTemplateQualifierLoc();
  2699. QualifierLoc =
  2700. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
  2701. TemplateName TName = SemaRef.SubstTemplateName(
  2702. QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
  2703. D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
  2704. if (!TName.isNull())
  2705. Param->setDefaultArgument(
  2706. SemaRef.Context,
  2707. TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
  2708. D->getDefaultArgument().getTemplateQualifierLoc(),
  2709. D->getDefaultArgument().getTemplateNameLoc()));
  2710. }
  2711. Param->setAccess(AS_public);
  2712. Param->setImplicit(D->isImplicit());
  2713. // Introduce this template parameter's instantiation into the instantiation
  2714. // scope.
  2715. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  2716. return Param;
  2717. }
  2718. Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  2719. // Using directives are never dependent (and never contain any types or
  2720. // expressions), so they require no explicit instantiation work.
  2721. UsingDirectiveDecl *Inst
  2722. = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  2723. D->getNamespaceKeyLocation(),
  2724. D->getQualifierLoc(),
  2725. D->getIdentLocation(),
  2726. D->getNominatedNamespace(),
  2727. D->getCommonAncestor());
  2728. // Add the using directive to its declaration context
  2729. // only if this is not a function or method.
  2730. if (!Owner->isFunctionOrMethod())
  2731. Owner->addDecl(Inst);
  2732. return Inst;
  2733. }
  2734. Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
  2735. BaseUsingDecl *Inst,
  2736. LookupResult *Lookup) {
  2737. bool isFunctionScope = Owner->isFunctionOrMethod();
  2738. for (auto *Shadow : D->shadows()) {
  2739. // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
  2740. // reconstruct it in the case where it matters. Hm, can we extract it from
  2741. // the DeclSpec when parsing and save it in the UsingDecl itself?
  2742. NamedDecl *OldTarget = Shadow->getTargetDecl();
  2743. if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
  2744. if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
  2745. OldTarget = BaseShadow;
  2746. NamedDecl *InstTarget = nullptr;
  2747. if (auto *EmptyD =
  2748. dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
  2749. InstTarget = UnresolvedUsingIfExistsDecl::Create(
  2750. SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
  2751. } else {
  2752. InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
  2753. Shadow->getLocation(), OldTarget, TemplateArgs));
  2754. }
  2755. if (!InstTarget)
  2756. return nullptr;
  2757. UsingShadowDecl *PrevDecl = nullptr;
  2758. if (Lookup &&
  2759. SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
  2760. continue;
  2761. if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
  2762. PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
  2763. Shadow->getLocation(), OldPrev, TemplateArgs));
  2764. UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
  2765. /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
  2766. SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
  2767. if (isFunctionScope)
  2768. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
  2769. }
  2770. return Inst;
  2771. }
  2772. Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
  2773. // The nested name specifier may be dependent, for example
  2774. // template <typename T> struct t {
  2775. // struct s1 { T f1(); };
  2776. // struct s2 : s1 { using s1::f1; };
  2777. // };
  2778. // template struct t<int>;
  2779. // Here, in using s1::f1, s1 refers to t<T>::s1;
  2780. // we need to substitute for t<int>::s1.
  2781. NestedNameSpecifierLoc QualifierLoc
  2782. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2783. TemplateArgs);
  2784. if (!QualifierLoc)
  2785. return nullptr;
  2786. // For an inheriting constructor declaration, the name of the using
  2787. // declaration is the name of a constructor in this class, not in the
  2788. // base class.
  2789. DeclarationNameInfo NameInfo = D->getNameInfo();
  2790. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
  2791. if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
  2792. NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
  2793. SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
  2794. // We only need to do redeclaration lookups if we're in a class scope (in
  2795. // fact, it's not really even possible in non-class scopes).
  2796. bool CheckRedeclaration = Owner->isRecord();
  2797. LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
  2798. Sema::ForVisibleRedeclaration);
  2799. UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
  2800. D->getUsingLoc(),
  2801. QualifierLoc,
  2802. NameInfo,
  2803. D->hasTypename());
  2804. CXXScopeSpec SS;
  2805. SS.Adopt(QualifierLoc);
  2806. if (CheckRedeclaration) {
  2807. Prev.setHideTags(false);
  2808. SemaRef.LookupQualifiedName(Prev, Owner);
  2809. // Check for invalid redeclarations.
  2810. if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
  2811. D->hasTypename(), SS,
  2812. D->getLocation(), Prev))
  2813. NewUD->setInvalidDecl();
  2814. }
  2815. if (!NewUD->isInvalidDecl() &&
  2816. SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
  2817. NameInfo, D->getLocation(), nullptr, D))
  2818. NewUD->setInvalidDecl();
  2819. SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
  2820. NewUD->setAccess(D->getAccess());
  2821. Owner->addDecl(NewUD);
  2822. // Don't process the shadow decls for an invalid decl.
  2823. if (NewUD->isInvalidDecl())
  2824. return NewUD;
  2825. // If the using scope was dependent, or we had dependent bases, we need to
  2826. // recheck the inheritance
  2827. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
  2828. SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
  2829. return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
  2830. }
  2831. Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
  2832. // Cannot be a dependent type, but still could be an instantiation
  2833. EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
  2834. D->getLocation(), D->getEnumDecl(), TemplateArgs));
  2835. if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
  2836. return nullptr;
  2837. TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
  2838. D->getLocation(), D->getDeclName());
  2839. UsingEnumDecl *NewUD =
  2840. UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
  2841. D->getEnumLoc(), D->getLocation(), TSI);
  2842. SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
  2843. NewUD->setAccess(D->getAccess());
  2844. Owner->addDecl(NewUD);
  2845. // Don't process the shadow decls for an invalid decl.
  2846. if (NewUD->isInvalidDecl())
  2847. return NewUD;
  2848. // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
  2849. // cannot be dependent, and will therefore have been checked during template
  2850. // definition.
  2851. return VisitBaseUsingDecls(D, NewUD, nullptr);
  2852. }
  2853. Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
  2854. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2855. return nullptr;
  2856. }
  2857. Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
  2858. ConstructorUsingShadowDecl *D) {
  2859. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2860. return nullptr;
  2861. }
  2862. template <typename T>
  2863. Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
  2864. T *D, bool InstantiatingPackElement) {
  2865. // If this is a pack expansion, expand it now.
  2866. if (D->isPackExpansion() && !InstantiatingPackElement) {
  2867. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2868. SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
  2869. SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
  2870. // Determine whether the set of unexpanded parameter packs can and should
  2871. // be expanded.
  2872. bool Expand = true;
  2873. bool RetainExpansion = false;
  2874. std::optional<unsigned> NumExpansions;
  2875. if (SemaRef.CheckParameterPacksForExpansion(
  2876. D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
  2877. Expand, RetainExpansion, NumExpansions))
  2878. return nullptr;
  2879. // This declaration cannot appear within a function template signature,
  2880. // so we can't have a partial argument list for a parameter pack.
  2881. assert(!RetainExpansion &&
  2882. "should never need to retain an expansion for UsingPackDecl");
  2883. if (!Expand) {
  2884. // We cannot fully expand the pack expansion now, so substitute into the
  2885. // pattern and create a new pack expansion.
  2886. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2887. return instantiateUnresolvedUsingDecl(D, true);
  2888. }
  2889. // Within a function, we don't have any normal way to check for conflicts
  2890. // between shadow declarations from different using declarations in the
  2891. // same pack expansion, but this is always ill-formed because all expansions
  2892. // must produce (conflicting) enumerators.
  2893. //
  2894. // Sadly we can't just reject this in the template definition because it
  2895. // could be valid if the pack is empty or has exactly one expansion.
  2896. if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
  2897. SemaRef.Diag(D->getEllipsisLoc(),
  2898. diag::err_using_decl_redeclaration_expansion);
  2899. return nullptr;
  2900. }
  2901. // Instantiate the slices of this pack and build a UsingPackDecl.
  2902. SmallVector<NamedDecl*, 8> Expansions;
  2903. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2904. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2905. Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
  2906. if (!Slice)
  2907. return nullptr;
  2908. // Note that we can still get unresolved using declarations here, if we
  2909. // had arguments for all packs but the pattern also contained other
  2910. // template arguments (this only happens during partial substitution, eg
  2911. // into the body of a generic lambda in a function template).
  2912. Expansions.push_back(cast<NamedDecl>(Slice));
  2913. }
  2914. auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
  2915. if (isDeclWithinFunction(D))
  2916. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
  2917. return NewD;
  2918. }
  2919. UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
  2920. SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
  2921. NestedNameSpecifierLoc QualifierLoc
  2922. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2923. TemplateArgs);
  2924. if (!QualifierLoc)
  2925. return nullptr;
  2926. CXXScopeSpec SS;
  2927. SS.Adopt(QualifierLoc);
  2928. DeclarationNameInfo NameInfo
  2929. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  2930. // Produce a pack expansion only if we're not instantiating a particular
  2931. // slice of a pack expansion.
  2932. bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
  2933. SemaRef.ArgumentPackSubstitutionIndex != -1;
  2934. SourceLocation EllipsisLoc =
  2935. InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
  2936. bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
  2937. NamedDecl *UD = SemaRef.BuildUsingDeclaration(
  2938. /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
  2939. /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
  2940. ParsedAttributesView(),
  2941. /*IsInstantiation*/ true, IsUsingIfExists);
  2942. if (UD) {
  2943. SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
  2944. SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
  2945. }
  2946. return UD;
  2947. }
  2948. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
  2949. UnresolvedUsingTypenameDecl *D) {
  2950. return instantiateUnresolvedUsingDecl(D);
  2951. }
  2952. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
  2953. UnresolvedUsingValueDecl *D) {
  2954. return instantiateUnresolvedUsingDecl(D);
  2955. }
  2956. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
  2957. UnresolvedUsingIfExistsDecl *D) {
  2958. llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
  2959. }
  2960. Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
  2961. SmallVector<NamedDecl*, 8> Expansions;
  2962. for (auto *UD : D->expansions()) {
  2963. if (NamedDecl *NewUD =
  2964. SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
  2965. Expansions.push_back(NewUD);
  2966. else
  2967. return nullptr;
  2968. }
  2969. auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
  2970. if (isDeclWithinFunction(D))
  2971. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
  2972. return NewD;
  2973. }
  2974. Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
  2975. ClassScopeFunctionSpecializationDecl *Decl) {
  2976. CXXMethodDecl *OldFD = Decl->getSpecialization();
  2977. return cast_or_null<CXXMethodDecl>(
  2978. VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
  2979. }
  2980. Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
  2981. OMPThreadPrivateDecl *D) {
  2982. SmallVector<Expr *, 5> Vars;
  2983. for (auto *I : D->varlists()) {
  2984. Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
  2985. assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
  2986. Vars.push_back(Var);
  2987. }
  2988. OMPThreadPrivateDecl *TD =
  2989. SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
  2990. TD->setAccess(AS_public);
  2991. Owner->addDecl(TD);
  2992. return TD;
  2993. }
  2994. Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
  2995. SmallVector<Expr *, 5> Vars;
  2996. for (auto *I : D->varlists()) {
  2997. Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
  2998. assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
  2999. Vars.push_back(Var);
  3000. }
  3001. SmallVector<OMPClause *, 4> Clauses;
  3002. // Copy map clauses from the original mapper.
  3003. for (OMPClause *C : D->clauselists()) {
  3004. OMPClause *IC = nullptr;
  3005. if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
  3006. ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
  3007. if (!NewE.isUsable())
  3008. continue;
  3009. IC = SemaRef.ActOnOpenMPAllocatorClause(
  3010. NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
  3011. } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
  3012. ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
  3013. if (!NewE.isUsable())
  3014. continue;
  3015. IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
  3016. AC->getLParenLoc(), AC->getEndLoc());
  3017. // If align clause value ends up being invalid, this can end up null.
  3018. if (!IC)
  3019. continue;
  3020. }
  3021. Clauses.push_back(IC);
  3022. }
  3023. Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
  3024. D->getLocation(), Vars, Clauses, Owner);
  3025. if (Res.get().isNull())
  3026. return nullptr;
  3027. return Res.get().getSingleDecl();
  3028. }
  3029. Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
  3030. llvm_unreachable(
  3031. "Requires directive cannot be instantiated within a dependent context");
  3032. }
  3033. Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
  3034. OMPDeclareReductionDecl *D) {
  3035. // Instantiate type and check if it is allowed.
  3036. const bool RequiresInstantiation =
  3037. D->getType()->isDependentType() ||
  3038. D->getType()->isInstantiationDependentType() ||
  3039. D->getType()->containsUnexpandedParameterPack();
  3040. QualType SubstReductionType;
  3041. if (RequiresInstantiation) {
  3042. SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
  3043. D->getLocation(),
  3044. ParsedType::make(SemaRef.SubstType(
  3045. D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
  3046. } else {
  3047. SubstReductionType = D->getType();
  3048. }
  3049. if (SubstReductionType.isNull())
  3050. return nullptr;
  3051. Expr *Combiner = D->getCombiner();
  3052. Expr *Init = D->getInitializer();
  3053. bool IsCorrect = true;
  3054. // Create instantiated copy.
  3055. std::pair<QualType, SourceLocation> ReductionTypes[] = {
  3056. std::make_pair(SubstReductionType, D->getLocation())};
  3057. auto *PrevDeclInScope = D->getPrevDeclInScope();
  3058. if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
  3059. PrevDeclInScope = cast<OMPDeclareReductionDecl>(
  3060. SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
  3061. ->get<Decl *>());
  3062. }
  3063. auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
  3064. /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
  3065. PrevDeclInScope);
  3066. auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
  3067. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
  3068. Expr *SubstCombiner = nullptr;
  3069. Expr *SubstInitializer = nullptr;
  3070. // Combiners instantiation sequence.
  3071. if (Combiner) {
  3072. SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
  3073. /*S=*/nullptr, NewDRD);
  3074. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  3075. cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
  3076. cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
  3077. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  3078. cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
  3079. cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
  3080. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
  3081. Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
  3082. ThisContext);
  3083. SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
  3084. SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
  3085. }
  3086. // Initializers instantiation sequence.
  3087. if (Init) {
  3088. VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
  3089. /*S=*/nullptr, NewDRD);
  3090. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  3091. cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
  3092. cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
  3093. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  3094. cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
  3095. cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
  3096. if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
  3097. SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
  3098. } else {
  3099. auto *OldPrivParm =
  3100. cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
  3101. IsCorrect = IsCorrect && OldPrivParm->hasInit();
  3102. if (IsCorrect)
  3103. SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
  3104. TemplateArgs);
  3105. }
  3106. SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
  3107. OmpPrivParm);
  3108. }
  3109. IsCorrect = IsCorrect && SubstCombiner &&
  3110. (!Init ||
  3111. (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
  3112. SubstInitializer) ||
  3113. (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
  3114. !SubstInitializer));
  3115. (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
  3116. /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
  3117. return NewDRD;
  3118. }
  3119. Decl *
  3120. TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
  3121. // Instantiate type and check if it is allowed.
  3122. const bool RequiresInstantiation =
  3123. D->getType()->isDependentType() ||
  3124. D->getType()->isInstantiationDependentType() ||
  3125. D->getType()->containsUnexpandedParameterPack();
  3126. QualType SubstMapperTy;
  3127. DeclarationName VN = D->getVarName();
  3128. if (RequiresInstantiation) {
  3129. SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
  3130. D->getLocation(),
  3131. ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
  3132. D->getLocation(), VN)));
  3133. } else {
  3134. SubstMapperTy = D->getType();
  3135. }
  3136. if (SubstMapperTy.isNull())
  3137. return nullptr;
  3138. // Create an instantiated copy of mapper.
  3139. auto *PrevDeclInScope = D->getPrevDeclInScope();
  3140. if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
  3141. PrevDeclInScope = cast<OMPDeclareMapperDecl>(
  3142. SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
  3143. ->get<Decl *>());
  3144. }
  3145. bool IsCorrect = true;
  3146. SmallVector<OMPClause *, 6> Clauses;
  3147. // Instantiate the mapper variable.
  3148. DeclarationNameInfo DirName;
  3149. SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
  3150. /*S=*/nullptr,
  3151. (*D->clauselist_begin())->getBeginLoc());
  3152. ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
  3153. /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
  3154. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  3155. cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
  3156. cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
  3157. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
  3158. Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
  3159. ThisContext);
  3160. // Instantiate map clauses.
  3161. for (OMPClause *C : D->clauselists()) {
  3162. auto *OldC = cast<OMPMapClause>(C);
  3163. SmallVector<Expr *, 4> NewVars;
  3164. for (Expr *OE : OldC->varlists()) {
  3165. Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
  3166. if (!NE) {
  3167. IsCorrect = false;
  3168. break;
  3169. }
  3170. NewVars.push_back(NE);
  3171. }
  3172. if (!IsCorrect)
  3173. break;
  3174. NestedNameSpecifierLoc NewQualifierLoc =
  3175. SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
  3176. TemplateArgs);
  3177. CXXScopeSpec SS;
  3178. SS.Adopt(NewQualifierLoc);
  3179. DeclarationNameInfo NewNameInfo =
  3180. SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
  3181. OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
  3182. OldC->getEndLoc());
  3183. OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
  3184. OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
  3185. OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
  3186. OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
  3187. NewVars, Locs);
  3188. Clauses.push_back(NewC);
  3189. }
  3190. SemaRef.EndOpenMPDSABlock(nullptr);
  3191. if (!IsCorrect)
  3192. return nullptr;
  3193. Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
  3194. /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
  3195. VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
  3196. Decl *NewDMD = DG.get().getSingleDecl();
  3197. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
  3198. return NewDMD;
  3199. }
  3200. Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
  3201. OMPCapturedExprDecl * /*D*/) {
  3202. llvm_unreachable("Should not be met in templates");
  3203. }
  3204. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
  3205. return VisitFunctionDecl(D, nullptr);
  3206. }
  3207. Decl *
  3208. TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
  3209. Decl *Inst = VisitFunctionDecl(D, nullptr);
  3210. if (Inst && !D->getDescribedFunctionTemplate())
  3211. Owner->addDecl(Inst);
  3212. return Inst;
  3213. }
  3214. Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
  3215. return VisitCXXMethodDecl(D, nullptr);
  3216. }
  3217. Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
  3218. llvm_unreachable("There are only CXXRecordDecls in C++");
  3219. }
  3220. Decl *
  3221. TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
  3222. ClassTemplateSpecializationDecl *D) {
  3223. // As a MS extension, we permit class-scope explicit specialization
  3224. // of member class templates.
  3225. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  3226. assert(ClassTemplate->getDeclContext()->isRecord() &&
  3227. D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  3228. "can only instantiate an explicit specialization "
  3229. "for a member class template");
  3230. // Lookup the already-instantiated declaration in the instantiation
  3231. // of the class template.
  3232. ClassTemplateDecl *InstClassTemplate =
  3233. cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
  3234. D->getLocation(), ClassTemplate, TemplateArgs));
  3235. if (!InstClassTemplate)
  3236. return nullptr;
  3237. // Substitute into the template arguments of the class template explicit
  3238. // specialization.
  3239. TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
  3240. castAs<TemplateSpecializationTypeLoc>();
  3241. TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
  3242. Loc.getRAngleLoc());
  3243. SmallVector<TemplateArgumentLoc, 4> ArgLocs;
  3244. for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
  3245. ArgLocs.push_back(Loc.getArgLoc(I));
  3246. if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
  3247. return nullptr;
  3248. // Check that the template argument list is well-formed for this
  3249. // class template.
  3250. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  3251. if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
  3252. InstTemplateArgs, false,
  3253. SugaredConverted, CanonicalConverted,
  3254. /*UpdateArgsWithConversions=*/true))
  3255. return nullptr;
  3256. // Figure out where to insert this class template explicit specialization
  3257. // in the member template's set of class template explicit specializations.
  3258. void *InsertPos = nullptr;
  3259. ClassTemplateSpecializationDecl *PrevDecl =
  3260. InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
  3261. // Check whether we've already seen a conflicting instantiation of this
  3262. // declaration (for instance, if there was a prior implicit instantiation).
  3263. bool Ignored;
  3264. if (PrevDecl &&
  3265. SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
  3266. D->getSpecializationKind(),
  3267. PrevDecl,
  3268. PrevDecl->getSpecializationKind(),
  3269. PrevDecl->getPointOfInstantiation(),
  3270. Ignored))
  3271. return nullptr;
  3272. // If PrevDecl was a definition and D is also a definition, diagnose.
  3273. // This happens in cases like:
  3274. //
  3275. // template<typename T, typename U>
  3276. // struct Outer {
  3277. // template<typename X> struct Inner;
  3278. // template<> struct Inner<T> {};
  3279. // template<> struct Inner<U> {};
  3280. // };
  3281. //
  3282. // Outer<int, int> outer; // error: the explicit specializations of Inner
  3283. // // have the same signature.
  3284. if (PrevDecl && PrevDecl->getDefinition() &&
  3285. D->isThisDeclarationADefinition()) {
  3286. SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
  3287. SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
  3288. diag::note_previous_definition);
  3289. return nullptr;
  3290. }
  3291. // Create the class template partial specialization declaration.
  3292. ClassTemplateSpecializationDecl *InstD =
  3293. ClassTemplateSpecializationDecl::Create(
  3294. SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
  3295. D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
  3296. // Add this partial specialization to the set of class template partial
  3297. // specializations.
  3298. if (!PrevDecl)
  3299. InstClassTemplate->AddSpecialization(InstD, InsertPos);
  3300. // Substitute the nested name specifier, if any.
  3301. if (SubstQualifier(D, InstD))
  3302. return nullptr;
  3303. // Build the canonical type that describes the converted template
  3304. // arguments of the class template explicit specialization.
  3305. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  3306. TemplateName(InstClassTemplate), CanonicalConverted,
  3307. SemaRef.Context.getRecordType(InstD));
  3308. // Build the fully-sugared type for this class template
  3309. // specialization as the user wrote in the specialization
  3310. // itself. This means that we'll pretty-print the type retrieved
  3311. // from the specialization's declaration the way that the user
  3312. // actually wrote the specialization, rather than formatting the
  3313. // name based on the "canonical" representation used to store the
  3314. // template arguments in the specialization.
  3315. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  3316. TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
  3317. CanonType);
  3318. InstD->setAccess(D->getAccess());
  3319. InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  3320. InstD->setSpecializationKind(D->getSpecializationKind());
  3321. InstD->setTypeAsWritten(WrittenTy);
  3322. InstD->setExternLoc(D->getExternLoc());
  3323. InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
  3324. Owner->addDecl(InstD);
  3325. // Instantiate the members of the class-scope explicit specialization eagerly.
  3326. // We don't have support for lazy instantiation of an explicit specialization
  3327. // yet, and MSVC eagerly instantiates in this case.
  3328. // FIXME: This is wrong in standard C++.
  3329. if (D->isThisDeclarationADefinition() &&
  3330. SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
  3331. TSK_ImplicitInstantiation,
  3332. /*Complain=*/true))
  3333. return nullptr;
  3334. return InstD;
  3335. }
  3336. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  3337. VarTemplateSpecializationDecl *D) {
  3338. TemplateArgumentListInfo VarTemplateArgsInfo;
  3339. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  3340. assert(VarTemplate &&
  3341. "A template specialization without specialized template?");
  3342. VarTemplateDecl *InstVarTemplate =
  3343. cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
  3344. D->getLocation(), VarTemplate, TemplateArgs));
  3345. if (!InstVarTemplate)
  3346. return nullptr;
  3347. // Substitute the current template arguments.
  3348. if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
  3349. D->getTemplateArgsInfo()) {
  3350. VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
  3351. VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
  3352. if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
  3353. TemplateArgs, VarTemplateArgsInfo))
  3354. return nullptr;
  3355. }
  3356. // Check that the template argument list is well-formed for this template.
  3357. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  3358. if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
  3359. VarTemplateArgsInfo, false,
  3360. SugaredConverted, CanonicalConverted,
  3361. /*UpdateArgsWithConversions=*/true))
  3362. return nullptr;
  3363. // Check whether we've already seen a declaration of this specialization.
  3364. void *InsertPos = nullptr;
  3365. VarTemplateSpecializationDecl *PrevDecl =
  3366. InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
  3367. // Check whether we've already seen a conflicting instantiation of this
  3368. // declaration (for instance, if there was a prior implicit instantiation).
  3369. bool Ignored;
  3370. if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
  3371. D->getLocation(), D->getSpecializationKind(), PrevDecl,
  3372. PrevDecl->getSpecializationKind(),
  3373. PrevDecl->getPointOfInstantiation(), Ignored))
  3374. return nullptr;
  3375. return VisitVarTemplateSpecializationDecl(
  3376. InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
  3377. }
  3378. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  3379. VarTemplateDecl *VarTemplate, VarDecl *D,
  3380. const TemplateArgumentListInfo &TemplateArgsInfo,
  3381. ArrayRef<TemplateArgument> Converted,
  3382. VarTemplateSpecializationDecl *PrevDecl) {
  3383. // Do substitution on the type of the declaration
  3384. TypeSourceInfo *DI =
  3385. SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  3386. D->getTypeSpecStartLoc(), D->getDeclName());
  3387. if (!DI)
  3388. return nullptr;
  3389. if (DI->getType()->isFunctionType()) {
  3390. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  3391. << D->isStaticDataMember() << DI->getType();
  3392. return nullptr;
  3393. }
  3394. // Build the instantiated declaration
  3395. VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
  3396. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  3397. VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
  3398. Var->setTemplateArgsInfo(TemplateArgsInfo);
  3399. if (!PrevDecl) {
  3400. void *InsertPos = nullptr;
  3401. VarTemplate->findSpecialization(Converted, InsertPos);
  3402. VarTemplate->AddSpecialization(Var, InsertPos);
  3403. }
  3404. if (SemaRef.getLangOpts().OpenCL)
  3405. SemaRef.deduceOpenCLAddressSpace(Var);
  3406. // Substitute the nested name specifier, if any.
  3407. if (SubstQualifier(D, Var))
  3408. return nullptr;
  3409. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  3410. StartingScope, false, PrevDecl);
  3411. return Var;
  3412. }
  3413. Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
  3414. llvm_unreachable("@defs is not supported in Objective-C++");
  3415. }
  3416. Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
  3417. // FIXME: We need to be able to instantiate FriendTemplateDecls.
  3418. unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
  3419. DiagnosticsEngine::Error,
  3420. "cannot instantiate %0 yet");
  3421. SemaRef.Diag(D->getLocation(), DiagID)
  3422. << D->getDeclKindName();
  3423. return nullptr;
  3424. }
  3425. Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
  3426. llvm_unreachable("Concept definitions cannot reside inside a template");
  3427. }
  3428. Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
  3429. ImplicitConceptSpecializationDecl *D) {
  3430. llvm_unreachable("Concept specializations cannot reside inside a template");
  3431. }
  3432. Decl *
  3433. TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
  3434. return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
  3435. D->getBeginLoc());
  3436. }
  3437. Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
  3438. llvm_unreachable("Unexpected decl");
  3439. }
  3440. Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
  3441. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3442. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  3443. if (D->isInvalidDecl())
  3444. return nullptr;
  3445. Decl *SubstD;
  3446. runWithSufficientStackSpace(D->getLocation(), [&] {
  3447. SubstD = Instantiator.Visit(D);
  3448. });
  3449. return SubstD;
  3450. }
  3451. void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
  3452. FunctionDecl *Orig, QualType &T,
  3453. TypeSourceInfo *&TInfo,
  3454. DeclarationNameInfo &NameInfo) {
  3455. assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
  3456. // C++2a [class.compare.default]p3:
  3457. // the return type is replaced with bool
  3458. auto *FPT = T->castAs<FunctionProtoType>();
  3459. T = SemaRef.Context.getFunctionType(
  3460. SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
  3461. // Update the return type in the source info too. The most straightforward
  3462. // way is to create new TypeSourceInfo for the new type. Use the location of
  3463. // the '= default' as the location of the new type.
  3464. //
  3465. // FIXME: Set the correct return type when we initially transform the type,
  3466. // rather than delaying it to now.
  3467. TypeSourceInfo *NewTInfo =
  3468. SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
  3469. auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
  3470. assert(OldLoc && "type of function is not a function type?");
  3471. auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
  3472. for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
  3473. NewLoc.setParam(I, OldLoc.getParam(I));
  3474. TInfo = NewTInfo;
  3475. // and the declarator-id is replaced with operator==
  3476. NameInfo.setName(
  3477. SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
  3478. }
  3479. FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
  3480. FunctionDecl *Spaceship) {
  3481. if (Spaceship->isInvalidDecl())
  3482. return nullptr;
  3483. // C++2a [class.compare.default]p3:
  3484. // an == operator function is declared implicitly [...] with the same
  3485. // access and function-definition and in the same class scope as the
  3486. // three-way comparison operator function
  3487. MultiLevelTemplateArgumentList NoTemplateArgs;
  3488. NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
  3489. NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
  3490. TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
  3491. Decl *R;
  3492. if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
  3493. R = Instantiator.VisitCXXMethodDecl(
  3494. MD, nullptr, std::nullopt,
  3495. TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
  3496. } else {
  3497. assert(Spaceship->getFriendObjectKind() &&
  3498. "defaulted spaceship is neither a member nor a friend");
  3499. R = Instantiator.VisitFunctionDecl(
  3500. Spaceship, nullptr,
  3501. TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
  3502. if (!R)
  3503. return nullptr;
  3504. FriendDecl *FD =
  3505. FriendDecl::Create(Context, RD, Spaceship->getLocation(),
  3506. cast<NamedDecl>(R), Spaceship->getBeginLoc());
  3507. FD->setAccess(AS_public);
  3508. RD->addDecl(FD);
  3509. }
  3510. return cast_or_null<FunctionDecl>(R);
  3511. }
  3512. /// Instantiates a nested template parameter list in the current
  3513. /// instantiation context.
  3514. ///
  3515. /// \param L The parameter list to instantiate
  3516. ///
  3517. /// \returns NULL if there was an error
  3518. TemplateParameterList *
  3519. TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
  3520. // Get errors for all the parameters before bailing out.
  3521. bool Invalid = false;
  3522. unsigned N = L->size();
  3523. typedef SmallVector<NamedDecl *, 8> ParamVector;
  3524. ParamVector Params;
  3525. Params.reserve(N);
  3526. for (auto &P : *L) {
  3527. NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
  3528. Params.push_back(D);
  3529. Invalid = Invalid || !D || D->isInvalidDecl();
  3530. }
  3531. // Clean up if we had an error.
  3532. if (Invalid)
  3533. return nullptr;
  3534. Expr *InstRequiresClause = L->getRequiresClause();
  3535. TemplateParameterList *InstL
  3536. = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
  3537. L->getLAngleLoc(), Params,
  3538. L->getRAngleLoc(), InstRequiresClause);
  3539. return InstL;
  3540. }
  3541. TemplateParameterList *
  3542. Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
  3543. const MultiLevelTemplateArgumentList &TemplateArgs,
  3544. bool EvaluateConstraints) {
  3545. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  3546. Instantiator.setEvaluateConstraints(EvaluateConstraints);
  3547. return Instantiator.SubstTemplateParams(Params);
  3548. }
  3549. /// Instantiate the declaration of a class template partial
  3550. /// specialization.
  3551. ///
  3552. /// \param ClassTemplate the (instantiated) class template that is partially
  3553. // specialized by the instantiation of \p PartialSpec.
  3554. ///
  3555. /// \param PartialSpec the (uninstantiated) class template partial
  3556. /// specialization that we are instantiating.
  3557. ///
  3558. /// \returns The instantiated partial specialization, if successful; otherwise,
  3559. /// NULL to indicate an error.
  3560. ClassTemplatePartialSpecializationDecl *
  3561. TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
  3562. ClassTemplateDecl *ClassTemplate,
  3563. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  3564. // Create a local instantiation scope for this class template partial
  3565. // specialization, which will contain the instantiations of the template
  3566. // parameters.
  3567. LocalInstantiationScope Scope(SemaRef);
  3568. // Substitute into the template parameters of the class template partial
  3569. // specialization.
  3570. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  3571. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  3572. if (!InstParams)
  3573. return nullptr;
  3574. // Substitute into the template arguments of the class template partial
  3575. // specialization.
  3576. const ASTTemplateArgumentListInfo *TemplArgInfo
  3577. = PartialSpec->getTemplateArgsAsWritten();
  3578. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  3579. TemplArgInfo->RAngleLoc);
  3580. if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
  3581. InstTemplateArgs))
  3582. return nullptr;
  3583. // Check that the template argument list is well-formed for this
  3584. // class template.
  3585. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  3586. if (SemaRef.CheckTemplateArgumentList(
  3587. ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
  3588. /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
  3589. return nullptr;
  3590. // Check these arguments are valid for a template partial specialization.
  3591. if (SemaRef.CheckTemplatePartialSpecializationArgs(
  3592. PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
  3593. CanonicalConverted))
  3594. return nullptr;
  3595. // Figure out where to insert this class template partial specialization
  3596. // in the member template's set of class template partial specializations.
  3597. void *InsertPos = nullptr;
  3598. ClassTemplateSpecializationDecl *PrevDecl =
  3599. ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
  3600. InsertPos);
  3601. // Build the canonical type that describes the converted template
  3602. // arguments of the class template partial specialization.
  3603. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  3604. TemplateName(ClassTemplate), CanonicalConverted);
  3605. // Build the fully-sugared type for this class template
  3606. // specialization as the user wrote in the specialization
  3607. // itself. This means that we'll pretty-print the type retrieved
  3608. // from the specialization's declaration the way that the user
  3609. // actually wrote the specialization, rather than formatting the
  3610. // name based on the "canonical" representation used to store the
  3611. // template arguments in the specialization.
  3612. TypeSourceInfo *WrittenTy
  3613. = SemaRef.Context.getTemplateSpecializationTypeInfo(
  3614. TemplateName(ClassTemplate),
  3615. PartialSpec->getLocation(),
  3616. InstTemplateArgs,
  3617. CanonType);
  3618. if (PrevDecl) {
  3619. // We've already seen a partial specialization with the same template
  3620. // parameters and template arguments. This can happen, for example, when
  3621. // substituting the outer template arguments ends up causing two
  3622. // class template partial specializations of a member class template
  3623. // to have identical forms, e.g.,
  3624. //
  3625. // template<typename T, typename U>
  3626. // struct Outer {
  3627. // template<typename X, typename Y> struct Inner;
  3628. // template<typename Y> struct Inner<T, Y>;
  3629. // template<typename Y> struct Inner<U, Y>;
  3630. // };
  3631. //
  3632. // Outer<int, int> outer; // error: the partial specializations of Inner
  3633. // // have the same signature.
  3634. SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
  3635. << WrittenTy->getType();
  3636. SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
  3637. << SemaRef.Context.getTypeDeclType(PrevDecl);
  3638. return nullptr;
  3639. }
  3640. // Create the class template partial specialization declaration.
  3641. ClassTemplatePartialSpecializationDecl *InstPartialSpec =
  3642. ClassTemplatePartialSpecializationDecl::Create(
  3643. SemaRef.Context, PartialSpec->getTagKind(), Owner,
  3644. PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
  3645. ClassTemplate, CanonicalConverted, InstTemplateArgs, CanonType,
  3646. nullptr);
  3647. // Substitute the nested name specifier, if any.
  3648. if (SubstQualifier(PartialSpec, InstPartialSpec))
  3649. return nullptr;
  3650. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  3651. InstPartialSpec->setTypeAsWritten(WrittenTy);
  3652. // Check the completed partial specialization.
  3653. SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
  3654. // Add this partial specialization to the set of class template partial
  3655. // specializations.
  3656. ClassTemplate->AddPartialSpecialization(InstPartialSpec,
  3657. /*InsertPos=*/nullptr);
  3658. return InstPartialSpec;
  3659. }
  3660. /// Instantiate the declaration of a variable template partial
  3661. /// specialization.
  3662. ///
  3663. /// \param VarTemplate the (instantiated) variable template that is partially
  3664. /// specialized by the instantiation of \p PartialSpec.
  3665. ///
  3666. /// \param PartialSpec the (uninstantiated) variable template partial
  3667. /// specialization that we are instantiating.
  3668. ///
  3669. /// \returns The instantiated partial specialization, if successful; otherwise,
  3670. /// NULL to indicate an error.
  3671. VarTemplatePartialSpecializationDecl *
  3672. TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
  3673. VarTemplateDecl *VarTemplate,
  3674. VarTemplatePartialSpecializationDecl *PartialSpec) {
  3675. // Create a local instantiation scope for this variable template partial
  3676. // specialization, which will contain the instantiations of the template
  3677. // parameters.
  3678. LocalInstantiationScope Scope(SemaRef);
  3679. // Substitute into the template parameters of the variable template partial
  3680. // specialization.
  3681. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  3682. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  3683. if (!InstParams)
  3684. return nullptr;
  3685. // Substitute into the template arguments of the variable template partial
  3686. // specialization.
  3687. const ASTTemplateArgumentListInfo *TemplArgInfo
  3688. = PartialSpec->getTemplateArgsAsWritten();
  3689. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  3690. TemplArgInfo->RAngleLoc);
  3691. if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
  3692. InstTemplateArgs))
  3693. return nullptr;
  3694. // Check that the template argument list is well-formed for this
  3695. // class template.
  3696. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  3697. if (SemaRef.CheckTemplateArgumentList(
  3698. VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
  3699. /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
  3700. return nullptr;
  3701. // Check these arguments are valid for a template partial specialization.
  3702. if (SemaRef.CheckTemplatePartialSpecializationArgs(
  3703. PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
  3704. CanonicalConverted))
  3705. return nullptr;
  3706. // Figure out where to insert this variable template partial specialization
  3707. // in the member template's set of variable template partial specializations.
  3708. void *InsertPos = nullptr;
  3709. VarTemplateSpecializationDecl *PrevDecl =
  3710. VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
  3711. InsertPos);
  3712. // Build the canonical type that describes the converted template
  3713. // arguments of the variable template partial specialization.
  3714. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  3715. TemplateName(VarTemplate), CanonicalConverted);
  3716. // Build the fully-sugared type for this variable template
  3717. // specialization as the user wrote in the specialization
  3718. // itself. This means that we'll pretty-print the type retrieved
  3719. // from the specialization's declaration the way that the user
  3720. // actually wrote the specialization, rather than formatting the
  3721. // name based on the "canonical" representation used to store the
  3722. // template arguments in the specialization.
  3723. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  3724. TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
  3725. CanonType);
  3726. if (PrevDecl) {
  3727. // We've already seen a partial specialization with the same template
  3728. // parameters and template arguments. This can happen, for example, when
  3729. // substituting the outer template arguments ends up causing two
  3730. // variable template partial specializations of a member variable template
  3731. // to have identical forms, e.g.,
  3732. //
  3733. // template<typename T, typename U>
  3734. // struct Outer {
  3735. // template<typename X, typename Y> pair<X,Y> p;
  3736. // template<typename Y> pair<T, Y> p;
  3737. // template<typename Y> pair<U, Y> p;
  3738. // };
  3739. //
  3740. // Outer<int, int> outer; // error: the partial specializations of Inner
  3741. // // have the same signature.
  3742. SemaRef.Diag(PartialSpec->getLocation(),
  3743. diag::err_var_partial_spec_redeclared)
  3744. << WrittenTy->getType();
  3745. SemaRef.Diag(PrevDecl->getLocation(),
  3746. diag::note_var_prev_partial_spec_here);
  3747. return nullptr;
  3748. }
  3749. // Do substitution on the type of the declaration
  3750. TypeSourceInfo *DI = SemaRef.SubstType(
  3751. PartialSpec->getTypeSourceInfo(), TemplateArgs,
  3752. PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
  3753. if (!DI)
  3754. return nullptr;
  3755. if (DI->getType()->isFunctionType()) {
  3756. SemaRef.Diag(PartialSpec->getLocation(),
  3757. diag::err_variable_instantiates_to_function)
  3758. << PartialSpec->isStaticDataMember() << DI->getType();
  3759. return nullptr;
  3760. }
  3761. // Create the variable template partial specialization declaration.
  3762. VarTemplatePartialSpecializationDecl *InstPartialSpec =
  3763. VarTemplatePartialSpecializationDecl::Create(
  3764. SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
  3765. PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
  3766. DI, PartialSpec->getStorageClass(), CanonicalConverted,
  3767. InstTemplateArgs);
  3768. // Substitute the nested name specifier, if any.
  3769. if (SubstQualifier(PartialSpec, InstPartialSpec))
  3770. return nullptr;
  3771. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  3772. InstPartialSpec->setTypeAsWritten(WrittenTy);
  3773. // Check the completed partial specialization.
  3774. SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
  3775. // Add this partial specialization to the set of variable template partial
  3776. // specializations. The instantiation of the initializer is not necessary.
  3777. VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
  3778. SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
  3779. LateAttrs, Owner, StartingScope);
  3780. return InstPartialSpec;
  3781. }
  3782. TypeSourceInfo*
  3783. TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
  3784. SmallVectorImpl<ParmVarDecl *> &Params) {
  3785. TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
  3786. assert(OldTInfo && "substituting function without type source info");
  3787. assert(Params.empty() && "parameter vector is non-empty at start");
  3788. CXXRecordDecl *ThisContext = nullptr;
  3789. Qualifiers ThisTypeQuals;
  3790. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  3791. ThisContext = cast<CXXRecordDecl>(Owner);
  3792. ThisTypeQuals = Method->getMethodQualifiers();
  3793. }
  3794. TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
  3795. OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
  3796. ThisContext, ThisTypeQuals, EvaluateConstraints);
  3797. if (!NewTInfo)
  3798. return nullptr;
  3799. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  3800. if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
  3801. if (NewTInfo != OldTInfo) {
  3802. // Get parameters from the new type info.
  3803. TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
  3804. FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
  3805. unsigned NewIdx = 0;
  3806. for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
  3807. OldIdx != NumOldParams; ++OldIdx) {
  3808. ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
  3809. if (!OldParam)
  3810. return nullptr;
  3811. LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
  3812. std::optional<unsigned> NumArgumentsInExpansion;
  3813. if (OldParam->isParameterPack())
  3814. NumArgumentsInExpansion =
  3815. SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
  3816. TemplateArgs);
  3817. if (!NumArgumentsInExpansion) {
  3818. // Simple case: normal parameter, or a parameter pack that's
  3819. // instantiated to a (still-dependent) parameter pack.
  3820. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  3821. Params.push_back(NewParam);
  3822. Scope->InstantiatedLocal(OldParam, NewParam);
  3823. } else {
  3824. // Parameter pack expansion: make the instantiation an argument pack.
  3825. Scope->MakeInstantiatedLocalArgPack(OldParam);
  3826. for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
  3827. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  3828. Params.push_back(NewParam);
  3829. Scope->InstantiatedLocalPackArg(OldParam, NewParam);
  3830. }
  3831. }
  3832. }
  3833. } else {
  3834. // The function type itself was not dependent and therefore no
  3835. // substitution occurred. However, we still need to instantiate
  3836. // the function parameters themselves.
  3837. const FunctionProtoType *OldProto =
  3838. cast<FunctionProtoType>(OldProtoLoc.getType());
  3839. for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
  3840. ++i) {
  3841. ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
  3842. if (!OldParam) {
  3843. Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
  3844. D, D->getLocation(), OldProto->getParamType(i)));
  3845. continue;
  3846. }
  3847. ParmVarDecl *Parm =
  3848. cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
  3849. if (!Parm)
  3850. return nullptr;
  3851. Params.push_back(Parm);
  3852. }
  3853. }
  3854. } else {
  3855. // If the type of this function, after ignoring parentheses, is not
  3856. // *directly* a function type, then we're instantiating a function that
  3857. // was declared via a typedef or with attributes, e.g.,
  3858. //
  3859. // typedef int functype(int, int);
  3860. // functype func;
  3861. // int __cdecl meth(int, int);
  3862. //
  3863. // In this case, we'll just go instantiate the ParmVarDecls that we
  3864. // synthesized in the method declaration.
  3865. SmallVector<QualType, 4> ParamTypes;
  3866. Sema::ExtParameterInfoBuilder ExtParamInfos;
  3867. if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
  3868. TemplateArgs, ParamTypes, &Params,
  3869. ExtParamInfos))
  3870. return nullptr;
  3871. }
  3872. return NewTInfo;
  3873. }
  3874. /// Introduce the instantiated function parameters into the local
  3875. /// instantiation scope, and set the parameter names to those used
  3876. /// in the template.
  3877. bool Sema::addInstantiatedParametersToScope(
  3878. FunctionDecl *Function, const FunctionDecl *PatternDecl,
  3879. LocalInstantiationScope &Scope,
  3880. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3881. unsigned FParamIdx = 0;
  3882. for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
  3883. const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
  3884. if (!PatternParam->isParameterPack()) {
  3885. // Simple case: not a parameter pack.
  3886. assert(FParamIdx < Function->getNumParams());
  3887. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  3888. FunctionParam->setDeclName(PatternParam->getDeclName());
  3889. // If the parameter's type is not dependent, update it to match the type
  3890. // in the pattern. They can differ in top-level cv-qualifiers, and we want
  3891. // the pattern's type here. If the type is dependent, they can't differ,
  3892. // per core issue 1668. Substitute into the type from the pattern, in case
  3893. // it's instantiation-dependent.
  3894. // FIXME: Updating the type to work around this is at best fragile.
  3895. if (!PatternDecl->getType()->isDependentType()) {
  3896. QualType T = SubstType(PatternParam->getType(), TemplateArgs,
  3897. FunctionParam->getLocation(),
  3898. FunctionParam->getDeclName());
  3899. if (T.isNull())
  3900. return true;
  3901. FunctionParam->setType(T);
  3902. }
  3903. Scope.InstantiatedLocal(PatternParam, FunctionParam);
  3904. ++FParamIdx;
  3905. continue;
  3906. }
  3907. // Expand the parameter pack.
  3908. Scope.MakeInstantiatedLocalArgPack(PatternParam);
  3909. std::optional<unsigned> NumArgumentsInExpansion =
  3910. getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
  3911. if (NumArgumentsInExpansion) {
  3912. QualType PatternType =
  3913. PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
  3914. for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
  3915. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  3916. FunctionParam->setDeclName(PatternParam->getDeclName());
  3917. if (!PatternDecl->getType()->isDependentType()) {
  3918. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
  3919. QualType T =
  3920. SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
  3921. FunctionParam->getDeclName());
  3922. if (T.isNull())
  3923. return true;
  3924. FunctionParam->setType(T);
  3925. }
  3926. Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
  3927. ++FParamIdx;
  3928. }
  3929. }
  3930. }
  3931. return false;
  3932. }
  3933. bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
  3934. ParmVarDecl *Param) {
  3935. assert(Param->hasUninstantiatedDefaultArg());
  3936. // Instantiate the expression.
  3937. //
  3938. // FIXME: Pass in a correct Pattern argument, otherwise
  3939. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  3940. //
  3941. // template<typename T>
  3942. // struct A {
  3943. // static int FooImpl();
  3944. //
  3945. // template<typename Tp>
  3946. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  3947. // // template argument list [[T], [Tp]], should be [[Tp]].
  3948. // friend A<Tp> Foo(int a);
  3949. // };
  3950. //
  3951. // template<typename T>
  3952. // A<T> Foo(int a = A<T>::FooImpl());
  3953. MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
  3954. FD, /*Final=*/false, nullptr, /*RelativeToPrimary=*/true);
  3955. if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
  3956. return true;
  3957. if (ASTMutationListener *L = getASTMutationListener())
  3958. L->DefaultArgumentInstantiated(Param);
  3959. return false;
  3960. }
  3961. void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
  3962. FunctionDecl *Decl) {
  3963. const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
  3964. if (Proto->getExceptionSpecType() != EST_Uninstantiated)
  3965. return;
  3966. InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
  3967. InstantiatingTemplate::ExceptionSpecification());
  3968. if (Inst.isInvalid()) {
  3969. // We hit the instantiation depth limit. Clear the exception specification
  3970. // so that our callers don't have to cope with EST_Uninstantiated.
  3971. UpdateExceptionSpec(Decl, EST_None);
  3972. return;
  3973. }
  3974. if (Inst.isAlreadyInstantiating()) {
  3975. // This exception specification indirectly depends on itself. Reject.
  3976. // FIXME: Corresponding rule in the standard?
  3977. Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
  3978. UpdateExceptionSpec(Decl, EST_None);
  3979. return;
  3980. }
  3981. // Enter the scope of this instantiation. We don't use
  3982. // PushDeclContext because we don't have a scope.
  3983. Sema::ContextRAII savedContext(*this, Decl);
  3984. LocalInstantiationScope Scope(*this);
  3985. MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
  3986. Decl, /*Final=*/false, nullptr, /*RelativeToPrimary*/ true);
  3987. // FIXME: We can't use getTemplateInstantiationPattern(false) in general
  3988. // here, because for a non-defining friend declaration in a class template,
  3989. // we don't store enough information to map back to the friend declaration in
  3990. // the template.
  3991. FunctionDecl *Template = Proto->getExceptionSpecTemplate();
  3992. if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
  3993. UpdateExceptionSpec(Decl, EST_None);
  3994. return;
  3995. }
  3996. SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
  3997. TemplateArgs);
  3998. }
  3999. /// Initializes the common fields of an instantiation function
  4000. /// declaration (New) from the corresponding fields of its template (Tmpl).
  4001. ///
  4002. /// \returns true if there was an error
  4003. bool
  4004. TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
  4005. FunctionDecl *Tmpl) {
  4006. New->setImplicit(Tmpl->isImplicit());
  4007. // Forward the mangling number from the template to the instantiated decl.
  4008. SemaRef.Context.setManglingNumber(New,
  4009. SemaRef.Context.getManglingNumber(Tmpl));
  4010. // If we are performing substituting explicitly-specified template arguments
  4011. // or deduced template arguments into a function template and we reach this
  4012. // point, we are now past the point where SFINAE applies and have committed
  4013. // to keeping the new function template specialization. We therefore
  4014. // convert the active template instantiation for the function template
  4015. // into a template instantiation for this specific function template
  4016. // specialization, which is not a SFINAE context, so that we diagnose any
  4017. // further errors in the declaration itself.
  4018. //
  4019. // FIXME: This is a hack.
  4020. typedef Sema::CodeSynthesisContext ActiveInstType;
  4021. ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
  4022. if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
  4023. ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
  4024. if (FunctionTemplateDecl *FunTmpl
  4025. = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
  4026. assert(FunTmpl->getTemplatedDecl() == Tmpl &&
  4027. "Deduction from the wrong function template?");
  4028. (void) FunTmpl;
  4029. SemaRef.InstantiatingSpecializations.erase(
  4030. {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
  4031. atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
  4032. ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
  4033. ActiveInst.Entity = New;
  4034. atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
  4035. }
  4036. }
  4037. const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
  4038. assert(Proto && "Function template without prototype?");
  4039. if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
  4040. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  4041. // DR1330: In C++11, defer instantiation of a non-trivial
  4042. // exception specification.
  4043. // DR1484: Local classes and their members are instantiated along with the
  4044. // containing function.
  4045. if (SemaRef.getLangOpts().CPlusPlus11 &&
  4046. EPI.ExceptionSpec.Type != EST_None &&
  4047. EPI.ExceptionSpec.Type != EST_DynamicNone &&
  4048. EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
  4049. !Tmpl->isInLocalScopeForInstantiation()) {
  4050. FunctionDecl *ExceptionSpecTemplate = Tmpl;
  4051. if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
  4052. ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
  4053. ExceptionSpecificationType NewEST = EST_Uninstantiated;
  4054. if (EPI.ExceptionSpec.Type == EST_Unevaluated)
  4055. NewEST = EST_Unevaluated;
  4056. // Mark the function has having an uninstantiated exception specification.
  4057. const FunctionProtoType *NewProto
  4058. = New->getType()->getAs<FunctionProtoType>();
  4059. assert(NewProto && "Template instantiation without function prototype?");
  4060. EPI = NewProto->getExtProtoInfo();
  4061. EPI.ExceptionSpec.Type = NewEST;
  4062. EPI.ExceptionSpec.SourceDecl = New;
  4063. EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
  4064. New->setType(SemaRef.Context.getFunctionType(
  4065. NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
  4066. } else {
  4067. Sema::ContextRAII SwitchContext(SemaRef, New);
  4068. SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
  4069. }
  4070. }
  4071. // Get the definition. Leaves the variable unchanged if undefined.
  4072. const FunctionDecl *Definition = Tmpl;
  4073. Tmpl->isDefined(Definition);
  4074. SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
  4075. LateAttrs, StartingScope);
  4076. return false;
  4077. }
  4078. /// Initializes common fields of an instantiated method
  4079. /// declaration (New) from the corresponding fields of its template
  4080. /// (Tmpl).
  4081. ///
  4082. /// \returns true if there was an error
  4083. bool
  4084. TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
  4085. CXXMethodDecl *Tmpl) {
  4086. if (InitFunctionInstantiation(New, Tmpl))
  4087. return true;
  4088. if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
  4089. SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
  4090. New->setAccess(Tmpl->getAccess());
  4091. if (Tmpl->isVirtualAsWritten())
  4092. New->setVirtualAsWritten(true);
  4093. // FIXME: New needs a pointer to Tmpl
  4094. return false;
  4095. }
  4096. bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
  4097. FunctionDecl *Tmpl) {
  4098. // Transfer across any unqualified lookups.
  4099. if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
  4100. SmallVector<DeclAccessPair, 32> Lookups;
  4101. Lookups.reserve(DFI->getUnqualifiedLookups().size());
  4102. bool AnyChanged = false;
  4103. for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
  4104. NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
  4105. DA.getDecl(), TemplateArgs);
  4106. if (!D)
  4107. return true;
  4108. AnyChanged |= (D != DA.getDecl());
  4109. Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
  4110. }
  4111. // It's unlikely that substitution will change any declarations. Don't
  4112. // store an unnecessary copy in that case.
  4113. New->setDefaultedFunctionInfo(
  4114. AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
  4115. SemaRef.Context, Lookups)
  4116. : DFI);
  4117. }
  4118. SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
  4119. return false;
  4120. }
  4121. /// Instantiate (or find existing instantiation of) a function template with a
  4122. /// given set of template arguments.
  4123. ///
  4124. /// Usually this should not be used, and template argument deduction should be
  4125. /// used in its place.
  4126. FunctionDecl *
  4127. Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
  4128. const TemplateArgumentList *Args,
  4129. SourceLocation Loc) {
  4130. FunctionDecl *FD = FTD->getTemplatedDecl();
  4131. sema::TemplateDeductionInfo Info(Loc);
  4132. InstantiatingTemplate Inst(
  4133. *this, Loc, FTD, Args->asArray(),
  4134. CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
  4135. if (Inst.isInvalid())
  4136. return nullptr;
  4137. ContextRAII SavedContext(*this, FD);
  4138. MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
  4139. /*Final=*/false);
  4140. return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
  4141. }
  4142. /// Instantiate the definition of the given function from its
  4143. /// template.
  4144. ///
  4145. /// \param PointOfInstantiation the point at which the instantiation was
  4146. /// required. Note that this is not precisely a "point of instantiation"
  4147. /// for the function, but it's close.
  4148. ///
  4149. /// \param Function the already-instantiated declaration of a
  4150. /// function template specialization or member function of a class template
  4151. /// specialization.
  4152. ///
  4153. /// \param Recursive if true, recursively instantiates any functions that
  4154. /// are required by this instantiation.
  4155. ///
  4156. /// \param DefinitionRequired if true, then we are performing an explicit
  4157. /// instantiation where the body of the function is required. Complain if
  4158. /// there is no such body.
  4159. void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
  4160. FunctionDecl *Function,
  4161. bool Recursive,
  4162. bool DefinitionRequired,
  4163. bool AtEndOfTU) {
  4164. if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
  4165. return;
  4166. // Never instantiate an explicit specialization except if it is a class scope
  4167. // explicit specialization.
  4168. TemplateSpecializationKind TSK =
  4169. Function->getTemplateSpecializationKindForInstantiation();
  4170. if (TSK == TSK_ExplicitSpecialization)
  4171. return;
  4172. // Never implicitly instantiate a builtin; we don't actually need a function
  4173. // body.
  4174. if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
  4175. !DefinitionRequired)
  4176. return;
  4177. // Don't instantiate a definition if we already have one.
  4178. const FunctionDecl *ExistingDefn = nullptr;
  4179. if (Function->isDefined(ExistingDefn,
  4180. /*CheckForPendingFriendDefinition=*/true)) {
  4181. if (ExistingDefn->isThisDeclarationADefinition())
  4182. return;
  4183. // If we're asked to instantiate a function whose body comes from an
  4184. // instantiated friend declaration, attach the instantiated body to the
  4185. // corresponding declaration of the function.
  4186. assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
  4187. Function = const_cast<FunctionDecl*>(ExistingDefn);
  4188. }
  4189. // Find the function body that we'll be substituting.
  4190. const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
  4191. assert(PatternDecl && "instantiating a non-template");
  4192. const FunctionDecl *PatternDef = PatternDecl->getDefinition();
  4193. Stmt *Pattern = nullptr;
  4194. if (PatternDef) {
  4195. Pattern = PatternDef->getBody(PatternDef);
  4196. PatternDecl = PatternDef;
  4197. if (PatternDef->willHaveBody())
  4198. PatternDef = nullptr;
  4199. }
  4200. // FIXME: We need to track the instantiation stack in order to know which
  4201. // definitions should be visible within this instantiation.
  4202. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
  4203. Function->getInstantiatedFromMemberFunction(),
  4204. PatternDecl, PatternDef, TSK,
  4205. /*Complain*/DefinitionRequired)) {
  4206. if (DefinitionRequired)
  4207. Function->setInvalidDecl();
  4208. else if (TSK == TSK_ExplicitInstantiationDefinition ||
  4209. (Function->isConstexpr() && !Recursive)) {
  4210. // Try again at the end of the translation unit (at which point a
  4211. // definition will be required).
  4212. assert(!Recursive);
  4213. Function->setInstantiationIsPending(true);
  4214. PendingInstantiations.push_back(
  4215. std::make_pair(Function, PointOfInstantiation));
  4216. } else if (TSK == TSK_ImplicitInstantiation) {
  4217. if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
  4218. !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
  4219. Diag(PointOfInstantiation, diag::warn_func_template_missing)
  4220. << Function;
  4221. Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
  4222. if (getLangOpts().CPlusPlus11)
  4223. Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
  4224. << Function;
  4225. }
  4226. }
  4227. return;
  4228. }
  4229. // Postpone late parsed template instantiations.
  4230. if (PatternDecl->isLateTemplateParsed() &&
  4231. !LateTemplateParser) {
  4232. Function->setInstantiationIsPending(true);
  4233. LateParsedInstantiations.push_back(
  4234. std::make_pair(Function, PointOfInstantiation));
  4235. return;
  4236. }
  4237. llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
  4238. std::string Name;
  4239. llvm::raw_string_ostream OS(Name);
  4240. Function->getNameForDiagnostic(OS, getPrintingPolicy(),
  4241. /*Qualified=*/true);
  4242. return Name;
  4243. });
  4244. // If we're performing recursive template instantiation, create our own
  4245. // queue of pending implicit instantiations that we will instantiate later,
  4246. // while we're still within our own instantiation context.
  4247. // This has to happen before LateTemplateParser below is called, so that
  4248. // it marks vtables used in late parsed templates as used.
  4249. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  4250. /*Enabled=*/Recursive);
  4251. LocalEagerInstantiationScope LocalInstantiations(*this);
  4252. // Call the LateTemplateParser callback if there is a need to late parse
  4253. // a templated function definition.
  4254. if (!Pattern && PatternDecl->isLateTemplateParsed() &&
  4255. LateTemplateParser) {
  4256. // FIXME: Optimize to allow individual templates to be deserialized.
  4257. if (PatternDecl->isFromASTFile())
  4258. ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
  4259. auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
  4260. assert(LPTIter != LateParsedTemplateMap.end() &&
  4261. "missing LateParsedTemplate");
  4262. LateTemplateParser(OpaqueParser, *LPTIter->second);
  4263. Pattern = PatternDecl->getBody(PatternDecl);
  4264. }
  4265. // Note, we should never try to instantiate a deleted function template.
  4266. assert((Pattern || PatternDecl->isDefaulted() ||
  4267. PatternDecl->hasSkippedBody()) &&
  4268. "unexpected kind of function template definition");
  4269. // C++1y [temp.explicit]p10:
  4270. // Except for inline functions, declarations with types deduced from their
  4271. // initializer or return value, and class template specializations, other
  4272. // explicit instantiation declarations have the effect of suppressing the
  4273. // implicit instantiation of the entity to which they refer.
  4274. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  4275. !PatternDecl->isInlined() &&
  4276. !PatternDecl->getReturnType()->getContainedAutoType())
  4277. return;
  4278. if (PatternDecl->isInlined()) {
  4279. // Function, and all later redeclarations of it (from imported modules,
  4280. // for instance), are now implicitly inline.
  4281. for (auto *D = Function->getMostRecentDecl(); /**/;
  4282. D = D->getPreviousDecl()) {
  4283. D->setImplicitlyInline();
  4284. if (D == Function)
  4285. break;
  4286. }
  4287. }
  4288. InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
  4289. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  4290. return;
  4291. PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
  4292. "instantiating function definition");
  4293. // The instantiation is visible here, even if it was first declared in an
  4294. // unimported module.
  4295. Function->setVisibleDespiteOwningModule();
  4296. // Copy the inner loc start from the pattern.
  4297. Function->setInnerLocStart(PatternDecl->getInnerLocStart());
  4298. EnterExpressionEvaluationContext EvalContext(
  4299. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  4300. // Introduce a new scope where local variable instantiations will be
  4301. // recorded, unless we're actually a member function within a local
  4302. // class, in which case we need to merge our results with the parent
  4303. // scope (of the enclosing function). The exception is instantiating
  4304. // a function template specialization, since the template to be
  4305. // instantiated already has references to locals properly substituted.
  4306. bool MergeWithParentScope = false;
  4307. if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
  4308. MergeWithParentScope =
  4309. Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
  4310. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  4311. auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
  4312. // Special members might get their TypeSourceInfo set up w.r.t the
  4313. // PatternDecl context, in which case parameters could still be pointing
  4314. // back to the original class, make sure arguments are bound to the
  4315. // instantiated record instead.
  4316. assert(PatternDecl->isDefaulted() &&
  4317. "Special member needs to be defaulted");
  4318. auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
  4319. if (!(PatternSM == Sema::CXXCopyConstructor ||
  4320. PatternSM == Sema::CXXCopyAssignment ||
  4321. PatternSM == Sema::CXXMoveConstructor ||
  4322. PatternSM == Sema::CXXMoveAssignment))
  4323. return;
  4324. auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
  4325. const auto *PatternRec =
  4326. dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
  4327. if (!NewRec || !PatternRec)
  4328. return;
  4329. if (!PatternRec->isLambda())
  4330. return;
  4331. struct SpecialMemberTypeInfoRebuilder
  4332. : TreeTransform<SpecialMemberTypeInfoRebuilder> {
  4333. using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
  4334. const CXXRecordDecl *OldDecl;
  4335. CXXRecordDecl *NewDecl;
  4336. SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
  4337. CXXRecordDecl *N)
  4338. : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
  4339. bool TransformExceptionSpec(SourceLocation Loc,
  4340. FunctionProtoType::ExceptionSpecInfo &ESI,
  4341. SmallVectorImpl<QualType> &Exceptions,
  4342. bool &Changed) {
  4343. return false;
  4344. }
  4345. QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
  4346. const RecordType *T = TL.getTypePtr();
  4347. RecordDecl *Record = cast_or_null<RecordDecl>(
  4348. getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
  4349. if (Record != OldDecl)
  4350. return Base::TransformRecordType(TLB, TL);
  4351. QualType Result = getDerived().RebuildRecordType(NewDecl);
  4352. if (Result.isNull())
  4353. return QualType();
  4354. RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
  4355. NewTL.setNameLoc(TL.getNameLoc());
  4356. return Result;
  4357. }
  4358. } IR{*this, PatternRec, NewRec};
  4359. TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
  4360. Function->setType(NewSI->getType());
  4361. Function->setTypeSourceInfo(NewSI);
  4362. ParmVarDecl *Parm = Function->getParamDecl(0);
  4363. TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
  4364. Parm->setType(NewParmSI->getType());
  4365. Parm->setTypeSourceInfo(NewParmSI);
  4366. };
  4367. if (PatternDecl->isDefaulted()) {
  4368. RebuildTypeSourceInfoForDefaultSpecialMembers();
  4369. SetDeclDefaulted(Function, PatternDecl->getLocation());
  4370. } else {
  4371. MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
  4372. Function, /*Final=*/false, nullptr, false, PatternDecl);
  4373. // Substitute into the qualifier; we can get a substitution failure here
  4374. // through evil use of alias templates.
  4375. // FIXME: Is CurContext correct for this? Should we go to the (instantiation
  4376. // of the) lexical context of the pattern?
  4377. SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
  4378. ActOnStartOfFunctionDef(nullptr, Function);
  4379. // Enter the scope of this instantiation. We don't use
  4380. // PushDeclContext because we don't have a scope.
  4381. Sema::ContextRAII savedContext(*this, Function);
  4382. if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
  4383. TemplateArgs))
  4384. return;
  4385. StmtResult Body;
  4386. if (PatternDecl->hasSkippedBody()) {
  4387. ActOnSkippedFunctionBody(Function);
  4388. Body = nullptr;
  4389. } else {
  4390. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
  4391. // If this is a constructor, instantiate the member initializers.
  4392. InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
  4393. TemplateArgs);
  4394. // If this is an MS ABI dllexport default constructor, instantiate any
  4395. // default arguments.
  4396. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4397. Ctor->isDefaultConstructor()) {
  4398. InstantiateDefaultCtorDefaultArgs(Ctor);
  4399. }
  4400. }
  4401. // Instantiate the function body.
  4402. Body = SubstStmt(Pattern, TemplateArgs);
  4403. if (Body.isInvalid())
  4404. Function->setInvalidDecl();
  4405. }
  4406. // FIXME: finishing the function body while in an expression evaluation
  4407. // context seems wrong. Investigate more.
  4408. ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
  4409. PerformDependentDiagnostics(PatternDecl, TemplateArgs);
  4410. if (auto *Listener = getASTMutationListener())
  4411. Listener->FunctionDefinitionInstantiated(Function);
  4412. savedContext.pop();
  4413. }
  4414. DeclGroupRef DG(Function);
  4415. Consumer.HandleTopLevelDecl(DG);
  4416. // This class may have local implicit instantiations that need to be
  4417. // instantiation within this scope.
  4418. LocalInstantiations.perform();
  4419. Scope.Exit();
  4420. GlobalInstantiations.perform();
  4421. }
  4422. VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
  4423. VarTemplateDecl *VarTemplate, VarDecl *FromVar,
  4424. const TemplateArgumentList &TemplateArgList,
  4425. const TemplateArgumentListInfo &TemplateArgsInfo,
  4426. SmallVectorImpl<TemplateArgument> &Converted,
  4427. SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
  4428. LocalInstantiationScope *StartingScope) {
  4429. if (FromVar->isInvalidDecl())
  4430. return nullptr;
  4431. InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
  4432. if (Inst.isInvalid())
  4433. return nullptr;
  4434. // Instantiate the first declaration of the variable template: for a partial
  4435. // specialization of a static data member template, the first declaration may
  4436. // or may not be the declaration in the class; if it's in the class, we want
  4437. // to instantiate a member in the class (a declaration), and if it's outside,
  4438. // we want to instantiate a definition.
  4439. //
  4440. // If we're instantiating an explicitly-specialized member template or member
  4441. // partial specialization, don't do this. The member specialization completely
  4442. // replaces the original declaration in this case.
  4443. bool IsMemberSpec = false;
  4444. MultiLevelTemplateArgumentList MultiLevelList;
  4445. if (auto *PartialSpec =
  4446. dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
  4447. IsMemberSpec = PartialSpec->isMemberSpecialization();
  4448. MultiLevelList.addOuterTemplateArguments(
  4449. PartialSpec, TemplateArgList.asArray(), /*Final=*/false);
  4450. } else {
  4451. assert(VarTemplate == FromVar->getDescribedVarTemplate());
  4452. IsMemberSpec = VarTemplate->isMemberSpecialization();
  4453. MultiLevelList.addOuterTemplateArguments(
  4454. VarTemplate, TemplateArgList.asArray(), /*Final=*/false);
  4455. }
  4456. if (!IsMemberSpec)
  4457. FromVar = FromVar->getFirstDecl();
  4458. TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
  4459. MultiLevelList);
  4460. // TODO: Set LateAttrs and StartingScope ...
  4461. return cast_or_null<VarTemplateSpecializationDecl>(
  4462. Instantiator.VisitVarTemplateSpecializationDecl(
  4463. VarTemplate, FromVar, TemplateArgsInfo, Converted));
  4464. }
  4465. /// Instantiates a variable template specialization by completing it
  4466. /// with appropriate type information and initializer.
  4467. VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
  4468. VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
  4469. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4470. assert(PatternDecl->isThisDeclarationADefinition() &&
  4471. "don't have a definition to instantiate from");
  4472. // Do substitution on the type of the declaration
  4473. TypeSourceInfo *DI =
  4474. SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
  4475. PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
  4476. if (!DI)
  4477. return nullptr;
  4478. // Update the type of this variable template specialization.
  4479. VarSpec->setType(DI->getType());
  4480. // Convert the declaration into a definition now.
  4481. VarSpec->setCompleteDefinition();
  4482. // Instantiate the initializer.
  4483. InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
  4484. if (getLangOpts().OpenCL)
  4485. deduceOpenCLAddressSpace(VarSpec);
  4486. return VarSpec;
  4487. }
  4488. /// BuildVariableInstantiation - Used after a new variable has been created.
  4489. /// Sets basic variable data and decides whether to postpone the
  4490. /// variable instantiation.
  4491. void Sema::BuildVariableInstantiation(
  4492. VarDecl *NewVar, VarDecl *OldVar,
  4493. const MultiLevelTemplateArgumentList &TemplateArgs,
  4494. LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
  4495. LocalInstantiationScope *StartingScope,
  4496. bool InstantiatingVarTemplate,
  4497. VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
  4498. // Instantiating a partial specialization to produce a partial
  4499. // specialization.
  4500. bool InstantiatingVarTemplatePartialSpec =
  4501. isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
  4502. isa<VarTemplatePartialSpecializationDecl>(NewVar);
  4503. // Instantiating from a variable template (or partial specialization) to
  4504. // produce a variable template specialization.
  4505. bool InstantiatingSpecFromTemplate =
  4506. isa<VarTemplateSpecializationDecl>(NewVar) &&
  4507. (OldVar->getDescribedVarTemplate() ||
  4508. isa<VarTemplatePartialSpecializationDecl>(OldVar));
  4509. // If we are instantiating a local extern declaration, the
  4510. // instantiation belongs lexically to the containing function.
  4511. // If we are instantiating a static data member defined
  4512. // out-of-line, the instantiation will have the same lexical
  4513. // context (which will be a namespace scope) as the template.
  4514. if (OldVar->isLocalExternDecl()) {
  4515. NewVar->setLocalExternDecl();
  4516. NewVar->setLexicalDeclContext(Owner);
  4517. } else if (OldVar->isOutOfLine())
  4518. NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
  4519. NewVar->setTSCSpec(OldVar->getTSCSpec());
  4520. NewVar->setInitStyle(OldVar->getInitStyle());
  4521. NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
  4522. NewVar->setObjCForDecl(OldVar->isObjCForDecl());
  4523. NewVar->setConstexpr(OldVar->isConstexpr());
  4524. NewVar->setInitCapture(OldVar->isInitCapture());
  4525. NewVar->setPreviousDeclInSameBlockScope(
  4526. OldVar->isPreviousDeclInSameBlockScope());
  4527. NewVar->setAccess(OldVar->getAccess());
  4528. if (!OldVar->isStaticDataMember()) {
  4529. if (OldVar->isUsed(false))
  4530. NewVar->setIsUsed();
  4531. NewVar->setReferenced(OldVar->isReferenced());
  4532. }
  4533. InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
  4534. LookupResult Previous(
  4535. *this, NewVar->getDeclName(), NewVar->getLocation(),
  4536. NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  4537. : Sema::LookupOrdinaryName,
  4538. NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
  4539. : forRedeclarationInCurContext());
  4540. if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
  4541. (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
  4542. OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
  4543. // We have a previous declaration. Use that one, so we merge with the
  4544. // right type.
  4545. if (NamedDecl *NewPrev = FindInstantiatedDecl(
  4546. NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
  4547. Previous.addDecl(NewPrev);
  4548. } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
  4549. OldVar->hasLinkage()) {
  4550. LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
  4551. } else if (PrevDeclForVarTemplateSpecialization) {
  4552. Previous.addDecl(PrevDeclForVarTemplateSpecialization);
  4553. }
  4554. CheckVariableDeclaration(NewVar, Previous);
  4555. if (!InstantiatingVarTemplate) {
  4556. NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
  4557. if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
  4558. NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
  4559. }
  4560. if (!OldVar->isOutOfLine()) {
  4561. if (NewVar->getDeclContext()->isFunctionOrMethod())
  4562. CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
  4563. }
  4564. // Link instantiations of static data members back to the template from
  4565. // which they were instantiated.
  4566. //
  4567. // Don't do this when instantiating a template (we link the template itself
  4568. // back in that case) nor when instantiating a static data member template
  4569. // (that's not a member specialization).
  4570. if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
  4571. !InstantiatingSpecFromTemplate)
  4572. NewVar->setInstantiationOfStaticDataMember(OldVar,
  4573. TSK_ImplicitInstantiation);
  4574. // If the pattern is an (in-class) explicit specialization, then the result
  4575. // is also an explicit specialization.
  4576. if (VarTemplateSpecializationDecl *OldVTSD =
  4577. dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
  4578. if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
  4579. !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
  4580. cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
  4581. TSK_ExplicitSpecialization);
  4582. }
  4583. // Forward the mangling number from the template to the instantiated decl.
  4584. Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
  4585. Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
  4586. // Figure out whether to eagerly instantiate the initializer.
  4587. if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
  4588. // We're producing a template. Don't instantiate the initializer yet.
  4589. } else if (NewVar->getType()->isUndeducedType()) {
  4590. // We need the type to complete the declaration of the variable.
  4591. InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
  4592. } else if (InstantiatingSpecFromTemplate ||
  4593. (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
  4594. !NewVar->isThisDeclarationADefinition())) {
  4595. // Delay instantiation of the initializer for variable template
  4596. // specializations or inline static data members until a definition of the
  4597. // variable is needed.
  4598. } else {
  4599. InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
  4600. }
  4601. // Diagnose unused local variables with dependent types, where the diagnostic
  4602. // will have been deferred.
  4603. if (!NewVar->isInvalidDecl() &&
  4604. NewVar->getDeclContext()->isFunctionOrMethod() &&
  4605. OldVar->getType()->isDependentType())
  4606. DiagnoseUnusedDecl(NewVar);
  4607. }
  4608. /// Instantiate the initializer of a variable.
  4609. void Sema::InstantiateVariableInitializer(
  4610. VarDecl *Var, VarDecl *OldVar,
  4611. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4612. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  4613. L->VariableDefinitionInstantiated(Var);
  4614. // We propagate the 'inline' flag with the initializer, because it
  4615. // would otherwise imply that the variable is a definition for a
  4616. // non-static data member.
  4617. if (OldVar->isInlineSpecified())
  4618. Var->setInlineSpecified();
  4619. else if (OldVar->isInline())
  4620. Var->setImplicitlyInline();
  4621. if (OldVar->getInit()) {
  4622. EnterExpressionEvaluationContext Evaluated(
  4623. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
  4624. // Instantiate the initializer.
  4625. ExprResult Init;
  4626. {
  4627. ContextRAII SwitchContext(*this, Var->getDeclContext());
  4628. Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
  4629. OldVar->getInitStyle() == VarDecl::CallInit);
  4630. }
  4631. if (!Init.isInvalid()) {
  4632. Expr *InitExpr = Init.get();
  4633. if (Var->hasAttr<DLLImportAttr>() &&
  4634. (!InitExpr ||
  4635. !InitExpr->isConstantInitializer(getASTContext(), false))) {
  4636. // Do not dynamically initialize dllimport variables.
  4637. } else if (InitExpr) {
  4638. bool DirectInit = OldVar->isDirectInit();
  4639. AddInitializerToDecl(Var, InitExpr, DirectInit);
  4640. } else
  4641. ActOnUninitializedDecl(Var);
  4642. } else {
  4643. // FIXME: Not too happy about invalidating the declaration
  4644. // because of a bogus initializer.
  4645. Var->setInvalidDecl();
  4646. }
  4647. } else {
  4648. // `inline` variables are a definition and declaration all in one; we won't
  4649. // pick up an initializer from anywhere else.
  4650. if (Var->isStaticDataMember() && !Var->isInline()) {
  4651. if (!Var->isOutOfLine())
  4652. return;
  4653. // If the declaration inside the class had an initializer, don't add
  4654. // another one to the out-of-line definition.
  4655. if (OldVar->getFirstDecl()->hasInit())
  4656. return;
  4657. }
  4658. // We'll add an initializer to a for-range declaration later.
  4659. if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
  4660. return;
  4661. ActOnUninitializedDecl(Var);
  4662. }
  4663. if (getLangOpts().CUDA)
  4664. checkAllowedCUDAInitializer(Var);
  4665. }
  4666. /// Instantiate the definition of the given variable from its
  4667. /// template.
  4668. ///
  4669. /// \param PointOfInstantiation the point at which the instantiation was
  4670. /// required. Note that this is not precisely a "point of instantiation"
  4671. /// for the variable, but it's close.
  4672. ///
  4673. /// \param Var the already-instantiated declaration of a templated variable.
  4674. ///
  4675. /// \param Recursive if true, recursively instantiates any functions that
  4676. /// are required by this instantiation.
  4677. ///
  4678. /// \param DefinitionRequired if true, then we are performing an explicit
  4679. /// instantiation where a definition of the variable is required. Complain
  4680. /// if there is no such definition.
  4681. void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
  4682. VarDecl *Var, bool Recursive,
  4683. bool DefinitionRequired, bool AtEndOfTU) {
  4684. if (Var->isInvalidDecl())
  4685. return;
  4686. // Never instantiate an explicitly-specialized entity.
  4687. TemplateSpecializationKind TSK =
  4688. Var->getTemplateSpecializationKindForInstantiation();
  4689. if (TSK == TSK_ExplicitSpecialization)
  4690. return;
  4691. // Find the pattern and the arguments to substitute into it.
  4692. VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
  4693. assert(PatternDecl && "no pattern for templated variable");
  4694. MultiLevelTemplateArgumentList TemplateArgs =
  4695. getTemplateInstantiationArgs(Var);
  4696. VarTemplateSpecializationDecl *VarSpec =
  4697. dyn_cast<VarTemplateSpecializationDecl>(Var);
  4698. if (VarSpec) {
  4699. // If this is a static data member template, there might be an
  4700. // uninstantiated initializer on the declaration. If so, instantiate
  4701. // it now.
  4702. //
  4703. // FIXME: This largely duplicates what we would do below. The difference
  4704. // is that along this path we may instantiate an initializer from an
  4705. // in-class declaration of the template and instantiate the definition
  4706. // from a separate out-of-class definition.
  4707. if (PatternDecl->isStaticDataMember() &&
  4708. (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
  4709. !Var->hasInit()) {
  4710. // FIXME: Factor out the duplicated instantiation context setup/tear down
  4711. // code here.
  4712. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  4713. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  4714. return;
  4715. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  4716. "instantiating variable initializer");
  4717. // The instantiation is visible here, even if it was first declared in an
  4718. // unimported module.
  4719. Var->setVisibleDespiteOwningModule();
  4720. // If we're performing recursive template instantiation, create our own
  4721. // queue of pending implicit instantiations that we will instantiate
  4722. // later, while we're still within our own instantiation context.
  4723. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  4724. /*Enabled=*/Recursive);
  4725. LocalInstantiationScope Local(*this);
  4726. LocalEagerInstantiationScope LocalInstantiations(*this);
  4727. // Enter the scope of this instantiation. We don't use
  4728. // PushDeclContext because we don't have a scope.
  4729. ContextRAII PreviousContext(*this, Var->getDeclContext());
  4730. InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
  4731. PreviousContext.pop();
  4732. // This variable may have local implicit instantiations that need to be
  4733. // instantiated within this scope.
  4734. LocalInstantiations.perform();
  4735. Local.Exit();
  4736. GlobalInstantiations.perform();
  4737. }
  4738. } else {
  4739. assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
  4740. "not a static data member?");
  4741. }
  4742. VarDecl *Def = PatternDecl->getDefinition(getASTContext());
  4743. // If we don't have a definition of the variable template, we won't perform
  4744. // any instantiation. Rather, we rely on the user to instantiate this
  4745. // definition (or provide a specialization for it) in another translation
  4746. // unit.
  4747. if (!Def && !DefinitionRequired) {
  4748. if (TSK == TSK_ExplicitInstantiationDefinition) {
  4749. PendingInstantiations.push_back(
  4750. std::make_pair(Var, PointOfInstantiation));
  4751. } else if (TSK == TSK_ImplicitInstantiation) {
  4752. // Warn about missing definition at the end of translation unit.
  4753. if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
  4754. !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
  4755. Diag(PointOfInstantiation, diag::warn_var_template_missing)
  4756. << Var;
  4757. Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
  4758. if (getLangOpts().CPlusPlus11)
  4759. Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
  4760. }
  4761. return;
  4762. }
  4763. }
  4764. // FIXME: We need to track the instantiation stack in order to know which
  4765. // definitions should be visible within this instantiation.
  4766. // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
  4767. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
  4768. /*InstantiatedFromMember*/false,
  4769. PatternDecl, Def, TSK,
  4770. /*Complain*/DefinitionRequired))
  4771. return;
  4772. // C++11 [temp.explicit]p10:
  4773. // Except for inline functions, const variables of literal types, variables
  4774. // of reference types, [...] explicit instantiation declarations
  4775. // have the effect of suppressing the implicit instantiation of the entity
  4776. // to which they refer.
  4777. //
  4778. // FIXME: That's not exactly the same as "might be usable in constant
  4779. // expressions", which only allows constexpr variables and const integral
  4780. // types, not arbitrary const literal types.
  4781. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  4782. !Var->mightBeUsableInConstantExpressions(getASTContext()))
  4783. return;
  4784. // Make sure to pass the instantiated variable to the consumer at the end.
  4785. struct PassToConsumerRAII {
  4786. ASTConsumer &Consumer;
  4787. VarDecl *Var;
  4788. PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
  4789. : Consumer(Consumer), Var(Var) { }
  4790. ~PassToConsumerRAII() {
  4791. Consumer.HandleCXXStaticMemberVarInstantiation(Var);
  4792. }
  4793. } PassToConsumerRAII(Consumer, Var);
  4794. // If we already have a definition, we're done.
  4795. if (VarDecl *Def = Var->getDefinition()) {
  4796. // We may be explicitly instantiating something we've already implicitly
  4797. // instantiated.
  4798. Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
  4799. PointOfInstantiation);
  4800. return;
  4801. }
  4802. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  4803. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  4804. return;
  4805. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  4806. "instantiating variable definition");
  4807. // If we're performing recursive template instantiation, create our own
  4808. // queue of pending implicit instantiations that we will instantiate later,
  4809. // while we're still within our own instantiation context.
  4810. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  4811. /*Enabled=*/Recursive);
  4812. // Enter the scope of this instantiation. We don't use
  4813. // PushDeclContext because we don't have a scope.
  4814. ContextRAII PreviousContext(*this, Var->getDeclContext());
  4815. LocalInstantiationScope Local(*this);
  4816. LocalEagerInstantiationScope LocalInstantiations(*this);
  4817. VarDecl *OldVar = Var;
  4818. if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
  4819. // We're instantiating an inline static data member whose definition was
  4820. // provided inside the class.
  4821. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  4822. } else if (!VarSpec) {
  4823. Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
  4824. TemplateArgs));
  4825. } else if (Var->isStaticDataMember() &&
  4826. Var->getLexicalDeclContext()->isRecord()) {
  4827. // We need to instantiate the definition of a static data member template,
  4828. // and all we have is the in-class declaration of it. Instantiate a separate
  4829. // declaration of the definition.
  4830. TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
  4831. TemplateArgs);
  4832. TemplateArgumentListInfo TemplateArgInfo;
  4833. if (const ASTTemplateArgumentListInfo *ArgInfo =
  4834. VarSpec->getTemplateArgsInfo()) {
  4835. TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
  4836. TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
  4837. for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
  4838. TemplateArgInfo.addArgument(Arg);
  4839. }
  4840. Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
  4841. VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
  4842. VarSpec->getTemplateArgs().asArray(), VarSpec));
  4843. if (Var) {
  4844. llvm::PointerUnion<VarTemplateDecl *,
  4845. VarTemplatePartialSpecializationDecl *> PatternPtr =
  4846. VarSpec->getSpecializedTemplateOrPartial();
  4847. if (VarTemplatePartialSpecializationDecl *Partial =
  4848. PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
  4849. cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
  4850. Partial, &VarSpec->getTemplateInstantiationArgs());
  4851. // Attach the initializer.
  4852. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  4853. }
  4854. } else
  4855. // Complete the existing variable's definition with an appropriately
  4856. // substituted type and initializer.
  4857. Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
  4858. PreviousContext.pop();
  4859. if (Var) {
  4860. PassToConsumerRAII.Var = Var;
  4861. Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
  4862. OldVar->getPointOfInstantiation());
  4863. }
  4864. // This variable may have local implicit instantiations that need to be
  4865. // instantiated within this scope.
  4866. LocalInstantiations.perform();
  4867. Local.Exit();
  4868. GlobalInstantiations.perform();
  4869. }
  4870. void
  4871. Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
  4872. const CXXConstructorDecl *Tmpl,
  4873. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4874. SmallVector<CXXCtorInitializer*, 4> NewInits;
  4875. bool AnyErrors = Tmpl->isInvalidDecl();
  4876. // Instantiate all the initializers.
  4877. for (const auto *Init : Tmpl->inits()) {
  4878. // Only instantiate written initializers, let Sema re-construct implicit
  4879. // ones.
  4880. if (!Init->isWritten())
  4881. continue;
  4882. SourceLocation EllipsisLoc;
  4883. if (Init->isPackExpansion()) {
  4884. // This is a pack expansion. We should expand it now.
  4885. TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
  4886. SmallVector<UnexpandedParameterPack, 4> Unexpanded;
  4887. collectUnexpandedParameterPacks(BaseTL, Unexpanded);
  4888. collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
  4889. bool ShouldExpand = false;
  4890. bool RetainExpansion = false;
  4891. std::optional<unsigned> NumExpansions;
  4892. if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
  4893. BaseTL.getSourceRange(),
  4894. Unexpanded,
  4895. TemplateArgs, ShouldExpand,
  4896. RetainExpansion,
  4897. NumExpansions)) {
  4898. AnyErrors = true;
  4899. New->setInvalidDecl();
  4900. continue;
  4901. }
  4902. assert(ShouldExpand && "Partial instantiation of base initializer?");
  4903. // Loop over all of the arguments in the argument pack(s),
  4904. for (unsigned I = 0; I != *NumExpansions; ++I) {
  4905. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  4906. // Instantiate the initializer.
  4907. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  4908. /*CXXDirectInit=*/true);
  4909. if (TempInit.isInvalid()) {
  4910. AnyErrors = true;
  4911. break;
  4912. }
  4913. // Instantiate the base type.
  4914. TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
  4915. TemplateArgs,
  4916. Init->getSourceLocation(),
  4917. New->getDeclName());
  4918. if (!BaseTInfo) {
  4919. AnyErrors = true;
  4920. break;
  4921. }
  4922. // Build the initializer.
  4923. MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
  4924. BaseTInfo, TempInit.get(),
  4925. New->getParent(),
  4926. SourceLocation());
  4927. if (NewInit.isInvalid()) {
  4928. AnyErrors = true;
  4929. break;
  4930. }
  4931. NewInits.push_back(NewInit.get());
  4932. }
  4933. continue;
  4934. }
  4935. // Instantiate the initializer.
  4936. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  4937. /*CXXDirectInit=*/true);
  4938. if (TempInit.isInvalid()) {
  4939. AnyErrors = true;
  4940. continue;
  4941. }
  4942. MemInitResult NewInit;
  4943. if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
  4944. TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
  4945. TemplateArgs,
  4946. Init->getSourceLocation(),
  4947. New->getDeclName());
  4948. if (!TInfo) {
  4949. AnyErrors = true;
  4950. New->setInvalidDecl();
  4951. continue;
  4952. }
  4953. if (Init->isBaseInitializer())
  4954. NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
  4955. New->getParent(), EllipsisLoc);
  4956. else
  4957. NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
  4958. cast<CXXRecordDecl>(CurContext->getParent()));
  4959. } else if (Init->isMemberInitializer()) {
  4960. FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
  4961. Init->getMemberLocation(),
  4962. Init->getMember(),
  4963. TemplateArgs));
  4964. if (!Member) {
  4965. AnyErrors = true;
  4966. New->setInvalidDecl();
  4967. continue;
  4968. }
  4969. NewInit = BuildMemberInitializer(Member, TempInit.get(),
  4970. Init->getSourceLocation());
  4971. } else if (Init->isIndirectMemberInitializer()) {
  4972. IndirectFieldDecl *IndirectMember =
  4973. cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
  4974. Init->getMemberLocation(),
  4975. Init->getIndirectMember(), TemplateArgs));
  4976. if (!IndirectMember) {
  4977. AnyErrors = true;
  4978. New->setInvalidDecl();
  4979. continue;
  4980. }
  4981. NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
  4982. Init->getSourceLocation());
  4983. }
  4984. if (NewInit.isInvalid()) {
  4985. AnyErrors = true;
  4986. New->setInvalidDecl();
  4987. } else {
  4988. NewInits.push_back(NewInit.get());
  4989. }
  4990. }
  4991. // Assign all the initializers to the new constructor.
  4992. ActOnMemInitializers(New,
  4993. /*FIXME: ColonLoc */
  4994. SourceLocation(),
  4995. NewInits,
  4996. AnyErrors);
  4997. }
  4998. // TODO: this could be templated if the various decl types used the
  4999. // same method name.
  5000. static bool isInstantiationOf(ClassTemplateDecl *Pattern,
  5001. ClassTemplateDecl *Instance) {
  5002. Pattern = Pattern->getCanonicalDecl();
  5003. do {
  5004. Instance = Instance->getCanonicalDecl();
  5005. if (Pattern == Instance) return true;
  5006. Instance = Instance->getInstantiatedFromMemberTemplate();
  5007. } while (Instance);
  5008. return false;
  5009. }
  5010. static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
  5011. FunctionTemplateDecl *Instance) {
  5012. Pattern = Pattern->getCanonicalDecl();
  5013. do {
  5014. Instance = Instance->getCanonicalDecl();
  5015. if (Pattern == Instance) return true;
  5016. Instance = Instance->getInstantiatedFromMemberTemplate();
  5017. } while (Instance);
  5018. return false;
  5019. }
  5020. static bool
  5021. isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
  5022. ClassTemplatePartialSpecializationDecl *Instance) {
  5023. Pattern
  5024. = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
  5025. do {
  5026. Instance = cast<ClassTemplatePartialSpecializationDecl>(
  5027. Instance->getCanonicalDecl());
  5028. if (Pattern == Instance)
  5029. return true;
  5030. Instance = Instance->getInstantiatedFromMember();
  5031. } while (Instance);
  5032. return false;
  5033. }
  5034. static bool isInstantiationOf(CXXRecordDecl *Pattern,
  5035. CXXRecordDecl *Instance) {
  5036. Pattern = Pattern->getCanonicalDecl();
  5037. do {
  5038. Instance = Instance->getCanonicalDecl();
  5039. if (Pattern == Instance) return true;
  5040. Instance = Instance->getInstantiatedFromMemberClass();
  5041. } while (Instance);
  5042. return false;
  5043. }
  5044. static bool isInstantiationOf(FunctionDecl *Pattern,
  5045. FunctionDecl *Instance) {
  5046. Pattern = Pattern->getCanonicalDecl();
  5047. do {
  5048. Instance = Instance->getCanonicalDecl();
  5049. if (Pattern == Instance) return true;
  5050. Instance = Instance->getInstantiatedFromMemberFunction();
  5051. } while (Instance);
  5052. return false;
  5053. }
  5054. static bool isInstantiationOf(EnumDecl *Pattern,
  5055. EnumDecl *Instance) {
  5056. Pattern = Pattern->getCanonicalDecl();
  5057. do {
  5058. Instance = Instance->getCanonicalDecl();
  5059. if (Pattern == Instance) return true;
  5060. Instance = Instance->getInstantiatedFromMemberEnum();
  5061. } while (Instance);
  5062. return false;
  5063. }
  5064. static bool isInstantiationOf(UsingShadowDecl *Pattern,
  5065. UsingShadowDecl *Instance,
  5066. ASTContext &C) {
  5067. return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
  5068. Pattern);
  5069. }
  5070. static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
  5071. ASTContext &C) {
  5072. return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
  5073. }
  5074. template<typename T>
  5075. static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
  5076. ASTContext &Ctx) {
  5077. // An unresolved using declaration can instantiate to an unresolved using
  5078. // declaration, or to a using declaration or a using declaration pack.
  5079. //
  5080. // Multiple declarations can claim to be instantiated from an unresolved
  5081. // using declaration if it's a pack expansion. We want the UsingPackDecl
  5082. // in that case, not the individual UsingDecls within the pack.
  5083. bool OtherIsPackExpansion;
  5084. NamedDecl *OtherFrom;
  5085. if (auto *OtherUUD = dyn_cast<T>(Other)) {
  5086. OtherIsPackExpansion = OtherUUD->isPackExpansion();
  5087. OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
  5088. } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
  5089. OtherIsPackExpansion = true;
  5090. OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
  5091. } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
  5092. OtherIsPackExpansion = false;
  5093. OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
  5094. } else {
  5095. return false;
  5096. }
  5097. return Pattern->isPackExpansion() == OtherIsPackExpansion &&
  5098. declaresSameEntity(OtherFrom, Pattern);
  5099. }
  5100. static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
  5101. VarDecl *Instance) {
  5102. assert(Instance->isStaticDataMember());
  5103. Pattern = Pattern->getCanonicalDecl();
  5104. do {
  5105. Instance = Instance->getCanonicalDecl();
  5106. if (Pattern == Instance) return true;
  5107. Instance = Instance->getInstantiatedFromStaticDataMember();
  5108. } while (Instance);
  5109. return false;
  5110. }
  5111. // Other is the prospective instantiation
  5112. // D is the prospective pattern
  5113. static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
  5114. if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
  5115. return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
  5116. if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
  5117. return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
  5118. if (D->getKind() != Other->getKind())
  5119. return false;
  5120. if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
  5121. return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
  5122. if (auto *Function = dyn_cast<FunctionDecl>(Other))
  5123. return isInstantiationOf(cast<FunctionDecl>(D), Function);
  5124. if (auto *Enum = dyn_cast<EnumDecl>(Other))
  5125. return isInstantiationOf(cast<EnumDecl>(D), Enum);
  5126. if (auto *Var = dyn_cast<VarDecl>(Other))
  5127. if (Var->isStaticDataMember())
  5128. return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
  5129. if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
  5130. return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
  5131. if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
  5132. return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
  5133. if (auto *PartialSpec =
  5134. dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
  5135. return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
  5136. PartialSpec);
  5137. if (auto *Field = dyn_cast<FieldDecl>(Other)) {
  5138. if (!Field->getDeclName()) {
  5139. // This is an unnamed field.
  5140. return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
  5141. cast<FieldDecl>(D));
  5142. }
  5143. }
  5144. if (auto *Using = dyn_cast<UsingDecl>(Other))
  5145. return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
  5146. if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
  5147. return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
  5148. return D->getDeclName() &&
  5149. D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
  5150. }
  5151. template<typename ForwardIterator>
  5152. static NamedDecl *findInstantiationOf(ASTContext &Ctx,
  5153. NamedDecl *D,
  5154. ForwardIterator first,
  5155. ForwardIterator last) {
  5156. for (; first != last; ++first)
  5157. if (isInstantiationOf(Ctx, D, *first))
  5158. return cast<NamedDecl>(*first);
  5159. return nullptr;
  5160. }
  5161. /// Finds the instantiation of the given declaration context
  5162. /// within the current instantiation.
  5163. ///
  5164. /// \returns NULL if there was an error
  5165. DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
  5166. const MultiLevelTemplateArgumentList &TemplateArgs) {
  5167. if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
  5168. Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
  5169. return cast_or_null<DeclContext>(ID);
  5170. } else return DC;
  5171. }
  5172. /// Determine whether the given context is dependent on template parameters at
  5173. /// level \p Level or below.
  5174. ///
  5175. /// Sometimes we only substitute an inner set of template arguments and leave
  5176. /// the outer templates alone. In such cases, contexts dependent only on the
  5177. /// outer levels are not effectively dependent.
  5178. static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
  5179. if (!DC->isDependentContext())
  5180. return false;
  5181. if (!Level)
  5182. return true;
  5183. return cast<Decl>(DC)->getTemplateDepth() > Level;
  5184. }
  5185. /// Find the instantiation of the given declaration within the
  5186. /// current instantiation.
  5187. ///
  5188. /// This routine is intended to be used when \p D is a declaration
  5189. /// referenced from within a template, that needs to mapped into the
  5190. /// corresponding declaration within an instantiation. For example,
  5191. /// given:
  5192. ///
  5193. /// \code
  5194. /// template<typename T>
  5195. /// struct X {
  5196. /// enum Kind {
  5197. /// KnownValue = sizeof(T)
  5198. /// };
  5199. ///
  5200. /// bool getKind() const { return KnownValue; }
  5201. /// };
  5202. ///
  5203. /// template struct X<int>;
  5204. /// \endcode
  5205. ///
  5206. /// In the instantiation of X<int>::getKind(), we need to map the \p
  5207. /// EnumConstantDecl for \p KnownValue (which refers to
  5208. /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
  5209. /// \p FindInstantiatedDecl performs this mapping from within the instantiation
  5210. /// of X<int>.
  5211. NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
  5212. const MultiLevelTemplateArgumentList &TemplateArgs,
  5213. bool FindingInstantiatedContext) {
  5214. DeclContext *ParentDC = D->getDeclContext();
  5215. // Determine whether our parent context depends on any of the template
  5216. // arguments we're currently substituting.
  5217. bool ParentDependsOnArgs = isDependentContextAtLevel(
  5218. ParentDC, TemplateArgs.getNumRetainedOuterLevels());
  5219. // FIXME: Parameters of pointer to functions (y below) that are themselves
  5220. // parameters (p below) can have their ParentDC set to the translation-unit
  5221. // - thus we can not consistently check if the ParentDC of such a parameter
  5222. // is Dependent or/and a FunctionOrMethod.
  5223. // For e.g. this code, during Template argument deduction tries to
  5224. // find an instantiated decl for (T y) when the ParentDC for y is
  5225. // the translation unit.
  5226. // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
  5227. // float baz(float(*)()) { return 0.0; }
  5228. // Foo(baz);
  5229. // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
  5230. // it gets here, always has a FunctionOrMethod as its ParentDC??
  5231. // For now:
  5232. // - as long as we have a ParmVarDecl whose parent is non-dependent and
  5233. // whose type is not instantiation dependent, do nothing to the decl
  5234. // - otherwise find its instantiated decl.
  5235. if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
  5236. !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
  5237. return D;
  5238. if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
  5239. isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
  5240. (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
  5241. isa<OMPDeclareReductionDecl>(ParentDC) ||
  5242. isa<OMPDeclareMapperDecl>(ParentDC))) ||
  5243. (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
  5244. cast<CXXRecordDecl>(D)->getTemplateDepth() >
  5245. TemplateArgs.getNumRetainedOuterLevels())) {
  5246. // D is a local of some kind. Look into the map of local
  5247. // declarations to their instantiations.
  5248. if (CurrentInstantiationScope) {
  5249. if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
  5250. if (Decl *FD = Found->dyn_cast<Decl *>())
  5251. return cast<NamedDecl>(FD);
  5252. int PackIdx = ArgumentPackSubstitutionIndex;
  5253. assert(PackIdx != -1 &&
  5254. "found declaration pack but not pack expanding");
  5255. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  5256. return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
  5257. }
  5258. }
  5259. // If we're performing a partial substitution during template argument
  5260. // deduction, we may not have values for template parameters yet. They
  5261. // just map to themselves.
  5262. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  5263. isa<TemplateTemplateParmDecl>(D))
  5264. return D;
  5265. if (D->isInvalidDecl())
  5266. return nullptr;
  5267. // Normally this function only searches for already instantiated declaration
  5268. // however we have to make an exclusion for local types used before
  5269. // definition as in the code:
  5270. //
  5271. // template<typename T> void f1() {
  5272. // void g1(struct x1);
  5273. // struct x1 {};
  5274. // }
  5275. //
  5276. // In this case instantiation of the type of 'g1' requires definition of
  5277. // 'x1', which is defined later. Error recovery may produce an enum used
  5278. // before definition. In these cases we need to instantiate relevant
  5279. // declarations here.
  5280. bool NeedInstantiate = false;
  5281. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  5282. NeedInstantiate = RD->isLocalClass();
  5283. else if (isa<TypedefNameDecl>(D) &&
  5284. isa<CXXDeductionGuideDecl>(D->getDeclContext()))
  5285. NeedInstantiate = true;
  5286. else
  5287. NeedInstantiate = isa<EnumDecl>(D);
  5288. if (NeedInstantiate) {
  5289. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  5290. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  5291. return cast<TypeDecl>(Inst);
  5292. }
  5293. // If we didn't find the decl, then we must have a label decl that hasn't
  5294. // been found yet. Lazily instantiate it and return it now.
  5295. assert(isa<LabelDecl>(D));
  5296. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  5297. assert(Inst && "Failed to instantiate label??");
  5298. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  5299. return cast<LabelDecl>(Inst);
  5300. }
  5301. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  5302. if (!Record->isDependentContext())
  5303. return D;
  5304. // Determine whether this record is the "templated" declaration describing
  5305. // a class template or class template partial specialization.
  5306. ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
  5307. if (ClassTemplate)
  5308. ClassTemplate = ClassTemplate->getCanonicalDecl();
  5309. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  5310. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
  5311. ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
  5312. // Walk the current context to find either the record or an instantiation of
  5313. // it.
  5314. DeclContext *DC = CurContext;
  5315. while (!DC->isFileContext()) {
  5316. // If we're performing substitution while we're inside the template
  5317. // definition, we'll find our own context. We're done.
  5318. if (DC->Equals(Record))
  5319. return Record;
  5320. if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
  5321. // Check whether we're in the process of instantiating a class template
  5322. // specialization of the template we're mapping.
  5323. if (ClassTemplateSpecializationDecl *InstSpec
  5324. = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
  5325. ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
  5326. if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
  5327. return InstRecord;
  5328. }
  5329. // Check whether we're in the process of instantiating a member class.
  5330. if (isInstantiationOf(Record, InstRecord))
  5331. return InstRecord;
  5332. }
  5333. // Move to the outer template scope.
  5334. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
  5335. if (FD->getFriendObjectKind() &&
  5336. FD->getNonTransparentDeclContext()->isFileContext()) {
  5337. DC = FD->getLexicalDeclContext();
  5338. continue;
  5339. }
  5340. // An implicit deduction guide acts as if it's within the class template
  5341. // specialization described by its name and first N template params.
  5342. auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
  5343. if (Guide && Guide->isImplicit()) {
  5344. TemplateDecl *TD = Guide->getDeducedTemplate();
  5345. // Convert the arguments to an "as-written" list.
  5346. TemplateArgumentListInfo Args(Loc, Loc);
  5347. for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
  5348. TD->getTemplateParameters()->size())) {
  5349. ArrayRef<TemplateArgument> Unpacked(Arg);
  5350. if (Arg.getKind() == TemplateArgument::Pack)
  5351. Unpacked = Arg.pack_elements();
  5352. for (TemplateArgument UnpackedArg : Unpacked)
  5353. Args.addArgument(
  5354. getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
  5355. }
  5356. QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
  5357. if (T.isNull())
  5358. return nullptr;
  5359. auto *SubstRecord = T->getAsCXXRecordDecl();
  5360. assert(SubstRecord && "class template id not a class type?");
  5361. // Check that this template-id names the primary template and not a
  5362. // partial or explicit specialization. (In the latter cases, it's
  5363. // meaningless to attempt to find an instantiation of D within the
  5364. // specialization.)
  5365. // FIXME: The standard doesn't say what should happen here.
  5366. if (FindingInstantiatedContext &&
  5367. usesPartialOrExplicitSpecialization(
  5368. Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
  5369. Diag(Loc, diag::err_specialization_not_primary_template)
  5370. << T << (SubstRecord->getTemplateSpecializationKind() ==
  5371. TSK_ExplicitSpecialization);
  5372. return nullptr;
  5373. }
  5374. DC = SubstRecord;
  5375. continue;
  5376. }
  5377. }
  5378. DC = DC->getParent();
  5379. }
  5380. // Fall through to deal with other dependent record types (e.g.,
  5381. // anonymous unions in class templates).
  5382. }
  5383. if (!ParentDependsOnArgs)
  5384. return D;
  5385. ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
  5386. if (!ParentDC)
  5387. return nullptr;
  5388. if (ParentDC != D->getDeclContext()) {
  5389. // We performed some kind of instantiation in the parent context,
  5390. // so now we need to look into the instantiated parent context to
  5391. // find the instantiation of the declaration D.
  5392. // If our context used to be dependent, we may need to instantiate
  5393. // it before performing lookup into that context.
  5394. bool IsBeingInstantiated = false;
  5395. if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
  5396. if (!Spec->isDependentContext()) {
  5397. QualType T = Context.getTypeDeclType(Spec);
  5398. const RecordType *Tag = T->getAs<RecordType>();
  5399. assert(Tag && "type of non-dependent record is not a RecordType");
  5400. if (Tag->isBeingDefined())
  5401. IsBeingInstantiated = true;
  5402. if (!Tag->isBeingDefined() &&
  5403. RequireCompleteType(Loc, T, diag::err_incomplete_type))
  5404. return nullptr;
  5405. ParentDC = Tag->getDecl();
  5406. }
  5407. }
  5408. NamedDecl *Result = nullptr;
  5409. // FIXME: If the name is a dependent name, this lookup won't necessarily
  5410. // find it. Does that ever matter?
  5411. if (auto Name = D->getDeclName()) {
  5412. DeclarationNameInfo NameInfo(Name, D->getLocation());
  5413. DeclarationNameInfo NewNameInfo =
  5414. SubstDeclarationNameInfo(NameInfo, TemplateArgs);
  5415. Name = NewNameInfo.getName();
  5416. if (!Name)
  5417. return nullptr;
  5418. DeclContext::lookup_result Found = ParentDC->lookup(Name);
  5419. Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
  5420. } else {
  5421. // Since we don't have a name for the entity we're looking for,
  5422. // our only option is to walk through all of the declarations to
  5423. // find that name. This will occur in a few cases:
  5424. //
  5425. // - anonymous struct/union within a template
  5426. // - unnamed class/struct/union/enum within a template
  5427. //
  5428. // FIXME: Find a better way to find these instantiations!
  5429. Result = findInstantiationOf(Context, D,
  5430. ParentDC->decls_begin(),
  5431. ParentDC->decls_end());
  5432. }
  5433. if (!Result) {
  5434. if (isa<UsingShadowDecl>(D)) {
  5435. // UsingShadowDecls can instantiate to nothing because of using hiding.
  5436. } else if (hasUncompilableErrorOccurred()) {
  5437. // We've already complained about some ill-formed code, so most likely
  5438. // this declaration failed to instantiate. There's no point in
  5439. // complaining further, since this is normal in invalid code.
  5440. // FIXME: Use more fine-grained 'invalid' tracking for this.
  5441. } else if (IsBeingInstantiated) {
  5442. // The class in which this member exists is currently being
  5443. // instantiated, and we haven't gotten around to instantiating this
  5444. // member yet. This can happen when the code uses forward declarations
  5445. // of member classes, and introduces ordering dependencies via
  5446. // template instantiation.
  5447. Diag(Loc, diag::err_member_not_yet_instantiated)
  5448. << D->getDeclName()
  5449. << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
  5450. Diag(D->getLocation(), diag::note_non_instantiated_member_here);
  5451. } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  5452. // This enumeration constant was found when the template was defined,
  5453. // but can't be found in the instantiation. This can happen if an
  5454. // unscoped enumeration member is explicitly specialized.
  5455. EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
  5456. EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
  5457. TemplateArgs));
  5458. assert(Spec->getTemplateSpecializationKind() ==
  5459. TSK_ExplicitSpecialization);
  5460. Diag(Loc, diag::err_enumerator_does_not_exist)
  5461. << D->getDeclName()
  5462. << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
  5463. Diag(Spec->getLocation(), diag::note_enum_specialized_here)
  5464. << Context.getTypeDeclType(Spec);
  5465. } else {
  5466. // We should have found something, but didn't.
  5467. llvm_unreachable("Unable to find instantiation of declaration!");
  5468. }
  5469. }
  5470. D = Result;
  5471. }
  5472. return D;
  5473. }
  5474. /// Performs template instantiation for all implicit template
  5475. /// instantiations we have seen until this point.
  5476. void Sema::PerformPendingInstantiations(bool LocalOnly) {
  5477. std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
  5478. while (!PendingLocalImplicitInstantiations.empty() ||
  5479. (!LocalOnly && !PendingInstantiations.empty())) {
  5480. PendingImplicitInstantiation Inst;
  5481. if (PendingLocalImplicitInstantiations.empty()) {
  5482. Inst = PendingInstantiations.front();
  5483. PendingInstantiations.pop_front();
  5484. } else {
  5485. Inst = PendingLocalImplicitInstantiations.front();
  5486. PendingLocalImplicitInstantiations.pop_front();
  5487. }
  5488. // Instantiate function definitions
  5489. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
  5490. bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
  5491. TSK_ExplicitInstantiationDefinition;
  5492. if (Function->isMultiVersion()) {
  5493. getASTContext().forEachMultiversionedFunctionVersion(
  5494. Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
  5495. InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
  5496. DefinitionRequired, true);
  5497. if (CurFD->isDefined())
  5498. CurFD->setInstantiationIsPending(false);
  5499. });
  5500. } else {
  5501. InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
  5502. DefinitionRequired, true);
  5503. if (Function->isDefined())
  5504. Function->setInstantiationIsPending(false);
  5505. }
  5506. // Definition of a PCH-ed template declaration may be available only in the TU.
  5507. if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
  5508. TUKind == TU_Prefix && Function->instantiationIsPending())
  5509. delayedPCHInstantiations.push_back(Inst);
  5510. continue;
  5511. }
  5512. // Instantiate variable definitions
  5513. VarDecl *Var = cast<VarDecl>(Inst.first);
  5514. assert((Var->isStaticDataMember() ||
  5515. isa<VarTemplateSpecializationDecl>(Var)) &&
  5516. "Not a static data member, nor a variable template"
  5517. " specialization?");
  5518. // Don't try to instantiate declarations if the most recent redeclaration
  5519. // is invalid.
  5520. if (Var->getMostRecentDecl()->isInvalidDecl())
  5521. continue;
  5522. // Check if the most recent declaration has changed the specialization kind
  5523. // and removed the need for implicit instantiation.
  5524. switch (Var->getMostRecentDecl()
  5525. ->getTemplateSpecializationKindForInstantiation()) {
  5526. case TSK_Undeclared:
  5527. llvm_unreachable("Cannot instantitiate an undeclared specialization.");
  5528. case TSK_ExplicitInstantiationDeclaration:
  5529. case TSK_ExplicitSpecialization:
  5530. continue; // No longer need to instantiate this type.
  5531. case TSK_ExplicitInstantiationDefinition:
  5532. // We only need an instantiation if the pending instantiation *is* the
  5533. // explicit instantiation.
  5534. if (Var != Var->getMostRecentDecl())
  5535. continue;
  5536. break;
  5537. case TSK_ImplicitInstantiation:
  5538. break;
  5539. }
  5540. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  5541. "instantiating variable definition");
  5542. bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
  5543. TSK_ExplicitInstantiationDefinition;
  5544. // Instantiate static data member definitions or variable template
  5545. // specializations.
  5546. InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
  5547. DefinitionRequired, true);
  5548. }
  5549. if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
  5550. PendingInstantiations.swap(delayedPCHInstantiations);
  5551. }
  5552. void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
  5553. const MultiLevelTemplateArgumentList &TemplateArgs) {
  5554. for (auto *DD : Pattern->ddiags()) {
  5555. switch (DD->getKind()) {
  5556. case DependentDiagnostic::Access:
  5557. HandleDependentAccessCheck(*DD, TemplateArgs);
  5558. break;
  5559. }
  5560. }
  5561. }