SemaTemplate.cpp 421 KB

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