SemaTemplateInstantiateDecl.cpp 222 KB

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