SemaTemplateInstantiateDecl.cpp 219 KB

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