SemaTemplate.cpp 445 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102
  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/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Overload.h"
  28. #include "clang/Sema/ParsedTemplate.h"
  29. #include "clang/Sema/Scope.h"
  30. #include "clang/Sema/SemaInternal.h"
  31. #include "clang/Sema/Template.h"
  32. #include "clang/Sema/TemplateDeduction.h"
  33. #include "llvm/ADT/SmallBitVector.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/StringExtras.h"
  36. #include <iterator>
  37. using namespace clang;
  38. using namespace sema;
  39. // Exported for use by Parser.
  40. SourceRange
  41. clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
  42. unsigned N) {
  43. if (!N) return SourceRange();
  44. return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
  45. }
  46. unsigned Sema::getTemplateDepth(Scope *S) const {
  47. unsigned Depth = 0;
  48. // Each template parameter scope represents one level of template parameter
  49. // depth.
  50. for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
  51. TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
  52. ++Depth;
  53. }
  54. // Note that there are template parameters with the given depth.
  55. auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
  56. // Look for parameters of an enclosing generic lambda. We don't create a
  57. // template parameter scope for these.
  58. for (FunctionScopeInfo *FSI : getFunctionScopes()) {
  59. if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
  60. if (!LSI->TemplateParams.empty()) {
  61. ParamsAtDepth(LSI->AutoTemplateParameterDepth);
  62. break;
  63. }
  64. if (LSI->GLTemplateParameterList) {
  65. ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
  66. break;
  67. }
  68. }
  69. }
  70. // Look for parameters of an enclosing terse function template. We don't
  71. // create a template parameter scope for these either.
  72. for (const InventedTemplateParameterInfo &Info :
  73. getInventedParameterInfos()) {
  74. if (!Info.TemplateParams.empty()) {
  75. ParamsAtDepth(Info.AutoTemplateParameterDepth);
  76. break;
  77. }
  78. }
  79. return Depth;
  80. }
  81. /// \brief Determine whether the declaration found is acceptable as the name
  82. /// of a template and, if so, return that template declaration. Otherwise,
  83. /// returns null.
  84. ///
  85. /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
  86. /// is true. In all other cases it will return a TemplateDecl (or null).
  87. NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
  88. bool AllowFunctionTemplates,
  89. bool AllowDependent) {
  90. D = D->getUnderlyingDecl();
  91. if (isa<TemplateDecl>(D)) {
  92. if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
  93. return nullptr;
  94. return D;
  95. }
  96. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  97. // C++ [temp.local]p1:
  98. // Like normal (non-template) classes, class templates have an
  99. // injected-class-name (Clause 9). The injected-class-name
  100. // can be used with or without a template-argument-list. When
  101. // it is used without a template-argument-list, it is
  102. // equivalent to the injected-class-name followed by the
  103. // template-parameters of the class template enclosed in
  104. // <>. When it is used with a template-argument-list, it
  105. // refers to the specified class template specialization,
  106. // which could be the current specialization or another
  107. // specialization.
  108. if (Record->isInjectedClassName()) {
  109. Record = cast<CXXRecordDecl>(Record->getDeclContext());
  110. if (Record->getDescribedClassTemplate())
  111. return Record->getDescribedClassTemplate();
  112. if (ClassTemplateSpecializationDecl *Spec
  113. = dyn_cast<ClassTemplateSpecializationDecl>(Record))
  114. return Spec->getSpecializedTemplate();
  115. }
  116. return nullptr;
  117. }
  118. // 'using Dependent::foo;' can resolve to a template name.
  119. // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
  120. // injected-class-name).
  121. if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
  122. return D;
  123. return nullptr;
  124. }
  125. void Sema::FilterAcceptableTemplateNames(LookupResult &R,
  126. bool AllowFunctionTemplates,
  127. bool AllowDependent) {
  128. LookupResult::Filter filter = R.makeFilter();
  129. while (filter.hasNext()) {
  130. NamedDecl *Orig = filter.next();
  131. if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
  132. filter.erase();
  133. }
  134. filter.done();
  135. }
  136. bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
  137. bool AllowFunctionTemplates,
  138. bool AllowDependent,
  139. bool AllowNonTemplateFunctions) {
  140. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  141. if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
  142. return true;
  143. if (AllowNonTemplateFunctions &&
  144. isa<FunctionDecl>((*I)->getUnderlyingDecl()))
  145. return true;
  146. }
  147. return false;
  148. }
  149. TemplateNameKind Sema::isTemplateName(Scope *S,
  150. CXXScopeSpec &SS,
  151. bool hasTemplateKeyword,
  152. const UnqualifiedId &Name,
  153. ParsedType ObjectTypePtr,
  154. bool EnteringContext,
  155. TemplateTy &TemplateResult,
  156. bool &MemberOfUnknownSpecialization,
  157. bool Disambiguation) {
  158. assert(getLangOpts().CPlusPlus && "No template names in C!");
  159. DeclarationName TName;
  160. MemberOfUnknownSpecialization = false;
  161. switch (Name.getKind()) {
  162. case UnqualifiedIdKind::IK_Identifier:
  163. TName = DeclarationName(Name.Identifier);
  164. break;
  165. case UnqualifiedIdKind::IK_OperatorFunctionId:
  166. TName = Context.DeclarationNames.getCXXOperatorName(
  167. Name.OperatorFunctionId.Operator);
  168. break;
  169. case UnqualifiedIdKind::IK_LiteralOperatorId:
  170. TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
  171. break;
  172. default:
  173. return TNK_Non_template;
  174. }
  175. QualType ObjectType = ObjectTypePtr.get();
  176. AssumedTemplateKind AssumedTemplate;
  177. LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
  178. if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
  179. MemberOfUnknownSpecialization, SourceLocation(),
  180. &AssumedTemplate,
  181. /*AllowTypoCorrection=*/!Disambiguation))
  182. return TNK_Non_template;
  183. if (AssumedTemplate != AssumedTemplateKind::None) {
  184. TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
  185. // Let the parser know whether we found nothing or found functions; if we
  186. // found nothing, we want to more carefully check whether this is actually
  187. // a function template name versus some other kind of undeclared identifier.
  188. return AssumedTemplate == AssumedTemplateKind::FoundNothing
  189. ? TNK_Undeclared_template
  190. : TNK_Function_template;
  191. }
  192. if (R.empty())
  193. return TNK_Non_template;
  194. NamedDecl *D = nullptr;
  195. if (R.isAmbiguous()) {
  196. // If we got an ambiguity involving a non-function template, treat this
  197. // as a template name, and pick an arbitrary template for error recovery.
  198. bool AnyFunctionTemplates = false;
  199. for (NamedDecl *FoundD : R) {
  200. if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
  201. if (isa<FunctionTemplateDecl>(FoundTemplate))
  202. AnyFunctionTemplates = true;
  203. else {
  204. D = FoundTemplate;
  205. break;
  206. }
  207. }
  208. }
  209. // If we didn't find any templates at all, this isn't a template name.
  210. // Leave the ambiguity for a later lookup to diagnose.
  211. if (!D && !AnyFunctionTemplates) {
  212. R.suppressDiagnostics();
  213. return TNK_Non_template;
  214. }
  215. // If the only templates were function templates, filter out the rest.
  216. // We'll diagnose the ambiguity later.
  217. if (!D)
  218. FilterAcceptableTemplateNames(R);
  219. }
  220. // At this point, we have either picked a single template name declaration D
  221. // or we have a non-empty set of results R containing either one template name
  222. // declaration or a set of function templates.
  223. TemplateName Template;
  224. TemplateNameKind TemplateKind;
  225. unsigned ResultCount = R.end() - R.begin();
  226. if (!D && ResultCount > 1) {
  227. // We assume that we'll preserve the qualifier from a function
  228. // template name in other ways.
  229. Template = Context.getOverloadedTemplateName(R.begin(), R.end());
  230. TemplateKind = TNK_Function_template;
  231. // We'll do this lookup again later.
  232. R.suppressDiagnostics();
  233. } else {
  234. if (!D) {
  235. D = getAsTemplateNameDecl(*R.begin());
  236. assert(D && "unambiguous result is not a template name");
  237. }
  238. if (isa<UnresolvedUsingValueDecl>(D)) {
  239. // We don't yet know whether this is a template-name or not.
  240. MemberOfUnknownSpecialization = true;
  241. return TNK_Non_template;
  242. }
  243. TemplateDecl *TD = cast<TemplateDecl>(D);
  244. if (SS.isSet() && !SS.isInvalid()) {
  245. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  246. Template = Context.getQualifiedTemplateName(Qualifier,
  247. hasTemplateKeyword, TD);
  248. } else {
  249. Template = TemplateName(TD);
  250. }
  251. if (isa<FunctionTemplateDecl>(TD)) {
  252. TemplateKind = TNK_Function_template;
  253. // We'll do this lookup again later.
  254. R.suppressDiagnostics();
  255. } else {
  256. assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
  257. isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
  258. isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
  259. TemplateKind =
  260. isa<VarTemplateDecl>(TD) ? TNK_Var_template :
  261. isa<ConceptDecl>(TD) ? TNK_Concept_template :
  262. TNK_Type_template;
  263. }
  264. }
  265. TemplateResult = TemplateTy::make(Template);
  266. return TemplateKind;
  267. }
  268. bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
  269. SourceLocation NameLoc,
  270. ParsedTemplateTy *Template) {
  271. CXXScopeSpec SS;
  272. bool MemberOfUnknownSpecialization = false;
  273. // We could use redeclaration lookup here, but we don't need to: the
  274. // syntactic form of a deduction guide is enough to identify it even
  275. // if we can't look up the template name at all.
  276. LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
  277. if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
  278. /*EnteringContext*/ false,
  279. MemberOfUnknownSpecialization))
  280. return false;
  281. if (R.empty()) return false;
  282. if (R.isAmbiguous()) {
  283. // FIXME: Diagnose an ambiguity if we find at least one template.
  284. R.suppressDiagnostics();
  285. return false;
  286. }
  287. // We only treat template-names that name type templates as valid deduction
  288. // guide names.
  289. TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
  290. if (!TD || !getAsTypeTemplateDecl(TD))
  291. return false;
  292. if (Template)
  293. *Template = TemplateTy::make(TemplateName(TD));
  294. return true;
  295. }
  296. bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
  297. SourceLocation IILoc,
  298. Scope *S,
  299. const CXXScopeSpec *SS,
  300. TemplateTy &SuggestedTemplate,
  301. TemplateNameKind &SuggestedKind) {
  302. // We can't recover unless there's a dependent scope specifier preceding the
  303. // template name.
  304. // FIXME: Typo correction?
  305. if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
  306. computeDeclContext(*SS))
  307. return false;
  308. // The code is missing a 'template' keyword prior to the dependent template
  309. // name.
  310. NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
  311. Diag(IILoc, diag::err_template_kw_missing)
  312. << Qualifier << II.getName()
  313. << FixItHint::CreateInsertion(IILoc, "template ");
  314. SuggestedTemplate
  315. = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
  316. SuggestedKind = TNK_Dependent_template_name;
  317. return true;
  318. }
  319. bool Sema::LookupTemplateName(LookupResult &Found,
  320. Scope *S, CXXScopeSpec &SS,
  321. QualType ObjectType,
  322. bool EnteringContext,
  323. bool &MemberOfUnknownSpecialization,
  324. RequiredTemplateKind RequiredTemplate,
  325. AssumedTemplateKind *ATK,
  326. bool AllowTypoCorrection) {
  327. if (ATK)
  328. *ATK = AssumedTemplateKind::None;
  329. if (SS.isInvalid())
  330. return true;
  331. Found.setTemplateNameLookup(true);
  332. // Determine where to perform name lookup
  333. MemberOfUnknownSpecialization = false;
  334. DeclContext *LookupCtx = nullptr;
  335. bool IsDependent = false;
  336. if (!ObjectType.isNull()) {
  337. // This nested-name-specifier occurs in a member access expression, e.g.,
  338. // x->B::f, and we are looking into the type of the object.
  339. assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
  340. LookupCtx = computeDeclContext(ObjectType);
  341. IsDependent = !LookupCtx && ObjectType->isDependentType();
  342. assert((IsDependent || !ObjectType->isIncompleteType() ||
  343. ObjectType->castAs<TagType>()->isBeingDefined()) &&
  344. "Caller should have completed object type");
  345. // Template names cannot appear inside an Objective-C class or object type
  346. // or a vector type.
  347. //
  348. // FIXME: This is wrong. For example:
  349. //
  350. // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
  351. // Vec<int> vi;
  352. // vi.Vec<int>::~Vec<int>();
  353. //
  354. // ... should be accepted but we will not treat 'Vec' as a template name
  355. // here. The right thing to do would be to check if the name is a valid
  356. // vector component name, and look up a template name if not. And similarly
  357. // for lookups into Objective-C class and object types, where the same
  358. // problem can arise.
  359. if (ObjectType->isObjCObjectOrInterfaceType() ||
  360. ObjectType->isVectorType()) {
  361. Found.clear();
  362. return false;
  363. }
  364. } else if (SS.isNotEmpty()) {
  365. // This nested-name-specifier occurs after another nested-name-specifier,
  366. // so long into the context associated with the prior nested-name-specifier.
  367. LookupCtx = computeDeclContext(SS, EnteringContext);
  368. IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
  369. // The declaration context must be complete.
  370. if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
  371. return true;
  372. }
  373. bool ObjectTypeSearchedInScope = false;
  374. bool AllowFunctionTemplatesInLookup = true;
  375. if (LookupCtx) {
  376. // Perform "qualified" name lookup into the declaration context we
  377. // computed, which is either the type of the base of a member access
  378. // expression or the declaration context associated with a prior
  379. // nested-name-specifier.
  380. LookupQualifiedName(Found, LookupCtx);
  381. // FIXME: The C++ standard does not clearly specify what happens in the
  382. // case where the object type is dependent, and implementations vary. In
  383. // Clang, we treat a name after a . or -> as a template-name if lookup
  384. // finds a non-dependent member or member of the current instantiation that
  385. // is a type template, or finds no such members and lookup in the context
  386. // of the postfix-expression finds a type template. In the latter case, the
  387. // name is nonetheless dependent, and we may resolve it to a member of an
  388. // unknown specialization when we come to instantiate the template.
  389. IsDependent |= Found.wasNotFoundInCurrentInstantiation();
  390. }
  391. if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
  392. // C++ [basic.lookup.classref]p1:
  393. // In a class member access expression (5.2.5), if the . or -> token is
  394. // immediately followed by an identifier followed by a <, the
  395. // identifier must be looked up to determine whether the < is the
  396. // beginning of a template argument list (14.2) or a less-than operator.
  397. // The identifier is first looked up in the class of the object
  398. // expression. If the identifier is not found, it is then looked up in
  399. // the context of the entire postfix-expression and shall name a class
  400. // template.
  401. if (S)
  402. LookupName(Found, S);
  403. if (!ObjectType.isNull()) {
  404. // FIXME: We should filter out all non-type templates here, particularly
  405. // variable templates and concepts. But the exclusion of alias templates
  406. // and template template parameters is a wording defect.
  407. AllowFunctionTemplatesInLookup = false;
  408. ObjectTypeSearchedInScope = true;
  409. }
  410. IsDependent |= Found.wasNotFoundInCurrentInstantiation();
  411. }
  412. if (Found.isAmbiguous())
  413. return false;
  414. if (ATK && SS.isEmpty() && ObjectType.isNull() &&
  415. !RequiredTemplate.hasTemplateKeyword()) {
  416. // C++2a [temp.names]p2:
  417. // A name is also considered to refer to a template if it is an
  418. // unqualified-id followed by a < and name lookup finds either one or more
  419. // functions or finds nothing.
  420. //
  421. // To keep our behavior consistent, we apply the "finds nothing" part in
  422. // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
  423. // successfully form a call to an undeclared template-id.
  424. bool AllFunctions =
  425. getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
  426. return isa<FunctionDecl>(ND->getUnderlyingDecl());
  427. });
  428. if (AllFunctions || (Found.empty() && !IsDependent)) {
  429. // If lookup found any functions, or if this is a name that can only be
  430. // used for a function, then strongly assume this is a function
  431. // template-id.
  432. *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
  433. ? AssumedTemplateKind::FoundNothing
  434. : AssumedTemplateKind::FoundFunctions;
  435. Found.clear();
  436. return false;
  437. }
  438. }
  439. if (Found.empty() && !IsDependent && AllowTypoCorrection) {
  440. // If we did not find any names, and this is not a disambiguation, attempt
  441. // to correct any typos.
  442. DeclarationName Name = Found.getLookupName();
  443. Found.clear();
  444. // Simple filter callback that, for keywords, only accepts the C++ *_cast
  445. DefaultFilterCCC FilterCCC{};
  446. FilterCCC.WantTypeSpecifiers = false;
  447. FilterCCC.WantExpressionKeywords = false;
  448. FilterCCC.WantRemainingKeywords = false;
  449. FilterCCC.WantCXXNamedCasts = true;
  450. if (TypoCorrection Corrected =
  451. CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
  452. &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
  453. if (auto *ND = Corrected.getFoundDecl())
  454. Found.addDecl(ND);
  455. FilterAcceptableTemplateNames(Found);
  456. if (Found.isAmbiguous()) {
  457. Found.clear();
  458. } else if (!Found.empty()) {
  459. Found.setLookupName(Corrected.getCorrection());
  460. if (LookupCtx) {
  461. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  462. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  463. Name.getAsString() == CorrectedStr;
  464. diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
  465. << Name << LookupCtx << DroppedSpecifier
  466. << SS.getRange());
  467. } else {
  468. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
  469. }
  470. }
  471. }
  472. }
  473. NamedDecl *ExampleLookupResult =
  474. Found.empty() ? nullptr : Found.getRepresentativeDecl();
  475. FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
  476. if (Found.empty()) {
  477. if (IsDependent) {
  478. MemberOfUnknownSpecialization = true;
  479. return false;
  480. }
  481. // If a 'template' keyword was used, a lookup that finds only non-template
  482. // names is an error.
  483. if (ExampleLookupResult && RequiredTemplate) {
  484. Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
  485. << Found.getLookupName() << SS.getRange()
  486. << RequiredTemplate.hasTemplateKeyword()
  487. << RequiredTemplate.getTemplateKeywordLoc();
  488. Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
  489. diag::note_template_kw_refers_to_non_template)
  490. << Found.getLookupName();
  491. return true;
  492. }
  493. return false;
  494. }
  495. if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
  496. !getLangOpts().CPlusPlus11) {
  497. // C++03 [basic.lookup.classref]p1:
  498. // [...] If the lookup in the class of the object expression finds a
  499. // template, the name is also looked up in the context of the entire
  500. // postfix-expression and [...]
  501. //
  502. // Note: C++11 does not perform this second lookup.
  503. LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
  504. LookupOrdinaryName);
  505. FoundOuter.setTemplateNameLookup(true);
  506. LookupName(FoundOuter, S);
  507. // FIXME: We silently accept an ambiguous lookup here, in violation of
  508. // [basic.lookup]/1.
  509. FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
  510. NamedDecl *OuterTemplate;
  511. if (FoundOuter.empty()) {
  512. // - if the name is not found, the name found in the class of the
  513. // object expression is used, otherwise
  514. } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
  515. !(OuterTemplate =
  516. getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
  517. // - if the name is found in the context of the entire
  518. // postfix-expression and does not name a class template, the name
  519. // found in the class of the object expression is used, otherwise
  520. FoundOuter.clear();
  521. } else if (!Found.isSuppressingDiagnostics()) {
  522. // - if the name found is a class template, it must refer to the same
  523. // entity as the one found in the class of the object expression,
  524. // otherwise the program is ill-formed.
  525. if (!Found.isSingleResult() ||
  526. getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
  527. OuterTemplate->getCanonicalDecl()) {
  528. Diag(Found.getNameLoc(),
  529. diag::ext_nested_name_member_ref_lookup_ambiguous)
  530. << Found.getLookupName()
  531. << ObjectType;
  532. Diag(Found.getRepresentativeDecl()->getLocation(),
  533. diag::note_ambig_member_ref_object_type)
  534. << ObjectType;
  535. Diag(FoundOuter.getFoundDecl()->getLocation(),
  536. diag::note_ambig_member_ref_scope);
  537. // Recover by taking the template that we found in the object
  538. // expression's type.
  539. }
  540. }
  541. }
  542. return false;
  543. }
  544. void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
  545. SourceLocation Less,
  546. SourceLocation Greater) {
  547. if (TemplateName.isInvalid())
  548. return;
  549. DeclarationNameInfo NameInfo;
  550. CXXScopeSpec SS;
  551. LookupNameKind LookupKind;
  552. DeclContext *LookupCtx = nullptr;
  553. NamedDecl *Found = nullptr;
  554. bool MissingTemplateKeyword = false;
  555. // Figure out what name we looked up.
  556. if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
  557. NameInfo = DRE->getNameInfo();
  558. SS.Adopt(DRE->getQualifierLoc());
  559. LookupKind = LookupOrdinaryName;
  560. Found = DRE->getFoundDecl();
  561. } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
  562. NameInfo = ME->getMemberNameInfo();
  563. SS.Adopt(ME->getQualifierLoc());
  564. LookupKind = LookupMemberName;
  565. LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
  566. Found = ME->getMemberDecl();
  567. } else if (auto *DSDRE =
  568. dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
  569. NameInfo = DSDRE->getNameInfo();
  570. SS.Adopt(DSDRE->getQualifierLoc());
  571. MissingTemplateKeyword = true;
  572. } else if (auto *DSME =
  573. dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
  574. NameInfo = DSME->getMemberNameInfo();
  575. SS.Adopt(DSME->getQualifierLoc());
  576. MissingTemplateKeyword = true;
  577. } else {
  578. llvm_unreachable("unexpected kind of potential template name");
  579. }
  580. // If this is a dependent-scope lookup, diagnose that the 'template' keyword
  581. // was missing.
  582. if (MissingTemplateKeyword) {
  583. Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
  584. << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
  585. return;
  586. }
  587. // Try to correct the name by looking for templates and C++ named casts.
  588. struct TemplateCandidateFilter : CorrectionCandidateCallback {
  589. Sema &S;
  590. TemplateCandidateFilter(Sema &S) : S(S) {
  591. WantTypeSpecifiers = false;
  592. WantExpressionKeywords = false;
  593. WantRemainingKeywords = false;
  594. WantCXXNamedCasts = true;
  595. };
  596. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  597. if (auto *ND = Candidate.getCorrectionDecl())
  598. return S.getAsTemplateNameDecl(ND);
  599. return Candidate.isKeyword();
  600. }
  601. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  602. return std::make_unique<TemplateCandidateFilter>(*this);
  603. }
  604. };
  605. DeclarationName Name = NameInfo.getName();
  606. TemplateCandidateFilter CCC(*this);
  607. if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
  608. CTK_ErrorRecovery, LookupCtx)) {
  609. auto *ND = Corrected.getFoundDecl();
  610. if (ND)
  611. ND = getAsTemplateNameDecl(ND);
  612. if (ND || Corrected.isKeyword()) {
  613. if (LookupCtx) {
  614. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  615. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  616. Name.getAsString() == CorrectedStr;
  617. diagnoseTypo(Corrected,
  618. PDiag(diag::err_non_template_in_member_template_id_suggest)
  619. << Name << LookupCtx << DroppedSpecifier
  620. << SS.getRange(), false);
  621. } else {
  622. diagnoseTypo(Corrected,
  623. PDiag(diag::err_non_template_in_template_id_suggest)
  624. << Name, false);
  625. }
  626. if (Found)
  627. Diag(Found->getLocation(),
  628. diag::note_non_template_in_template_id_found);
  629. return;
  630. }
  631. }
  632. Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
  633. << Name << SourceRange(Less, Greater);
  634. if (Found)
  635. Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
  636. }
  637. /// ActOnDependentIdExpression - Handle a dependent id-expression that
  638. /// was just parsed. This is only possible with an explicit scope
  639. /// specifier naming a dependent type.
  640. ExprResult
  641. Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
  642. SourceLocation TemplateKWLoc,
  643. const DeclarationNameInfo &NameInfo,
  644. bool isAddressOfOperand,
  645. const TemplateArgumentListInfo *TemplateArgs) {
  646. DeclContext *DC = getFunctionLevelDeclContext();
  647. // C++11 [expr.prim.general]p12:
  648. // An id-expression that denotes a non-static data member or non-static
  649. // member function of a class can only be used:
  650. // (...)
  651. // - if that id-expression denotes a non-static data member and it
  652. // appears in an unevaluated operand.
  653. //
  654. // If this might be the case, form a DependentScopeDeclRefExpr instead of a
  655. // CXXDependentScopeMemberExpr. The former can instantiate to either
  656. // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
  657. // always a MemberExpr.
  658. bool MightBeCxx11UnevalField =
  659. getLangOpts().CPlusPlus11 && isUnevaluatedContext();
  660. // Check if the nested name specifier is an enum type.
  661. bool IsEnum = false;
  662. if (NestedNameSpecifier *NNS = SS.getScopeRep())
  663. IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
  664. if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
  665. isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
  666. QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
  667. // Since the 'this' expression is synthesized, we don't need to
  668. // perform the double-lookup check.
  669. NamedDecl *FirstQualifierInScope = nullptr;
  670. return CXXDependentScopeMemberExpr::Create(
  671. Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
  672. /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
  673. FirstQualifierInScope, NameInfo, TemplateArgs);
  674. }
  675. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  676. }
  677. ExprResult
  678. Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
  679. SourceLocation TemplateKWLoc,
  680. const DeclarationNameInfo &NameInfo,
  681. const TemplateArgumentListInfo *TemplateArgs) {
  682. // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
  683. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  684. if (!QualifierLoc)
  685. return ExprError();
  686. return DependentScopeDeclRefExpr::Create(
  687. Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
  688. }
  689. /// Determine whether we would be unable to instantiate this template (because
  690. /// it either has no definition, or is in the process of being instantiated).
  691. bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
  692. NamedDecl *Instantiation,
  693. bool InstantiatedFromMember,
  694. const NamedDecl *Pattern,
  695. const NamedDecl *PatternDef,
  696. TemplateSpecializationKind TSK,
  697. bool Complain /*= true*/) {
  698. assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
  699. isa<VarDecl>(Instantiation));
  700. bool IsEntityBeingDefined = false;
  701. if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
  702. IsEntityBeingDefined = TD->isBeingDefined();
  703. if (PatternDef && !IsEntityBeingDefined) {
  704. NamedDecl *SuggestedDef = nullptr;
  705. if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
  706. /*OnlyNeedComplete*/false)) {
  707. // If we're allowed to diagnose this and recover, do so.
  708. bool Recover = Complain && !isSFINAEContext();
  709. if (Complain)
  710. diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
  711. Sema::MissingImportKind::Definition, Recover);
  712. return !Recover;
  713. }
  714. return false;
  715. }
  716. if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
  717. return true;
  718. llvm::Optional<unsigned> Note;
  719. QualType InstantiationTy;
  720. if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
  721. InstantiationTy = Context.getTypeDeclType(TD);
  722. if (PatternDef) {
  723. Diag(PointOfInstantiation,
  724. diag::err_template_instantiate_within_definition)
  725. << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
  726. << InstantiationTy;
  727. // Not much point in noting the template declaration here, since
  728. // we're lexically inside it.
  729. Instantiation->setInvalidDecl();
  730. } else if (InstantiatedFromMember) {
  731. if (isa<FunctionDecl>(Instantiation)) {
  732. Diag(PointOfInstantiation,
  733. diag::err_explicit_instantiation_undefined_member)
  734. << /*member function*/ 1 << Instantiation->getDeclName()
  735. << Instantiation->getDeclContext();
  736. Note = diag::note_explicit_instantiation_here;
  737. } else {
  738. assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
  739. Diag(PointOfInstantiation,
  740. diag::err_implicit_instantiate_member_undefined)
  741. << InstantiationTy;
  742. Note = diag::note_member_declared_at;
  743. }
  744. } else {
  745. if (isa<FunctionDecl>(Instantiation)) {
  746. Diag(PointOfInstantiation,
  747. diag::err_explicit_instantiation_undefined_func_template)
  748. << Pattern;
  749. Note = diag::note_explicit_instantiation_here;
  750. } else if (isa<TagDecl>(Instantiation)) {
  751. Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
  752. << (TSK != TSK_ImplicitInstantiation)
  753. << InstantiationTy;
  754. Note = diag::note_template_decl_here;
  755. } else {
  756. assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
  757. if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
  758. Diag(PointOfInstantiation,
  759. diag::err_explicit_instantiation_undefined_var_template)
  760. << Instantiation;
  761. Instantiation->setInvalidDecl();
  762. } else
  763. Diag(PointOfInstantiation,
  764. diag::err_explicit_instantiation_undefined_member)
  765. << /*static data member*/ 2 << Instantiation->getDeclName()
  766. << Instantiation->getDeclContext();
  767. Note = diag::note_explicit_instantiation_here;
  768. }
  769. }
  770. if (Note) // Diagnostics were emitted.
  771. Diag(Pattern->getLocation(), Note.getValue());
  772. // In general, Instantiation isn't marked invalid to get more than one
  773. // error for multiple undefined instantiations. But the code that does
  774. // explicit declaration -> explicit definition conversion can't handle
  775. // invalid declarations, so mark as invalid in that case.
  776. if (TSK == TSK_ExplicitInstantiationDeclaration)
  777. Instantiation->setInvalidDecl();
  778. return true;
  779. }
  780. /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
  781. /// that the template parameter 'PrevDecl' is being shadowed by a new
  782. /// declaration at location Loc. Returns true to indicate that this is
  783. /// an error, and false otherwise.
  784. void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
  785. assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
  786. // C++ [temp.local]p4:
  787. // A template-parameter shall not be redeclared within its
  788. // scope (including nested scopes).
  789. //
  790. // Make this a warning when MSVC compatibility is requested.
  791. unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
  792. : diag::err_template_param_shadow;
  793. Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
  794. Diag(PrevDecl->getLocation(), diag::note_template_param_here);
  795. }
  796. /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
  797. /// the parameter D to reference the templated declaration and return a pointer
  798. /// to the template declaration. Otherwise, do nothing to D and return null.
  799. TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
  800. if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
  801. D = Temp->getTemplatedDecl();
  802. return Temp;
  803. }
  804. return nullptr;
  805. }
  806. ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
  807. SourceLocation EllipsisLoc) const {
  808. assert(Kind == Template &&
  809. "Only template template arguments can be pack expansions here");
  810. assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
  811. "Template template argument pack expansion without packs");
  812. ParsedTemplateArgument Result(*this);
  813. Result.EllipsisLoc = EllipsisLoc;
  814. return Result;
  815. }
  816. static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
  817. const ParsedTemplateArgument &Arg) {
  818. switch (Arg.getKind()) {
  819. case ParsedTemplateArgument::Type: {
  820. TypeSourceInfo *DI;
  821. QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
  822. if (!DI)
  823. DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
  824. return TemplateArgumentLoc(TemplateArgument(T), DI);
  825. }
  826. case ParsedTemplateArgument::NonType: {
  827. Expr *E = static_cast<Expr *>(Arg.getAsExpr());
  828. return TemplateArgumentLoc(TemplateArgument(E), E);
  829. }
  830. case ParsedTemplateArgument::Template: {
  831. TemplateName Template = Arg.getAsTemplate().get();
  832. TemplateArgument TArg;
  833. if (Arg.getEllipsisLoc().isValid())
  834. TArg = TemplateArgument(Template, Optional<unsigned int>());
  835. else
  836. TArg = Template;
  837. return TemplateArgumentLoc(
  838. SemaRef.Context, TArg,
  839. Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
  840. Arg.getLocation(), Arg.getEllipsisLoc());
  841. }
  842. }
  843. llvm_unreachable("Unhandled parsed template argument");
  844. }
  845. /// Translates template arguments as provided by the parser
  846. /// into template arguments used by semantic analysis.
  847. void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
  848. TemplateArgumentListInfo &TemplateArgs) {
  849. for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
  850. TemplateArgs.addArgument(translateTemplateArgument(*this,
  851. TemplateArgsIn[I]));
  852. }
  853. static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
  854. SourceLocation Loc,
  855. IdentifierInfo *Name) {
  856. NamedDecl *PrevDecl = SemaRef.LookupSingleName(
  857. S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  858. if (PrevDecl && PrevDecl->isTemplateParameter())
  859. SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
  860. }
  861. /// Convert a parsed type into a parsed template argument. This is mostly
  862. /// trivial, except that we may have parsed a C++17 deduced class template
  863. /// specialization type, in which case we should form a template template
  864. /// argument instead of a type template argument.
  865. ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
  866. TypeSourceInfo *TInfo;
  867. QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
  868. if (T.isNull())
  869. return ParsedTemplateArgument();
  870. assert(TInfo && "template argument with no location");
  871. // If we might have formed a deduced template specialization type, convert
  872. // it to a template template argument.
  873. if (getLangOpts().CPlusPlus17) {
  874. TypeLoc TL = TInfo->getTypeLoc();
  875. SourceLocation EllipsisLoc;
  876. if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
  877. EllipsisLoc = PET.getEllipsisLoc();
  878. TL = PET.getPatternLoc();
  879. }
  880. CXXScopeSpec SS;
  881. if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
  882. SS.Adopt(ET.getQualifierLoc());
  883. TL = ET.getNamedTypeLoc();
  884. }
  885. if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
  886. TemplateName Name = DTST.getTypePtr()->getTemplateName();
  887. if (SS.isSet())
  888. Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
  889. /*HasTemplateKeyword*/ false,
  890. Name.getAsTemplateDecl());
  891. ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
  892. DTST.getTemplateNameLoc());
  893. if (EllipsisLoc.isValid())
  894. Result = Result.getTemplatePackExpansion(EllipsisLoc);
  895. return Result;
  896. }
  897. }
  898. // This is a normal type template argument. Note, if the type template
  899. // argument is an injected-class-name for a template, it has a dual nature
  900. // and can be used as either a type or a template. We handle that in
  901. // convertTypeTemplateArgumentToTemplate.
  902. return ParsedTemplateArgument(ParsedTemplateArgument::Type,
  903. ParsedType.get().getAsOpaquePtr(),
  904. TInfo->getTypeLoc().getBeginLoc());
  905. }
  906. /// ActOnTypeParameter - Called when a C++ template type parameter
  907. /// (e.g., "typename T") has been parsed. Typename specifies whether
  908. /// the keyword "typename" was used to declare the type parameter
  909. /// (otherwise, "class" was used), and KeyLoc is the location of the
  910. /// "class" or "typename" keyword. ParamName is the name of the
  911. /// parameter (NULL indicates an unnamed template parameter) and
  912. /// ParamNameLoc is the location of the parameter name (if any).
  913. /// If the type parameter has a default argument, it will be added
  914. /// later via ActOnTypeParameterDefault.
  915. NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
  916. SourceLocation EllipsisLoc,
  917. SourceLocation KeyLoc,
  918. IdentifierInfo *ParamName,
  919. SourceLocation ParamNameLoc,
  920. unsigned Depth, unsigned Position,
  921. SourceLocation EqualLoc,
  922. ParsedType DefaultArg,
  923. bool HasTypeConstraint) {
  924. assert(S->isTemplateParamScope() &&
  925. "Template type parameter not in template parameter scope!");
  926. bool IsParameterPack = EllipsisLoc.isValid();
  927. TemplateTypeParmDecl *Param
  928. = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  929. KeyLoc, ParamNameLoc, Depth, Position,
  930. ParamName, Typename, IsParameterPack,
  931. HasTypeConstraint);
  932. Param->setAccess(AS_public);
  933. if (Param->isParameterPack())
  934. if (auto *LSI = getEnclosingLambda())
  935. LSI->LocalPacks.push_back(Param);
  936. if (ParamName) {
  937. maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
  938. // Add the template parameter into the current scope.
  939. S->AddDecl(Param);
  940. IdResolver.AddDecl(Param);
  941. }
  942. // C++0x [temp.param]p9:
  943. // A default template-argument may be specified for any kind of
  944. // template-parameter that is not a template parameter pack.
  945. if (DefaultArg && IsParameterPack) {
  946. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  947. DefaultArg = nullptr;
  948. }
  949. // Handle the default argument, if provided.
  950. if (DefaultArg) {
  951. TypeSourceInfo *DefaultTInfo;
  952. GetTypeFromParser(DefaultArg, &DefaultTInfo);
  953. assert(DefaultTInfo && "expected source information for type");
  954. // Check for unexpanded parameter packs.
  955. if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
  956. UPPC_DefaultArgument))
  957. return Param;
  958. // Check the template argument itself.
  959. if (CheckTemplateArgument(DefaultTInfo)) {
  960. Param->setInvalidDecl();
  961. return Param;
  962. }
  963. Param->setDefaultArgument(DefaultTInfo);
  964. }
  965. return Param;
  966. }
  967. /// Convert the parser's template argument list representation into our form.
  968. static TemplateArgumentListInfo
  969. makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
  970. TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
  971. TemplateId.RAngleLoc);
  972. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
  973. TemplateId.NumArgs);
  974. S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
  975. return TemplateArgs;
  976. }
  977. bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
  978. TemplateIdAnnotation *TypeConstr,
  979. TemplateTypeParmDecl *ConstrainedParameter,
  980. SourceLocation EllipsisLoc) {
  981. return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
  982. false);
  983. }
  984. bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
  985. TemplateIdAnnotation *TypeConstr,
  986. TemplateTypeParmDecl *ConstrainedParameter,
  987. SourceLocation EllipsisLoc,
  988. bool AllowUnexpandedPack) {
  989. TemplateName TN = TypeConstr->Template.get();
  990. ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
  991. // C++2a [temp.param]p4:
  992. // [...] The concept designated by a type-constraint shall be a type
  993. // concept ([temp.concept]).
  994. if (!CD->isTypeConcept()) {
  995. Diag(TypeConstr->TemplateNameLoc,
  996. diag::err_type_constraint_non_type_concept);
  997. return true;
  998. }
  999. bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
  1000. if (!WereArgsSpecified &&
  1001. CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
  1002. Diag(TypeConstr->TemplateNameLoc,
  1003. diag::err_type_constraint_missing_arguments) << CD;
  1004. return true;
  1005. }
  1006. DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
  1007. TypeConstr->TemplateNameLoc);
  1008. TemplateArgumentListInfo TemplateArgs;
  1009. if (TypeConstr->LAngleLoc.isValid()) {
  1010. TemplateArgs =
  1011. makeTemplateArgumentListInfo(*this, *TypeConstr);
  1012. if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
  1013. for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
  1014. if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
  1015. return true;
  1016. }
  1017. }
  1018. }
  1019. return AttachTypeConstraint(
  1020. SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
  1021. ConceptName, CD,
  1022. TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
  1023. ConstrainedParameter, EllipsisLoc);
  1024. }
  1025. template<typename ArgumentLocAppender>
  1026. static ExprResult formImmediatelyDeclaredConstraint(
  1027. Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
  1028. ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
  1029. SourceLocation RAngleLoc, QualType ConstrainedType,
  1030. SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
  1031. SourceLocation EllipsisLoc) {
  1032. TemplateArgumentListInfo ConstraintArgs;
  1033. ConstraintArgs.addArgument(
  1034. S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
  1035. /*NTTPType=*/QualType(), ParamNameLoc));
  1036. ConstraintArgs.setRAngleLoc(RAngleLoc);
  1037. ConstraintArgs.setLAngleLoc(LAngleLoc);
  1038. Appender(ConstraintArgs);
  1039. // C++2a [temp.param]p4:
  1040. // [...] This constraint-expression E is called the immediately-declared
  1041. // constraint of T. [...]
  1042. CXXScopeSpec SS;
  1043. SS.Adopt(NS);
  1044. ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
  1045. SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
  1046. /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
  1047. if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
  1048. return ImmediatelyDeclaredConstraint;
  1049. // C++2a [temp.param]p4:
  1050. // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
  1051. //
  1052. // We have the following case:
  1053. //
  1054. // template<typename T> concept C1 = true;
  1055. // template<C1... T> struct s1;
  1056. //
  1057. // The constraint: (C1<T> && ...)
  1058. //
  1059. // Note that the type of C1<T> is known to be 'bool', so we don't need to do
  1060. // any unqualified lookups for 'operator&&' here.
  1061. return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
  1062. /*LParenLoc=*/SourceLocation(),
  1063. ImmediatelyDeclaredConstraint.get(), BO_LAnd,
  1064. EllipsisLoc, /*RHS=*/nullptr,
  1065. /*RParenLoc=*/SourceLocation(),
  1066. /*NumExpansions=*/None);
  1067. }
  1068. /// Attach a type-constraint to a template parameter.
  1069. /// \returns true if an error occurred. This can happen if the
  1070. /// immediately-declared constraint could not be formed (e.g. incorrect number
  1071. /// of arguments for the named concept).
  1072. bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
  1073. DeclarationNameInfo NameInfo,
  1074. ConceptDecl *NamedConcept,
  1075. const TemplateArgumentListInfo *TemplateArgs,
  1076. TemplateTypeParmDecl *ConstrainedParameter,
  1077. SourceLocation EllipsisLoc) {
  1078. // C++2a [temp.param]p4:
  1079. // [...] If Q is of the form C<A1, ..., An>, then let E' be
  1080. // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
  1081. const ASTTemplateArgumentListInfo *ArgsAsWritten =
  1082. TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
  1083. *TemplateArgs) : nullptr;
  1084. QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
  1085. ExprResult ImmediatelyDeclaredConstraint =
  1086. formImmediatelyDeclaredConstraint(
  1087. *this, NS, NameInfo, NamedConcept,
  1088. TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
  1089. TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
  1090. ParamAsArgument, ConstrainedParameter->getLocation(),
  1091. [&] (TemplateArgumentListInfo &ConstraintArgs) {
  1092. if (TemplateArgs)
  1093. for (const auto &ArgLoc : TemplateArgs->arguments())
  1094. ConstraintArgs.addArgument(ArgLoc);
  1095. }, EllipsisLoc);
  1096. if (ImmediatelyDeclaredConstraint.isInvalid())
  1097. return true;
  1098. ConstrainedParameter->setTypeConstraint(NS, NameInfo,
  1099. /*FoundDecl=*/NamedConcept,
  1100. NamedConcept, ArgsAsWritten,
  1101. ImmediatelyDeclaredConstraint.get());
  1102. return false;
  1103. }
  1104. bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
  1105. SourceLocation EllipsisLoc) {
  1106. if (NTTP->getType() != TL.getType() ||
  1107. TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
  1108. Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  1109. diag::err_unsupported_placeholder_constraint)
  1110. << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
  1111. return true;
  1112. }
  1113. // FIXME: Concepts: This should be the type of the placeholder, but this is
  1114. // unclear in the wording right now.
  1115. DeclRefExpr *Ref =
  1116. BuildDeclRefExpr(NTTP, NTTP->getType(), VK_PRValue, NTTP->getLocation());
  1117. if (!Ref)
  1118. return true;
  1119. ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
  1120. *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
  1121. TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
  1122. BuildDecltypeType(Ref), NTTP->getLocation(),
  1123. [&](TemplateArgumentListInfo &ConstraintArgs) {
  1124. for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
  1125. ConstraintArgs.addArgument(TL.getArgLoc(I));
  1126. },
  1127. EllipsisLoc);
  1128. if (ImmediatelyDeclaredConstraint.isInvalid() ||
  1129. !ImmediatelyDeclaredConstraint.isUsable())
  1130. return true;
  1131. NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
  1132. return false;
  1133. }
  1134. /// Check that the type of a non-type template parameter is
  1135. /// well-formed.
  1136. ///
  1137. /// \returns the (possibly-promoted) parameter type if valid;
  1138. /// otherwise, produces a diagnostic and returns a NULL type.
  1139. QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
  1140. SourceLocation Loc) {
  1141. if (TSI->getType()->isUndeducedType()) {
  1142. // C++17 [temp.dep.expr]p3:
  1143. // An id-expression is type-dependent if it contains
  1144. // - an identifier associated by name lookup with a non-type
  1145. // template-parameter declared with a type that contains a
  1146. // placeholder type (7.1.7.4),
  1147. TSI = SubstAutoTypeSourceInfoDependent(TSI);
  1148. }
  1149. return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
  1150. }
  1151. /// Require the given type to be a structural type, and diagnose if it is not.
  1152. ///
  1153. /// \return \c true if an error was produced.
  1154. bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
  1155. if (T->isDependentType())
  1156. return false;
  1157. if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
  1158. return true;
  1159. if (T->isStructuralType())
  1160. return false;
  1161. // Structural types are required to be object types or lvalue references.
  1162. if (T->isRValueReferenceType()) {
  1163. Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
  1164. return true;
  1165. }
  1166. // Don't mention structural types in our diagnostic prior to C++20. Also,
  1167. // there's not much more we can say about non-scalar non-class types --
  1168. // because we can't see functions or arrays here, those can only be language
  1169. // extensions.
  1170. if (!getLangOpts().CPlusPlus20 ||
  1171. (!T->isScalarType() && !T->isRecordType())) {
  1172. Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
  1173. return true;
  1174. }
  1175. // Structural types are required to be literal types.
  1176. if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
  1177. return true;
  1178. Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
  1179. // Drill down into the reason why the class is non-structural.
  1180. while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  1181. // All members are required to be public and non-mutable, and can't be of
  1182. // rvalue reference type. Check these conditions first to prefer a "local"
  1183. // reason over a more distant one.
  1184. for (const FieldDecl *FD : RD->fields()) {
  1185. if (FD->getAccess() != AS_public) {
  1186. Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
  1187. return true;
  1188. }
  1189. if (FD->isMutable()) {
  1190. Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
  1191. return true;
  1192. }
  1193. if (FD->getType()->isRValueReferenceType()) {
  1194. Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
  1195. << T;
  1196. return true;
  1197. }
  1198. }
  1199. // All bases are required to be public.
  1200. for (const auto &BaseSpec : RD->bases()) {
  1201. if (BaseSpec.getAccessSpecifier() != AS_public) {
  1202. Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
  1203. << T << 1;
  1204. return true;
  1205. }
  1206. }
  1207. // All subobjects are required to be of structural types.
  1208. SourceLocation SubLoc;
  1209. QualType SubType;
  1210. int Kind = -1;
  1211. for (const FieldDecl *FD : RD->fields()) {
  1212. QualType T = Context.getBaseElementType(FD->getType());
  1213. if (!T->isStructuralType()) {
  1214. SubLoc = FD->getLocation();
  1215. SubType = T;
  1216. Kind = 0;
  1217. break;
  1218. }
  1219. }
  1220. if (Kind == -1) {
  1221. for (const auto &BaseSpec : RD->bases()) {
  1222. QualType T = BaseSpec.getType();
  1223. if (!T->isStructuralType()) {
  1224. SubLoc = BaseSpec.getBaseTypeLoc();
  1225. SubType = T;
  1226. Kind = 1;
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. assert(Kind != -1 && "couldn't find reason why type is not structural");
  1232. Diag(SubLoc, diag::note_not_structural_subobject)
  1233. << T << Kind << SubType;
  1234. T = SubType;
  1235. RD = T->getAsCXXRecordDecl();
  1236. }
  1237. return true;
  1238. }
  1239. QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
  1240. SourceLocation Loc) {
  1241. // We don't allow variably-modified types as the type of non-type template
  1242. // parameters.
  1243. if (T->isVariablyModifiedType()) {
  1244. Diag(Loc, diag::err_variably_modified_nontype_template_param)
  1245. << T;
  1246. return QualType();
  1247. }
  1248. // C++ [temp.param]p4:
  1249. //
  1250. // A non-type template-parameter shall have one of the following
  1251. // (optionally cv-qualified) types:
  1252. //
  1253. // -- integral or enumeration type,
  1254. if (T->isIntegralOrEnumerationType() ||
  1255. // -- pointer to object or pointer to function,
  1256. T->isPointerType() ||
  1257. // -- lvalue reference to object or lvalue reference to function,
  1258. T->isLValueReferenceType() ||
  1259. // -- pointer to member,
  1260. T->isMemberPointerType() ||
  1261. // -- std::nullptr_t, or
  1262. T->isNullPtrType() ||
  1263. // -- a type that contains a placeholder type.
  1264. T->isUndeducedType()) {
  1265. // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
  1266. // are ignored when determining its type.
  1267. return T.getUnqualifiedType();
  1268. }
  1269. // C++ [temp.param]p8:
  1270. //
  1271. // A non-type template-parameter of type "array of T" or
  1272. // "function returning T" is adjusted to be of type "pointer to
  1273. // T" or "pointer to function returning T", respectively.
  1274. if (T->isArrayType() || T->isFunctionType())
  1275. return Context.getDecayedType(T);
  1276. // If T is a dependent type, we can't do the check now, so we
  1277. // assume that it is well-formed. Note that stripping off the
  1278. // qualifiers here is not really correct if T turns out to be
  1279. // an array type, but we'll recompute the type everywhere it's
  1280. // used during instantiation, so that should be OK. (Using the
  1281. // qualified type is equally wrong.)
  1282. if (T->isDependentType())
  1283. return T.getUnqualifiedType();
  1284. // C++20 [temp.param]p6:
  1285. // -- a structural type
  1286. if (RequireStructuralType(T, Loc))
  1287. return QualType();
  1288. if (!getLangOpts().CPlusPlus20) {
  1289. // FIXME: Consider allowing structural types as an extension in C++17. (In
  1290. // earlier language modes, the template argument evaluation rules are too
  1291. // inflexible.)
  1292. Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
  1293. return QualType();
  1294. }
  1295. Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
  1296. return T.getUnqualifiedType();
  1297. }
  1298. NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
  1299. unsigned Depth,
  1300. unsigned Position,
  1301. SourceLocation EqualLoc,
  1302. Expr *Default) {
  1303. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  1304. // Check that we have valid decl-specifiers specified.
  1305. auto CheckValidDeclSpecifiers = [this, &D] {
  1306. // C++ [temp.param]
  1307. // p1
  1308. // template-parameter:
  1309. // ...
  1310. // parameter-declaration
  1311. // p2
  1312. // ... A storage class shall not be specified in a template-parameter
  1313. // declaration.
  1314. // [dcl.typedef]p1:
  1315. // The typedef specifier [...] shall not be used in the decl-specifier-seq
  1316. // of a parameter-declaration
  1317. const DeclSpec &DS = D.getDeclSpec();
  1318. auto EmitDiag = [this](SourceLocation Loc) {
  1319. Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
  1320. << FixItHint::CreateRemoval(Loc);
  1321. };
  1322. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
  1323. EmitDiag(DS.getStorageClassSpecLoc());
  1324. if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
  1325. EmitDiag(DS.getThreadStorageClassSpecLoc());
  1326. // [dcl.inline]p1:
  1327. // The inline specifier can be applied only to the declaration or
  1328. // definition of a variable or function.
  1329. if (DS.isInlineSpecified())
  1330. EmitDiag(DS.getInlineSpecLoc());
  1331. // [dcl.constexpr]p1:
  1332. // The constexpr specifier shall be applied only to the definition of a
  1333. // variable or variable template or the declaration of a function or
  1334. // function template.
  1335. if (DS.hasConstexprSpecifier())
  1336. EmitDiag(DS.getConstexprSpecLoc());
  1337. // [dcl.fct.spec]p1:
  1338. // Function-specifiers can be used only in function declarations.
  1339. if (DS.isVirtualSpecified())
  1340. EmitDiag(DS.getVirtualSpecLoc());
  1341. if (DS.hasExplicitSpecifier())
  1342. EmitDiag(DS.getExplicitSpecLoc());
  1343. if (DS.isNoreturnSpecified())
  1344. EmitDiag(DS.getNoreturnSpecLoc());
  1345. };
  1346. CheckValidDeclSpecifiers();
  1347. if (TInfo->getType()->isUndeducedType()) {
  1348. Diag(D.getIdentifierLoc(),
  1349. diag::warn_cxx14_compat_template_nontype_parm_auto_type)
  1350. << QualType(TInfo->getType()->getContainedAutoType(), 0);
  1351. }
  1352. assert(S->isTemplateParamScope() &&
  1353. "Non-type template parameter not in template parameter scope!");
  1354. bool Invalid = false;
  1355. QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
  1356. if (T.isNull()) {
  1357. T = Context.IntTy; // Recover with an 'int' type.
  1358. Invalid = true;
  1359. }
  1360. CheckFunctionOrTemplateParamDeclarator(S, D);
  1361. IdentifierInfo *ParamName = D.getIdentifier();
  1362. bool IsParameterPack = D.hasEllipsis();
  1363. NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
  1364. Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
  1365. D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
  1366. TInfo);
  1367. Param->setAccess(AS_public);
  1368. if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
  1369. if (TL.isConstrained())
  1370. if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
  1371. Invalid = true;
  1372. if (Invalid)
  1373. Param->setInvalidDecl();
  1374. if (Param->isParameterPack())
  1375. if (auto *LSI = getEnclosingLambda())
  1376. LSI->LocalPacks.push_back(Param);
  1377. if (ParamName) {
  1378. maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
  1379. ParamName);
  1380. // Add the template parameter into the current scope.
  1381. S->AddDecl(Param);
  1382. IdResolver.AddDecl(Param);
  1383. }
  1384. // C++0x [temp.param]p9:
  1385. // A default template-argument may be specified for any kind of
  1386. // template-parameter that is not a template parameter pack.
  1387. if (Default && IsParameterPack) {
  1388. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  1389. Default = nullptr;
  1390. }
  1391. // Check the well-formedness of the default template argument, if provided.
  1392. if (Default) {
  1393. // Check for unexpanded parameter packs.
  1394. if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
  1395. return Param;
  1396. TemplateArgument Converted;
  1397. ExprResult DefaultRes =
  1398. CheckTemplateArgument(Param, Param->getType(), Default, Converted);
  1399. if (DefaultRes.isInvalid()) {
  1400. Param->setInvalidDecl();
  1401. return Param;
  1402. }
  1403. Default = DefaultRes.get();
  1404. Param->setDefaultArgument(Default);
  1405. }
  1406. return Param;
  1407. }
  1408. /// ActOnTemplateTemplateParameter - Called when a C++ template template
  1409. /// parameter (e.g. T in template <template \<typename> class T> class array)
  1410. /// has been parsed. S is the current scope.
  1411. NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
  1412. SourceLocation TmpLoc,
  1413. TemplateParameterList *Params,
  1414. SourceLocation EllipsisLoc,
  1415. IdentifierInfo *Name,
  1416. SourceLocation NameLoc,
  1417. unsigned Depth,
  1418. unsigned Position,
  1419. SourceLocation EqualLoc,
  1420. ParsedTemplateArgument Default) {
  1421. assert(S->isTemplateParamScope() &&
  1422. "Template template parameter not in template parameter scope!");
  1423. // Construct the parameter object.
  1424. bool IsParameterPack = EllipsisLoc.isValid();
  1425. TemplateTemplateParmDecl *Param =
  1426. TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  1427. NameLoc.isInvalid()? TmpLoc : NameLoc,
  1428. Depth, Position, IsParameterPack,
  1429. Name, Params);
  1430. Param->setAccess(AS_public);
  1431. if (Param->isParameterPack())
  1432. if (auto *LSI = getEnclosingLambda())
  1433. LSI->LocalPacks.push_back(Param);
  1434. // If the template template parameter has a name, then link the identifier
  1435. // into the scope and lookup mechanisms.
  1436. if (Name) {
  1437. maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
  1438. S->AddDecl(Param);
  1439. IdResolver.AddDecl(Param);
  1440. }
  1441. if (Params->size() == 0) {
  1442. Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
  1443. << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
  1444. Param->setInvalidDecl();
  1445. }
  1446. // C++0x [temp.param]p9:
  1447. // A default template-argument may be specified for any kind of
  1448. // template-parameter that is not a template parameter pack.
  1449. if (IsParameterPack && !Default.isInvalid()) {
  1450. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  1451. Default = ParsedTemplateArgument();
  1452. }
  1453. if (!Default.isInvalid()) {
  1454. // Check only that we have a template template argument. We don't want to
  1455. // try to check well-formedness now, because our template template parameter
  1456. // might have dependent types in its template parameters, which we wouldn't
  1457. // be able to match now.
  1458. //
  1459. // If none of the template template parameter's template arguments mention
  1460. // other template parameters, we could actually perform more checking here.
  1461. // However, it isn't worth doing.
  1462. TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
  1463. if (DefaultArg.getArgument().getAsTemplate().isNull()) {
  1464. Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
  1465. << DefaultArg.getSourceRange();
  1466. return Param;
  1467. }
  1468. // Check for unexpanded parameter packs.
  1469. if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
  1470. DefaultArg.getArgument().getAsTemplate(),
  1471. UPPC_DefaultArgument))
  1472. return Param;
  1473. Param->setDefaultArgument(Context, DefaultArg);
  1474. }
  1475. return Param;
  1476. }
  1477. /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
  1478. /// constrained by RequiresClause, that contains the template parameters in
  1479. /// Params.
  1480. TemplateParameterList *
  1481. Sema::ActOnTemplateParameterList(unsigned Depth,
  1482. SourceLocation ExportLoc,
  1483. SourceLocation TemplateLoc,
  1484. SourceLocation LAngleLoc,
  1485. ArrayRef<NamedDecl *> Params,
  1486. SourceLocation RAngleLoc,
  1487. Expr *RequiresClause) {
  1488. if (ExportLoc.isValid())
  1489. Diag(ExportLoc, diag::warn_template_export_unsupported);
  1490. for (NamedDecl *P : Params)
  1491. warnOnReservedIdentifier(P);
  1492. return TemplateParameterList::Create(
  1493. Context, TemplateLoc, LAngleLoc,
  1494. llvm::makeArrayRef(Params.data(), Params.size()),
  1495. RAngleLoc, RequiresClause);
  1496. }
  1497. static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
  1498. const CXXScopeSpec &SS) {
  1499. if (SS.isSet())
  1500. T->setQualifierInfo(SS.getWithLocInContext(S.Context));
  1501. }
  1502. DeclResult Sema::CheckClassTemplate(
  1503. Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  1504. CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
  1505. const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
  1506. AccessSpecifier AS, SourceLocation ModulePrivateLoc,
  1507. SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
  1508. TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
  1509. assert(TemplateParams && TemplateParams->size() > 0 &&
  1510. "No template parameters");
  1511. assert(TUK != TUK_Reference && "Can only declare or define class templates");
  1512. bool Invalid = false;
  1513. // Check that we can declare a template here.
  1514. if (CheckTemplateDeclScope(S, TemplateParams))
  1515. return true;
  1516. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  1517. assert(Kind != TTK_Enum && "can't build template of enumerated type");
  1518. // There is no such thing as an unnamed class template.
  1519. if (!Name) {
  1520. Diag(KWLoc, diag::err_template_unnamed_class);
  1521. return true;
  1522. }
  1523. // Find any previous declaration with this name. For a friend with no
  1524. // scope explicitly specified, we only look for tag declarations (per
  1525. // C++11 [basic.lookup.elab]p2).
  1526. DeclContext *SemanticContext;
  1527. LookupResult Previous(*this, Name, NameLoc,
  1528. (SS.isEmpty() && TUK == TUK_Friend)
  1529. ? LookupTagName : LookupOrdinaryName,
  1530. forRedeclarationInCurContext());
  1531. if (SS.isNotEmpty() && !SS.isInvalid()) {
  1532. SemanticContext = computeDeclContext(SS, true);
  1533. if (!SemanticContext) {
  1534. // FIXME: Horrible, horrible hack! We can't currently represent this
  1535. // in the AST, and historically we have just ignored such friend
  1536. // class templates, so don't complain here.
  1537. Diag(NameLoc, TUK == TUK_Friend
  1538. ? diag::warn_template_qualified_friend_ignored
  1539. : diag::err_template_qualified_declarator_no_match)
  1540. << SS.getScopeRep() << SS.getRange();
  1541. return TUK != TUK_Friend;
  1542. }
  1543. if (RequireCompleteDeclContext(SS, SemanticContext))
  1544. return true;
  1545. // If we're adding a template to a dependent context, we may need to
  1546. // rebuilding some of the types used within the template parameter list,
  1547. // now that we know what the current instantiation is.
  1548. if (SemanticContext->isDependentContext()) {
  1549. ContextRAII SavedContext(*this, SemanticContext);
  1550. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  1551. Invalid = true;
  1552. } else if (TUK != TUK_Friend && TUK != TUK_Reference)
  1553. diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
  1554. LookupQualifiedName(Previous, SemanticContext);
  1555. } else {
  1556. SemanticContext = CurContext;
  1557. // C++14 [class.mem]p14:
  1558. // If T is the name of a class, then each of the following shall have a
  1559. // name different from T:
  1560. // -- every member template of class T
  1561. if (TUK != TUK_Friend &&
  1562. DiagnoseClassNameShadow(SemanticContext,
  1563. DeclarationNameInfo(Name, NameLoc)))
  1564. return true;
  1565. LookupName(Previous, S);
  1566. }
  1567. if (Previous.isAmbiguous())
  1568. return true;
  1569. NamedDecl *PrevDecl = nullptr;
  1570. if (Previous.begin() != Previous.end())
  1571. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1572. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  1573. // Maybe we will complain about the shadowed template parameter.
  1574. DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
  1575. // Just pretend that we didn't see the previous declaration.
  1576. PrevDecl = nullptr;
  1577. }
  1578. // If there is a previous declaration with the same name, check
  1579. // whether this is a valid redeclaration.
  1580. ClassTemplateDecl *PrevClassTemplate =
  1581. dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
  1582. // We may have found the injected-class-name of a class template,
  1583. // class template partial specialization, or class template specialization.
  1584. // In these cases, grab the template that is being defined or specialized.
  1585. if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
  1586. cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
  1587. PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
  1588. PrevClassTemplate
  1589. = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
  1590. if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
  1591. PrevClassTemplate
  1592. = cast<ClassTemplateSpecializationDecl>(PrevDecl)
  1593. ->getSpecializedTemplate();
  1594. }
  1595. }
  1596. if (TUK == TUK_Friend) {
  1597. // C++ [namespace.memdef]p3:
  1598. // [...] When looking for a prior declaration of a class or a function
  1599. // declared as a friend, and when the name of the friend class or
  1600. // function is neither a qualified name nor a template-id, scopes outside
  1601. // the innermost enclosing namespace scope are not considered.
  1602. if (!SS.isSet()) {
  1603. DeclContext *OutermostContext = CurContext;
  1604. while (!OutermostContext->isFileContext())
  1605. OutermostContext = OutermostContext->getLookupParent();
  1606. if (PrevDecl &&
  1607. (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
  1608. OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
  1609. SemanticContext = PrevDecl->getDeclContext();
  1610. } else {
  1611. // Declarations in outer scopes don't matter. However, the outermost
  1612. // context we computed is the semantic context for our new
  1613. // declaration.
  1614. PrevDecl = PrevClassTemplate = nullptr;
  1615. SemanticContext = OutermostContext;
  1616. // Check that the chosen semantic context doesn't already contain a
  1617. // declaration of this name as a non-tag type.
  1618. Previous.clear(LookupOrdinaryName);
  1619. DeclContext *LookupContext = SemanticContext;
  1620. while (LookupContext->isTransparentContext())
  1621. LookupContext = LookupContext->getLookupParent();
  1622. LookupQualifiedName(Previous, LookupContext);
  1623. if (Previous.isAmbiguous())
  1624. return true;
  1625. if (Previous.begin() != Previous.end())
  1626. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1627. }
  1628. }
  1629. } else if (PrevDecl &&
  1630. !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
  1631. S, SS.isValid()))
  1632. PrevDecl = PrevClassTemplate = nullptr;
  1633. if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
  1634. PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
  1635. if (SS.isEmpty() &&
  1636. !(PrevClassTemplate &&
  1637. PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
  1638. SemanticContext->getRedeclContext()))) {
  1639. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  1640. Diag(Shadow->getTargetDecl()->getLocation(),
  1641. diag::note_using_decl_target);
  1642. Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
  1643. // Recover by ignoring the old declaration.
  1644. PrevDecl = PrevClassTemplate = nullptr;
  1645. }
  1646. }
  1647. if (PrevClassTemplate) {
  1648. // Ensure that the template parameter lists are compatible. Skip this check
  1649. // for a friend in a dependent context: the template parameter list itself
  1650. // could be dependent.
  1651. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1652. !TemplateParameterListsAreEqual(TemplateParams,
  1653. PrevClassTemplate->getTemplateParameters(),
  1654. /*Complain=*/true,
  1655. TPL_TemplateMatch))
  1656. return true;
  1657. // C++ [temp.class]p4:
  1658. // In a redeclaration, partial specialization, explicit
  1659. // specialization or explicit instantiation of a class template,
  1660. // the class-key shall agree in kind with the original class
  1661. // template declaration (7.1.5.3).
  1662. RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
  1663. if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
  1664. TUK == TUK_Definition, KWLoc, Name)) {
  1665. Diag(KWLoc, diag::err_use_with_wrong_tag)
  1666. << Name
  1667. << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
  1668. Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
  1669. Kind = PrevRecordDecl->getTagKind();
  1670. }
  1671. // Check for redefinition of this class template.
  1672. if (TUK == TUK_Definition) {
  1673. if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
  1674. // If we have a prior definition that is not visible, treat this as
  1675. // simply making that previous definition visible.
  1676. NamedDecl *Hidden = nullptr;
  1677. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  1678. SkipBody->ShouldSkip = true;
  1679. SkipBody->Previous = Def;
  1680. auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
  1681. assert(Tmpl && "original definition of a class template is not a "
  1682. "class template?");
  1683. makeMergedDefinitionVisible(Hidden);
  1684. makeMergedDefinitionVisible(Tmpl);
  1685. } else {
  1686. Diag(NameLoc, diag::err_redefinition) << Name;
  1687. Diag(Def->getLocation(), diag::note_previous_definition);
  1688. // FIXME: Would it make sense to try to "forget" the previous
  1689. // definition, as part of error recovery?
  1690. return true;
  1691. }
  1692. }
  1693. }
  1694. } else if (PrevDecl) {
  1695. // C++ [temp]p5:
  1696. // A class template shall not have the same name as any other
  1697. // template, class, function, object, enumeration, enumerator,
  1698. // namespace, or type in the same scope (3.3), except as specified
  1699. // in (14.5.4).
  1700. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  1701. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1702. return true;
  1703. }
  1704. // Check the template parameter list of this declaration, possibly
  1705. // merging in the template parameter list from the previous class
  1706. // template declaration. Skip this check for a friend in a dependent
  1707. // context, because the template parameter list might be dependent.
  1708. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1709. CheckTemplateParameterList(
  1710. TemplateParams,
  1711. PrevClassTemplate
  1712. ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
  1713. : nullptr,
  1714. (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
  1715. SemanticContext->isDependentContext())
  1716. ? TPC_ClassTemplateMember
  1717. : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
  1718. SkipBody))
  1719. Invalid = true;
  1720. if (SS.isSet()) {
  1721. // If the name of the template was qualified, we must be defining the
  1722. // template out-of-line.
  1723. if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
  1724. Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
  1725. : diag::err_member_decl_does_not_match)
  1726. << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
  1727. Invalid = true;
  1728. }
  1729. }
  1730. // If this is a templated friend in a dependent context we should not put it
  1731. // on the redecl chain. In some cases, the templated friend can be the most
  1732. // recent declaration tricking the template instantiator to make substitutions
  1733. // there.
  1734. // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
  1735. bool ShouldAddRedecl
  1736. = !(TUK == TUK_Friend && CurContext->isDependentContext());
  1737. CXXRecordDecl *NewClass =
  1738. CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
  1739. PrevClassTemplate && ShouldAddRedecl ?
  1740. PrevClassTemplate->getTemplatedDecl() : nullptr,
  1741. /*DelayTypeCreation=*/true);
  1742. SetNestedNameSpecifier(*this, NewClass, SS);
  1743. if (NumOuterTemplateParamLists > 0)
  1744. NewClass->setTemplateParameterListsInfo(
  1745. Context, llvm::makeArrayRef(OuterTemplateParamLists,
  1746. NumOuterTemplateParamLists));
  1747. // Add alignment attributes if necessary; these attributes are checked when
  1748. // the ASTContext lays out the structure.
  1749. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  1750. AddAlignmentAttributesForRecord(NewClass);
  1751. AddMsStructLayoutForRecord(NewClass);
  1752. }
  1753. ClassTemplateDecl *NewTemplate
  1754. = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
  1755. DeclarationName(Name), TemplateParams,
  1756. NewClass);
  1757. if (ShouldAddRedecl)
  1758. NewTemplate->setPreviousDecl(PrevClassTemplate);
  1759. NewClass->setDescribedClassTemplate(NewTemplate);
  1760. if (ModulePrivateLoc.isValid())
  1761. NewTemplate->setModulePrivate();
  1762. // Build the type for the class template declaration now.
  1763. QualType T = NewTemplate->getInjectedClassNameSpecialization();
  1764. T = Context.getInjectedClassNameType(NewClass, T);
  1765. assert(T->isDependentType() && "Class template type is not dependent?");
  1766. (void)T;
  1767. // If we are providing an explicit specialization of a member that is a
  1768. // class template, make a note of that.
  1769. if (PrevClassTemplate &&
  1770. PrevClassTemplate->getInstantiatedFromMemberTemplate())
  1771. PrevClassTemplate->setMemberSpecialization();
  1772. // Set the access specifier.
  1773. if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
  1774. SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
  1775. // Set the lexical context of these templates
  1776. NewClass->setLexicalDeclContext(CurContext);
  1777. NewTemplate->setLexicalDeclContext(CurContext);
  1778. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  1779. NewClass->startDefinition();
  1780. ProcessDeclAttributeList(S, NewClass, Attr);
  1781. if (PrevClassTemplate)
  1782. mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
  1783. AddPushedVisibilityAttribute(NewClass);
  1784. inferGslOwnerPointerAttribute(NewClass);
  1785. if (TUK != TUK_Friend) {
  1786. // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
  1787. Scope *Outer = S;
  1788. while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
  1789. Outer = Outer->getParent();
  1790. PushOnScopeChains(NewTemplate, Outer);
  1791. } else {
  1792. if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
  1793. NewTemplate->setAccess(PrevClassTemplate->getAccess());
  1794. NewClass->setAccess(PrevClassTemplate->getAccess());
  1795. }
  1796. NewTemplate->setObjectOfFriendDecl();
  1797. // Friend templates are visible in fairly strange ways.
  1798. if (!CurContext->isDependentContext()) {
  1799. DeclContext *DC = SemanticContext->getRedeclContext();
  1800. DC->makeDeclVisibleInContext(NewTemplate);
  1801. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  1802. PushOnScopeChains(NewTemplate, EnclosingScope,
  1803. /* AddToContext = */ false);
  1804. }
  1805. FriendDecl *Friend = FriendDecl::Create(
  1806. Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
  1807. Friend->setAccess(AS_public);
  1808. CurContext->addDecl(Friend);
  1809. }
  1810. if (PrevClassTemplate)
  1811. CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
  1812. if (Invalid) {
  1813. NewTemplate->setInvalidDecl();
  1814. NewClass->setInvalidDecl();
  1815. }
  1816. ActOnDocumentableDecl(NewTemplate);
  1817. if (SkipBody && SkipBody->ShouldSkip)
  1818. return SkipBody->Previous;
  1819. return NewTemplate;
  1820. }
  1821. namespace {
  1822. /// Tree transform to "extract" a transformed type from a class template's
  1823. /// constructor to a deduction guide.
  1824. class ExtractTypeForDeductionGuide
  1825. : public TreeTransform<ExtractTypeForDeductionGuide> {
  1826. llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
  1827. public:
  1828. typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
  1829. ExtractTypeForDeductionGuide(
  1830. Sema &SemaRef,
  1831. llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
  1832. : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
  1833. TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
  1834. QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
  1835. ASTContext &Context = SemaRef.getASTContext();
  1836. TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
  1837. TypedefNameDecl *Decl = OrigDecl;
  1838. // Transform the underlying type of the typedef and clone the Decl only if
  1839. // the typedef has a dependent context.
  1840. if (OrigDecl->getDeclContext()->isDependentContext()) {
  1841. TypeLocBuilder InnerTLB;
  1842. QualType Transformed =
  1843. TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
  1844. TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
  1845. if (isa<TypeAliasDecl>(OrigDecl))
  1846. Decl = TypeAliasDecl::Create(
  1847. Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
  1848. OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
  1849. else {
  1850. assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
  1851. Decl = TypedefDecl::Create(
  1852. Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
  1853. OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
  1854. }
  1855. MaterializedTypedefs.push_back(Decl);
  1856. }
  1857. QualType TDTy = Context.getTypedefType(Decl);
  1858. TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
  1859. TypedefTL.setNameLoc(TL.getNameLoc());
  1860. return TDTy;
  1861. }
  1862. };
  1863. /// Transform to convert portions of a constructor declaration into the
  1864. /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
  1865. struct ConvertConstructorToDeductionGuideTransform {
  1866. ConvertConstructorToDeductionGuideTransform(Sema &S,
  1867. ClassTemplateDecl *Template)
  1868. : SemaRef(S), Template(Template) {}
  1869. Sema &SemaRef;
  1870. ClassTemplateDecl *Template;
  1871. DeclContext *DC = Template->getDeclContext();
  1872. CXXRecordDecl *Primary = Template->getTemplatedDecl();
  1873. DeclarationName DeductionGuideName =
  1874. SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
  1875. QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
  1876. // Index adjustment to apply to convert depth-1 template parameters into
  1877. // depth-0 template parameters.
  1878. unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
  1879. /// Transform a constructor declaration into a deduction guide.
  1880. NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
  1881. CXXConstructorDecl *CD) {
  1882. SmallVector<TemplateArgument, 16> SubstArgs;
  1883. LocalInstantiationScope Scope(SemaRef);
  1884. // C++ [over.match.class.deduct]p1:
  1885. // -- For each constructor of the class template designated by the
  1886. // template-name, a function template with the following properties:
  1887. // -- The template parameters are the template parameters of the class
  1888. // template followed by the template parameters (including default
  1889. // template arguments) of the constructor, if any.
  1890. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  1891. if (FTD) {
  1892. TemplateParameterList *InnerParams = FTD->getTemplateParameters();
  1893. SmallVector<NamedDecl *, 16> AllParams;
  1894. AllParams.reserve(TemplateParams->size() + InnerParams->size());
  1895. AllParams.insert(AllParams.begin(),
  1896. TemplateParams->begin(), TemplateParams->end());
  1897. SubstArgs.reserve(InnerParams->size());
  1898. // Later template parameters could refer to earlier ones, so build up
  1899. // a list of substituted template arguments as we go.
  1900. for (NamedDecl *Param : *InnerParams) {
  1901. MultiLevelTemplateArgumentList Args;
  1902. Args.setKind(TemplateSubstitutionKind::Rewrite);
  1903. Args.addOuterTemplateArguments(SubstArgs);
  1904. Args.addOuterRetainedLevel();
  1905. NamedDecl *NewParam = transformTemplateParameter(Param, Args);
  1906. if (!NewParam)
  1907. return nullptr;
  1908. AllParams.push_back(NewParam);
  1909. SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
  1910. SemaRef.Context.getInjectedTemplateArg(NewParam)));
  1911. }
  1912. TemplateParams = TemplateParameterList::Create(
  1913. SemaRef.Context, InnerParams->getTemplateLoc(),
  1914. InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
  1915. /*FIXME: RequiresClause*/ nullptr);
  1916. }
  1917. // If we built a new template-parameter-list, track that we need to
  1918. // substitute references to the old parameters into references to the
  1919. // new ones.
  1920. MultiLevelTemplateArgumentList Args;
  1921. Args.setKind(TemplateSubstitutionKind::Rewrite);
  1922. if (FTD) {
  1923. Args.addOuterTemplateArguments(SubstArgs);
  1924. Args.addOuterRetainedLevel();
  1925. }
  1926. FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
  1927. .getAsAdjusted<FunctionProtoTypeLoc>();
  1928. assert(FPTL && "no prototype for constructor declaration");
  1929. // Transform the type of the function, adjusting the return type and
  1930. // replacing references to the old parameters with references to the
  1931. // new ones.
  1932. TypeLocBuilder TLB;
  1933. SmallVector<ParmVarDecl*, 8> Params;
  1934. SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
  1935. QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
  1936. MaterializedTypedefs);
  1937. if (NewType.isNull())
  1938. return nullptr;
  1939. TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
  1940. return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
  1941. NewTInfo, CD->getBeginLoc(), CD->getLocation(),
  1942. CD->getEndLoc(), MaterializedTypedefs);
  1943. }
  1944. /// Build a deduction guide with the specified parameter types.
  1945. NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
  1946. SourceLocation Loc = Template->getLocation();
  1947. // Build the requested type.
  1948. FunctionProtoType::ExtProtoInfo EPI;
  1949. EPI.HasTrailingReturn = true;
  1950. QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
  1951. DeductionGuideName, EPI);
  1952. TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
  1953. FunctionProtoTypeLoc FPTL =
  1954. TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
  1955. // Build the parameters, needed during deduction / substitution.
  1956. SmallVector<ParmVarDecl*, 4> Params;
  1957. for (auto T : ParamTypes) {
  1958. ParmVarDecl *NewParam = ParmVarDecl::Create(
  1959. SemaRef.Context, DC, Loc, Loc, nullptr, T,
  1960. SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
  1961. NewParam->setScopeInfo(0, Params.size());
  1962. FPTL.setParam(Params.size(), NewParam);
  1963. Params.push_back(NewParam);
  1964. }
  1965. return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
  1966. ExplicitSpecifier(), TSI, Loc, Loc, Loc);
  1967. }
  1968. private:
  1969. /// Transform a constructor template parameter into a deduction guide template
  1970. /// parameter, rebuilding any internal references to earlier parameters and
  1971. /// renumbering as we go.
  1972. NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
  1973. MultiLevelTemplateArgumentList &Args) {
  1974. if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
  1975. // TemplateTypeParmDecl's index cannot be changed after creation, so
  1976. // substitute it directly.
  1977. auto *NewTTP = TemplateTypeParmDecl::Create(
  1978. SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
  1979. /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
  1980. TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
  1981. TTP->isParameterPack(), TTP->hasTypeConstraint(),
  1982. TTP->isExpandedParameterPack() ?
  1983. llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
  1984. if (const auto *TC = TTP->getTypeConstraint())
  1985. SemaRef.SubstTypeConstraint(NewTTP, TC, Args);
  1986. if (TTP->hasDefaultArgument()) {
  1987. TypeSourceInfo *InstantiatedDefaultArg =
  1988. SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
  1989. TTP->getDefaultArgumentLoc(), TTP->getDeclName());
  1990. if (InstantiatedDefaultArg)
  1991. NewTTP->setDefaultArgument(InstantiatedDefaultArg);
  1992. }
  1993. SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
  1994. NewTTP);
  1995. return NewTTP;
  1996. }
  1997. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
  1998. return transformTemplateParameterImpl(TTP, Args);
  1999. return transformTemplateParameterImpl(
  2000. cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
  2001. }
  2002. template<typename TemplateParmDecl>
  2003. TemplateParmDecl *
  2004. transformTemplateParameterImpl(TemplateParmDecl *OldParam,
  2005. MultiLevelTemplateArgumentList &Args) {
  2006. // Ask the template instantiator to do the heavy lifting for us, then adjust
  2007. // the index of the parameter once it's done.
  2008. auto *NewParam =
  2009. cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
  2010. assert(NewParam->getDepth() == 0 && "unexpected template param depth");
  2011. NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
  2012. return NewParam;
  2013. }
  2014. QualType transformFunctionProtoType(
  2015. TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
  2016. SmallVectorImpl<ParmVarDecl *> &Params,
  2017. MultiLevelTemplateArgumentList &Args,
  2018. SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
  2019. SmallVector<QualType, 4> ParamTypes;
  2020. const FunctionProtoType *T = TL.getTypePtr();
  2021. // -- The types of the function parameters are those of the constructor.
  2022. for (auto *OldParam : TL.getParams()) {
  2023. ParmVarDecl *NewParam =
  2024. transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
  2025. if (!NewParam)
  2026. return QualType();
  2027. ParamTypes.push_back(NewParam->getType());
  2028. Params.push_back(NewParam);
  2029. }
  2030. // -- The return type is the class template specialization designated by
  2031. // the template-name and template arguments corresponding to the
  2032. // template parameters obtained from the class template.
  2033. //
  2034. // We use the injected-class-name type of the primary template instead.
  2035. // This has the convenient property that it is different from any type that
  2036. // the user can write in a deduction-guide (because they cannot enter the
  2037. // context of the template), so implicit deduction guides can never collide
  2038. // with explicit ones.
  2039. QualType ReturnType = DeducedType;
  2040. TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
  2041. // Resolving a wording defect, we also inherit the variadicness of the
  2042. // constructor.
  2043. FunctionProtoType::ExtProtoInfo EPI;
  2044. EPI.Variadic = T->isVariadic();
  2045. EPI.HasTrailingReturn = true;
  2046. QualType Result = SemaRef.BuildFunctionType(
  2047. ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
  2048. if (Result.isNull())
  2049. return QualType();
  2050. FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
  2051. NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
  2052. NewTL.setLParenLoc(TL.getLParenLoc());
  2053. NewTL.setRParenLoc(TL.getRParenLoc());
  2054. NewTL.setExceptionSpecRange(SourceRange());
  2055. NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
  2056. for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
  2057. NewTL.setParam(I, Params[I]);
  2058. return Result;
  2059. }
  2060. ParmVarDecl *transformFunctionTypeParam(
  2061. ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
  2062. llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
  2063. TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
  2064. TypeSourceInfo *NewDI;
  2065. if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
  2066. // Expand out the one and only element in each inner pack.
  2067. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
  2068. NewDI =
  2069. SemaRef.SubstType(PackTL.getPatternLoc(), Args,
  2070. OldParam->getLocation(), OldParam->getDeclName());
  2071. if (!NewDI) return nullptr;
  2072. NewDI =
  2073. SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
  2074. PackTL.getTypePtr()->getNumExpansions());
  2075. } else
  2076. NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
  2077. OldParam->getDeclName());
  2078. if (!NewDI)
  2079. return nullptr;
  2080. // Extract the type. This (for instance) replaces references to typedef
  2081. // members of the current instantiations with the definitions of those
  2082. // typedefs, avoiding triggering instantiation of the deduced type during
  2083. // deduction.
  2084. NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
  2085. .transform(NewDI);
  2086. // Resolving a wording defect, we also inherit default arguments from the
  2087. // constructor.
  2088. ExprResult NewDefArg;
  2089. if (OldParam->hasDefaultArg()) {
  2090. // We don't care what the value is (we won't use it); just create a
  2091. // placeholder to indicate there is a default argument.
  2092. QualType ParamTy = NewDI->getType();
  2093. NewDefArg = new (SemaRef.Context)
  2094. OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
  2095. ParamTy.getNonLValueExprType(SemaRef.Context),
  2096. ParamTy->isLValueReferenceType() ? VK_LValue
  2097. : ParamTy->isRValueReferenceType() ? VK_XValue
  2098. : VK_PRValue);
  2099. }
  2100. ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
  2101. OldParam->getInnerLocStart(),
  2102. OldParam->getLocation(),
  2103. OldParam->getIdentifier(),
  2104. NewDI->getType(),
  2105. NewDI,
  2106. OldParam->getStorageClass(),
  2107. NewDefArg.get());
  2108. NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
  2109. OldParam->getFunctionScopeIndex());
  2110. SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
  2111. return NewParam;
  2112. }
  2113. FunctionTemplateDecl *buildDeductionGuide(
  2114. TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
  2115. ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
  2116. SourceLocation Loc, SourceLocation LocEnd,
  2117. llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
  2118. DeclarationNameInfo Name(DeductionGuideName, Loc);
  2119. ArrayRef<ParmVarDecl *> Params =
  2120. TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
  2121. // Build the implicit deduction guide template.
  2122. auto *Guide =
  2123. CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
  2124. TInfo->getType(), TInfo, LocEnd, Ctor);
  2125. Guide->setImplicit();
  2126. Guide->setParams(Params);
  2127. for (auto *Param : Params)
  2128. Param->setDeclContext(Guide);
  2129. for (auto *TD : MaterializedTypedefs)
  2130. TD->setDeclContext(Guide);
  2131. auto *GuideTemplate = FunctionTemplateDecl::Create(
  2132. SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
  2133. GuideTemplate->setImplicit();
  2134. Guide->setDescribedFunctionTemplate(GuideTemplate);
  2135. if (isa<CXXRecordDecl>(DC)) {
  2136. Guide->setAccess(AS_public);
  2137. GuideTemplate->setAccess(AS_public);
  2138. }
  2139. DC->addDecl(GuideTemplate);
  2140. return GuideTemplate;
  2141. }
  2142. };
  2143. }
  2144. void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
  2145. SourceLocation Loc) {
  2146. if (CXXRecordDecl *DefRecord =
  2147. cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
  2148. TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
  2149. Template = DescribedTemplate ? DescribedTemplate : Template;
  2150. }
  2151. DeclContext *DC = Template->getDeclContext();
  2152. if (DC->isDependentContext())
  2153. return;
  2154. ConvertConstructorToDeductionGuideTransform Transform(
  2155. *this, cast<ClassTemplateDecl>(Template));
  2156. if (!isCompleteType(Loc, Transform.DeducedType))
  2157. return;
  2158. // Check whether we've already declared deduction guides for this template.
  2159. // FIXME: Consider storing a flag on the template to indicate this.
  2160. auto Existing = DC->lookup(Transform.DeductionGuideName);
  2161. for (auto *D : Existing)
  2162. if (D->isImplicit())
  2163. return;
  2164. // In case we were expanding a pack when we attempted to declare deduction
  2165. // guides, turn off pack expansion for everything we're about to do.
  2166. ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  2167. // Create a template instantiation record to track the "instantiation" of
  2168. // constructors into deduction guides.
  2169. // FIXME: Add a kind for this to give more meaningful diagnostics. But can
  2170. // this substitution process actually fail?
  2171. InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
  2172. if (BuildingDeductionGuides.isInvalid())
  2173. return;
  2174. // Convert declared constructors into deduction guide templates.
  2175. // FIXME: Skip constructors for which deduction must necessarily fail (those
  2176. // for which some class template parameter without a default argument never
  2177. // appears in a deduced context).
  2178. bool AddedAny = false;
  2179. for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
  2180. D = D->getUnderlyingDecl();
  2181. if (D->isInvalidDecl() || D->isImplicit())
  2182. continue;
  2183. D = cast<NamedDecl>(D->getCanonicalDecl());
  2184. auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
  2185. auto *CD =
  2186. dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
  2187. // Class-scope explicit specializations (MS extension) do not result in
  2188. // deduction guides.
  2189. if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
  2190. continue;
  2191. // Cannot make a deduction guide when unparsed arguments are present.
  2192. if (std::any_of(CD->param_begin(), CD->param_end(), [](ParmVarDecl *P) {
  2193. return !P || P->hasUnparsedDefaultArg();
  2194. }))
  2195. continue;
  2196. Transform.transformConstructor(FTD, CD);
  2197. AddedAny = true;
  2198. }
  2199. // C++17 [over.match.class.deduct]
  2200. // -- If C is not defined or does not declare any constructors, an
  2201. // additional function template derived as above from a hypothetical
  2202. // constructor C().
  2203. if (!AddedAny)
  2204. Transform.buildSimpleDeductionGuide(None);
  2205. // -- An additional function template derived as above from a hypothetical
  2206. // constructor C(C), called the copy deduction candidate.
  2207. cast<CXXDeductionGuideDecl>(
  2208. cast<FunctionTemplateDecl>(
  2209. Transform.buildSimpleDeductionGuide(Transform.DeducedType))
  2210. ->getTemplatedDecl())
  2211. ->setIsCopyDeductionCandidate();
  2212. }
  2213. /// Diagnose the presence of a default template argument on a
  2214. /// template parameter, which is ill-formed in certain contexts.
  2215. ///
  2216. /// \returns true if the default template argument should be dropped.
  2217. static bool DiagnoseDefaultTemplateArgument(Sema &S,
  2218. Sema::TemplateParamListContext TPC,
  2219. SourceLocation ParamLoc,
  2220. SourceRange DefArgRange) {
  2221. switch (TPC) {
  2222. case Sema::TPC_ClassTemplate:
  2223. case Sema::TPC_VarTemplate:
  2224. case Sema::TPC_TypeAliasTemplate:
  2225. return false;
  2226. case Sema::TPC_FunctionTemplate:
  2227. case Sema::TPC_FriendFunctionTemplateDefinition:
  2228. // C++ [temp.param]p9:
  2229. // A default template-argument shall not be specified in a
  2230. // function template declaration or a function template
  2231. // definition [...]
  2232. // If a friend function template declaration specifies a default
  2233. // template-argument, that declaration shall be a definition and shall be
  2234. // the only declaration of the function template in the translation unit.
  2235. // (C++98/03 doesn't have this wording; see DR226).
  2236. S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
  2237. diag::warn_cxx98_compat_template_parameter_default_in_function_template
  2238. : diag::ext_template_parameter_default_in_function_template)
  2239. << DefArgRange;
  2240. return false;
  2241. case Sema::TPC_ClassTemplateMember:
  2242. // C++0x [temp.param]p9:
  2243. // A default template-argument shall not be specified in the
  2244. // template-parameter-lists of the definition of a member of a
  2245. // class template that appears outside of the member's class.
  2246. S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
  2247. << DefArgRange;
  2248. return true;
  2249. case Sema::TPC_FriendClassTemplate:
  2250. case Sema::TPC_FriendFunctionTemplate:
  2251. // C++ [temp.param]p9:
  2252. // A default template-argument shall not be specified in a
  2253. // friend template declaration.
  2254. S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
  2255. << DefArgRange;
  2256. return true;
  2257. // FIXME: C++0x [temp.param]p9 allows default template-arguments
  2258. // for friend function templates if there is only a single
  2259. // declaration (and it is a definition). Strange!
  2260. }
  2261. llvm_unreachable("Invalid TemplateParamListContext!");
  2262. }
  2263. /// Check for unexpanded parameter packs within the template parameters
  2264. /// of a template template parameter, recursively.
  2265. static bool DiagnoseUnexpandedParameterPacks(Sema &S,
  2266. TemplateTemplateParmDecl *TTP) {
  2267. // A template template parameter which is a parameter pack is also a pack
  2268. // expansion.
  2269. if (TTP->isParameterPack())
  2270. return false;
  2271. TemplateParameterList *Params = TTP->getTemplateParameters();
  2272. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  2273. NamedDecl *P = Params->getParam(I);
  2274. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
  2275. if (!TTP->isParameterPack())
  2276. if (const TypeConstraint *TC = TTP->getTypeConstraint())
  2277. if (TC->hasExplicitTemplateArgs())
  2278. for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
  2279. if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
  2280. Sema::UPPC_TypeConstraint))
  2281. return true;
  2282. continue;
  2283. }
  2284. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
  2285. if (!NTTP->isParameterPack() &&
  2286. S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
  2287. NTTP->getTypeSourceInfo(),
  2288. Sema::UPPC_NonTypeTemplateParameterType))
  2289. return true;
  2290. continue;
  2291. }
  2292. if (TemplateTemplateParmDecl *InnerTTP
  2293. = dyn_cast<TemplateTemplateParmDecl>(P))
  2294. if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
  2295. return true;
  2296. }
  2297. return false;
  2298. }
  2299. /// Checks the validity of a template parameter list, possibly
  2300. /// considering the template parameter list from a previous
  2301. /// declaration.
  2302. ///
  2303. /// If an "old" template parameter list is provided, it must be
  2304. /// equivalent (per TemplateParameterListsAreEqual) to the "new"
  2305. /// template parameter list.
  2306. ///
  2307. /// \param NewParams Template parameter list for a new template
  2308. /// declaration. This template parameter list will be updated with any
  2309. /// default arguments that are carried through from the previous
  2310. /// template parameter list.
  2311. ///
  2312. /// \param OldParams If provided, template parameter list from a
  2313. /// previous declaration of the same template. Default template
  2314. /// arguments will be merged from the old template parameter list to
  2315. /// the new template parameter list.
  2316. ///
  2317. /// \param TPC Describes the context in which we are checking the given
  2318. /// template parameter list.
  2319. ///
  2320. /// \param SkipBody If we might have already made a prior merged definition
  2321. /// of this template visible, the corresponding body-skipping information.
  2322. /// Default argument redefinition is not an error when skipping such a body,
  2323. /// because (under the ODR) we can assume the default arguments are the same
  2324. /// as the prior merged definition.
  2325. ///
  2326. /// \returns true if an error occurred, false otherwise.
  2327. bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
  2328. TemplateParameterList *OldParams,
  2329. TemplateParamListContext TPC,
  2330. SkipBodyInfo *SkipBody) {
  2331. bool Invalid = false;
  2332. // C++ [temp.param]p10:
  2333. // The set of default template-arguments available for use with a
  2334. // template declaration or definition is obtained by merging the
  2335. // default arguments from the definition (if in scope) and all
  2336. // declarations in scope in the same way default function
  2337. // arguments are (8.3.6).
  2338. bool SawDefaultArgument = false;
  2339. SourceLocation PreviousDefaultArgLoc;
  2340. // Dummy initialization to avoid warnings.
  2341. TemplateParameterList::iterator OldParam = NewParams->end();
  2342. if (OldParams)
  2343. OldParam = OldParams->begin();
  2344. bool RemoveDefaultArguments = false;
  2345. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  2346. NewParamEnd = NewParams->end();
  2347. NewParam != NewParamEnd; ++NewParam) {
  2348. // Variables used to diagnose redundant default arguments
  2349. bool RedundantDefaultArg = false;
  2350. SourceLocation OldDefaultLoc;
  2351. SourceLocation NewDefaultLoc;
  2352. // Variable used to diagnose missing default arguments
  2353. bool MissingDefaultArg = false;
  2354. // Variable used to diagnose non-final parameter packs
  2355. bool SawParameterPack = false;
  2356. if (TemplateTypeParmDecl *NewTypeParm
  2357. = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
  2358. // Check the presence of a default argument here.
  2359. if (NewTypeParm->hasDefaultArgument() &&
  2360. DiagnoseDefaultTemplateArgument(*this, TPC,
  2361. NewTypeParm->getLocation(),
  2362. NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
  2363. .getSourceRange()))
  2364. NewTypeParm->removeDefaultArgument();
  2365. // Merge default arguments for template type parameters.
  2366. TemplateTypeParmDecl *OldTypeParm
  2367. = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
  2368. if (NewTypeParm->isParameterPack()) {
  2369. assert(!NewTypeParm->hasDefaultArgument() &&
  2370. "Parameter packs can't have a default argument!");
  2371. SawParameterPack = true;
  2372. } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
  2373. NewTypeParm->hasDefaultArgument() &&
  2374. (!SkipBody || !SkipBody->ShouldSkip)) {
  2375. OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
  2376. NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
  2377. SawDefaultArgument = true;
  2378. RedundantDefaultArg = true;
  2379. PreviousDefaultArgLoc = NewDefaultLoc;
  2380. } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
  2381. // Merge the default argument from the old declaration to the
  2382. // new declaration.
  2383. NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
  2384. PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
  2385. } else if (NewTypeParm->hasDefaultArgument()) {
  2386. SawDefaultArgument = true;
  2387. PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
  2388. } else if (SawDefaultArgument)
  2389. MissingDefaultArg = true;
  2390. } else if (NonTypeTemplateParmDecl *NewNonTypeParm
  2391. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
  2392. // Check for unexpanded parameter packs.
  2393. if (!NewNonTypeParm->isParameterPack() &&
  2394. DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
  2395. NewNonTypeParm->getTypeSourceInfo(),
  2396. UPPC_NonTypeTemplateParameterType)) {
  2397. Invalid = true;
  2398. continue;
  2399. }
  2400. // Check the presence of a default argument here.
  2401. if (NewNonTypeParm->hasDefaultArgument() &&
  2402. DiagnoseDefaultTemplateArgument(*this, TPC,
  2403. NewNonTypeParm->getLocation(),
  2404. NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
  2405. NewNonTypeParm->removeDefaultArgument();
  2406. }
  2407. // Merge default arguments for non-type template parameters
  2408. NonTypeTemplateParmDecl *OldNonTypeParm
  2409. = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
  2410. if (NewNonTypeParm->isParameterPack()) {
  2411. assert(!NewNonTypeParm->hasDefaultArgument() &&
  2412. "Parameter packs can't have a default argument!");
  2413. if (!NewNonTypeParm->isPackExpansion())
  2414. SawParameterPack = true;
  2415. } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
  2416. NewNonTypeParm->hasDefaultArgument() &&
  2417. (!SkipBody || !SkipBody->ShouldSkip)) {
  2418. OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
  2419. NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
  2420. SawDefaultArgument = true;
  2421. RedundantDefaultArg = true;
  2422. PreviousDefaultArgLoc = NewDefaultLoc;
  2423. } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
  2424. // Merge the default argument from the old declaration to the
  2425. // new declaration.
  2426. NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
  2427. PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
  2428. } else if (NewNonTypeParm->hasDefaultArgument()) {
  2429. SawDefaultArgument = true;
  2430. PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
  2431. } else if (SawDefaultArgument)
  2432. MissingDefaultArg = true;
  2433. } else {
  2434. TemplateTemplateParmDecl *NewTemplateParm
  2435. = cast<TemplateTemplateParmDecl>(*NewParam);
  2436. // Check for unexpanded parameter packs, recursively.
  2437. if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
  2438. Invalid = true;
  2439. continue;
  2440. }
  2441. // Check the presence of a default argument here.
  2442. if (NewTemplateParm->hasDefaultArgument() &&
  2443. DiagnoseDefaultTemplateArgument(*this, TPC,
  2444. NewTemplateParm->getLocation(),
  2445. NewTemplateParm->getDefaultArgument().getSourceRange()))
  2446. NewTemplateParm->removeDefaultArgument();
  2447. // Merge default arguments for template template parameters
  2448. TemplateTemplateParmDecl *OldTemplateParm
  2449. = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
  2450. if (NewTemplateParm->isParameterPack()) {
  2451. assert(!NewTemplateParm->hasDefaultArgument() &&
  2452. "Parameter packs can't have a default argument!");
  2453. if (!NewTemplateParm->isPackExpansion())
  2454. SawParameterPack = true;
  2455. } else if (OldTemplateParm &&
  2456. hasVisibleDefaultArgument(OldTemplateParm) &&
  2457. NewTemplateParm->hasDefaultArgument() &&
  2458. (!SkipBody || !SkipBody->ShouldSkip)) {
  2459. OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
  2460. NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
  2461. SawDefaultArgument = true;
  2462. RedundantDefaultArg = true;
  2463. PreviousDefaultArgLoc = NewDefaultLoc;
  2464. } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
  2465. // Merge the default argument from the old declaration to the
  2466. // new declaration.
  2467. NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
  2468. PreviousDefaultArgLoc
  2469. = OldTemplateParm->getDefaultArgument().getLocation();
  2470. } else if (NewTemplateParm->hasDefaultArgument()) {
  2471. SawDefaultArgument = true;
  2472. PreviousDefaultArgLoc
  2473. = NewTemplateParm->getDefaultArgument().getLocation();
  2474. } else if (SawDefaultArgument)
  2475. MissingDefaultArg = true;
  2476. }
  2477. // C++11 [temp.param]p11:
  2478. // If a template parameter of a primary class template or alias template
  2479. // is a template parameter pack, it shall be the last template parameter.
  2480. if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
  2481. (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
  2482. TPC == TPC_TypeAliasTemplate)) {
  2483. Diag((*NewParam)->getLocation(),
  2484. diag::err_template_param_pack_must_be_last_template_parameter);
  2485. Invalid = true;
  2486. }
  2487. if (RedundantDefaultArg) {
  2488. // C++ [temp.param]p12:
  2489. // A template-parameter shall not be given default arguments
  2490. // by two different declarations in the same scope.
  2491. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
  2492. Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
  2493. Invalid = true;
  2494. } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
  2495. // C++ [temp.param]p11:
  2496. // If a template-parameter of a class template has a default
  2497. // template-argument, each subsequent template-parameter shall either
  2498. // have a default template-argument supplied or be a template parameter
  2499. // pack.
  2500. Diag((*NewParam)->getLocation(),
  2501. diag::err_template_param_default_arg_missing);
  2502. Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
  2503. Invalid = true;
  2504. RemoveDefaultArguments = true;
  2505. }
  2506. // If we have an old template parameter list that we're merging
  2507. // in, move on to the next parameter.
  2508. if (OldParams)
  2509. ++OldParam;
  2510. }
  2511. // We were missing some default arguments at the end of the list, so remove
  2512. // all of the default arguments.
  2513. if (RemoveDefaultArguments) {
  2514. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  2515. NewParamEnd = NewParams->end();
  2516. NewParam != NewParamEnd; ++NewParam) {
  2517. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
  2518. TTP->removeDefaultArgument();
  2519. else if (NonTypeTemplateParmDecl *NTTP
  2520. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
  2521. NTTP->removeDefaultArgument();
  2522. else
  2523. cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
  2524. }
  2525. }
  2526. return Invalid;
  2527. }
  2528. namespace {
  2529. /// A class which looks for a use of a certain level of template
  2530. /// parameter.
  2531. struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
  2532. typedef RecursiveASTVisitor<DependencyChecker> super;
  2533. unsigned Depth;
  2534. // Whether we're looking for a use of a template parameter that makes the
  2535. // overall construct type-dependent / a dependent type. This is strictly
  2536. // best-effort for now; we may fail to match at all for a dependent type
  2537. // in some cases if this is set.
  2538. bool IgnoreNonTypeDependent;
  2539. bool Match;
  2540. SourceLocation MatchLoc;
  2541. DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
  2542. : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
  2543. Match(false) {}
  2544. DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
  2545. : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
  2546. NamedDecl *ND = Params->getParam(0);
  2547. if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
  2548. Depth = PD->getDepth();
  2549. } else if (NonTypeTemplateParmDecl *PD =
  2550. dyn_cast<NonTypeTemplateParmDecl>(ND)) {
  2551. Depth = PD->getDepth();
  2552. } else {
  2553. Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
  2554. }
  2555. }
  2556. bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
  2557. if (ParmDepth >= Depth) {
  2558. Match = true;
  2559. MatchLoc = Loc;
  2560. return true;
  2561. }
  2562. return false;
  2563. }
  2564. bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
  2565. // Prune out non-type-dependent expressions if requested. This can
  2566. // sometimes result in us failing to find a template parameter reference
  2567. // (if a value-dependent expression creates a dependent type), but this
  2568. // mode is best-effort only.
  2569. if (auto *E = dyn_cast_or_null<Expr>(S))
  2570. if (IgnoreNonTypeDependent && !E->isTypeDependent())
  2571. return true;
  2572. return super::TraverseStmt(S, Q);
  2573. }
  2574. bool TraverseTypeLoc(TypeLoc TL) {
  2575. if (IgnoreNonTypeDependent && !TL.isNull() &&
  2576. !TL.getType()->isDependentType())
  2577. return true;
  2578. return super::TraverseTypeLoc(TL);
  2579. }
  2580. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  2581. return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
  2582. }
  2583. bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  2584. // For a best-effort search, keep looking until we find a location.
  2585. return IgnoreNonTypeDependent || !Matches(T->getDepth());
  2586. }
  2587. bool TraverseTemplateName(TemplateName N) {
  2588. if (TemplateTemplateParmDecl *PD =
  2589. dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
  2590. if (Matches(PD->getDepth()))
  2591. return false;
  2592. return super::TraverseTemplateName(N);
  2593. }
  2594. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2595. if (NonTypeTemplateParmDecl *PD =
  2596. dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
  2597. if (Matches(PD->getDepth(), E->getExprLoc()))
  2598. return false;
  2599. return super::VisitDeclRefExpr(E);
  2600. }
  2601. bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
  2602. return TraverseType(T->getReplacementType());
  2603. }
  2604. bool
  2605. VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
  2606. return TraverseTemplateArgument(T->getArgumentPack());
  2607. }
  2608. bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
  2609. return TraverseType(T->getInjectedSpecializationType());
  2610. }
  2611. };
  2612. } // end anonymous namespace
  2613. /// Determines whether a given type depends on the given parameter
  2614. /// list.
  2615. static bool
  2616. DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
  2617. if (!Params->size())
  2618. return false;
  2619. DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
  2620. Checker.TraverseType(T);
  2621. return Checker.Match;
  2622. }
  2623. // Find the source range corresponding to the named type in the given
  2624. // nested-name-specifier, if any.
  2625. static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
  2626. QualType T,
  2627. const CXXScopeSpec &SS) {
  2628. NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
  2629. while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
  2630. if (const Type *CurType = NNS->getAsType()) {
  2631. if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
  2632. return NNSLoc.getTypeLoc().getSourceRange();
  2633. } else
  2634. break;
  2635. NNSLoc = NNSLoc.getPrefix();
  2636. }
  2637. return SourceRange();
  2638. }
  2639. /// Match the given template parameter lists to the given scope
  2640. /// specifier, returning the template parameter list that applies to the
  2641. /// name.
  2642. ///
  2643. /// \param DeclStartLoc the start of the declaration that has a scope
  2644. /// specifier or a template parameter list.
  2645. ///
  2646. /// \param DeclLoc The location of the declaration itself.
  2647. ///
  2648. /// \param SS the scope specifier that will be matched to the given template
  2649. /// parameter lists. This scope specifier precedes a qualified name that is
  2650. /// being declared.
  2651. ///
  2652. /// \param TemplateId The template-id following the scope specifier, if there
  2653. /// is one. Used to check for a missing 'template<>'.
  2654. ///
  2655. /// \param ParamLists the template parameter lists, from the outermost to the
  2656. /// innermost template parameter lists.
  2657. ///
  2658. /// \param IsFriend Whether to apply the slightly different rules for
  2659. /// matching template parameters to scope specifiers in friend
  2660. /// declarations.
  2661. ///
  2662. /// \param IsMemberSpecialization will be set true if the scope specifier
  2663. /// denotes a fully-specialized type, and therefore this is a declaration of
  2664. /// a member specialization.
  2665. ///
  2666. /// \returns the template parameter list, if any, that corresponds to the
  2667. /// name that is preceded by the scope specifier @p SS. This template
  2668. /// parameter list may have template parameters (if we're declaring a
  2669. /// template) or may have no template parameters (if we're declaring a
  2670. /// template specialization), or may be NULL (if what we're declaring isn't
  2671. /// itself a template).
  2672. TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
  2673. SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
  2674. TemplateIdAnnotation *TemplateId,
  2675. ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
  2676. bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
  2677. IsMemberSpecialization = false;
  2678. Invalid = false;
  2679. // The sequence of nested types to which we will match up the template
  2680. // parameter lists. We first build this list by starting with the type named
  2681. // by the nested-name-specifier and walking out until we run out of types.
  2682. SmallVector<QualType, 4> NestedTypes;
  2683. QualType T;
  2684. if (SS.getScopeRep()) {
  2685. if (CXXRecordDecl *Record
  2686. = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
  2687. T = Context.getTypeDeclType(Record);
  2688. else
  2689. T = QualType(SS.getScopeRep()->getAsType(), 0);
  2690. }
  2691. // If we found an explicit specialization that prevents us from needing
  2692. // 'template<>' headers, this will be set to the location of that
  2693. // explicit specialization.
  2694. SourceLocation ExplicitSpecLoc;
  2695. while (!T.isNull()) {
  2696. NestedTypes.push_back(T);
  2697. // Retrieve the parent of a record type.
  2698. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2699. // If this type is an explicit specialization, we're done.
  2700. if (ClassTemplateSpecializationDecl *Spec
  2701. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2702. if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
  2703. Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
  2704. ExplicitSpecLoc = Spec->getLocation();
  2705. break;
  2706. }
  2707. } else if (Record->getTemplateSpecializationKind()
  2708. == TSK_ExplicitSpecialization) {
  2709. ExplicitSpecLoc = Record->getLocation();
  2710. break;
  2711. }
  2712. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
  2713. T = Context.getTypeDeclType(Parent);
  2714. else
  2715. T = QualType();
  2716. continue;
  2717. }
  2718. if (const TemplateSpecializationType *TST
  2719. = T->getAs<TemplateSpecializationType>()) {
  2720. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2721. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
  2722. T = Context.getTypeDeclType(Parent);
  2723. else
  2724. T = QualType();
  2725. continue;
  2726. }
  2727. }
  2728. // Look one step prior in a dependent template specialization type.
  2729. if (const DependentTemplateSpecializationType *DependentTST
  2730. = T->getAs<DependentTemplateSpecializationType>()) {
  2731. if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
  2732. T = QualType(NNS->getAsType(), 0);
  2733. else
  2734. T = QualType();
  2735. continue;
  2736. }
  2737. // Look one step prior in a dependent name type.
  2738. if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
  2739. if (NestedNameSpecifier *NNS = DependentName->getQualifier())
  2740. T = QualType(NNS->getAsType(), 0);
  2741. else
  2742. T = QualType();
  2743. continue;
  2744. }
  2745. // Retrieve the parent of an enumeration type.
  2746. if (const EnumType *EnumT = T->getAs<EnumType>()) {
  2747. // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
  2748. // check here.
  2749. EnumDecl *Enum = EnumT->getDecl();
  2750. // Get to the parent type.
  2751. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
  2752. T = Context.getTypeDeclType(Parent);
  2753. else
  2754. T = QualType();
  2755. continue;
  2756. }
  2757. T = QualType();
  2758. }
  2759. // Reverse the nested types list, since we want to traverse from the outermost
  2760. // to the innermost while checking template-parameter-lists.
  2761. std::reverse(NestedTypes.begin(), NestedTypes.end());
  2762. // C++0x [temp.expl.spec]p17:
  2763. // A member or a member template may be nested within many
  2764. // enclosing class templates. In an explicit specialization for
  2765. // such a member, the member declaration shall be preceded by a
  2766. // template<> for each enclosing class template that is
  2767. // explicitly specialized.
  2768. bool SawNonEmptyTemplateParameterList = false;
  2769. auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
  2770. if (SawNonEmptyTemplateParameterList) {
  2771. if (!SuppressDiagnostic)
  2772. Diag(DeclLoc, diag::err_specialize_member_of_template)
  2773. << !Recovery << Range;
  2774. Invalid = true;
  2775. IsMemberSpecialization = false;
  2776. return true;
  2777. }
  2778. return false;
  2779. };
  2780. auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
  2781. // Check that we can have an explicit specialization here.
  2782. if (CheckExplicitSpecialization(Range, true))
  2783. return true;
  2784. // We don't have a template header, but we should.
  2785. SourceLocation ExpectedTemplateLoc;
  2786. if (!ParamLists.empty())
  2787. ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
  2788. else
  2789. ExpectedTemplateLoc = DeclStartLoc;
  2790. if (!SuppressDiagnostic)
  2791. Diag(DeclLoc, diag::err_template_spec_needs_header)
  2792. << Range
  2793. << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
  2794. return false;
  2795. };
  2796. unsigned ParamIdx = 0;
  2797. for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
  2798. ++TypeIdx) {
  2799. T = NestedTypes[TypeIdx];
  2800. // Whether we expect a 'template<>' header.
  2801. bool NeedEmptyTemplateHeader = false;
  2802. // Whether we expect a template header with parameters.
  2803. bool NeedNonemptyTemplateHeader = false;
  2804. // For a dependent type, the set of template parameters that we
  2805. // expect to see.
  2806. TemplateParameterList *ExpectedTemplateParams = nullptr;
  2807. // C++0x [temp.expl.spec]p15:
  2808. // A member or a member template may be nested within many enclosing
  2809. // class templates. In an explicit specialization for such a member, the
  2810. // member declaration shall be preceded by a template<> for each
  2811. // enclosing class template that is explicitly specialized.
  2812. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2813. if (ClassTemplatePartialSpecializationDecl *Partial
  2814. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
  2815. ExpectedTemplateParams = Partial->getTemplateParameters();
  2816. NeedNonemptyTemplateHeader = true;
  2817. } else if (Record->isDependentType()) {
  2818. if (Record->getDescribedClassTemplate()) {
  2819. ExpectedTemplateParams = Record->getDescribedClassTemplate()
  2820. ->getTemplateParameters();
  2821. NeedNonemptyTemplateHeader = true;
  2822. }
  2823. } else if (ClassTemplateSpecializationDecl *Spec
  2824. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2825. // C++0x [temp.expl.spec]p4:
  2826. // Members of an explicitly specialized class template are defined
  2827. // in the same manner as members of normal classes, and not using
  2828. // the template<> syntax.
  2829. if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
  2830. NeedEmptyTemplateHeader = true;
  2831. else
  2832. continue;
  2833. } else if (Record->getTemplateSpecializationKind()) {
  2834. if (Record->getTemplateSpecializationKind()
  2835. != TSK_ExplicitSpecialization &&
  2836. TypeIdx == NumTypes - 1)
  2837. IsMemberSpecialization = true;
  2838. continue;
  2839. }
  2840. } else if (const TemplateSpecializationType *TST
  2841. = T->getAs<TemplateSpecializationType>()) {
  2842. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2843. ExpectedTemplateParams = Template->getTemplateParameters();
  2844. NeedNonemptyTemplateHeader = true;
  2845. }
  2846. } else if (T->getAs<DependentTemplateSpecializationType>()) {
  2847. // FIXME: We actually could/should check the template arguments here
  2848. // against the corresponding template parameter list.
  2849. NeedNonemptyTemplateHeader = false;
  2850. }
  2851. // C++ [temp.expl.spec]p16:
  2852. // In an explicit specialization declaration for a member of a class
  2853. // template or a member template that ap- pears in namespace scope, the
  2854. // member template and some of its enclosing class templates may remain
  2855. // unspecialized, except that the declaration shall not explicitly
  2856. // specialize a class member template if its en- closing class templates
  2857. // are not explicitly specialized as well.
  2858. if (ParamIdx < ParamLists.size()) {
  2859. if (ParamLists[ParamIdx]->size() == 0) {
  2860. if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  2861. false))
  2862. return nullptr;
  2863. } else
  2864. SawNonEmptyTemplateParameterList = true;
  2865. }
  2866. if (NeedEmptyTemplateHeader) {
  2867. // If we're on the last of the types, and we need a 'template<>' header
  2868. // here, then it's a member specialization.
  2869. if (TypeIdx == NumTypes - 1)
  2870. IsMemberSpecialization = true;
  2871. if (ParamIdx < ParamLists.size()) {
  2872. if (ParamLists[ParamIdx]->size() > 0) {
  2873. // The header has template parameters when it shouldn't. Complain.
  2874. if (!SuppressDiagnostic)
  2875. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  2876. diag::err_template_param_list_matches_nontemplate)
  2877. << T
  2878. << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
  2879. ParamLists[ParamIdx]->getRAngleLoc())
  2880. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  2881. Invalid = true;
  2882. return nullptr;
  2883. }
  2884. // Consume this template header.
  2885. ++ParamIdx;
  2886. continue;
  2887. }
  2888. if (!IsFriend)
  2889. if (DiagnoseMissingExplicitSpecialization(
  2890. getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
  2891. return nullptr;
  2892. continue;
  2893. }
  2894. if (NeedNonemptyTemplateHeader) {
  2895. // In friend declarations we can have template-ids which don't
  2896. // depend on the corresponding template parameter lists. But
  2897. // assume that empty parameter lists are supposed to match this
  2898. // template-id.
  2899. if (IsFriend && T->isDependentType()) {
  2900. if (ParamIdx < ParamLists.size() &&
  2901. DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
  2902. ExpectedTemplateParams = nullptr;
  2903. else
  2904. continue;
  2905. }
  2906. if (ParamIdx < ParamLists.size()) {
  2907. // Check the template parameter list, if we can.
  2908. if (ExpectedTemplateParams &&
  2909. !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
  2910. ExpectedTemplateParams,
  2911. !SuppressDiagnostic, TPL_TemplateMatch))
  2912. Invalid = true;
  2913. if (!Invalid &&
  2914. CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
  2915. TPC_ClassTemplateMember))
  2916. Invalid = true;
  2917. ++ParamIdx;
  2918. continue;
  2919. }
  2920. if (!SuppressDiagnostic)
  2921. Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
  2922. << T
  2923. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  2924. Invalid = true;
  2925. continue;
  2926. }
  2927. }
  2928. // If there were at least as many template-ids as there were template
  2929. // parameter lists, then there are no template parameter lists remaining for
  2930. // the declaration itself.
  2931. if (ParamIdx >= ParamLists.size()) {
  2932. if (TemplateId && !IsFriend) {
  2933. // We don't have a template header for the declaration itself, but we
  2934. // should.
  2935. DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
  2936. TemplateId->RAngleLoc));
  2937. // Fabricate an empty template parameter list for the invented header.
  2938. return TemplateParameterList::Create(Context, SourceLocation(),
  2939. SourceLocation(), None,
  2940. SourceLocation(), nullptr);
  2941. }
  2942. return nullptr;
  2943. }
  2944. // If there were too many template parameter lists, complain about that now.
  2945. if (ParamIdx < ParamLists.size() - 1) {
  2946. bool HasAnyExplicitSpecHeader = false;
  2947. bool AllExplicitSpecHeaders = true;
  2948. for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
  2949. if (ParamLists[I]->size() == 0)
  2950. HasAnyExplicitSpecHeader = true;
  2951. else
  2952. AllExplicitSpecHeaders = false;
  2953. }
  2954. if (!SuppressDiagnostic)
  2955. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  2956. AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
  2957. : diag::err_template_spec_extra_headers)
  2958. << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  2959. ParamLists[ParamLists.size() - 2]->getRAngleLoc());
  2960. // If there was a specialization somewhere, such that 'template<>' is
  2961. // not required, and there were any 'template<>' headers, note where the
  2962. // specialization occurred.
  2963. if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
  2964. !SuppressDiagnostic)
  2965. Diag(ExplicitSpecLoc,
  2966. diag::note_explicit_template_spec_does_not_need_header)
  2967. << NestedTypes.back();
  2968. // We have a template parameter list with no corresponding scope, which
  2969. // means that the resulting template declaration can't be instantiated
  2970. // properly (we'll end up with dependent nodes when we shouldn't).
  2971. if (!AllExplicitSpecHeaders)
  2972. Invalid = true;
  2973. }
  2974. // C++ [temp.expl.spec]p16:
  2975. // In an explicit specialization declaration for a member of a class
  2976. // template or a member template that ap- pears in namespace scope, the
  2977. // member template and some of its enclosing class templates may remain
  2978. // unspecialized, except that the declaration shall not explicitly
  2979. // specialize a class member template if its en- closing class templates
  2980. // are not explicitly specialized as well.
  2981. if (ParamLists.back()->size() == 0 &&
  2982. CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  2983. false))
  2984. return nullptr;
  2985. // Return the last template parameter list, which corresponds to the
  2986. // entity being declared.
  2987. return ParamLists.back();
  2988. }
  2989. void Sema::NoteAllFoundTemplates(TemplateName Name) {
  2990. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  2991. Diag(Template->getLocation(), diag::note_template_declared_here)
  2992. << (isa<FunctionTemplateDecl>(Template)
  2993. ? 0
  2994. : isa<ClassTemplateDecl>(Template)
  2995. ? 1
  2996. : isa<VarTemplateDecl>(Template)
  2997. ? 2
  2998. : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
  2999. << Template->getDeclName();
  3000. return;
  3001. }
  3002. if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
  3003. for (OverloadedTemplateStorage::iterator I = OST->begin(),
  3004. IEnd = OST->end();
  3005. I != IEnd; ++I)
  3006. Diag((*I)->getLocation(), diag::note_template_declared_here)
  3007. << 0 << (*I)->getDeclName();
  3008. return;
  3009. }
  3010. }
  3011. static QualType
  3012. checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
  3013. const SmallVectorImpl<TemplateArgument> &Converted,
  3014. SourceLocation TemplateLoc,
  3015. TemplateArgumentListInfo &TemplateArgs) {
  3016. ASTContext &Context = SemaRef.getASTContext();
  3017. switch (BTD->getBuiltinTemplateKind()) {
  3018. case BTK__make_integer_seq: {
  3019. // Specializations of __make_integer_seq<S, T, N> are treated like
  3020. // S<T, 0, ..., N-1>.
  3021. // C++14 [inteseq.intseq]p1:
  3022. // T shall be an integer type.
  3023. if (!Converted[1].getAsType()->isIntegralType(Context)) {
  3024. SemaRef.Diag(TemplateArgs[1].getLocation(),
  3025. diag::err_integer_sequence_integral_element_type);
  3026. return QualType();
  3027. }
  3028. // C++14 [inteseq.make]p1:
  3029. // If N is negative the program is ill-formed.
  3030. TemplateArgument NumArgsArg = Converted[2];
  3031. llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
  3032. if (NumArgs < 0) {
  3033. SemaRef.Diag(TemplateArgs[2].getLocation(),
  3034. diag::err_integer_sequence_negative_length);
  3035. return QualType();
  3036. }
  3037. QualType ArgTy = NumArgsArg.getIntegralType();
  3038. TemplateArgumentListInfo SyntheticTemplateArgs;
  3039. // The type argument gets reused as the first template argument in the
  3040. // synthetic template argument list.
  3041. SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
  3042. // Expand N into 0 ... N-1.
  3043. for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
  3044. I < NumArgs; ++I) {
  3045. TemplateArgument TA(Context, I, ArgTy);
  3046. SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
  3047. TA, ArgTy, TemplateArgs[2].getLocation()));
  3048. }
  3049. // The first template argument will be reused as the template decl that
  3050. // our synthetic template arguments will be applied to.
  3051. return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
  3052. TemplateLoc, SyntheticTemplateArgs);
  3053. }
  3054. case BTK__type_pack_element:
  3055. // Specializations of
  3056. // __type_pack_element<Index, T_1, ..., T_N>
  3057. // are treated like T_Index.
  3058. assert(Converted.size() == 2 &&
  3059. "__type_pack_element should be given an index and a parameter pack");
  3060. // If the Index is out of bounds, the program is ill-formed.
  3061. TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
  3062. llvm::APSInt Index = IndexArg.getAsIntegral();
  3063. assert(Index >= 0 && "the index used with __type_pack_element should be of "
  3064. "type std::size_t, and hence be non-negative");
  3065. if (Index >= Ts.pack_size()) {
  3066. SemaRef.Diag(TemplateArgs[0].getLocation(),
  3067. diag::err_type_pack_element_out_of_bounds);
  3068. return QualType();
  3069. }
  3070. // We simply return the type at index `Index`.
  3071. auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
  3072. return Nth->getAsType();
  3073. }
  3074. llvm_unreachable("unexpected BuiltinTemplateDecl!");
  3075. }
  3076. /// Determine whether this alias template is "enable_if_t".
  3077. /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
  3078. static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
  3079. return AliasTemplate->getName().equals("enable_if_t") ||
  3080. AliasTemplate->getName().equals("__enable_if_t");
  3081. }
  3082. /// Collect all of the separable terms in the given condition, which
  3083. /// might be a conjunction.
  3084. ///
  3085. /// FIXME: The right answer is to convert the logical expression into
  3086. /// disjunctive normal form, so we can find the first failed term
  3087. /// within each possible clause.
  3088. static void collectConjunctionTerms(Expr *Clause,
  3089. SmallVectorImpl<Expr *> &Terms) {
  3090. if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
  3091. if (BinOp->getOpcode() == BO_LAnd) {
  3092. collectConjunctionTerms(BinOp->getLHS(), Terms);
  3093. collectConjunctionTerms(BinOp->getRHS(), Terms);
  3094. }
  3095. return;
  3096. }
  3097. Terms.push_back(Clause);
  3098. }
  3099. // The ranges-v3 library uses an odd pattern of a top-level "||" with
  3100. // a left-hand side that is value-dependent but never true. Identify
  3101. // the idiom and ignore that term.
  3102. static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
  3103. // Top-level '||'.
  3104. auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
  3105. if (!BinOp) return Cond;
  3106. if (BinOp->getOpcode() != BO_LOr) return Cond;
  3107. // With an inner '==' that has a literal on the right-hand side.
  3108. Expr *LHS = BinOp->getLHS();
  3109. auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
  3110. if (!InnerBinOp) return Cond;
  3111. if (InnerBinOp->getOpcode() != BO_EQ ||
  3112. !isa<IntegerLiteral>(InnerBinOp->getRHS()))
  3113. return Cond;
  3114. // If the inner binary operation came from a macro expansion named
  3115. // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
  3116. // of the '||', which is the real, user-provided condition.
  3117. SourceLocation Loc = InnerBinOp->getExprLoc();
  3118. if (!Loc.isMacroID()) return Cond;
  3119. StringRef MacroName = PP.getImmediateMacroName(Loc);
  3120. if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
  3121. return BinOp->getRHS();
  3122. return Cond;
  3123. }
  3124. namespace {
  3125. // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
  3126. // within failing boolean expression, such as substituting template parameters
  3127. // for actual types.
  3128. class FailedBooleanConditionPrinterHelper : public PrinterHelper {
  3129. public:
  3130. explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
  3131. : Policy(P) {}
  3132. bool handledStmt(Stmt *E, raw_ostream &OS) override {
  3133. const auto *DR = dyn_cast<DeclRefExpr>(E);
  3134. if (DR && DR->getQualifier()) {
  3135. // If this is a qualified name, expand the template arguments in nested
  3136. // qualifiers.
  3137. DR->getQualifier()->print(OS, Policy, true);
  3138. // Then print the decl itself.
  3139. const ValueDecl *VD = DR->getDecl();
  3140. OS << VD->getName();
  3141. if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
  3142. // This is a template variable, print the expanded template arguments.
  3143. printTemplateArgumentList(
  3144. OS, IV->getTemplateArgs().asArray(), Policy,
  3145. IV->getSpecializedTemplate()->getTemplateParameters());
  3146. }
  3147. return true;
  3148. }
  3149. return false;
  3150. }
  3151. private:
  3152. const PrintingPolicy Policy;
  3153. };
  3154. } // end anonymous namespace
  3155. std::pair<Expr *, std::string>
  3156. Sema::findFailedBooleanCondition(Expr *Cond) {
  3157. Cond = lookThroughRangesV3Condition(PP, Cond);
  3158. // Separate out all of the terms in a conjunction.
  3159. SmallVector<Expr *, 4> Terms;
  3160. collectConjunctionTerms(Cond, Terms);
  3161. // Determine which term failed.
  3162. Expr *FailedCond = nullptr;
  3163. for (Expr *Term : Terms) {
  3164. Expr *TermAsWritten = Term->IgnoreParenImpCasts();
  3165. // Literals are uninteresting.
  3166. if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
  3167. isa<IntegerLiteral>(TermAsWritten))
  3168. continue;
  3169. // The initialization of the parameter from the argument is
  3170. // a constant-evaluated context.
  3171. EnterExpressionEvaluationContext ConstantEvaluated(
  3172. *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  3173. bool Succeeded;
  3174. if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
  3175. !Succeeded) {
  3176. FailedCond = TermAsWritten;
  3177. break;
  3178. }
  3179. }
  3180. if (!FailedCond)
  3181. FailedCond = Cond->IgnoreParenImpCasts();
  3182. std::string Description;
  3183. {
  3184. llvm::raw_string_ostream Out(Description);
  3185. PrintingPolicy Policy = getPrintingPolicy();
  3186. Policy.PrintCanonicalTypes = true;
  3187. FailedBooleanConditionPrinterHelper Helper(Policy);
  3188. FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
  3189. }
  3190. return { FailedCond, Description };
  3191. }
  3192. QualType Sema::CheckTemplateIdType(TemplateName Name,
  3193. SourceLocation TemplateLoc,
  3194. TemplateArgumentListInfo &TemplateArgs) {
  3195. DependentTemplateName *DTN
  3196. = Name.getUnderlying().getAsDependentTemplateName();
  3197. if (DTN && DTN->isIdentifier())
  3198. // When building a template-id where the template-name is dependent,
  3199. // assume the template is a type template. Either our assumption is
  3200. // correct, or the code is ill-formed and will be diagnosed when the
  3201. // dependent name is substituted.
  3202. return Context.getDependentTemplateSpecializationType(ETK_None,
  3203. DTN->getQualifier(),
  3204. DTN->getIdentifier(),
  3205. TemplateArgs);
  3206. if (Name.getAsAssumedTemplateName() &&
  3207. resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
  3208. return QualType();
  3209. TemplateDecl *Template = Name.getAsTemplateDecl();
  3210. if (!Template || isa<FunctionTemplateDecl>(Template) ||
  3211. isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
  3212. // We might have a substituted template template parameter pack. If so,
  3213. // build a template specialization type for it.
  3214. if (Name.getAsSubstTemplateTemplateParmPack())
  3215. return Context.getTemplateSpecializationType(Name, TemplateArgs);
  3216. Diag(TemplateLoc, diag::err_template_id_not_a_type)
  3217. << Name;
  3218. NoteAllFoundTemplates(Name);
  3219. return QualType();
  3220. }
  3221. // Check that the template argument list is well-formed for this
  3222. // template.
  3223. SmallVector<TemplateArgument, 4> Converted;
  3224. if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
  3225. false, Converted,
  3226. /*UpdateArgsWithConversions=*/true))
  3227. return QualType();
  3228. QualType CanonType;
  3229. if (TypeAliasTemplateDecl *AliasTemplate =
  3230. dyn_cast<TypeAliasTemplateDecl>(Template)) {
  3231. // Find the canonical type for this type alias template specialization.
  3232. TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
  3233. if (Pattern->isInvalidDecl())
  3234. return QualType();
  3235. TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
  3236. Converted);
  3237. // Only substitute for the innermost template argument list.
  3238. MultiLevelTemplateArgumentList TemplateArgLists;
  3239. TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
  3240. TemplateArgLists.addOuterRetainedLevels(
  3241. AliasTemplate->getTemplateParameters()->getDepth());
  3242. LocalInstantiationScope Scope(*this);
  3243. InstantiatingTemplate Inst(*this, TemplateLoc, Template);
  3244. if (Inst.isInvalid())
  3245. return QualType();
  3246. CanonType = SubstType(Pattern->getUnderlyingType(),
  3247. TemplateArgLists, AliasTemplate->getLocation(),
  3248. AliasTemplate->getDeclName());
  3249. if (CanonType.isNull()) {
  3250. // If this was enable_if and we failed to find the nested type
  3251. // within enable_if in a SFINAE context, dig out the specific
  3252. // enable_if condition that failed and present that instead.
  3253. if (isEnableIfAliasTemplate(AliasTemplate)) {
  3254. if (auto DeductionInfo = isSFINAEContext()) {
  3255. if (*DeductionInfo &&
  3256. (*DeductionInfo)->hasSFINAEDiagnostic() &&
  3257. (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
  3258. diag::err_typename_nested_not_found_enable_if &&
  3259. TemplateArgs[0].getArgument().getKind()
  3260. == TemplateArgument::Expression) {
  3261. Expr *FailedCond;
  3262. std::string FailedDescription;
  3263. std::tie(FailedCond, FailedDescription) =
  3264. findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
  3265. // Remove the old SFINAE diagnostic.
  3266. PartialDiagnosticAt OldDiag =
  3267. {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
  3268. (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
  3269. // Add a new SFINAE diagnostic specifying which condition
  3270. // failed.
  3271. (*DeductionInfo)->addSFINAEDiagnostic(
  3272. OldDiag.first,
  3273. PDiag(diag::err_typename_nested_not_found_requirement)
  3274. << FailedDescription
  3275. << FailedCond->getSourceRange());
  3276. }
  3277. }
  3278. }
  3279. return QualType();
  3280. }
  3281. } else if (Name.isDependent() ||
  3282. TemplateSpecializationType::anyDependentTemplateArguments(
  3283. TemplateArgs, Converted)) {
  3284. // This class template specialization is a dependent
  3285. // type. Therefore, its canonical type is another class template
  3286. // specialization type that contains all of the converted
  3287. // arguments in canonical form. This ensures that, e.g., A<T> and
  3288. // A<T, T> have identical types when A is declared as:
  3289. //
  3290. // template<typename T, typename U = T> struct A;
  3291. CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
  3292. // This might work out to be a current instantiation, in which
  3293. // case the canonical type needs to be the InjectedClassNameType.
  3294. //
  3295. // TODO: in theory this could be a simple hashtable lookup; most
  3296. // changes to CurContext don't change the set of current
  3297. // instantiations.
  3298. if (isa<ClassTemplateDecl>(Template)) {
  3299. for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
  3300. // If we get out to a namespace, we're done.
  3301. if (Ctx->isFileContext()) break;
  3302. // If this isn't a record, keep looking.
  3303. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
  3304. if (!Record) continue;
  3305. // Look for one of the two cases with InjectedClassNameTypes
  3306. // and check whether it's the same template.
  3307. if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
  3308. !Record->getDescribedClassTemplate())
  3309. continue;
  3310. // Fetch the injected class name type and check whether its
  3311. // injected type is equal to the type we just built.
  3312. QualType ICNT = Context.getTypeDeclType(Record);
  3313. QualType Injected = cast<InjectedClassNameType>(ICNT)
  3314. ->getInjectedSpecializationType();
  3315. if (CanonType != Injected->getCanonicalTypeInternal())
  3316. continue;
  3317. // If so, the canonical type of this TST is the injected
  3318. // class name type of the record we just found.
  3319. assert(ICNT.isCanonical());
  3320. CanonType = ICNT;
  3321. break;
  3322. }
  3323. }
  3324. } else if (ClassTemplateDecl *ClassTemplate
  3325. = dyn_cast<ClassTemplateDecl>(Template)) {
  3326. // Find the class template specialization declaration that
  3327. // corresponds to these arguments.
  3328. void *InsertPos = nullptr;
  3329. ClassTemplateSpecializationDecl *Decl
  3330. = ClassTemplate->findSpecialization(Converted, InsertPos);
  3331. if (!Decl) {
  3332. // This is the first time we have referenced this class template
  3333. // specialization. Create the canonical declaration and add it to
  3334. // the set of specializations.
  3335. Decl = ClassTemplateSpecializationDecl::Create(
  3336. Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
  3337. ClassTemplate->getDeclContext(),
  3338. ClassTemplate->getTemplatedDecl()->getBeginLoc(),
  3339. ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
  3340. ClassTemplate->AddSpecialization(Decl, InsertPos);
  3341. if (ClassTemplate->isOutOfLine())
  3342. Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
  3343. }
  3344. if (Decl->getSpecializationKind() == TSK_Undeclared &&
  3345. ClassTemplate->getTemplatedDecl()->hasAttrs()) {
  3346. InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
  3347. if (!Inst.isInvalid()) {
  3348. MultiLevelTemplateArgumentList TemplateArgLists;
  3349. TemplateArgLists.addOuterTemplateArguments(Converted);
  3350. InstantiateAttrsForDecl(TemplateArgLists,
  3351. ClassTemplate->getTemplatedDecl(), Decl);
  3352. }
  3353. }
  3354. // Diagnose uses of this specialization.
  3355. (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
  3356. CanonType = Context.getTypeDeclType(Decl);
  3357. assert(isa<RecordType>(CanonType) &&
  3358. "type of non-dependent specialization is not a RecordType");
  3359. } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
  3360. CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
  3361. TemplateArgs);
  3362. }
  3363. // Build the fully-sugared type for this class template
  3364. // specialization, which refers back to the class template
  3365. // specialization we created or found.
  3366. return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
  3367. }
  3368. void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
  3369. TemplateNameKind &TNK,
  3370. SourceLocation NameLoc,
  3371. IdentifierInfo *&II) {
  3372. assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
  3373. TemplateName Name = ParsedName.get();
  3374. auto *ATN = Name.getAsAssumedTemplateName();
  3375. assert(ATN && "not an assumed template name");
  3376. II = ATN->getDeclName().getAsIdentifierInfo();
  3377. if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
  3378. // Resolved to a type template name.
  3379. ParsedName = TemplateTy::make(Name);
  3380. TNK = TNK_Type_template;
  3381. }
  3382. }
  3383. bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
  3384. SourceLocation NameLoc,
  3385. bool Diagnose) {
  3386. // We assumed this undeclared identifier to be an (ADL-only) function
  3387. // template name, but it was used in a context where a type was required.
  3388. // Try to typo-correct it now.
  3389. AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
  3390. assert(ATN && "not an assumed template name");
  3391. LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
  3392. struct CandidateCallback : CorrectionCandidateCallback {
  3393. bool ValidateCandidate(const TypoCorrection &TC) override {
  3394. return TC.getCorrectionDecl() &&
  3395. getAsTypeTemplateDecl(TC.getCorrectionDecl());
  3396. }
  3397. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3398. return std::make_unique<CandidateCallback>(*this);
  3399. }
  3400. } FilterCCC;
  3401. TypoCorrection Corrected =
  3402. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  3403. FilterCCC, CTK_ErrorRecovery);
  3404. if (Corrected && Corrected.getFoundDecl()) {
  3405. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
  3406. << ATN->getDeclName());
  3407. Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
  3408. return false;
  3409. }
  3410. if (Diagnose)
  3411. Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
  3412. return true;
  3413. }
  3414. TypeResult Sema::ActOnTemplateIdType(
  3415. Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
  3416. TemplateTy TemplateD, IdentifierInfo *TemplateII,
  3417. SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
  3418. ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
  3419. bool IsCtorOrDtorName, bool IsClassName) {
  3420. if (SS.isInvalid())
  3421. return true;
  3422. if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
  3423. DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
  3424. // C++ [temp.res]p3:
  3425. // A qualified-id that refers to a type and in which the
  3426. // nested-name-specifier depends on a template-parameter (14.6.2)
  3427. // shall be prefixed by the keyword typename to indicate that the
  3428. // qualified-id denotes a type, forming an
  3429. // elaborated-type-specifier (7.1.5.3).
  3430. if (!LookupCtx && isDependentScopeSpecifier(SS)) {
  3431. Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
  3432. << SS.getScopeRep() << TemplateII->getName();
  3433. // Recover as if 'typename' were specified.
  3434. // FIXME: This is not quite correct recovery as we don't transform SS
  3435. // into the corresponding dependent form (and we don't diagnose missing
  3436. // 'template' keywords within SS as a result).
  3437. return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
  3438. TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
  3439. TemplateArgsIn, RAngleLoc);
  3440. }
  3441. // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
  3442. // it's not actually allowed to be used as a type in most cases. Because
  3443. // we annotate it before we know whether it's valid, we have to check for
  3444. // this case here.
  3445. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  3446. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  3447. Diag(TemplateIILoc,
  3448. TemplateKWLoc.isInvalid()
  3449. ? diag::err_out_of_line_qualified_id_type_names_constructor
  3450. : diag::ext_out_of_line_qualified_id_type_names_constructor)
  3451. << TemplateII << 0 /*injected-class-name used as template name*/
  3452. << 1 /*if any keyword was present, it was 'template'*/;
  3453. }
  3454. }
  3455. TemplateName Template = TemplateD.get();
  3456. if (Template.getAsAssumedTemplateName() &&
  3457. resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
  3458. return true;
  3459. // Translate the parser's template argument list in our AST format.
  3460. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  3461. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  3462. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  3463. QualType T
  3464. = Context.getDependentTemplateSpecializationType(ETK_None,
  3465. DTN->getQualifier(),
  3466. DTN->getIdentifier(),
  3467. TemplateArgs);
  3468. // Build type-source information.
  3469. TypeLocBuilder TLB;
  3470. DependentTemplateSpecializationTypeLoc SpecTL
  3471. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  3472. SpecTL.setElaboratedKeywordLoc(SourceLocation());
  3473. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3474. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3475. SpecTL.setTemplateNameLoc(TemplateIILoc);
  3476. SpecTL.setLAngleLoc(LAngleLoc);
  3477. SpecTL.setRAngleLoc(RAngleLoc);
  3478. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  3479. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  3480. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  3481. }
  3482. QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  3483. if (Result.isNull())
  3484. return true;
  3485. // Build type-source information.
  3486. TypeLocBuilder TLB;
  3487. TemplateSpecializationTypeLoc SpecTL
  3488. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  3489. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3490. SpecTL.setTemplateNameLoc(TemplateIILoc);
  3491. SpecTL.setLAngleLoc(LAngleLoc);
  3492. SpecTL.setRAngleLoc(RAngleLoc);
  3493. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  3494. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  3495. // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
  3496. // constructor or destructor name (in such a case, the scope specifier
  3497. // will be attached to the enclosing Decl or Expr node).
  3498. if (SS.isNotEmpty() && !IsCtorOrDtorName) {
  3499. // Create an elaborated-type-specifier containing the nested-name-specifier.
  3500. Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
  3501. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  3502. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  3503. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3504. }
  3505. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  3506. }
  3507. TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
  3508. TypeSpecifierType TagSpec,
  3509. SourceLocation TagLoc,
  3510. CXXScopeSpec &SS,
  3511. SourceLocation TemplateKWLoc,
  3512. TemplateTy TemplateD,
  3513. SourceLocation TemplateLoc,
  3514. SourceLocation LAngleLoc,
  3515. ASTTemplateArgsPtr TemplateArgsIn,
  3516. SourceLocation RAngleLoc) {
  3517. if (SS.isInvalid())
  3518. return TypeResult(true);
  3519. TemplateName Template = TemplateD.get();
  3520. // Translate the parser's template argument list in our AST format.
  3521. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  3522. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  3523. // Determine the tag kind
  3524. TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  3525. ElaboratedTypeKeyword Keyword
  3526. = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
  3527. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  3528. QualType T = Context.getDependentTemplateSpecializationType(Keyword,
  3529. DTN->getQualifier(),
  3530. DTN->getIdentifier(),
  3531. TemplateArgs);
  3532. // Build type-source information.
  3533. TypeLocBuilder TLB;
  3534. DependentTemplateSpecializationTypeLoc SpecTL
  3535. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  3536. SpecTL.setElaboratedKeywordLoc(TagLoc);
  3537. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3538. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3539. SpecTL.setTemplateNameLoc(TemplateLoc);
  3540. SpecTL.setLAngleLoc(LAngleLoc);
  3541. SpecTL.setRAngleLoc(RAngleLoc);
  3542. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  3543. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  3544. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  3545. }
  3546. if (TypeAliasTemplateDecl *TAT =
  3547. dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
  3548. // C++0x [dcl.type.elab]p2:
  3549. // If the identifier resolves to a typedef-name or the simple-template-id
  3550. // resolves to an alias template specialization, the
  3551. // elaborated-type-specifier is ill-formed.
  3552. Diag(TemplateLoc, diag::err_tag_reference_non_tag)
  3553. << TAT << NTK_TypeAliasTemplate << TagKind;
  3554. Diag(TAT->getLocation(), diag::note_declared_at);
  3555. }
  3556. QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
  3557. if (Result.isNull())
  3558. return TypeResult(true);
  3559. // Check the tag kind
  3560. if (const RecordType *RT = Result->getAs<RecordType>()) {
  3561. RecordDecl *D = RT->getDecl();
  3562. IdentifierInfo *Id = D->getIdentifier();
  3563. assert(Id && "templated class must have an identifier");
  3564. if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
  3565. TagLoc, Id)) {
  3566. Diag(TagLoc, diag::err_use_with_wrong_tag)
  3567. << Result
  3568. << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
  3569. Diag(D->getLocation(), diag::note_previous_use);
  3570. }
  3571. }
  3572. // Provide source-location information for the template specialization.
  3573. TypeLocBuilder TLB;
  3574. TemplateSpecializationTypeLoc SpecTL
  3575. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  3576. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3577. SpecTL.setTemplateNameLoc(TemplateLoc);
  3578. SpecTL.setLAngleLoc(LAngleLoc);
  3579. SpecTL.setRAngleLoc(RAngleLoc);
  3580. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  3581. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  3582. // Construct an elaborated type containing the nested-name-specifier (if any)
  3583. // and tag keyword.
  3584. Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
  3585. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  3586. ElabTL.setElaboratedKeywordLoc(TagLoc);
  3587. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3588. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  3589. }
  3590. static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
  3591. NamedDecl *PrevDecl,
  3592. SourceLocation Loc,
  3593. bool IsPartialSpecialization);
  3594. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
  3595. static bool isTemplateArgumentTemplateParameter(
  3596. const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
  3597. switch (Arg.getKind()) {
  3598. case TemplateArgument::Null:
  3599. case TemplateArgument::NullPtr:
  3600. case TemplateArgument::Integral:
  3601. case TemplateArgument::Declaration:
  3602. case TemplateArgument::Pack:
  3603. case TemplateArgument::TemplateExpansion:
  3604. return false;
  3605. case TemplateArgument::Type: {
  3606. QualType Type = Arg.getAsType();
  3607. const TemplateTypeParmType *TPT =
  3608. Arg.getAsType()->getAs<TemplateTypeParmType>();
  3609. return TPT && !Type.hasQualifiers() &&
  3610. TPT->getDepth() == Depth && TPT->getIndex() == Index;
  3611. }
  3612. case TemplateArgument::Expression: {
  3613. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
  3614. if (!DRE || !DRE->getDecl())
  3615. return false;
  3616. const NonTypeTemplateParmDecl *NTTP =
  3617. dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
  3618. return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
  3619. }
  3620. case TemplateArgument::Template:
  3621. const TemplateTemplateParmDecl *TTP =
  3622. dyn_cast_or_null<TemplateTemplateParmDecl>(
  3623. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
  3624. return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
  3625. }
  3626. llvm_unreachable("unexpected kind of template argument");
  3627. }
  3628. static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
  3629. ArrayRef<TemplateArgument> Args) {
  3630. if (Params->size() != Args.size())
  3631. return false;
  3632. unsigned Depth = Params->getDepth();
  3633. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3634. TemplateArgument Arg = Args[I];
  3635. // If the parameter is a pack expansion, the argument must be a pack
  3636. // whose only element is a pack expansion.
  3637. if (Params->getParam(I)->isParameterPack()) {
  3638. if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
  3639. !Arg.pack_begin()->isPackExpansion())
  3640. return false;
  3641. Arg = Arg.pack_begin()->getPackExpansionPattern();
  3642. }
  3643. if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
  3644. return false;
  3645. }
  3646. return true;
  3647. }
  3648. template<typename PartialSpecDecl>
  3649. static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
  3650. if (Partial->getDeclContext()->isDependentContext())
  3651. return;
  3652. // FIXME: Get the TDK from deduction in order to provide better diagnostics
  3653. // for non-substitution-failure issues?
  3654. TemplateDeductionInfo Info(Partial->getLocation());
  3655. if (S.isMoreSpecializedThanPrimary(Partial, Info))
  3656. return;
  3657. auto *Template = Partial->getSpecializedTemplate();
  3658. S.Diag(Partial->getLocation(),
  3659. diag::ext_partial_spec_not_more_specialized_than_primary)
  3660. << isa<VarTemplateDecl>(Template);
  3661. if (Info.hasSFINAEDiagnostic()) {
  3662. PartialDiagnosticAt Diag = {SourceLocation(),
  3663. PartialDiagnostic::NullDiagnostic()};
  3664. Info.takeSFINAEDiagnostic(Diag);
  3665. SmallString<128> SFINAEArgString;
  3666. Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  3667. S.Diag(Diag.first,
  3668. diag::note_partial_spec_not_more_specialized_than_primary)
  3669. << SFINAEArgString;
  3670. }
  3671. S.Diag(Template->getLocation(), diag::note_template_decl_here);
  3672. SmallVector<const Expr *, 3> PartialAC, TemplateAC;
  3673. Template->getAssociatedConstraints(TemplateAC);
  3674. Partial->getAssociatedConstraints(PartialAC);
  3675. S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
  3676. TemplateAC);
  3677. }
  3678. static void
  3679. noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
  3680. const llvm::SmallBitVector &DeducibleParams) {
  3681. for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
  3682. if (!DeducibleParams[I]) {
  3683. NamedDecl *Param = TemplateParams->getParam(I);
  3684. if (Param->getDeclName())
  3685. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  3686. << Param->getDeclName();
  3687. else
  3688. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  3689. << "(anonymous)";
  3690. }
  3691. }
  3692. }
  3693. template<typename PartialSpecDecl>
  3694. static void checkTemplatePartialSpecialization(Sema &S,
  3695. PartialSpecDecl *Partial) {
  3696. // C++1z [temp.class.spec]p8: (DR1495)
  3697. // - The specialization shall be more specialized than the primary
  3698. // template (14.5.5.2).
  3699. checkMoreSpecializedThanPrimary(S, Partial);
  3700. // C++ [temp.class.spec]p8: (DR1315)
  3701. // - Each template-parameter shall appear at least once in the
  3702. // template-id outside a non-deduced context.
  3703. // C++1z [temp.class.spec.match]p3 (P0127R2)
  3704. // If the template arguments of a partial specialization cannot be
  3705. // deduced because of the structure of its template-parameter-list
  3706. // and the template-id, the program is ill-formed.
  3707. auto *TemplateParams = Partial->getTemplateParameters();
  3708. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  3709. S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
  3710. TemplateParams->getDepth(), DeducibleParams);
  3711. if (!DeducibleParams.all()) {
  3712. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  3713. S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
  3714. << isa<VarTemplatePartialSpecializationDecl>(Partial)
  3715. << (NumNonDeducible > 1)
  3716. << SourceRange(Partial->getLocation(),
  3717. Partial->getTemplateArgsAsWritten()->RAngleLoc);
  3718. noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
  3719. }
  3720. }
  3721. void Sema::CheckTemplatePartialSpecialization(
  3722. ClassTemplatePartialSpecializationDecl *Partial) {
  3723. checkTemplatePartialSpecialization(*this, Partial);
  3724. }
  3725. void Sema::CheckTemplatePartialSpecialization(
  3726. VarTemplatePartialSpecializationDecl *Partial) {
  3727. checkTemplatePartialSpecialization(*this, Partial);
  3728. }
  3729. void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
  3730. // C++1z [temp.param]p11:
  3731. // A template parameter of a deduction guide template that does not have a
  3732. // default-argument shall be deducible from the parameter-type-list of the
  3733. // deduction guide template.
  3734. auto *TemplateParams = TD->getTemplateParameters();
  3735. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  3736. MarkDeducedTemplateParameters(TD, DeducibleParams);
  3737. for (unsigned I = 0; I != TemplateParams->size(); ++I) {
  3738. // A parameter pack is deducible (to an empty pack).
  3739. auto *Param = TemplateParams->getParam(I);
  3740. if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
  3741. DeducibleParams[I] = true;
  3742. }
  3743. if (!DeducibleParams.all()) {
  3744. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  3745. Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
  3746. << (NumNonDeducible > 1);
  3747. noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
  3748. }
  3749. }
  3750. DeclResult Sema::ActOnVarTemplateSpecialization(
  3751. Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
  3752. TemplateParameterList *TemplateParams, StorageClass SC,
  3753. bool IsPartialSpecialization) {
  3754. // D must be variable template id.
  3755. assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
  3756. "Variable template specialization is declared with a template it.");
  3757. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  3758. TemplateArgumentListInfo TemplateArgs =
  3759. makeTemplateArgumentListInfo(*this, *TemplateId);
  3760. SourceLocation TemplateNameLoc = D.getIdentifierLoc();
  3761. SourceLocation LAngleLoc = TemplateId->LAngleLoc;
  3762. SourceLocation RAngleLoc = TemplateId->RAngleLoc;
  3763. TemplateName Name = TemplateId->Template.get();
  3764. // The template-id must name a variable template.
  3765. VarTemplateDecl *VarTemplate =
  3766. dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
  3767. if (!VarTemplate) {
  3768. NamedDecl *FnTemplate;
  3769. if (auto *OTS = Name.getAsOverloadedTemplate())
  3770. FnTemplate = *OTS->begin();
  3771. else
  3772. FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
  3773. if (FnTemplate)
  3774. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
  3775. << FnTemplate->getDeclName();
  3776. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
  3777. << IsPartialSpecialization;
  3778. }
  3779. // Check for unexpanded parameter packs in any of the template arguments.
  3780. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  3781. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  3782. UPPC_PartialSpecialization))
  3783. return true;
  3784. // Check that the template argument list is well-formed for this
  3785. // template.
  3786. SmallVector<TemplateArgument, 4> Converted;
  3787. if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
  3788. false, Converted,
  3789. /*UpdateArgsWithConversions=*/true))
  3790. return true;
  3791. // Find the variable template (partial) specialization declaration that
  3792. // corresponds to these arguments.
  3793. if (IsPartialSpecialization) {
  3794. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
  3795. TemplateArgs.size(), Converted))
  3796. return true;
  3797. // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
  3798. // also do them during instantiation.
  3799. if (!Name.isDependent() &&
  3800. !TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
  3801. Converted)) {
  3802. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  3803. << VarTemplate->getDeclName();
  3804. IsPartialSpecialization = false;
  3805. }
  3806. if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
  3807. Converted) &&
  3808. (!Context.getLangOpts().CPlusPlus20 ||
  3809. !TemplateParams->hasAssociatedConstraints())) {
  3810. // C++ [temp.class.spec]p9b3:
  3811. //
  3812. // -- The argument list of the specialization shall not be identical
  3813. // to the implicit argument list of the primary template.
  3814. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  3815. << /*variable template*/ 1
  3816. << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
  3817. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  3818. // FIXME: Recover from this by treating the declaration as a redeclaration
  3819. // of the primary template.
  3820. return true;
  3821. }
  3822. }
  3823. void *InsertPos = nullptr;
  3824. VarTemplateSpecializationDecl *PrevDecl = nullptr;
  3825. if (IsPartialSpecialization)
  3826. PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
  3827. InsertPos);
  3828. else
  3829. PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
  3830. VarTemplateSpecializationDecl *Specialization = nullptr;
  3831. // Check whether we can declare a variable template specialization in
  3832. // the current scope.
  3833. if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
  3834. TemplateNameLoc,
  3835. IsPartialSpecialization))
  3836. return true;
  3837. if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
  3838. // Since the only prior variable template specialization with these
  3839. // arguments was referenced but not declared, reuse that
  3840. // declaration node as our own, updating its source location and
  3841. // the list of outer template parameters to reflect our new declaration.
  3842. Specialization = PrevDecl;
  3843. Specialization->setLocation(TemplateNameLoc);
  3844. PrevDecl = nullptr;
  3845. } else if (IsPartialSpecialization) {
  3846. // Create a new class template partial specialization declaration node.
  3847. VarTemplatePartialSpecializationDecl *PrevPartial =
  3848. cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
  3849. VarTemplatePartialSpecializationDecl *Partial =
  3850. VarTemplatePartialSpecializationDecl::Create(
  3851. Context, VarTemplate->getDeclContext(), TemplateKWLoc,
  3852. TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
  3853. Converted, TemplateArgs);
  3854. if (!PrevPartial)
  3855. VarTemplate->AddPartialSpecialization(Partial, InsertPos);
  3856. Specialization = Partial;
  3857. // If we are providing an explicit specialization of a member variable
  3858. // template specialization, make a note of that.
  3859. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  3860. PrevPartial->setMemberSpecialization();
  3861. CheckTemplatePartialSpecialization(Partial);
  3862. } else {
  3863. // Create a new class template specialization declaration node for
  3864. // this explicit specialization or friend declaration.
  3865. Specialization = VarTemplateSpecializationDecl::Create(
  3866. Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
  3867. VarTemplate, DI->getType(), DI, SC, Converted);
  3868. Specialization->setTemplateArgsInfo(TemplateArgs);
  3869. if (!PrevDecl)
  3870. VarTemplate->AddSpecialization(Specialization, InsertPos);
  3871. }
  3872. // C++ [temp.expl.spec]p6:
  3873. // If a template, a member template or the member of a class template is
  3874. // explicitly specialized then that specialization shall be declared
  3875. // before the first use of that specialization that would cause an implicit
  3876. // instantiation to take place, in every translation unit in which such a
  3877. // use occurs; no diagnostic is required.
  3878. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  3879. bool Okay = false;
  3880. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  3881. // Is there any previous explicit specialization declaration?
  3882. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  3883. Okay = true;
  3884. break;
  3885. }
  3886. }
  3887. if (!Okay) {
  3888. SourceRange Range(TemplateNameLoc, RAngleLoc);
  3889. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  3890. << Name << Range;
  3891. Diag(PrevDecl->getPointOfInstantiation(),
  3892. diag::note_instantiation_required_here)
  3893. << (PrevDecl->getTemplateSpecializationKind() !=
  3894. TSK_ImplicitInstantiation);
  3895. return true;
  3896. }
  3897. }
  3898. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  3899. Specialization->setLexicalDeclContext(CurContext);
  3900. // Add the specialization into its lexical context, so that it can
  3901. // be seen when iterating through the list of declarations in that
  3902. // context. However, specializations are not found by name lookup.
  3903. CurContext->addDecl(Specialization);
  3904. // Note that this is an explicit specialization.
  3905. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  3906. if (PrevDecl) {
  3907. // Check that this isn't a redefinition of this specialization,
  3908. // merging with previous declarations.
  3909. LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
  3910. forRedeclarationInCurContext());
  3911. PrevSpec.addDecl(PrevDecl);
  3912. D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
  3913. } else if (Specialization->isStaticDataMember() &&
  3914. Specialization->isOutOfLine()) {
  3915. Specialization->setAccess(VarTemplate->getAccess());
  3916. }
  3917. return Specialization;
  3918. }
  3919. namespace {
  3920. /// A partial specialization whose template arguments have matched
  3921. /// a given template-id.
  3922. struct PartialSpecMatchResult {
  3923. VarTemplatePartialSpecializationDecl *Partial;
  3924. TemplateArgumentList *Args;
  3925. };
  3926. } // end anonymous namespace
  3927. DeclResult
  3928. Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
  3929. SourceLocation TemplateNameLoc,
  3930. const TemplateArgumentListInfo &TemplateArgs) {
  3931. assert(Template && "A variable template id without template?");
  3932. // Check that the template argument list is well-formed for this template.
  3933. SmallVector<TemplateArgument, 4> Converted;
  3934. if (CheckTemplateArgumentList(
  3935. Template, TemplateNameLoc,
  3936. const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
  3937. Converted, /*UpdateArgsWithConversions=*/true))
  3938. return true;
  3939. // Produce a placeholder value if the specialization is dependent.
  3940. if (Template->getDeclContext()->isDependentContext() ||
  3941. TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
  3942. Converted))
  3943. return DeclResult();
  3944. // Find the variable template specialization declaration that
  3945. // corresponds to these arguments.
  3946. void *InsertPos = nullptr;
  3947. if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
  3948. Converted, InsertPos)) {
  3949. checkSpecializationVisibility(TemplateNameLoc, Spec);
  3950. // If we already have a variable template specialization, return it.
  3951. return Spec;
  3952. }
  3953. // This is the first time we have referenced this variable template
  3954. // specialization. Create the canonical declaration and add it to
  3955. // the set of specializations, based on the closest partial specialization
  3956. // that it represents. That is,
  3957. VarDecl *InstantiationPattern = Template->getTemplatedDecl();
  3958. TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
  3959. Converted);
  3960. TemplateArgumentList *InstantiationArgs = &TemplateArgList;
  3961. bool AmbiguousPartialSpec = false;
  3962. typedef PartialSpecMatchResult MatchResult;
  3963. SmallVector<MatchResult, 4> Matched;
  3964. SourceLocation PointOfInstantiation = TemplateNameLoc;
  3965. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
  3966. /*ForTakingAddress=*/false);
  3967. // 1. Attempt to find the closest partial specialization that this
  3968. // specializes, if any.
  3969. // TODO: Unify with InstantiateClassTemplateSpecialization()?
  3970. // Perhaps better after unification of DeduceTemplateArguments() and
  3971. // getMoreSpecializedPartialSpecialization().
  3972. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  3973. Template->getPartialSpecializations(PartialSpecs);
  3974. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  3975. VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  3976. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  3977. if (TemplateDeductionResult Result =
  3978. DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
  3979. // Store the failed-deduction information for use in diagnostics, later.
  3980. // TODO: Actually use the failed-deduction info?
  3981. FailedCandidates.addCandidate().set(
  3982. DeclAccessPair::make(Template, AS_public), Partial,
  3983. MakeDeductionFailureInfo(Context, Result, Info));
  3984. (void)Result;
  3985. } else {
  3986. Matched.push_back(PartialSpecMatchResult());
  3987. Matched.back().Partial = Partial;
  3988. Matched.back().Args = Info.take();
  3989. }
  3990. }
  3991. if (Matched.size() >= 1) {
  3992. SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
  3993. if (Matched.size() == 1) {
  3994. // -- If exactly one matching specialization is found, the
  3995. // instantiation is generated from that specialization.
  3996. // We don't need to do anything for this.
  3997. } else {
  3998. // -- If more than one matching specialization is found, the
  3999. // partial order rules (14.5.4.2) are used to determine
  4000. // whether one of the specializations is more specialized
  4001. // than the others. If none of the specializations is more
  4002. // specialized than all of the other matching
  4003. // specializations, then the use of the variable template is
  4004. // ambiguous and the program is ill-formed.
  4005. for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
  4006. PEnd = Matched.end();
  4007. P != PEnd; ++P) {
  4008. if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
  4009. PointOfInstantiation) ==
  4010. P->Partial)
  4011. Best = P;
  4012. }
  4013. // Determine if the best partial specialization is more specialized than
  4014. // the others.
  4015. for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
  4016. PEnd = Matched.end();
  4017. P != PEnd; ++P) {
  4018. if (P != Best && getMoreSpecializedPartialSpecialization(
  4019. P->Partial, Best->Partial,
  4020. PointOfInstantiation) != Best->Partial) {
  4021. AmbiguousPartialSpec = true;
  4022. break;
  4023. }
  4024. }
  4025. }
  4026. // Instantiate using the best variable template partial specialization.
  4027. InstantiationPattern = Best->Partial;
  4028. InstantiationArgs = Best->Args;
  4029. } else {
  4030. // -- If no match is found, the instantiation is generated
  4031. // from the primary template.
  4032. // InstantiationPattern = Template->getTemplatedDecl();
  4033. }
  4034. // 2. Create the canonical declaration.
  4035. // Note that we do not instantiate a definition until we see an odr-use
  4036. // in DoMarkVarDeclReferenced().
  4037. // FIXME: LateAttrs et al.?
  4038. VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
  4039. Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
  4040. Converted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
  4041. if (!Decl)
  4042. return true;
  4043. if (AmbiguousPartialSpec) {
  4044. // Partial ordering did not produce a clear winner. Complain.
  4045. Decl->setInvalidDecl();
  4046. Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
  4047. << Decl;
  4048. // Print the matching partial specializations.
  4049. for (MatchResult P : Matched)
  4050. Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
  4051. << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
  4052. *P.Args);
  4053. return true;
  4054. }
  4055. if (VarTemplatePartialSpecializationDecl *D =
  4056. dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
  4057. Decl->setInstantiationOf(D, InstantiationArgs);
  4058. checkSpecializationVisibility(TemplateNameLoc, Decl);
  4059. assert(Decl && "No variable template specialization?");
  4060. return Decl;
  4061. }
  4062. ExprResult
  4063. Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
  4064. const DeclarationNameInfo &NameInfo,
  4065. VarTemplateDecl *Template, SourceLocation TemplateLoc,
  4066. const TemplateArgumentListInfo *TemplateArgs) {
  4067. DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
  4068. *TemplateArgs);
  4069. if (Decl.isInvalid())
  4070. return ExprError();
  4071. if (!Decl.get())
  4072. return ExprResult();
  4073. VarDecl *Var = cast<VarDecl>(Decl.get());
  4074. if (!Var->getTemplateSpecializationKind())
  4075. Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
  4076. NameInfo.getLoc());
  4077. // Build an ordinary singleton decl ref.
  4078. return BuildDeclarationNameExpr(SS, NameInfo, Var,
  4079. /*FoundD=*/nullptr, TemplateArgs);
  4080. }
  4081. void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
  4082. SourceLocation Loc) {
  4083. Diag(Loc, diag::err_template_missing_args)
  4084. << (int)getTemplateNameKindForDiagnostics(Name) << Name;
  4085. if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
  4086. Diag(TD->getLocation(), diag::note_template_decl_here)
  4087. << TD->getTemplateParameters()->getSourceRange();
  4088. }
  4089. }
  4090. ExprResult
  4091. Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
  4092. SourceLocation TemplateKWLoc,
  4093. const DeclarationNameInfo &ConceptNameInfo,
  4094. NamedDecl *FoundDecl,
  4095. ConceptDecl *NamedConcept,
  4096. const TemplateArgumentListInfo *TemplateArgs) {
  4097. assert(NamedConcept && "A concept template id without a template?");
  4098. llvm::SmallVector<TemplateArgument, 4> Converted;
  4099. if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
  4100. const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
  4101. /*PartialTemplateArgs=*/false, Converted,
  4102. /*UpdateArgsWithConversions=*/false))
  4103. return ExprError();
  4104. ConstraintSatisfaction Satisfaction;
  4105. bool AreArgsDependent =
  4106. TemplateSpecializationType::anyDependentTemplateArguments(*TemplateArgs,
  4107. Converted);
  4108. if (!AreArgsDependent &&
  4109. CheckConstraintSatisfaction(
  4110. NamedConcept, {NamedConcept->getConstraintExpr()}, Converted,
  4111. SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
  4112. TemplateArgs->getRAngleLoc()),
  4113. Satisfaction))
  4114. return ExprError();
  4115. return ConceptSpecializationExpr::Create(Context,
  4116. SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
  4117. TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
  4118. ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
  4119. AreArgsDependent ? nullptr : &Satisfaction);
  4120. }
  4121. ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
  4122. SourceLocation TemplateKWLoc,
  4123. LookupResult &R,
  4124. bool RequiresADL,
  4125. const TemplateArgumentListInfo *TemplateArgs) {
  4126. // FIXME: Can we do any checking at this point? I guess we could check the
  4127. // template arguments that we have against the template name, if the template
  4128. // name refers to a single template. That's not a terribly common case,
  4129. // though.
  4130. // foo<int> could identify a single function unambiguously
  4131. // This approach does NOT work, since f<int>(1);
  4132. // gets resolved prior to resorting to overload resolution
  4133. // i.e., template<class T> void f(double);
  4134. // vs template<class T, class U> void f(U);
  4135. // These should be filtered out by our callers.
  4136. assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
  4137. // Non-function templates require a template argument list.
  4138. if (auto *TD = R.getAsSingle<TemplateDecl>()) {
  4139. if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
  4140. diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
  4141. return ExprError();
  4142. }
  4143. }
  4144. // In C++1y, check variable template ids.
  4145. if (R.getAsSingle<VarTemplateDecl>()) {
  4146. ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
  4147. R.getAsSingle<VarTemplateDecl>(),
  4148. TemplateKWLoc, TemplateArgs);
  4149. if (Res.isInvalid() || Res.isUsable())
  4150. return Res;
  4151. // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
  4152. }
  4153. if (R.getAsSingle<ConceptDecl>()) {
  4154. return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
  4155. R.getFoundDecl(),
  4156. R.getAsSingle<ConceptDecl>(), TemplateArgs);
  4157. }
  4158. // We don't want lookup warnings at this point.
  4159. R.suppressDiagnostics();
  4160. UnresolvedLookupExpr *ULE
  4161. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  4162. SS.getWithLocInContext(Context),
  4163. TemplateKWLoc,
  4164. R.getLookupNameInfo(),
  4165. RequiresADL, TemplateArgs,
  4166. R.begin(), R.end());
  4167. return ULE;
  4168. }
  4169. // We actually only call this from template instantiation.
  4170. ExprResult
  4171. Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
  4172. SourceLocation TemplateKWLoc,
  4173. const DeclarationNameInfo &NameInfo,
  4174. const TemplateArgumentListInfo *TemplateArgs) {
  4175. assert(TemplateArgs || TemplateKWLoc.isValid());
  4176. DeclContext *DC;
  4177. if (!(DC = computeDeclContext(SS, false)) ||
  4178. DC->isDependentContext() ||
  4179. RequireCompleteDeclContext(SS, DC))
  4180. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  4181. bool MemberOfUnknownSpecialization;
  4182. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  4183. if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
  4184. /*Entering*/false, MemberOfUnknownSpecialization,
  4185. TemplateKWLoc))
  4186. return ExprError();
  4187. if (R.isAmbiguous())
  4188. return ExprError();
  4189. if (R.empty()) {
  4190. Diag(NameInfo.getLoc(), diag::err_no_member)
  4191. << NameInfo.getName() << DC << SS.getRange();
  4192. return ExprError();
  4193. }
  4194. if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
  4195. Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
  4196. << SS.getScopeRep()
  4197. << NameInfo.getName().getAsString() << SS.getRange();
  4198. Diag(Temp->getLocation(), diag::note_referenced_class_template);
  4199. return ExprError();
  4200. }
  4201. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
  4202. }
  4203. /// Form a template name from a name that is syntactically required to name a
  4204. /// template, either due to use of the 'template' keyword or because a name in
  4205. /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
  4206. ///
  4207. /// This action forms a template name given the name of the template and its
  4208. /// optional scope specifier. This is used when the 'template' keyword is used
  4209. /// or when the parsing context unambiguously treats a following '<' as
  4210. /// introducing a template argument list. Note that this may produce a
  4211. /// non-dependent template name if we can perform the lookup now and identify
  4212. /// the named template.
  4213. ///
  4214. /// For example, given "x.MetaFun::template apply", the scope specifier
  4215. /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
  4216. /// of the "template" keyword, and "apply" is the \p Name.
  4217. TemplateNameKind Sema::ActOnTemplateName(Scope *S,
  4218. CXXScopeSpec &SS,
  4219. SourceLocation TemplateKWLoc,
  4220. const UnqualifiedId &Name,
  4221. ParsedType ObjectType,
  4222. bool EnteringContext,
  4223. TemplateTy &Result,
  4224. bool AllowInjectedClassName) {
  4225. if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
  4226. Diag(TemplateKWLoc,
  4227. getLangOpts().CPlusPlus11 ?
  4228. diag::warn_cxx98_compat_template_outside_of_template :
  4229. diag::ext_template_outside_of_template)
  4230. << FixItHint::CreateRemoval(TemplateKWLoc);
  4231. if (SS.isInvalid())
  4232. return TNK_Non_template;
  4233. // Figure out where isTemplateName is going to look.
  4234. DeclContext *LookupCtx = nullptr;
  4235. if (SS.isNotEmpty())
  4236. LookupCtx = computeDeclContext(SS, EnteringContext);
  4237. else if (ObjectType)
  4238. LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
  4239. // C++0x [temp.names]p5:
  4240. // If a name prefixed by the keyword template is not the name of
  4241. // a template, the program is ill-formed. [Note: the keyword
  4242. // template may not be applied to non-template members of class
  4243. // templates. -end note ] [ Note: as is the case with the
  4244. // typename prefix, the template prefix is allowed in cases
  4245. // where it is not strictly necessary; i.e., when the
  4246. // nested-name-specifier or the expression on the left of the ->
  4247. // or . is not dependent on a template-parameter, or the use
  4248. // does not appear in the scope of a template. -end note]
  4249. //
  4250. // Note: C++03 was more strict here, because it banned the use of
  4251. // the "template" keyword prior to a template-name that was not a
  4252. // dependent name. C++ DR468 relaxed this requirement (the
  4253. // "template" keyword is now permitted). We follow the C++0x
  4254. // rules, even in C++03 mode with a warning, retroactively applying the DR.
  4255. bool MemberOfUnknownSpecialization;
  4256. TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
  4257. ObjectType, EnteringContext, Result,
  4258. MemberOfUnknownSpecialization);
  4259. if (TNK != TNK_Non_template) {
  4260. // We resolved this to a (non-dependent) template name. Return it.
  4261. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  4262. if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
  4263. Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
  4264. Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
  4265. // C++14 [class.qual]p2:
  4266. // In a lookup in which function names are not ignored and the
  4267. // nested-name-specifier nominates a class C, if the name specified
  4268. // [...] is the injected-class-name of C, [...] the name is instead
  4269. // considered to name the constructor
  4270. //
  4271. // We don't get here if naming the constructor would be valid, so we
  4272. // just reject immediately and recover by treating the
  4273. // injected-class-name as naming the template.
  4274. Diag(Name.getBeginLoc(),
  4275. diag::ext_out_of_line_qualified_id_type_names_constructor)
  4276. << Name.Identifier
  4277. << 0 /*injected-class-name used as template name*/
  4278. << TemplateKWLoc.isValid();
  4279. }
  4280. return TNK;
  4281. }
  4282. if (!MemberOfUnknownSpecialization) {
  4283. // Didn't find a template name, and the lookup wasn't dependent.
  4284. // Do the lookup again to determine if this is a "nothing found" case or
  4285. // a "not a template" case. FIXME: Refactor isTemplateName so we don't
  4286. // need to do this.
  4287. DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
  4288. LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
  4289. LookupOrdinaryName);
  4290. bool MOUS;
  4291. // Tell LookupTemplateName that we require a template so that it diagnoses
  4292. // cases where it finds a non-template.
  4293. RequiredTemplateKind RTK = TemplateKWLoc.isValid()
  4294. ? RequiredTemplateKind(TemplateKWLoc)
  4295. : TemplateNameIsRequired;
  4296. if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
  4297. RTK, nullptr, /*AllowTypoCorrection=*/false) &&
  4298. !R.isAmbiguous()) {
  4299. if (LookupCtx)
  4300. Diag(Name.getBeginLoc(), diag::err_no_member)
  4301. << DNI.getName() << LookupCtx << SS.getRange();
  4302. else
  4303. Diag(Name.getBeginLoc(), diag::err_undeclared_use)
  4304. << DNI.getName() << SS.getRange();
  4305. }
  4306. return TNK_Non_template;
  4307. }
  4308. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  4309. switch (Name.getKind()) {
  4310. case UnqualifiedIdKind::IK_Identifier:
  4311. Result = TemplateTy::make(
  4312. Context.getDependentTemplateName(Qualifier, Name.Identifier));
  4313. return TNK_Dependent_template_name;
  4314. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4315. Result = TemplateTy::make(Context.getDependentTemplateName(
  4316. Qualifier, Name.OperatorFunctionId.Operator));
  4317. return TNK_Function_template;
  4318. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4319. // This is a kind of template name, but can never occur in a dependent
  4320. // scope (literal operators can only be declared at namespace scope).
  4321. break;
  4322. default:
  4323. break;
  4324. }
  4325. // This name cannot possibly name a dependent template. Diagnose this now
  4326. // rather than building a dependent template name that can never be valid.
  4327. Diag(Name.getBeginLoc(),
  4328. diag::err_template_kw_refers_to_dependent_non_template)
  4329. << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
  4330. << TemplateKWLoc.isValid() << TemplateKWLoc;
  4331. return TNK_Non_template;
  4332. }
  4333. bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
  4334. TemplateArgumentLoc &AL,
  4335. SmallVectorImpl<TemplateArgument> &Converted) {
  4336. const TemplateArgument &Arg = AL.getArgument();
  4337. QualType ArgType;
  4338. TypeSourceInfo *TSI = nullptr;
  4339. // Check template type parameter.
  4340. switch(Arg.getKind()) {
  4341. case TemplateArgument::Type:
  4342. // C++ [temp.arg.type]p1:
  4343. // A template-argument for a template-parameter which is a
  4344. // type shall be a type-id.
  4345. ArgType = Arg.getAsType();
  4346. TSI = AL.getTypeSourceInfo();
  4347. break;
  4348. case TemplateArgument::Template:
  4349. case TemplateArgument::TemplateExpansion: {
  4350. // We have a template type parameter but the template argument
  4351. // is a template without any arguments.
  4352. SourceRange SR = AL.getSourceRange();
  4353. TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
  4354. diagnoseMissingTemplateArguments(Name, SR.getEnd());
  4355. return true;
  4356. }
  4357. case TemplateArgument::Expression: {
  4358. // We have a template type parameter but the template argument is an
  4359. // expression; see if maybe it is missing the "typename" keyword.
  4360. CXXScopeSpec SS;
  4361. DeclarationNameInfo NameInfo;
  4362. if (DependentScopeDeclRefExpr *ArgExpr =
  4363. dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
  4364. SS.Adopt(ArgExpr->getQualifierLoc());
  4365. NameInfo = ArgExpr->getNameInfo();
  4366. } else if (CXXDependentScopeMemberExpr *ArgExpr =
  4367. dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
  4368. if (ArgExpr->isImplicitAccess()) {
  4369. SS.Adopt(ArgExpr->getQualifierLoc());
  4370. NameInfo = ArgExpr->getMemberNameInfo();
  4371. }
  4372. }
  4373. if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
  4374. LookupResult Result(*this, NameInfo, LookupOrdinaryName);
  4375. LookupParsedName(Result, CurScope, &SS);
  4376. if (Result.getAsSingle<TypeDecl>() ||
  4377. Result.getResultKind() ==
  4378. LookupResult::NotFoundInCurrentInstantiation) {
  4379. assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
  4380. // Suggest that the user add 'typename' before the NNS.
  4381. SourceLocation Loc = AL.getSourceRange().getBegin();
  4382. Diag(Loc, getLangOpts().MSVCCompat
  4383. ? diag::ext_ms_template_type_arg_missing_typename
  4384. : diag::err_template_arg_must_be_type_suggest)
  4385. << FixItHint::CreateInsertion(Loc, "typename ");
  4386. Diag(Param->getLocation(), diag::note_template_param_here);
  4387. // Recover by synthesizing a type using the location information that we
  4388. // already have.
  4389. ArgType =
  4390. Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
  4391. TypeLocBuilder TLB;
  4392. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
  4393. TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
  4394. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  4395. TL.setNameLoc(NameInfo.getLoc());
  4396. TSI = TLB.getTypeSourceInfo(Context, ArgType);
  4397. // Overwrite our input TemplateArgumentLoc so that we can recover
  4398. // properly.
  4399. AL = TemplateArgumentLoc(TemplateArgument(ArgType),
  4400. TemplateArgumentLocInfo(TSI));
  4401. break;
  4402. }
  4403. }
  4404. // fallthrough
  4405. LLVM_FALLTHROUGH;
  4406. }
  4407. default: {
  4408. // We have a template type parameter but the template argument
  4409. // is not a type.
  4410. SourceRange SR = AL.getSourceRange();
  4411. Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
  4412. Diag(Param->getLocation(), diag::note_template_param_here);
  4413. return true;
  4414. }
  4415. }
  4416. if (CheckTemplateArgument(TSI))
  4417. return true;
  4418. // Add the converted template type argument.
  4419. ArgType = Context.getCanonicalType(ArgType);
  4420. // Objective-C ARC:
  4421. // If an explicitly-specified template argument type is a lifetime type
  4422. // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
  4423. if (getLangOpts().ObjCAutoRefCount &&
  4424. ArgType->isObjCLifetimeType() &&
  4425. !ArgType.getObjCLifetime()) {
  4426. Qualifiers Qs;
  4427. Qs.setObjCLifetime(Qualifiers::OCL_Strong);
  4428. ArgType = Context.getQualifiedType(ArgType, Qs);
  4429. }
  4430. Converted.push_back(TemplateArgument(ArgType));
  4431. return false;
  4432. }
  4433. /// Substitute template arguments into the default template argument for
  4434. /// the given template type parameter.
  4435. ///
  4436. /// \param SemaRef the semantic analysis object for which we are performing
  4437. /// the substitution.
  4438. ///
  4439. /// \param Template the template that we are synthesizing template arguments
  4440. /// for.
  4441. ///
  4442. /// \param TemplateLoc the location of the template name that started the
  4443. /// template-id we are checking.
  4444. ///
  4445. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4446. /// terminates the template-id.
  4447. ///
  4448. /// \param Param the template template parameter whose default we are
  4449. /// substituting into.
  4450. ///
  4451. /// \param Converted the list of template arguments provided for template
  4452. /// parameters that precede \p Param in the template parameter list.
  4453. /// \returns the substituted template argument, or NULL if an error occurred.
  4454. static TypeSourceInfo *
  4455. SubstDefaultTemplateArgument(Sema &SemaRef,
  4456. TemplateDecl *Template,
  4457. SourceLocation TemplateLoc,
  4458. SourceLocation RAngleLoc,
  4459. TemplateTypeParmDecl *Param,
  4460. SmallVectorImpl<TemplateArgument> &Converted) {
  4461. TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
  4462. // If the argument type is dependent, instantiate it now based
  4463. // on the previously-computed template arguments.
  4464. if (ArgType->getType()->isInstantiationDependentType()) {
  4465. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
  4466. Param, Template, Converted,
  4467. SourceRange(TemplateLoc, RAngleLoc));
  4468. if (Inst.isInvalid())
  4469. return nullptr;
  4470. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4471. // Only substitute for the innermost template argument list.
  4472. MultiLevelTemplateArgumentList TemplateArgLists;
  4473. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  4474. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4475. TemplateArgLists.addOuterTemplateArguments(None);
  4476. bool ForLambdaCallOperator = false;
  4477. if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
  4478. ForLambdaCallOperator = Rec->isLambda();
  4479. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
  4480. !ForLambdaCallOperator);
  4481. ArgType =
  4482. SemaRef.SubstType(ArgType, TemplateArgLists,
  4483. Param->getDefaultArgumentLoc(), Param->getDeclName());
  4484. }
  4485. return ArgType;
  4486. }
  4487. /// Substitute template arguments into the default template argument for
  4488. /// the given non-type template parameter.
  4489. ///
  4490. /// \param SemaRef the semantic analysis object for which we are performing
  4491. /// the substitution.
  4492. ///
  4493. /// \param Template the template that we are synthesizing template arguments
  4494. /// for.
  4495. ///
  4496. /// \param TemplateLoc the location of the template name that started the
  4497. /// template-id we are checking.
  4498. ///
  4499. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4500. /// terminates the template-id.
  4501. ///
  4502. /// \param Param the non-type template parameter whose default we are
  4503. /// substituting into.
  4504. ///
  4505. /// \param Converted the list of template arguments provided for template
  4506. /// parameters that precede \p Param in the template parameter list.
  4507. ///
  4508. /// \returns the substituted template argument, or NULL if an error occurred.
  4509. static ExprResult
  4510. SubstDefaultTemplateArgument(Sema &SemaRef,
  4511. TemplateDecl *Template,
  4512. SourceLocation TemplateLoc,
  4513. SourceLocation RAngleLoc,
  4514. NonTypeTemplateParmDecl *Param,
  4515. SmallVectorImpl<TemplateArgument> &Converted) {
  4516. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
  4517. Param, Template, Converted,
  4518. SourceRange(TemplateLoc, RAngleLoc));
  4519. if (Inst.isInvalid())
  4520. return ExprError();
  4521. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4522. // Only substitute for the innermost template argument list.
  4523. MultiLevelTemplateArgumentList TemplateArgLists;
  4524. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  4525. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4526. TemplateArgLists.addOuterTemplateArguments(None);
  4527. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4528. EnterExpressionEvaluationContext ConstantEvaluated(
  4529. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  4530. return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
  4531. }
  4532. /// Substitute template arguments into the default template argument for
  4533. /// the given template template parameter.
  4534. ///
  4535. /// \param SemaRef the semantic analysis object for which we are performing
  4536. /// the substitution.
  4537. ///
  4538. /// \param Template the template that we are synthesizing template arguments
  4539. /// for.
  4540. ///
  4541. /// \param TemplateLoc the location of the template name that started the
  4542. /// template-id we are checking.
  4543. ///
  4544. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4545. /// terminates the template-id.
  4546. ///
  4547. /// \param Param the template template parameter whose default we are
  4548. /// substituting into.
  4549. ///
  4550. /// \param Converted the list of template arguments provided for template
  4551. /// parameters that precede \p Param in the template parameter list.
  4552. ///
  4553. /// \param QualifierLoc Will be set to the nested-name-specifier (with
  4554. /// source-location information) that precedes the template name.
  4555. ///
  4556. /// \returns the substituted template argument, or NULL if an error occurred.
  4557. static TemplateName
  4558. SubstDefaultTemplateArgument(Sema &SemaRef,
  4559. TemplateDecl *Template,
  4560. SourceLocation TemplateLoc,
  4561. SourceLocation RAngleLoc,
  4562. TemplateTemplateParmDecl *Param,
  4563. SmallVectorImpl<TemplateArgument> &Converted,
  4564. NestedNameSpecifierLoc &QualifierLoc) {
  4565. Sema::InstantiatingTemplate Inst(
  4566. SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
  4567. SourceRange(TemplateLoc, RAngleLoc));
  4568. if (Inst.isInvalid())
  4569. return TemplateName();
  4570. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4571. // Only substitute for the innermost template argument list.
  4572. MultiLevelTemplateArgumentList TemplateArgLists;
  4573. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  4574. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4575. TemplateArgLists.addOuterTemplateArguments(None);
  4576. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4577. // Substitute into the nested-name-specifier first,
  4578. QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
  4579. if (QualifierLoc) {
  4580. QualifierLoc =
  4581. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
  4582. if (!QualifierLoc)
  4583. return TemplateName();
  4584. }
  4585. return SemaRef.SubstTemplateName(
  4586. QualifierLoc,
  4587. Param->getDefaultArgument().getArgument().getAsTemplate(),
  4588. Param->getDefaultArgument().getTemplateNameLoc(),
  4589. TemplateArgLists);
  4590. }
  4591. /// If the given template parameter has a default template
  4592. /// argument, substitute into that default template argument and
  4593. /// return the corresponding template argument.
  4594. TemplateArgumentLoc
  4595. Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
  4596. SourceLocation TemplateLoc,
  4597. SourceLocation RAngleLoc,
  4598. Decl *Param,
  4599. SmallVectorImpl<TemplateArgument>
  4600. &Converted,
  4601. bool &HasDefaultArg) {
  4602. HasDefaultArg = false;
  4603. if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
  4604. if (!hasVisibleDefaultArgument(TypeParm))
  4605. return TemplateArgumentLoc();
  4606. HasDefaultArg = true;
  4607. TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
  4608. TemplateLoc,
  4609. RAngleLoc,
  4610. TypeParm,
  4611. Converted);
  4612. if (DI)
  4613. return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
  4614. return TemplateArgumentLoc();
  4615. }
  4616. if (NonTypeTemplateParmDecl *NonTypeParm
  4617. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4618. if (!hasVisibleDefaultArgument(NonTypeParm))
  4619. return TemplateArgumentLoc();
  4620. HasDefaultArg = true;
  4621. ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
  4622. TemplateLoc,
  4623. RAngleLoc,
  4624. NonTypeParm,
  4625. Converted);
  4626. if (Arg.isInvalid())
  4627. return TemplateArgumentLoc();
  4628. Expr *ArgE = Arg.getAs<Expr>();
  4629. return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
  4630. }
  4631. TemplateTemplateParmDecl *TempTempParm
  4632. = cast<TemplateTemplateParmDecl>(Param);
  4633. if (!hasVisibleDefaultArgument(TempTempParm))
  4634. return TemplateArgumentLoc();
  4635. HasDefaultArg = true;
  4636. NestedNameSpecifierLoc QualifierLoc;
  4637. TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
  4638. TemplateLoc,
  4639. RAngleLoc,
  4640. TempTempParm,
  4641. Converted,
  4642. QualifierLoc);
  4643. if (TName.isNull())
  4644. return TemplateArgumentLoc();
  4645. return TemplateArgumentLoc(
  4646. Context, TemplateArgument(TName),
  4647. TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
  4648. TempTempParm->getDefaultArgument().getTemplateNameLoc());
  4649. }
  4650. /// Convert a template-argument that we parsed as a type into a template, if
  4651. /// possible. C++ permits injected-class-names to perform dual service as
  4652. /// template template arguments and as template type arguments.
  4653. static TemplateArgumentLoc
  4654. convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
  4655. // Extract and step over any surrounding nested-name-specifier.
  4656. NestedNameSpecifierLoc QualLoc;
  4657. if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
  4658. if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
  4659. return TemplateArgumentLoc();
  4660. QualLoc = ETLoc.getQualifierLoc();
  4661. TLoc = ETLoc.getNamedTypeLoc();
  4662. }
  4663. // If this type was written as an injected-class-name, it can be used as a
  4664. // template template argument.
  4665. if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
  4666. return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
  4667. QualLoc, InjLoc.getNameLoc());
  4668. // If this type was written as an injected-class-name, it may have been
  4669. // converted to a RecordType during instantiation. If the RecordType is
  4670. // *not* wrapped in a TemplateSpecializationType and denotes a class
  4671. // template specialization, it must have come from an injected-class-name.
  4672. if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
  4673. if (auto *CTSD =
  4674. dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
  4675. return TemplateArgumentLoc(Context,
  4676. TemplateName(CTSD->getSpecializedTemplate()),
  4677. QualLoc, RecLoc.getNameLoc());
  4678. return TemplateArgumentLoc();
  4679. }
  4680. /// Check that the given template argument corresponds to the given
  4681. /// template parameter.
  4682. ///
  4683. /// \param Param The template parameter against which the argument will be
  4684. /// checked.
  4685. ///
  4686. /// \param Arg The template argument, which may be updated due to conversions.
  4687. ///
  4688. /// \param Template The template in which the template argument resides.
  4689. ///
  4690. /// \param TemplateLoc The location of the template name for the template
  4691. /// whose argument list we're matching.
  4692. ///
  4693. /// \param RAngleLoc The location of the right angle bracket ('>') that closes
  4694. /// the template argument list.
  4695. ///
  4696. /// \param ArgumentPackIndex The index into the argument pack where this
  4697. /// argument will be placed. Only valid if the parameter is a parameter pack.
  4698. ///
  4699. /// \param Converted The checked, converted argument will be added to the
  4700. /// end of this small vector.
  4701. ///
  4702. /// \param CTAK Describes how we arrived at this particular template argument:
  4703. /// explicitly written, deduced, etc.
  4704. ///
  4705. /// \returns true on error, false otherwise.
  4706. bool Sema::CheckTemplateArgument(NamedDecl *Param,
  4707. TemplateArgumentLoc &Arg,
  4708. NamedDecl *Template,
  4709. SourceLocation TemplateLoc,
  4710. SourceLocation RAngleLoc,
  4711. unsigned ArgumentPackIndex,
  4712. SmallVectorImpl<TemplateArgument> &Converted,
  4713. CheckTemplateArgumentKind CTAK) {
  4714. // Check template type parameters.
  4715. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  4716. return CheckTemplateTypeArgument(TTP, Arg, Converted);
  4717. // Check non-type template parameters.
  4718. if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4719. // Do substitution on the type of the non-type template parameter
  4720. // with the template arguments we've seen thus far. But if the
  4721. // template has a dependent context then we cannot substitute yet.
  4722. QualType NTTPType = NTTP->getType();
  4723. if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
  4724. NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
  4725. if (NTTPType->isInstantiationDependentType() &&
  4726. !isa<TemplateTemplateParmDecl>(Template) &&
  4727. !Template->getDeclContext()->isDependentContext()) {
  4728. // Do substitution on the type of the non-type template parameter.
  4729. InstantiatingTemplate Inst(*this, TemplateLoc, Template,
  4730. NTTP, Converted,
  4731. SourceRange(TemplateLoc, RAngleLoc));
  4732. if (Inst.isInvalid())
  4733. return true;
  4734. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
  4735. Converted);
  4736. // If the parameter is a pack expansion, expand this slice of the pack.
  4737. if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
  4738. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
  4739. ArgumentPackIndex);
  4740. NTTPType = SubstType(PET->getPattern(),
  4741. MultiLevelTemplateArgumentList(TemplateArgs),
  4742. NTTP->getLocation(),
  4743. NTTP->getDeclName());
  4744. } else {
  4745. NTTPType = SubstType(NTTPType,
  4746. MultiLevelTemplateArgumentList(TemplateArgs),
  4747. NTTP->getLocation(),
  4748. NTTP->getDeclName());
  4749. }
  4750. // If that worked, check the non-type template parameter type
  4751. // for validity.
  4752. if (!NTTPType.isNull())
  4753. NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
  4754. NTTP->getLocation());
  4755. if (NTTPType.isNull())
  4756. return true;
  4757. }
  4758. switch (Arg.getArgument().getKind()) {
  4759. case TemplateArgument::Null:
  4760. llvm_unreachable("Should never see a NULL template argument here");
  4761. case TemplateArgument::Expression: {
  4762. TemplateArgument Result;
  4763. unsigned CurSFINAEErrors = NumSFINAEErrors;
  4764. ExprResult Res =
  4765. CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
  4766. Result, CTAK);
  4767. if (Res.isInvalid())
  4768. return true;
  4769. // If the current template argument causes an error, give up now.
  4770. if (CurSFINAEErrors < NumSFINAEErrors)
  4771. return true;
  4772. // If the resulting expression is new, then use it in place of the
  4773. // old expression in the template argument.
  4774. if (Res.get() != Arg.getArgument().getAsExpr()) {
  4775. TemplateArgument TA(Res.get());
  4776. Arg = TemplateArgumentLoc(TA, Res.get());
  4777. }
  4778. Converted.push_back(Result);
  4779. break;
  4780. }
  4781. case TemplateArgument::Declaration:
  4782. case TemplateArgument::Integral:
  4783. case TemplateArgument::NullPtr:
  4784. // We've already checked this template argument, so just copy
  4785. // it to the list of converted arguments.
  4786. Converted.push_back(Arg.getArgument());
  4787. break;
  4788. case TemplateArgument::Template:
  4789. case TemplateArgument::TemplateExpansion:
  4790. // We were given a template template argument. It may not be ill-formed;
  4791. // see below.
  4792. if (DependentTemplateName *DTN
  4793. = Arg.getArgument().getAsTemplateOrTemplatePattern()
  4794. .getAsDependentTemplateName()) {
  4795. // We have a template argument such as \c T::template X, which we
  4796. // parsed as a template template argument. However, since we now
  4797. // know that we need a non-type template argument, convert this
  4798. // template name into an expression.
  4799. DeclarationNameInfo NameInfo(DTN->getIdentifier(),
  4800. Arg.getTemplateNameLoc());
  4801. CXXScopeSpec SS;
  4802. SS.Adopt(Arg.getTemplateQualifierLoc());
  4803. // FIXME: the template-template arg was a DependentTemplateName,
  4804. // so it was provided with a template keyword. However, its source
  4805. // location is not stored in the template argument structure.
  4806. SourceLocation TemplateKWLoc;
  4807. ExprResult E = DependentScopeDeclRefExpr::Create(
  4808. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  4809. nullptr);
  4810. // If we parsed the template argument as a pack expansion, create a
  4811. // pack expansion expression.
  4812. if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
  4813. E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
  4814. if (E.isInvalid())
  4815. return true;
  4816. }
  4817. TemplateArgument Result;
  4818. E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
  4819. if (E.isInvalid())
  4820. return true;
  4821. Converted.push_back(Result);
  4822. break;
  4823. }
  4824. // We have a template argument that actually does refer to a class
  4825. // template, alias template, or template template parameter, and
  4826. // therefore cannot be a non-type template argument.
  4827. Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
  4828. << Arg.getSourceRange();
  4829. Diag(Param->getLocation(), diag::note_template_param_here);
  4830. return true;
  4831. case TemplateArgument::Type: {
  4832. // We have a non-type template parameter but the template
  4833. // argument is a type.
  4834. // C++ [temp.arg]p2:
  4835. // In a template-argument, an ambiguity between a type-id and
  4836. // an expression is resolved to a type-id, regardless of the
  4837. // form of the corresponding template-parameter.
  4838. //
  4839. // We warn specifically about this case, since it can be rather
  4840. // confusing for users.
  4841. QualType T = Arg.getArgument().getAsType();
  4842. SourceRange SR = Arg.getSourceRange();
  4843. if (T->isFunctionType())
  4844. Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
  4845. else
  4846. Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
  4847. Diag(Param->getLocation(), diag::note_template_param_here);
  4848. return true;
  4849. }
  4850. case TemplateArgument::Pack:
  4851. llvm_unreachable("Caller must expand template argument packs");
  4852. }
  4853. return false;
  4854. }
  4855. // Check template template parameters.
  4856. TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
  4857. TemplateParameterList *Params = TempParm->getTemplateParameters();
  4858. if (TempParm->isExpandedParameterPack())
  4859. Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
  4860. // Substitute into the template parameter list of the template
  4861. // template parameter, since previously-supplied template arguments
  4862. // may appear within the template template parameter.
  4863. //
  4864. // FIXME: Skip this if the parameters aren't instantiation-dependent.
  4865. {
  4866. // Set up a template instantiation context.
  4867. LocalInstantiationScope Scope(*this);
  4868. InstantiatingTemplate Inst(*this, TemplateLoc, Template,
  4869. TempParm, Converted,
  4870. SourceRange(TemplateLoc, RAngleLoc));
  4871. if (Inst.isInvalid())
  4872. return true;
  4873. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4874. Params = SubstTemplateParams(Params, CurContext,
  4875. MultiLevelTemplateArgumentList(TemplateArgs));
  4876. if (!Params)
  4877. return true;
  4878. }
  4879. // C++1z [temp.local]p1: (DR1004)
  4880. // When [the injected-class-name] is used [...] as a template-argument for
  4881. // a template template-parameter [...] it refers to the class template
  4882. // itself.
  4883. if (Arg.getArgument().getKind() == TemplateArgument::Type) {
  4884. TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
  4885. Context, Arg.getTypeSourceInfo()->getTypeLoc());
  4886. if (!ConvertedArg.getArgument().isNull())
  4887. Arg = ConvertedArg;
  4888. }
  4889. switch (Arg.getArgument().getKind()) {
  4890. case TemplateArgument::Null:
  4891. llvm_unreachable("Should never see a NULL template argument here");
  4892. case TemplateArgument::Template:
  4893. case TemplateArgument::TemplateExpansion:
  4894. if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
  4895. return true;
  4896. Converted.push_back(Arg.getArgument());
  4897. break;
  4898. case TemplateArgument::Expression:
  4899. case TemplateArgument::Type:
  4900. // We have a template template parameter but the template
  4901. // argument does not refer to a template.
  4902. Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
  4903. << getLangOpts().CPlusPlus11;
  4904. return true;
  4905. case TemplateArgument::Declaration:
  4906. llvm_unreachable("Declaration argument with template template parameter");
  4907. case TemplateArgument::Integral:
  4908. llvm_unreachable("Integral argument with template template parameter");
  4909. case TemplateArgument::NullPtr:
  4910. llvm_unreachable("Null pointer argument with template template parameter");
  4911. case TemplateArgument::Pack:
  4912. llvm_unreachable("Caller must expand template argument packs");
  4913. }
  4914. return false;
  4915. }
  4916. /// Diagnose a missing template argument.
  4917. template<typename TemplateParmDecl>
  4918. static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
  4919. TemplateDecl *TD,
  4920. const TemplateParmDecl *D,
  4921. TemplateArgumentListInfo &Args) {
  4922. // Dig out the most recent declaration of the template parameter; there may be
  4923. // declarations of the template that are more recent than TD.
  4924. D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
  4925. ->getTemplateParameters()
  4926. ->getParam(D->getIndex()));
  4927. // If there's a default argument that's not visible, diagnose that we're
  4928. // missing a module import.
  4929. llvm::SmallVector<Module*, 8> Modules;
  4930. if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
  4931. S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
  4932. D->getDefaultArgumentLoc(), Modules,
  4933. Sema::MissingImportKind::DefaultArgument,
  4934. /*Recover*/true);
  4935. return true;
  4936. }
  4937. // FIXME: If there's a more recent default argument that *is* visible,
  4938. // diagnose that it was declared too late.
  4939. TemplateParameterList *Params = TD->getTemplateParameters();
  4940. S.Diag(Loc, diag::err_template_arg_list_different_arity)
  4941. << /*not enough args*/0
  4942. << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
  4943. << TD;
  4944. S.Diag(TD->getLocation(), diag::note_template_decl_here)
  4945. << Params->getSourceRange();
  4946. return true;
  4947. }
  4948. /// Check that the given template argument list is well-formed
  4949. /// for specializing the given template.
  4950. bool Sema::CheckTemplateArgumentList(
  4951. TemplateDecl *Template, SourceLocation TemplateLoc,
  4952. TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
  4953. SmallVectorImpl<TemplateArgument> &Converted,
  4954. bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
  4955. if (ConstraintsNotSatisfied)
  4956. *ConstraintsNotSatisfied = false;
  4957. // Make a copy of the template arguments for processing. Only make the
  4958. // changes at the end when successful in matching the arguments to the
  4959. // template.
  4960. TemplateArgumentListInfo NewArgs = TemplateArgs;
  4961. // Make sure we get the template parameter list from the most
  4962. // recent declaration, since that is the only one that is guaranteed to
  4963. // have all the default template argument information.
  4964. TemplateParameterList *Params =
  4965. cast<TemplateDecl>(Template->getMostRecentDecl())
  4966. ->getTemplateParameters();
  4967. SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
  4968. // C++ [temp.arg]p1:
  4969. // [...] The type and form of each template-argument specified in
  4970. // a template-id shall match the type and form specified for the
  4971. // corresponding parameter declared by the template in its
  4972. // template-parameter-list.
  4973. bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
  4974. SmallVector<TemplateArgument, 2> ArgumentPack;
  4975. unsigned ArgIdx = 0, NumArgs = NewArgs.size();
  4976. LocalInstantiationScope InstScope(*this, true);
  4977. for (TemplateParameterList::iterator Param = Params->begin(),
  4978. ParamEnd = Params->end();
  4979. Param != ParamEnd; /* increment in loop */) {
  4980. // If we have an expanded parameter pack, make sure we don't have too
  4981. // many arguments.
  4982. if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
  4983. if (*Expansions == ArgumentPack.size()) {
  4984. // We're done with this parameter pack. Pack up its arguments and add
  4985. // them to the list.
  4986. Converted.push_back(
  4987. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4988. ArgumentPack.clear();
  4989. // This argument is assigned to the next parameter.
  4990. ++Param;
  4991. continue;
  4992. } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
  4993. // Not enough arguments for this parameter pack.
  4994. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  4995. << /*not enough args*/0
  4996. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  4997. << Template;
  4998. Diag(Template->getLocation(), diag::note_template_decl_here)
  4999. << Params->getSourceRange();
  5000. return true;
  5001. }
  5002. }
  5003. if (ArgIdx < NumArgs) {
  5004. // Check the template argument we were given.
  5005. if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
  5006. TemplateLoc, RAngleLoc,
  5007. ArgumentPack.size(), Converted))
  5008. return true;
  5009. bool PackExpansionIntoNonPack =
  5010. NewArgs[ArgIdx].getArgument().isPackExpansion() &&
  5011. (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
  5012. if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
  5013. isa<ConceptDecl>(Template))) {
  5014. // Core issue 1430: we have a pack expansion as an argument to an
  5015. // alias template, and it's not part of a parameter pack. This
  5016. // can't be canonicalized, so reject it now.
  5017. // As for concepts - we cannot normalize constraints where this
  5018. // situation exists.
  5019. Diag(NewArgs[ArgIdx].getLocation(),
  5020. diag::err_template_expansion_into_fixed_list)
  5021. << (isa<ConceptDecl>(Template) ? 1 : 0)
  5022. << NewArgs[ArgIdx].getSourceRange();
  5023. Diag((*Param)->getLocation(), diag::note_template_param_here);
  5024. return true;
  5025. }
  5026. // We're now done with this argument.
  5027. ++ArgIdx;
  5028. if ((*Param)->isTemplateParameterPack()) {
  5029. // The template parameter was a template parameter pack, so take the
  5030. // deduced argument and place it on the argument pack. Note that we
  5031. // stay on the same template parameter so that we can deduce more
  5032. // arguments.
  5033. ArgumentPack.push_back(Converted.pop_back_val());
  5034. } else {
  5035. // Move to the next template parameter.
  5036. ++Param;
  5037. }
  5038. // If we just saw a pack expansion into a non-pack, then directly convert
  5039. // the remaining arguments, because we don't know what parameters they'll
  5040. // match up with.
  5041. if (PackExpansionIntoNonPack) {
  5042. if (!ArgumentPack.empty()) {
  5043. // If we were part way through filling in an expanded parameter pack,
  5044. // fall back to just producing individual arguments.
  5045. Converted.insert(Converted.end(),
  5046. ArgumentPack.begin(), ArgumentPack.end());
  5047. ArgumentPack.clear();
  5048. }
  5049. while (ArgIdx < NumArgs) {
  5050. Converted.push_back(NewArgs[ArgIdx].getArgument());
  5051. ++ArgIdx;
  5052. }
  5053. return false;
  5054. }
  5055. continue;
  5056. }
  5057. // If we're checking a partial template argument list, we're done.
  5058. if (PartialTemplateArgs) {
  5059. if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
  5060. Converted.push_back(
  5061. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  5062. return false;
  5063. }
  5064. // If we have a template parameter pack with no more corresponding
  5065. // arguments, just break out now and we'll fill in the argument pack below.
  5066. if ((*Param)->isTemplateParameterPack()) {
  5067. assert(!getExpandedPackSize(*Param) &&
  5068. "Should have dealt with this already");
  5069. // A non-expanded parameter pack before the end of the parameter list
  5070. // only occurs for an ill-formed template parameter list, unless we've
  5071. // got a partial argument list for a function template, so just bail out.
  5072. if (Param + 1 != ParamEnd)
  5073. return true;
  5074. Converted.push_back(
  5075. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  5076. ArgumentPack.clear();
  5077. ++Param;
  5078. continue;
  5079. }
  5080. // Check whether we have a default argument.
  5081. TemplateArgumentLoc Arg;
  5082. // Retrieve the default template argument from the template
  5083. // parameter. For each kind of template parameter, we substitute the
  5084. // template arguments provided thus far and any "outer" template arguments
  5085. // (when the template parameter was part of a nested template) into
  5086. // the default argument.
  5087. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
  5088. if (!hasVisibleDefaultArgument(TTP))
  5089. return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
  5090. NewArgs);
  5091. TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
  5092. Template,
  5093. TemplateLoc,
  5094. RAngleLoc,
  5095. TTP,
  5096. Converted);
  5097. if (!ArgType)
  5098. return true;
  5099. Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
  5100. ArgType);
  5101. } else if (NonTypeTemplateParmDecl *NTTP
  5102. = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
  5103. if (!hasVisibleDefaultArgument(NTTP))
  5104. return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
  5105. NewArgs);
  5106. ExprResult E = SubstDefaultTemplateArgument(*this, Template,
  5107. TemplateLoc,
  5108. RAngleLoc,
  5109. NTTP,
  5110. Converted);
  5111. if (E.isInvalid())
  5112. return true;
  5113. Expr *Ex = E.getAs<Expr>();
  5114. Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
  5115. } else {
  5116. TemplateTemplateParmDecl *TempParm
  5117. = cast<TemplateTemplateParmDecl>(*Param);
  5118. if (!hasVisibleDefaultArgument(TempParm))
  5119. return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
  5120. NewArgs);
  5121. NestedNameSpecifierLoc QualifierLoc;
  5122. TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
  5123. TemplateLoc,
  5124. RAngleLoc,
  5125. TempParm,
  5126. Converted,
  5127. QualifierLoc);
  5128. if (Name.isNull())
  5129. return true;
  5130. Arg = TemplateArgumentLoc(
  5131. Context, TemplateArgument(Name), QualifierLoc,
  5132. TempParm->getDefaultArgument().getTemplateNameLoc());
  5133. }
  5134. // Introduce an instantiation record that describes where we are using
  5135. // the default template argument. We're not actually instantiating a
  5136. // template here, we just create this object to put a note into the
  5137. // context stack.
  5138. InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
  5139. SourceRange(TemplateLoc, RAngleLoc));
  5140. if (Inst.isInvalid())
  5141. return true;
  5142. // Check the default template argument.
  5143. if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
  5144. RAngleLoc, 0, Converted))
  5145. return true;
  5146. // Core issue 150 (assumed resolution): if this is a template template
  5147. // parameter, keep track of the default template arguments from the
  5148. // template definition.
  5149. if (isTemplateTemplateParameter)
  5150. NewArgs.addArgument(Arg);
  5151. // Move to the next template parameter and argument.
  5152. ++Param;
  5153. ++ArgIdx;
  5154. }
  5155. // If we're performing a partial argument substitution, allow any trailing
  5156. // pack expansions; they might be empty. This can happen even if
  5157. // PartialTemplateArgs is false (the list of arguments is complete but
  5158. // still dependent).
  5159. if (ArgIdx < NumArgs && CurrentInstantiationScope &&
  5160. CurrentInstantiationScope->getPartiallySubstitutedPack()) {
  5161. while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
  5162. Converted.push_back(NewArgs[ArgIdx++].getArgument());
  5163. }
  5164. // If we have any leftover arguments, then there were too many arguments.
  5165. // Complain and fail.
  5166. if (ArgIdx < NumArgs) {
  5167. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  5168. << /*too many args*/1
  5169. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  5170. << Template
  5171. << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
  5172. Diag(Template->getLocation(), diag::note_template_decl_here)
  5173. << Params->getSourceRange();
  5174. return true;
  5175. }
  5176. // No problems found with the new argument list, propagate changes back
  5177. // to caller.
  5178. if (UpdateArgsWithConversions)
  5179. TemplateArgs = std::move(NewArgs);
  5180. if (!PartialTemplateArgs &&
  5181. EnsureTemplateArgumentListConstraints(
  5182. Template, Converted, SourceRange(TemplateLoc,
  5183. TemplateArgs.getRAngleLoc()))) {
  5184. if (ConstraintsNotSatisfied)
  5185. *ConstraintsNotSatisfied = true;
  5186. return true;
  5187. }
  5188. return false;
  5189. }
  5190. namespace {
  5191. class UnnamedLocalNoLinkageFinder
  5192. : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
  5193. {
  5194. Sema &S;
  5195. SourceRange SR;
  5196. typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
  5197. public:
  5198. UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
  5199. bool Visit(QualType T) {
  5200. return T.isNull() ? false : inherited::Visit(T.getTypePtr());
  5201. }
  5202. #define TYPE(Class, Parent) \
  5203. bool Visit##Class##Type(const Class##Type *);
  5204. #define ABSTRACT_TYPE(Class, Parent) \
  5205. bool Visit##Class##Type(const Class##Type *) { return false; }
  5206. #define NON_CANONICAL_TYPE(Class, Parent) \
  5207. bool Visit##Class##Type(const Class##Type *) { return false; }
  5208. #include "clang/AST/TypeNodes.inc"
  5209. bool VisitTagDecl(const TagDecl *Tag);
  5210. bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
  5211. };
  5212. } // end anonymous namespace
  5213. bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
  5214. return false;
  5215. }
  5216. bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
  5217. return Visit(T->getElementType());
  5218. }
  5219. bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
  5220. return Visit(T->getPointeeType());
  5221. }
  5222. bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
  5223. const BlockPointerType* T) {
  5224. return Visit(T->getPointeeType());
  5225. }
  5226. bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
  5227. const LValueReferenceType* T) {
  5228. return Visit(T->getPointeeType());
  5229. }
  5230. bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
  5231. const RValueReferenceType* T) {
  5232. return Visit(T->getPointeeType());
  5233. }
  5234. bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
  5235. const MemberPointerType* T) {
  5236. return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
  5237. }
  5238. bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
  5239. const ConstantArrayType* T) {
  5240. return Visit(T->getElementType());
  5241. }
  5242. bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
  5243. const IncompleteArrayType* T) {
  5244. return Visit(T->getElementType());
  5245. }
  5246. bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
  5247. const VariableArrayType* T) {
  5248. return Visit(T->getElementType());
  5249. }
  5250. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
  5251. const DependentSizedArrayType* T) {
  5252. return Visit(T->getElementType());
  5253. }
  5254. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
  5255. const DependentSizedExtVectorType* T) {
  5256. return Visit(T->getElementType());
  5257. }
  5258. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
  5259. const DependentSizedMatrixType *T) {
  5260. return Visit(T->getElementType());
  5261. }
  5262. bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
  5263. const DependentAddressSpaceType *T) {
  5264. return Visit(T->getPointeeType());
  5265. }
  5266. bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
  5267. return Visit(T->getElementType());
  5268. }
  5269. bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
  5270. const DependentVectorType *T) {
  5271. return Visit(T->getElementType());
  5272. }
  5273. bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
  5274. return Visit(T->getElementType());
  5275. }
  5276. bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
  5277. const ConstantMatrixType *T) {
  5278. return Visit(T->getElementType());
  5279. }
  5280. bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
  5281. const FunctionProtoType* T) {
  5282. for (const auto &A : T->param_types()) {
  5283. if (Visit(A))
  5284. return true;
  5285. }
  5286. return Visit(T->getReturnType());
  5287. }
  5288. bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
  5289. const FunctionNoProtoType* T) {
  5290. return Visit(T->getReturnType());
  5291. }
  5292. bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
  5293. const UnresolvedUsingType*) {
  5294. return false;
  5295. }
  5296. bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
  5297. return false;
  5298. }
  5299. bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
  5300. return Visit(T->getUnderlyingType());
  5301. }
  5302. bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
  5303. return false;
  5304. }
  5305. bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
  5306. const UnaryTransformType*) {
  5307. return false;
  5308. }
  5309. bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
  5310. return Visit(T->getDeducedType());
  5311. }
  5312. bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
  5313. const DeducedTemplateSpecializationType *T) {
  5314. return Visit(T->getDeducedType());
  5315. }
  5316. bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
  5317. return VisitTagDecl(T->getDecl());
  5318. }
  5319. bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
  5320. return VisitTagDecl(T->getDecl());
  5321. }
  5322. bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
  5323. const TemplateTypeParmType*) {
  5324. return false;
  5325. }
  5326. bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
  5327. const SubstTemplateTypeParmPackType *) {
  5328. return false;
  5329. }
  5330. bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
  5331. const TemplateSpecializationType*) {
  5332. return false;
  5333. }
  5334. bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
  5335. const InjectedClassNameType* T) {
  5336. return VisitTagDecl(T->getDecl());
  5337. }
  5338. bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
  5339. const DependentNameType* T) {
  5340. return VisitNestedNameSpecifier(T->getQualifier());
  5341. }
  5342. bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
  5343. const DependentTemplateSpecializationType* T) {
  5344. if (auto *Q = T->getQualifier())
  5345. return VisitNestedNameSpecifier(Q);
  5346. return false;
  5347. }
  5348. bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
  5349. const PackExpansionType* T) {
  5350. return Visit(T->getPattern());
  5351. }
  5352. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
  5353. return false;
  5354. }
  5355. bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
  5356. const ObjCInterfaceType *) {
  5357. return false;
  5358. }
  5359. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
  5360. const ObjCObjectPointerType *) {
  5361. return false;
  5362. }
  5363. bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
  5364. return Visit(T->getValueType());
  5365. }
  5366. bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
  5367. return false;
  5368. }
  5369. bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
  5370. return false;
  5371. }
  5372. bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
  5373. const DependentBitIntType *T) {
  5374. return false;
  5375. }
  5376. bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
  5377. if (Tag->getDeclContext()->isFunctionOrMethod()) {
  5378. S.Diag(SR.getBegin(),
  5379. S.getLangOpts().CPlusPlus11 ?
  5380. diag::warn_cxx98_compat_template_arg_local_type :
  5381. diag::ext_template_arg_local_type)
  5382. << S.Context.getTypeDeclType(Tag) << SR;
  5383. return true;
  5384. }
  5385. if (!Tag->hasNameForLinkage()) {
  5386. S.Diag(SR.getBegin(),
  5387. S.getLangOpts().CPlusPlus11 ?
  5388. diag::warn_cxx98_compat_template_arg_unnamed_type :
  5389. diag::ext_template_arg_unnamed_type) << SR;
  5390. S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
  5391. return true;
  5392. }
  5393. return false;
  5394. }
  5395. bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
  5396. NestedNameSpecifier *NNS) {
  5397. assert(NNS);
  5398. if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
  5399. return true;
  5400. switch (NNS->getKind()) {
  5401. case NestedNameSpecifier::Identifier:
  5402. case NestedNameSpecifier::Namespace:
  5403. case NestedNameSpecifier::NamespaceAlias:
  5404. case NestedNameSpecifier::Global:
  5405. case NestedNameSpecifier::Super:
  5406. return false;
  5407. case NestedNameSpecifier::TypeSpec:
  5408. case NestedNameSpecifier::TypeSpecWithTemplate:
  5409. return Visit(QualType(NNS->getAsType(), 0));
  5410. }
  5411. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  5412. }
  5413. /// Check a template argument against its corresponding
  5414. /// template type parameter.
  5415. ///
  5416. /// This routine implements the semantics of C++ [temp.arg.type]. It
  5417. /// returns true if an error occurred, and false otherwise.
  5418. bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
  5419. assert(ArgInfo && "invalid TypeSourceInfo");
  5420. QualType Arg = ArgInfo->getType();
  5421. SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
  5422. if (Arg->isVariablyModifiedType()) {
  5423. return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
  5424. } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
  5425. return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
  5426. }
  5427. // C++03 [temp.arg.type]p2:
  5428. // A local type, a type with no linkage, an unnamed type or a type
  5429. // compounded from any of these types shall not be used as a
  5430. // template-argument for a template type-parameter.
  5431. //
  5432. // C++11 allows these, and even in C++03 we allow them as an extension with
  5433. // a warning.
  5434. if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
  5435. UnnamedLocalNoLinkageFinder Finder(*this, SR);
  5436. (void)Finder.Visit(Context.getCanonicalType(Arg));
  5437. }
  5438. return false;
  5439. }
  5440. enum NullPointerValueKind {
  5441. NPV_NotNullPointer,
  5442. NPV_NullPointer,
  5443. NPV_Error
  5444. };
  5445. /// Determine whether the given template argument is a null pointer
  5446. /// value of the appropriate type.
  5447. static NullPointerValueKind
  5448. isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
  5449. QualType ParamType, Expr *Arg,
  5450. Decl *Entity = nullptr) {
  5451. if (Arg->isValueDependent() || Arg->isTypeDependent())
  5452. return NPV_NotNullPointer;
  5453. // dllimport'd entities aren't constant but are available inside of template
  5454. // arguments.
  5455. if (Entity && Entity->hasAttr<DLLImportAttr>())
  5456. return NPV_NotNullPointer;
  5457. if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
  5458. llvm_unreachable(
  5459. "Incomplete parameter type in isNullPointerValueTemplateArgument!");
  5460. if (!S.getLangOpts().CPlusPlus11)
  5461. return NPV_NotNullPointer;
  5462. // Determine whether we have a constant expression.
  5463. ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
  5464. if (ArgRV.isInvalid())
  5465. return NPV_Error;
  5466. Arg = ArgRV.get();
  5467. Expr::EvalResult EvalResult;
  5468. SmallVector<PartialDiagnosticAt, 8> Notes;
  5469. EvalResult.Diag = &Notes;
  5470. if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
  5471. EvalResult.HasSideEffects) {
  5472. SourceLocation DiagLoc = Arg->getExprLoc();
  5473. // If our only note is the usual "invalid subexpression" note, just point
  5474. // the caret at its location rather than producing an essentially
  5475. // redundant note.
  5476. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  5477. diag::note_invalid_subexpr_in_const_expr) {
  5478. DiagLoc = Notes[0].first;
  5479. Notes.clear();
  5480. }
  5481. S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
  5482. << Arg->getType() << Arg->getSourceRange();
  5483. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  5484. S.Diag(Notes[I].first, Notes[I].second);
  5485. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5486. return NPV_Error;
  5487. }
  5488. // C++11 [temp.arg.nontype]p1:
  5489. // - an address constant expression of type std::nullptr_t
  5490. if (Arg->getType()->isNullPtrType())
  5491. return NPV_NullPointer;
  5492. // - a constant expression that evaluates to a null pointer value (4.10); or
  5493. // - a constant expression that evaluates to a null member pointer value
  5494. // (4.11); or
  5495. if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
  5496. (EvalResult.Val.isMemberPointer() &&
  5497. !EvalResult.Val.getMemberPointerDecl())) {
  5498. // If our expression has an appropriate type, we've succeeded.
  5499. bool ObjCLifetimeConversion;
  5500. if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
  5501. S.IsQualificationConversion(Arg->getType(), ParamType, false,
  5502. ObjCLifetimeConversion))
  5503. return NPV_NullPointer;
  5504. // The types didn't match, but we know we got a null pointer; complain,
  5505. // then recover as if the types were correct.
  5506. S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
  5507. << Arg->getType() << ParamType << Arg->getSourceRange();
  5508. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5509. return NPV_NullPointer;
  5510. }
  5511. // If we don't have a null pointer value, but we do have a NULL pointer
  5512. // constant, suggest a cast to the appropriate type.
  5513. if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
  5514. std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
  5515. S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
  5516. << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
  5517. << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
  5518. ")");
  5519. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5520. return NPV_NullPointer;
  5521. }
  5522. // FIXME: If we ever want to support general, address-constant expressions
  5523. // as non-type template arguments, we should return the ExprResult here to
  5524. // be interpreted by the caller.
  5525. return NPV_NotNullPointer;
  5526. }
  5527. /// Checks whether the given template argument is compatible with its
  5528. /// template parameter.
  5529. static bool CheckTemplateArgumentIsCompatibleWithParameter(
  5530. Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
  5531. Expr *Arg, QualType ArgType) {
  5532. bool ObjCLifetimeConversion;
  5533. if (ParamType->isPointerType() &&
  5534. !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
  5535. S.IsQualificationConversion(ArgType, ParamType, false,
  5536. ObjCLifetimeConversion)) {
  5537. // For pointer-to-object types, qualification conversions are
  5538. // permitted.
  5539. } else {
  5540. if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
  5541. if (!ParamRef->getPointeeType()->isFunctionType()) {
  5542. // C++ [temp.arg.nontype]p5b3:
  5543. // For a non-type template-parameter of type reference to
  5544. // object, no conversions apply. The type referred to by the
  5545. // reference may be more cv-qualified than the (otherwise
  5546. // identical) type of the template- argument. The
  5547. // template-parameter is bound directly to the
  5548. // template-argument, which shall be an lvalue.
  5549. // FIXME: Other qualifiers?
  5550. unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
  5551. unsigned ArgQuals = ArgType.getCVRQualifiers();
  5552. if ((ParamQuals | ArgQuals) != ParamQuals) {
  5553. S.Diag(Arg->getBeginLoc(),
  5554. diag::err_template_arg_ref_bind_ignores_quals)
  5555. << ParamType << Arg->getType() << Arg->getSourceRange();
  5556. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5557. return true;
  5558. }
  5559. }
  5560. }
  5561. // At this point, the template argument refers to an object or
  5562. // function with external linkage. We now need to check whether the
  5563. // argument and parameter types are compatible.
  5564. if (!S.Context.hasSameUnqualifiedType(ArgType,
  5565. ParamType.getNonReferenceType())) {
  5566. // We can't perform this conversion or binding.
  5567. if (ParamType->isReferenceType())
  5568. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
  5569. << ParamType << ArgIn->getType() << Arg->getSourceRange();
  5570. else
  5571. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
  5572. << ArgIn->getType() << ParamType << Arg->getSourceRange();
  5573. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5574. return true;
  5575. }
  5576. }
  5577. return false;
  5578. }
  5579. /// Checks whether the given template argument is the address
  5580. /// of an object or function according to C++ [temp.arg.nontype]p1.
  5581. static bool
  5582. CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
  5583. NonTypeTemplateParmDecl *Param,
  5584. QualType ParamType,
  5585. Expr *ArgIn,
  5586. TemplateArgument &Converted) {
  5587. bool Invalid = false;
  5588. Expr *Arg = ArgIn;
  5589. QualType ArgType = Arg->getType();
  5590. bool AddressTaken = false;
  5591. SourceLocation AddrOpLoc;
  5592. if (S.getLangOpts().MicrosoftExt) {
  5593. // Microsoft Visual C++ strips all casts, allows an arbitrary number of
  5594. // dereference and address-of operators.
  5595. Arg = Arg->IgnoreParenCasts();
  5596. bool ExtWarnMSTemplateArg = false;
  5597. UnaryOperatorKind FirstOpKind;
  5598. SourceLocation FirstOpLoc;
  5599. while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5600. UnaryOperatorKind UnOpKind = UnOp->getOpcode();
  5601. if (UnOpKind == UO_Deref)
  5602. ExtWarnMSTemplateArg = true;
  5603. if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
  5604. Arg = UnOp->getSubExpr()->IgnoreParenCasts();
  5605. if (!AddrOpLoc.isValid()) {
  5606. FirstOpKind = UnOpKind;
  5607. FirstOpLoc = UnOp->getOperatorLoc();
  5608. }
  5609. } else
  5610. break;
  5611. }
  5612. if (FirstOpLoc.isValid()) {
  5613. if (ExtWarnMSTemplateArg)
  5614. S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
  5615. << ArgIn->getSourceRange();
  5616. if (FirstOpKind == UO_AddrOf)
  5617. AddressTaken = true;
  5618. else if (Arg->getType()->isPointerType()) {
  5619. // We cannot let pointers get dereferenced here, that is obviously not a
  5620. // constant expression.
  5621. assert(FirstOpKind == UO_Deref);
  5622. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5623. << Arg->getSourceRange();
  5624. }
  5625. }
  5626. } else {
  5627. // See through any implicit casts we added to fix the type.
  5628. Arg = Arg->IgnoreImpCasts();
  5629. // C++ [temp.arg.nontype]p1:
  5630. //
  5631. // A template-argument for a non-type, non-template
  5632. // template-parameter shall be one of: [...]
  5633. //
  5634. // -- the address of an object or function with external
  5635. // linkage, including function templates and function
  5636. // template-ids but excluding non-static class members,
  5637. // expressed as & id-expression where the & is optional if
  5638. // the name refers to a function or array, or if the
  5639. // corresponding template-parameter is a reference; or
  5640. // In C++98/03 mode, give an extension warning on any extra parentheses.
  5641. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  5642. bool ExtraParens = false;
  5643. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  5644. if (!Invalid && !ExtraParens) {
  5645. S.Diag(Arg->getBeginLoc(),
  5646. S.getLangOpts().CPlusPlus11
  5647. ? diag::warn_cxx98_compat_template_arg_extra_parens
  5648. : diag::ext_template_arg_extra_parens)
  5649. << Arg->getSourceRange();
  5650. ExtraParens = true;
  5651. }
  5652. Arg = Parens->getSubExpr();
  5653. }
  5654. while (SubstNonTypeTemplateParmExpr *subst =
  5655. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5656. Arg = subst->getReplacement()->IgnoreImpCasts();
  5657. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5658. if (UnOp->getOpcode() == UO_AddrOf) {
  5659. Arg = UnOp->getSubExpr();
  5660. AddressTaken = true;
  5661. AddrOpLoc = UnOp->getOperatorLoc();
  5662. }
  5663. }
  5664. while (SubstNonTypeTemplateParmExpr *subst =
  5665. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5666. Arg = subst->getReplacement()->IgnoreImpCasts();
  5667. }
  5668. ValueDecl *Entity = nullptr;
  5669. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
  5670. Entity = DRE->getDecl();
  5671. else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
  5672. Entity = CUE->getGuidDecl();
  5673. // If our parameter has pointer type, check for a null template value.
  5674. if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
  5675. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
  5676. Entity)) {
  5677. case NPV_NullPointer:
  5678. S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5679. Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  5680. /*isNullPtr=*/true);
  5681. return false;
  5682. case NPV_Error:
  5683. return true;
  5684. case NPV_NotNullPointer:
  5685. break;
  5686. }
  5687. }
  5688. // Stop checking the precise nature of the argument if it is value dependent,
  5689. // it should be checked when instantiated.
  5690. if (Arg->isValueDependent()) {
  5691. Converted = TemplateArgument(ArgIn);
  5692. return false;
  5693. }
  5694. if (!Entity) {
  5695. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5696. << Arg->getSourceRange();
  5697. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5698. return true;
  5699. }
  5700. // Cannot refer to non-static data members
  5701. if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
  5702. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
  5703. << Entity << Arg->getSourceRange();
  5704. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5705. return true;
  5706. }
  5707. // Cannot refer to non-static member functions
  5708. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
  5709. if (!Method->isStatic()) {
  5710. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
  5711. << Method << Arg->getSourceRange();
  5712. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5713. return true;
  5714. }
  5715. }
  5716. FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
  5717. VarDecl *Var = dyn_cast<VarDecl>(Entity);
  5718. MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
  5719. // A non-type template argument must refer to an object or function.
  5720. if (!Func && !Var && !Guid) {
  5721. // We found something, but we don't know specifically what it is.
  5722. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
  5723. << Arg->getSourceRange();
  5724. S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
  5725. return true;
  5726. }
  5727. // Address / reference template args must have external linkage in C++98.
  5728. if (Entity->getFormalLinkage() == InternalLinkage) {
  5729. S.Diag(Arg->getBeginLoc(),
  5730. S.getLangOpts().CPlusPlus11
  5731. ? diag::warn_cxx98_compat_template_arg_object_internal
  5732. : diag::ext_template_arg_object_internal)
  5733. << !Func << Entity << Arg->getSourceRange();
  5734. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  5735. << !Func;
  5736. } else if (!Entity->hasLinkage()) {
  5737. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
  5738. << !Func << Entity << Arg->getSourceRange();
  5739. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  5740. << !Func;
  5741. return true;
  5742. }
  5743. if (Var) {
  5744. // A value of reference type is not an object.
  5745. if (Var->getType()->isReferenceType()) {
  5746. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
  5747. << Var->getType() << Arg->getSourceRange();
  5748. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5749. return true;
  5750. }
  5751. // A template argument must have static storage duration.
  5752. if (Var->getTLSKind()) {
  5753. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
  5754. << Arg->getSourceRange();
  5755. S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
  5756. return true;
  5757. }
  5758. }
  5759. if (AddressTaken && ParamType->isReferenceType()) {
  5760. // If we originally had an address-of operator, but the
  5761. // parameter has reference type, complain and (if things look
  5762. // like they will work) drop the address-of operator.
  5763. if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
  5764. ParamType.getNonReferenceType())) {
  5765. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5766. << ParamType;
  5767. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5768. return true;
  5769. }
  5770. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5771. << ParamType
  5772. << FixItHint::CreateRemoval(AddrOpLoc);
  5773. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5774. ArgType = Entity->getType();
  5775. }
  5776. // If the template parameter has pointer type, either we must have taken the
  5777. // address or the argument must decay to a pointer.
  5778. if (!AddressTaken && ParamType->isPointerType()) {
  5779. if (Func) {
  5780. // Function-to-pointer decay.
  5781. ArgType = S.Context.getPointerType(Func->getType());
  5782. } else if (Entity->getType()->isArrayType()) {
  5783. // Array-to-pointer decay.
  5784. ArgType = S.Context.getArrayDecayedType(Entity->getType());
  5785. } else {
  5786. // If the template parameter has pointer type but the address of
  5787. // this object was not taken, complain and (possibly) recover by
  5788. // taking the address of the entity.
  5789. ArgType = S.Context.getPointerType(Entity->getType());
  5790. if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
  5791. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
  5792. << ParamType;
  5793. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5794. return true;
  5795. }
  5796. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
  5797. << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
  5798. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5799. }
  5800. }
  5801. if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
  5802. Arg, ArgType))
  5803. return true;
  5804. // Create the template argument.
  5805. Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
  5806. S.Context.getCanonicalType(ParamType));
  5807. S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
  5808. return false;
  5809. }
  5810. /// Checks whether the given template argument is a pointer to
  5811. /// member constant according to C++ [temp.arg.nontype]p1.
  5812. static bool CheckTemplateArgumentPointerToMember(Sema &S,
  5813. NonTypeTemplateParmDecl *Param,
  5814. QualType ParamType,
  5815. Expr *&ResultArg,
  5816. TemplateArgument &Converted) {
  5817. bool Invalid = false;
  5818. Expr *Arg = ResultArg;
  5819. bool ObjCLifetimeConversion;
  5820. // C++ [temp.arg.nontype]p1:
  5821. //
  5822. // A template-argument for a non-type, non-template
  5823. // template-parameter shall be one of: [...]
  5824. //
  5825. // -- a pointer to member expressed as described in 5.3.1.
  5826. DeclRefExpr *DRE = nullptr;
  5827. // In C++98/03 mode, give an extension warning on any extra parentheses.
  5828. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  5829. bool ExtraParens = false;
  5830. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  5831. if (!Invalid && !ExtraParens) {
  5832. S.Diag(Arg->getBeginLoc(),
  5833. S.getLangOpts().CPlusPlus11
  5834. ? diag::warn_cxx98_compat_template_arg_extra_parens
  5835. : diag::ext_template_arg_extra_parens)
  5836. << Arg->getSourceRange();
  5837. ExtraParens = true;
  5838. }
  5839. Arg = Parens->getSubExpr();
  5840. }
  5841. while (SubstNonTypeTemplateParmExpr *subst =
  5842. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5843. Arg = subst->getReplacement()->IgnoreImpCasts();
  5844. // A pointer-to-member constant written &Class::member.
  5845. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5846. if (UnOp->getOpcode() == UO_AddrOf) {
  5847. DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
  5848. if (DRE && !DRE->getQualifier())
  5849. DRE = nullptr;
  5850. }
  5851. }
  5852. // A constant of pointer-to-member type.
  5853. else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
  5854. ValueDecl *VD = DRE->getDecl();
  5855. if (VD->getType()->isMemberPointerType()) {
  5856. if (isa<NonTypeTemplateParmDecl>(VD)) {
  5857. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  5858. Converted = TemplateArgument(Arg);
  5859. } else {
  5860. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  5861. Converted = TemplateArgument(VD, ParamType);
  5862. }
  5863. return Invalid;
  5864. }
  5865. }
  5866. DRE = nullptr;
  5867. }
  5868. ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
  5869. // Check for a null pointer value.
  5870. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
  5871. Entity)) {
  5872. case NPV_Error:
  5873. return true;
  5874. case NPV_NullPointer:
  5875. S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5876. Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  5877. /*isNullPtr*/true);
  5878. return false;
  5879. case NPV_NotNullPointer:
  5880. break;
  5881. }
  5882. if (S.IsQualificationConversion(ResultArg->getType(),
  5883. ParamType.getNonReferenceType(), false,
  5884. ObjCLifetimeConversion)) {
  5885. ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
  5886. ResultArg->getValueKind())
  5887. .get();
  5888. } else if (!S.Context.hasSameUnqualifiedType(
  5889. ResultArg->getType(), ParamType.getNonReferenceType())) {
  5890. // We can't perform this conversion.
  5891. S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
  5892. << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
  5893. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5894. return true;
  5895. }
  5896. if (!DRE)
  5897. return S.Diag(Arg->getBeginLoc(),
  5898. diag::err_template_arg_not_pointer_to_member_form)
  5899. << Arg->getSourceRange();
  5900. if (isa<FieldDecl>(DRE->getDecl()) ||
  5901. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  5902. isa<CXXMethodDecl>(DRE->getDecl())) {
  5903. assert((isa<FieldDecl>(DRE->getDecl()) ||
  5904. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  5905. !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
  5906. "Only non-static member pointers can make it here");
  5907. // Okay: this is the address of a non-static member, and therefore
  5908. // a member pointer constant.
  5909. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  5910. Converted = TemplateArgument(Arg);
  5911. } else {
  5912. ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
  5913. Converted = TemplateArgument(D, S.Context.getCanonicalType(ParamType));
  5914. }
  5915. return Invalid;
  5916. }
  5917. // We found something else, but we don't know specifically what it is.
  5918. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
  5919. << Arg->getSourceRange();
  5920. S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
  5921. return true;
  5922. }
  5923. /// Check a template argument against its corresponding
  5924. /// non-type template parameter.
  5925. ///
  5926. /// This routine implements the semantics of C++ [temp.arg.nontype].
  5927. /// If an error occurred, it returns ExprError(); otherwise, it
  5928. /// returns the converted template argument. \p ParamType is the
  5929. /// type of the non-type template parameter after it has been instantiated.
  5930. ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
  5931. QualType ParamType, Expr *Arg,
  5932. TemplateArgument &Converted,
  5933. CheckTemplateArgumentKind CTAK) {
  5934. SourceLocation StartLoc = Arg->getBeginLoc();
  5935. // If the parameter type somehow involves auto, deduce the type now.
  5936. DeducedType *DeducedT = ParamType->getContainedDeducedType();
  5937. if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
  5938. // During template argument deduction, we allow 'decltype(auto)' to
  5939. // match an arbitrary dependent argument.
  5940. // FIXME: The language rules don't say what happens in this case.
  5941. // FIXME: We get an opaque dependent type out of decltype(auto) if the
  5942. // expression is merely instantiation-dependent; is this enough?
  5943. if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
  5944. auto *AT = dyn_cast<AutoType>(DeducedT);
  5945. if (AT && AT->isDecltypeAuto()) {
  5946. Converted = TemplateArgument(Arg);
  5947. return Arg;
  5948. }
  5949. }
  5950. // When checking a deduced template argument, deduce from its type even if
  5951. // the type is dependent, in order to check the types of non-type template
  5952. // arguments line up properly in partial ordering.
  5953. Optional<unsigned> Depth = Param->getDepth() + 1;
  5954. Expr *DeductionArg = Arg;
  5955. if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
  5956. DeductionArg = PE->getPattern();
  5957. TypeSourceInfo *TSI =
  5958. Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
  5959. if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
  5960. InitializedEntity Entity =
  5961. InitializedEntity::InitializeTemplateParameter(ParamType, Param);
  5962. InitializationKind Kind = InitializationKind::CreateForInit(
  5963. DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
  5964. Expr *Inits[1] = {DeductionArg};
  5965. ParamType =
  5966. DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
  5967. if (ParamType.isNull())
  5968. return ExprError();
  5969. } else if (DeduceAutoType(
  5970. TSI, DeductionArg, ParamType, Depth,
  5971. // We do not check constraints right now because the
  5972. // immediately-declared constraint of the auto type is also
  5973. // an associated constraint, and will be checked along with
  5974. // the other associated constraints after checking the
  5975. // template argument list.
  5976. /*IgnoreConstraints=*/true) == DAR_Failed) {
  5977. Diag(Arg->getExprLoc(),
  5978. diag::err_non_type_template_parm_type_deduction_failure)
  5979. << Param->getDeclName() << Param->getType() << Arg->getType()
  5980. << Arg->getSourceRange();
  5981. Diag(Param->getLocation(), diag::note_template_param_here);
  5982. return ExprError();
  5983. }
  5984. // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
  5985. // an error. The error message normally references the parameter
  5986. // declaration, but here we'll pass the argument location because that's
  5987. // where the parameter type is deduced.
  5988. ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
  5989. if (ParamType.isNull()) {
  5990. Diag(Param->getLocation(), diag::note_template_param_here);
  5991. return ExprError();
  5992. }
  5993. }
  5994. // We should have already dropped all cv-qualifiers by now.
  5995. assert(!ParamType.hasQualifiers() &&
  5996. "non-type template parameter type cannot be qualified");
  5997. // FIXME: When Param is a reference, should we check that Arg is an lvalue?
  5998. if (CTAK == CTAK_Deduced &&
  5999. (ParamType->isReferenceType()
  6000. ? !Context.hasSameType(ParamType.getNonReferenceType(),
  6001. Arg->getType())
  6002. : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
  6003. // FIXME: If either type is dependent, we skip the check. This isn't
  6004. // correct, since during deduction we're supposed to have replaced each
  6005. // template parameter with some unique (non-dependent) placeholder.
  6006. // FIXME: If the argument type contains 'auto', we carry on and fail the
  6007. // type check in order to force specific types to be more specialized than
  6008. // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
  6009. // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
  6010. if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
  6011. !Arg->getType()->getContainedDeducedType()) {
  6012. Converted = TemplateArgument(Arg);
  6013. return Arg;
  6014. }
  6015. // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
  6016. // we should actually be checking the type of the template argument in P,
  6017. // not the type of the template argument deduced from A, against the
  6018. // template parameter type.
  6019. Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
  6020. << Arg->getType()
  6021. << ParamType.getUnqualifiedType();
  6022. Diag(Param->getLocation(), diag::note_template_param_here);
  6023. return ExprError();
  6024. }
  6025. // If either the parameter has a dependent type or the argument is
  6026. // type-dependent, there's nothing we can check now. The argument only
  6027. // contains an unexpanded pack during partial ordering, and there's
  6028. // nothing more we can check in that case.
  6029. if (ParamType->isDependentType() || Arg->isTypeDependent() ||
  6030. Arg->containsUnexpandedParameterPack()) {
  6031. // Force the argument to the type of the parameter to maintain invariants.
  6032. auto *PE = dyn_cast<PackExpansionExpr>(Arg);
  6033. if (PE)
  6034. Arg = PE->getPattern();
  6035. ExprResult E = ImpCastExprToType(
  6036. Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
  6037. ParamType->isLValueReferenceType() ? VK_LValue
  6038. : ParamType->isRValueReferenceType() ? VK_XValue
  6039. : VK_PRValue);
  6040. if (E.isInvalid())
  6041. return ExprError();
  6042. if (PE) {
  6043. // Recreate a pack expansion if we unwrapped one.
  6044. E = new (Context)
  6045. PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
  6046. PE->getNumExpansions());
  6047. }
  6048. Converted = TemplateArgument(E.get());
  6049. return E;
  6050. }
  6051. // The initialization of the parameter from the argument is
  6052. // a constant-evaluated context.
  6053. EnterExpressionEvaluationContext ConstantEvaluated(
  6054. *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  6055. if (getLangOpts().CPlusPlus17) {
  6056. QualType CanonParamType = Context.getCanonicalType(ParamType);
  6057. // Avoid making a copy when initializing a template parameter of class type
  6058. // from a template parameter object of the same type. This is going beyond
  6059. // the standard, but is required for soundness: in
  6060. // template<A a> struct X { X *p; X<a> *q; };
  6061. // ... we need p and q to have the same type.
  6062. //
  6063. // Similarly, don't inject a call to a copy constructor when initializing
  6064. // from a template parameter of the same type.
  6065. Expr *InnerArg = Arg->IgnoreParenImpCasts();
  6066. if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
  6067. Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
  6068. NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
  6069. if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
  6070. Converted = TemplateArgument(TPO, CanonParamType);
  6071. return Arg;
  6072. }
  6073. if (isa<NonTypeTemplateParmDecl>(ND)) {
  6074. Converted = TemplateArgument(Arg);
  6075. return Arg;
  6076. }
  6077. }
  6078. // C++17 [temp.arg.nontype]p1:
  6079. // A template-argument for a non-type template parameter shall be
  6080. // a converted constant expression of the type of the template-parameter.
  6081. APValue Value;
  6082. ExprResult ArgResult = CheckConvertedConstantExpression(
  6083. Arg, ParamType, Value, CCEK_TemplateArg, Param);
  6084. if (ArgResult.isInvalid())
  6085. return ExprError();
  6086. // For a value-dependent argument, CheckConvertedConstantExpression is
  6087. // permitted (and expected) to be unable to determine a value.
  6088. if (ArgResult.get()->isValueDependent()) {
  6089. Converted = TemplateArgument(ArgResult.get());
  6090. return ArgResult;
  6091. }
  6092. // Convert the APValue to a TemplateArgument.
  6093. switch (Value.getKind()) {
  6094. case APValue::None:
  6095. assert(ParamType->isNullPtrType());
  6096. Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
  6097. break;
  6098. case APValue::Indeterminate:
  6099. llvm_unreachable("result of constant evaluation should be initialized");
  6100. break;
  6101. case APValue::Int:
  6102. assert(ParamType->isIntegralOrEnumerationType());
  6103. Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
  6104. break;
  6105. case APValue::MemberPointer: {
  6106. assert(ParamType->isMemberPointerType());
  6107. // FIXME: We need TemplateArgument representation and mangling for these.
  6108. if (!Value.getMemberPointerPath().empty()) {
  6109. Diag(Arg->getBeginLoc(),
  6110. diag::err_template_arg_member_ptr_base_derived_not_supported)
  6111. << Value.getMemberPointerDecl() << ParamType
  6112. << Arg->getSourceRange();
  6113. return ExprError();
  6114. }
  6115. auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
  6116. Converted = VD ? TemplateArgument(VD, CanonParamType)
  6117. : TemplateArgument(CanonParamType, /*isNullPtr*/true);
  6118. break;
  6119. }
  6120. case APValue::LValue: {
  6121. // For a non-type template-parameter of pointer or reference type,
  6122. // the value of the constant expression shall not refer to
  6123. assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
  6124. ParamType->isNullPtrType());
  6125. // -- a temporary object
  6126. // -- a string literal
  6127. // -- the result of a typeid expression, or
  6128. // -- a predefined __func__ variable
  6129. APValue::LValueBase Base = Value.getLValueBase();
  6130. auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
  6131. if (Base && (!VD || isa<LifetimeExtendedTemporaryDecl>(VD))) {
  6132. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  6133. << Arg->getSourceRange();
  6134. return ExprError();
  6135. }
  6136. // -- a subobject
  6137. // FIXME: Until C++20
  6138. if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
  6139. VD && VD->getType()->isArrayType() &&
  6140. Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
  6141. !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
  6142. // Per defect report (no number yet):
  6143. // ... other than a pointer to the first element of a complete array
  6144. // object.
  6145. } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
  6146. Value.isLValueOnePastTheEnd()) {
  6147. Diag(StartLoc, diag::err_non_type_template_arg_subobject)
  6148. << Value.getAsString(Context, ParamType);
  6149. return ExprError();
  6150. }
  6151. assert((VD || !ParamType->isReferenceType()) &&
  6152. "null reference should not be a constant expression");
  6153. assert((!VD || !ParamType->isNullPtrType()) &&
  6154. "non-null value of type nullptr_t?");
  6155. Converted = VD ? TemplateArgument(VD, CanonParamType)
  6156. : TemplateArgument(CanonParamType, /*isNullPtr*/true);
  6157. break;
  6158. }
  6159. case APValue::Struct:
  6160. case APValue::Union:
  6161. // Get or create the corresponding template parameter object.
  6162. Converted = TemplateArgument(
  6163. Context.getTemplateParamObjectDecl(CanonParamType, Value),
  6164. CanonParamType);
  6165. break;
  6166. case APValue::AddrLabelDiff:
  6167. return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
  6168. case APValue::FixedPoint:
  6169. case APValue::Float:
  6170. case APValue::ComplexInt:
  6171. case APValue::ComplexFloat:
  6172. case APValue::Vector:
  6173. case APValue::Array:
  6174. return Diag(StartLoc, diag::err_non_type_template_arg_unsupported)
  6175. << ParamType;
  6176. }
  6177. return ArgResult.get();
  6178. }
  6179. // C++ [temp.arg.nontype]p5:
  6180. // The following conversions are performed on each expression used
  6181. // as a non-type template-argument. If a non-type
  6182. // template-argument cannot be converted to the type of the
  6183. // corresponding template-parameter then the program is
  6184. // ill-formed.
  6185. if (ParamType->isIntegralOrEnumerationType()) {
  6186. // C++11:
  6187. // -- for a non-type template-parameter of integral or
  6188. // enumeration type, conversions permitted in a converted
  6189. // constant expression are applied.
  6190. //
  6191. // C++98:
  6192. // -- for a non-type template-parameter of integral or
  6193. // enumeration type, integral promotions (4.5) and integral
  6194. // conversions (4.7) are applied.
  6195. if (getLangOpts().CPlusPlus11) {
  6196. // C++ [temp.arg.nontype]p1:
  6197. // A template-argument for a non-type, non-template template-parameter
  6198. // shall be one of:
  6199. //
  6200. // -- for a non-type template-parameter of integral or enumeration
  6201. // type, a converted constant expression of the type of the
  6202. // template-parameter; or
  6203. llvm::APSInt Value;
  6204. ExprResult ArgResult =
  6205. CheckConvertedConstantExpression(Arg, ParamType, Value,
  6206. CCEK_TemplateArg);
  6207. if (ArgResult.isInvalid())
  6208. return ExprError();
  6209. // We can't check arbitrary value-dependent arguments.
  6210. if (ArgResult.get()->isValueDependent()) {
  6211. Converted = TemplateArgument(ArgResult.get());
  6212. return ArgResult;
  6213. }
  6214. // Widen the argument value to sizeof(parameter type). This is almost
  6215. // always a no-op, except when the parameter type is bool. In
  6216. // that case, this may extend the argument from 1 bit to 8 bits.
  6217. QualType IntegerType = ParamType;
  6218. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  6219. IntegerType = Enum->getDecl()->getIntegerType();
  6220. Value = Value.extOrTrunc(IntegerType->isBitIntType()
  6221. ? Context.getIntWidth(IntegerType)
  6222. : Context.getTypeSize(IntegerType));
  6223. Converted = TemplateArgument(Context, Value,
  6224. Context.getCanonicalType(ParamType));
  6225. return ArgResult;
  6226. }
  6227. ExprResult ArgResult = DefaultLvalueConversion(Arg);
  6228. if (ArgResult.isInvalid())
  6229. return ExprError();
  6230. Arg = ArgResult.get();
  6231. QualType ArgType = Arg->getType();
  6232. // C++ [temp.arg.nontype]p1:
  6233. // A template-argument for a non-type, non-template
  6234. // template-parameter shall be one of:
  6235. //
  6236. // -- an integral constant-expression of integral or enumeration
  6237. // type; or
  6238. // -- the name of a non-type template-parameter; or
  6239. llvm::APSInt Value;
  6240. if (!ArgType->isIntegralOrEnumerationType()) {
  6241. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
  6242. << ArgType << Arg->getSourceRange();
  6243. Diag(Param->getLocation(), diag::note_template_param_here);
  6244. return ExprError();
  6245. } else if (!Arg->isValueDependent()) {
  6246. class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
  6247. QualType T;
  6248. public:
  6249. TmplArgICEDiagnoser(QualType T) : T(T) { }
  6250. SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
  6251. SourceLocation Loc) override {
  6252. return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
  6253. }
  6254. } Diagnoser(ArgType);
  6255. Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
  6256. if (!Arg)
  6257. return ExprError();
  6258. }
  6259. // From here on out, all we care about is the unqualified form
  6260. // of the argument type.
  6261. ArgType = ArgType.getUnqualifiedType();
  6262. // Try to convert the argument to the parameter's type.
  6263. if (Context.hasSameType(ParamType, ArgType)) {
  6264. // Okay: no conversion necessary
  6265. } else if (ParamType->isBooleanType()) {
  6266. // This is an integral-to-boolean conversion.
  6267. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
  6268. } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
  6269. !ParamType->isEnumeralType()) {
  6270. // This is an integral promotion or conversion.
  6271. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
  6272. } else {
  6273. // We can't perform this conversion.
  6274. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
  6275. << Arg->getType() << ParamType << Arg->getSourceRange();
  6276. Diag(Param->getLocation(), diag::note_template_param_here);
  6277. return ExprError();
  6278. }
  6279. // Add the value of this argument to the list of converted
  6280. // arguments. We use the bitwidth and signedness of the template
  6281. // parameter.
  6282. if (Arg->isValueDependent()) {
  6283. // The argument is value-dependent. Create a new
  6284. // TemplateArgument with the converted expression.
  6285. Converted = TemplateArgument(Arg);
  6286. return Arg;
  6287. }
  6288. QualType IntegerType = Context.getCanonicalType(ParamType);
  6289. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  6290. IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
  6291. if (ParamType->isBooleanType()) {
  6292. // Value must be zero or one.
  6293. Value = Value != 0;
  6294. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  6295. if (Value.getBitWidth() != AllowedBits)
  6296. Value = Value.extOrTrunc(AllowedBits);
  6297. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  6298. } else {
  6299. llvm::APSInt OldValue = Value;
  6300. // Coerce the template argument's value to the value it will have
  6301. // based on the template parameter's type.
  6302. unsigned AllowedBits = IntegerType->isBitIntType()
  6303. ? Context.getIntWidth(IntegerType)
  6304. : Context.getTypeSize(IntegerType);
  6305. if (Value.getBitWidth() != AllowedBits)
  6306. Value = Value.extOrTrunc(AllowedBits);
  6307. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  6308. // Complain if an unsigned parameter received a negative value.
  6309. if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
  6310. (OldValue.isSigned() && OldValue.isNegative())) {
  6311. Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
  6312. << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
  6313. << Arg->getSourceRange();
  6314. Diag(Param->getLocation(), diag::note_template_param_here);
  6315. }
  6316. // Complain if we overflowed the template parameter's type.
  6317. unsigned RequiredBits;
  6318. if (IntegerType->isUnsignedIntegerOrEnumerationType())
  6319. RequiredBits = OldValue.getActiveBits();
  6320. else if (OldValue.isUnsigned())
  6321. RequiredBits = OldValue.getActiveBits() + 1;
  6322. else
  6323. RequiredBits = OldValue.getMinSignedBits();
  6324. if (RequiredBits > AllowedBits) {
  6325. Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
  6326. << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
  6327. << Arg->getSourceRange();
  6328. Diag(Param->getLocation(), diag::note_template_param_here);
  6329. }
  6330. }
  6331. Converted = TemplateArgument(Context, Value,
  6332. ParamType->isEnumeralType()
  6333. ? Context.getCanonicalType(ParamType)
  6334. : IntegerType);
  6335. return Arg;
  6336. }
  6337. QualType ArgType = Arg->getType();
  6338. DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
  6339. // Handle pointer-to-function, reference-to-function, and
  6340. // pointer-to-member-function all in (roughly) the same way.
  6341. if (// -- For a non-type template-parameter of type pointer to
  6342. // function, only the function-to-pointer conversion (4.3) is
  6343. // applied. If the template-argument represents a set of
  6344. // overloaded functions (or a pointer to such), the matching
  6345. // function is selected from the set (13.4).
  6346. (ParamType->isPointerType() &&
  6347. ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
  6348. // -- For a non-type template-parameter of type reference to
  6349. // function, no conversions apply. If the template-argument
  6350. // represents a set of overloaded functions, the matching
  6351. // function is selected from the set (13.4).
  6352. (ParamType->isReferenceType() &&
  6353. ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
  6354. // -- For a non-type template-parameter of type pointer to
  6355. // member function, no conversions apply. If the
  6356. // template-argument represents a set of overloaded member
  6357. // functions, the matching member function is selected from
  6358. // the set (13.4).
  6359. (ParamType->isMemberPointerType() &&
  6360. ParamType->castAs<MemberPointerType>()->getPointeeType()
  6361. ->isFunctionType())) {
  6362. if (Arg->getType() == Context.OverloadTy) {
  6363. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
  6364. true,
  6365. FoundResult)) {
  6366. if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
  6367. return ExprError();
  6368. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  6369. ArgType = Arg->getType();
  6370. } else
  6371. return ExprError();
  6372. }
  6373. if (!ParamType->isMemberPointerType()) {
  6374. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  6375. ParamType,
  6376. Arg, Converted))
  6377. return ExprError();
  6378. return Arg;
  6379. }
  6380. if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
  6381. Converted))
  6382. return ExprError();
  6383. return Arg;
  6384. }
  6385. if (ParamType->isPointerType()) {
  6386. // -- for a non-type template-parameter of type pointer to
  6387. // object, qualification conversions (4.4) and the
  6388. // array-to-pointer conversion (4.2) are applied.
  6389. // C++0x also allows a value of std::nullptr_t.
  6390. assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
  6391. "Only object pointers allowed here");
  6392. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  6393. ParamType,
  6394. Arg, Converted))
  6395. return ExprError();
  6396. return Arg;
  6397. }
  6398. if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
  6399. // -- For a non-type template-parameter of type reference to
  6400. // object, no conversions apply. The type referred to by the
  6401. // reference may be more cv-qualified than the (otherwise
  6402. // identical) type of the template-argument. The
  6403. // template-parameter is bound directly to the
  6404. // template-argument, which must be an lvalue.
  6405. assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
  6406. "Only object references allowed here");
  6407. if (Arg->getType() == Context.OverloadTy) {
  6408. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
  6409. ParamRefType->getPointeeType(),
  6410. true,
  6411. FoundResult)) {
  6412. if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
  6413. return ExprError();
  6414. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  6415. ArgType = Arg->getType();
  6416. } else
  6417. return ExprError();
  6418. }
  6419. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  6420. ParamType,
  6421. Arg, Converted))
  6422. return ExprError();
  6423. return Arg;
  6424. }
  6425. // Deal with parameters of type std::nullptr_t.
  6426. if (ParamType->isNullPtrType()) {
  6427. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  6428. Converted = TemplateArgument(Arg);
  6429. return Arg;
  6430. }
  6431. switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
  6432. case NPV_NotNullPointer:
  6433. Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
  6434. << Arg->getType() << ParamType;
  6435. Diag(Param->getLocation(), diag::note_template_param_here);
  6436. return ExprError();
  6437. case NPV_Error:
  6438. return ExprError();
  6439. case NPV_NullPointer:
  6440. Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  6441. Converted = TemplateArgument(Context.getCanonicalType(ParamType),
  6442. /*isNullPtr*/true);
  6443. return Arg;
  6444. }
  6445. }
  6446. // -- For a non-type template-parameter of type pointer to data
  6447. // member, qualification conversions (4.4) are applied.
  6448. assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
  6449. if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
  6450. Converted))
  6451. return ExprError();
  6452. return Arg;
  6453. }
  6454. static void DiagnoseTemplateParameterListArityMismatch(
  6455. Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
  6456. Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
  6457. /// Check a template argument against its corresponding
  6458. /// template template parameter.
  6459. ///
  6460. /// This routine implements the semantics of C++ [temp.arg.template].
  6461. /// It returns true if an error occurred, and false otherwise.
  6462. bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  6463. TemplateParameterList *Params,
  6464. TemplateArgumentLoc &Arg) {
  6465. TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
  6466. TemplateDecl *Template = Name.getAsTemplateDecl();
  6467. if (!Template) {
  6468. // Any dependent template name is fine.
  6469. assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
  6470. return false;
  6471. }
  6472. if (Template->isInvalidDecl())
  6473. return true;
  6474. // C++0x [temp.arg.template]p1:
  6475. // A template-argument for a template template-parameter shall be
  6476. // the name of a class template or an alias template, expressed as an
  6477. // id-expression. When the template-argument names a class template, only
  6478. // primary class templates are considered when matching the
  6479. // template template argument with the corresponding parameter;
  6480. // partial specializations are not considered even if their
  6481. // parameter lists match that of the template template parameter.
  6482. //
  6483. // Note that we also allow template template parameters here, which
  6484. // will happen when we are dealing with, e.g., class template
  6485. // partial specializations.
  6486. if (!isa<ClassTemplateDecl>(Template) &&
  6487. !isa<TemplateTemplateParmDecl>(Template) &&
  6488. !isa<TypeAliasTemplateDecl>(Template) &&
  6489. !isa<BuiltinTemplateDecl>(Template)) {
  6490. assert(isa<FunctionTemplateDecl>(Template) &&
  6491. "Only function templates are possible here");
  6492. Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
  6493. Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
  6494. << Template;
  6495. }
  6496. // C++1z [temp.arg.template]p3: (DR 150)
  6497. // A template-argument matches a template template-parameter P when P
  6498. // is at least as specialized as the template-argument A.
  6499. // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
  6500. // defect report resolution from C++17 and shouldn't be introduced by
  6501. // concepts.
  6502. if (getLangOpts().RelaxedTemplateTemplateArgs) {
  6503. // Quick check for the common case:
  6504. // If P contains a parameter pack, then A [...] matches P if each of A's
  6505. // template parameters matches the corresponding template parameter in
  6506. // the template-parameter-list of P.
  6507. if (TemplateParameterListsAreEqual(
  6508. Template->getTemplateParameters(), Params, false,
  6509. TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
  6510. // If the argument has no associated constraints, then the parameter is
  6511. // definitely at least as specialized as the argument.
  6512. // Otherwise - we need a more thorough check.
  6513. !Template->hasAssociatedConstraints())
  6514. return false;
  6515. if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
  6516. Arg.getLocation())) {
  6517. // C++2a[temp.func.order]p2
  6518. // [...] If both deductions succeed, the partial ordering selects the
  6519. // more constrained template as described by the rules in
  6520. // [temp.constr.order].
  6521. SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
  6522. Params->getAssociatedConstraints(ParamsAC);
  6523. // C++2a[temp.arg.template]p3
  6524. // [...] In this comparison, if P is unconstrained, the constraints on A
  6525. // are not considered.
  6526. if (ParamsAC.empty())
  6527. return false;
  6528. Template->getAssociatedConstraints(TemplateAC);
  6529. bool IsParamAtLeastAsConstrained;
  6530. if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
  6531. IsParamAtLeastAsConstrained))
  6532. return true;
  6533. if (!IsParamAtLeastAsConstrained) {
  6534. Diag(Arg.getLocation(),
  6535. diag::err_template_template_parameter_not_at_least_as_constrained)
  6536. << Template << Param << Arg.getSourceRange();
  6537. Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
  6538. Diag(Template->getLocation(), diag::note_entity_declared_at)
  6539. << Template;
  6540. MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
  6541. TemplateAC);
  6542. return true;
  6543. }
  6544. return false;
  6545. }
  6546. // FIXME: Produce better diagnostics for deduction failures.
  6547. }
  6548. return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
  6549. Params,
  6550. true,
  6551. TPL_TemplateTemplateArgumentMatch,
  6552. Arg.getLocation());
  6553. }
  6554. /// Given a non-type template argument that refers to a
  6555. /// declaration and the type of its corresponding non-type template
  6556. /// parameter, produce an expression that properly refers to that
  6557. /// declaration.
  6558. ExprResult
  6559. Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
  6560. QualType ParamType,
  6561. SourceLocation Loc) {
  6562. // C++ [temp.param]p8:
  6563. //
  6564. // A non-type template-parameter of type "array of T" or
  6565. // "function returning T" is adjusted to be of type "pointer to
  6566. // T" or "pointer to function returning T", respectively.
  6567. if (ParamType->isArrayType())
  6568. ParamType = Context.getArrayDecayedType(ParamType);
  6569. else if (ParamType->isFunctionType())
  6570. ParamType = Context.getPointerType(ParamType);
  6571. // For a NULL non-type template argument, return nullptr casted to the
  6572. // parameter's type.
  6573. if (Arg.getKind() == TemplateArgument::NullPtr) {
  6574. return ImpCastExprToType(
  6575. new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
  6576. ParamType,
  6577. ParamType->getAs<MemberPointerType>()
  6578. ? CK_NullToMemberPointer
  6579. : CK_NullToPointer);
  6580. }
  6581. assert(Arg.getKind() == TemplateArgument::Declaration &&
  6582. "Only declaration template arguments permitted here");
  6583. ValueDecl *VD = Arg.getAsDecl();
  6584. CXXScopeSpec SS;
  6585. if (ParamType->isMemberPointerType()) {
  6586. // If this is a pointer to member, we need to use a qualified name to
  6587. // form a suitable pointer-to-member constant.
  6588. assert(VD->getDeclContext()->isRecord() &&
  6589. (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
  6590. isa<IndirectFieldDecl>(VD)));
  6591. QualType ClassType
  6592. = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
  6593. NestedNameSpecifier *Qualifier
  6594. = NestedNameSpecifier::Create(Context, nullptr, false,
  6595. ClassType.getTypePtr());
  6596. SS.MakeTrivial(Context, Qualifier, Loc);
  6597. }
  6598. ExprResult RefExpr = BuildDeclarationNameExpr(
  6599. SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
  6600. if (RefExpr.isInvalid())
  6601. return ExprError();
  6602. // For a pointer, the argument declaration is the pointee. Take its address.
  6603. QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
  6604. if (ParamType->isPointerType() && !ElemT.isNull() &&
  6605. Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
  6606. // Decay an array argument if we want a pointer to its first element.
  6607. RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
  6608. if (RefExpr.isInvalid())
  6609. return ExprError();
  6610. } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
  6611. // For any other pointer, take the address (or form a pointer-to-member).
  6612. RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
  6613. if (RefExpr.isInvalid())
  6614. return ExprError();
  6615. } else if (ParamType->isRecordType()) {
  6616. assert(isa<TemplateParamObjectDecl>(VD) &&
  6617. "arg for class template param not a template parameter object");
  6618. // No conversions apply in this case.
  6619. return RefExpr;
  6620. } else {
  6621. assert(ParamType->isReferenceType() &&
  6622. "unexpected type for decl template argument");
  6623. }
  6624. // At this point we should have the right value category.
  6625. assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
  6626. "value kind mismatch for non-type template argument");
  6627. // The type of the template parameter can differ from the type of the
  6628. // argument in various ways; convert it now if necessary.
  6629. QualType DestExprType = ParamType.getNonLValueExprType(Context);
  6630. if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
  6631. CastKind CK;
  6632. QualType Ignored;
  6633. if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
  6634. IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
  6635. CK = CK_NoOp;
  6636. } else if (ParamType->isVoidPointerType() &&
  6637. RefExpr.get()->getType()->isPointerType()) {
  6638. CK = CK_BitCast;
  6639. } else {
  6640. // FIXME: Pointers to members can need conversion derived-to-base or
  6641. // base-to-derived conversions. We currently don't retain enough
  6642. // information to convert properly (we need to track a cast path or
  6643. // subobject number in the template argument).
  6644. llvm_unreachable(
  6645. "unexpected conversion required for non-type template argument");
  6646. }
  6647. RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
  6648. RefExpr.get()->getValueKind());
  6649. }
  6650. return RefExpr;
  6651. }
  6652. /// Construct a new expression that refers to the given
  6653. /// integral template argument with the given source-location
  6654. /// information.
  6655. ///
  6656. /// This routine takes care of the mapping from an integral template
  6657. /// argument (which may have any integral type) to the appropriate
  6658. /// literal value.
  6659. ExprResult
  6660. Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
  6661. SourceLocation Loc) {
  6662. assert(Arg.getKind() == TemplateArgument::Integral &&
  6663. "Operation is only valid for integral template arguments");
  6664. QualType OrigT = Arg.getIntegralType();
  6665. // If this is an enum type that we're instantiating, we need to use an integer
  6666. // type the same size as the enumerator. We don't want to build an
  6667. // IntegerLiteral with enum type. The integer type of an enum type can be of
  6668. // any integral type with C++11 enum classes, make sure we create the right
  6669. // type of literal for it.
  6670. QualType T = OrigT;
  6671. if (const EnumType *ET = OrigT->getAs<EnumType>())
  6672. T = ET->getDecl()->getIntegerType();
  6673. Expr *E;
  6674. if (T->isAnyCharacterType()) {
  6675. CharacterLiteral::CharacterKind Kind;
  6676. if (T->isWideCharType())
  6677. Kind = CharacterLiteral::Wide;
  6678. else if (T->isChar8Type() && getLangOpts().Char8)
  6679. Kind = CharacterLiteral::UTF8;
  6680. else if (T->isChar16Type())
  6681. Kind = CharacterLiteral::UTF16;
  6682. else if (T->isChar32Type())
  6683. Kind = CharacterLiteral::UTF32;
  6684. else
  6685. Kind = CharacterLiteral::Ascii;
  6686. E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
  6687. Kind, T, Loc);
  6688. } else if (T->isBooleanType()) {
  6689. E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
  6690. T, Loc);
  6691. } else if (T->isNullPtrType()) {
  6692. E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  6693. } else {
  6694. E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
  6695. }
  6696. if (OrigT->isEnumeralType()) {
  6697. // FIXME: This is a hack. We need a better way to handle substituted
  6698. // non-type template parameters.
  6699. E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E,
  6700. nullptr, CurFPFeatureOverrides(),
  6701. Context.getTrivialTypeSourceInfo(OrigT, Loc),
  6702. Loc, Loc);
  6703. }
  6704. return E;
  6705. }
  6706. /// Match two template parameters within template parameter lists.
  6707. static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
  6708. bool Complain,
  6709. Sema::TemplateParameterListEqualKind Kind,
  6710. SourceLocation TemplateArgLoc) {
  6711. // Check the actual kind (type, non-type, template).
  6712. if (Old->getKind() != New->getKind()) {
  6713. if (Complain) {
  6714. unsigned NextDiag = diag::err_template_param_different_kind;
  6715. if (TemplateArgLoc.isValid()) {
  6716. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  6717. NextDiag = diag::note_template_param_different_kind;
  6718. }
  6719. S.Diag(New->getLocation(), NextDiag)
  6720. << (Kind != Sema::TPL_TemplateMatch);
  6721. S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
  6722. << (Kind != Sema::TPL_TemplateMatch);
  6723. }
  6724. return false;
  6725. }
  6726. // Check that both are parameter packs or neither are parameter packs.
  6727. // However, if we are matching a template template argument to a
  6728. // template template parameter, the template template parameter can have
  6729. // a parameter pack where the template template argument does not.
  6730. if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
  6731. !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
  6732. Old->isTemplateParameterPack())) {
  6733. if (Complain) {
  6734. unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
  6735. if (TemplateArgLoc.isValid()) {
  6736. S.Diag(TemplateArgLoc,
  6737. diag::err_template_arg_template_params_mismatch);
  6738. NextDiag = diag::note_template_parameter_pack_non_pack;
  6739. }
  6740. unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
  6741. : isa<NonTypeTemplateParmDecl>(New)? 1
  6742. : 2;
  6743. S.Diag(New->getLocation(), NextDiag)
  6744. << ParamKind << New->isParameterPack();
  6745. S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
  6746. << ParamKind << Old->isParameterPack();
  6747. }
  6748. return false;
  6749. }
  6750. // For non-type template parameters, check the type of the parameter.
  6751. if (NonTypeTemplateParmDecl *OldNTTP
  6752. = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
  6753. NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
  6754. // If we are matching a template template argument to a template
  6755. // template parameter and one of the non-type template parameter types
  6756. // is dependent, then we must wait until template instantiation time
  6757. // to actually compare the arguments.
  6758. if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
  6759. (!OldNTTP->getType()->isDependentType() &&
  6760. !NewNTTP->getType()->isDependentType()))
  6761. if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
  6762. if (Complain) {
  6763. unsigned NextDiag = diag::err_template_nontype_parm_different_type;
  6764. if (TemplateArgLoc.isValid()) {
  6765. S.Diag(TemplateArgLoc,
  6766. diag::err_template_arg_template_params_mismatch);
  6767. NextDiag = diag::note_template_nontype_parm_different_type;
  6768. }
  6769. S.Diag(NewNTTP->getLocation(), NextDiag)
  6770. << NewNTTP->getType()
  6771. << (Kind != Sema::TPL_TemplateMatch);
  6772. S.Diag(OldNTTP->getLocation(),
  6773. diag::note_template_nontype_parm_prev_declaration)
  6774. << OldNTTP->getType();
  6775. }
  6776. return false;
  6777. }
  6778. }
  6779. // For template template parameters, check the template parameter types.
  6780. // The template parameter lists of template template
  6781. // parameters must agree.
  6782. else if (TemplateTemplateParmDecl *OldTTP
  6783. = dyn_cast<TemplateTemplateParmDecl>(Old)) {
  6784. TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
  6785. if (!S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
  6786. OldTTP->getTemplateParameters(),
  6787. Complain,
  6788. (Kind == Sema::TPL_TemplateMatch
  6789. ? Sema::TPL_TemplateTemplateParmMatch
  6790. : Kind),
  6791. TemplateArgLoc))
  6792. return false;
  6793. } else if (Kind != Sema::TPL_TemplateTemplateArgumentMatch) {
  6794. const Expr *NewC = nullptr, *OldC = nullptr;
  6795. if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
  6796. NewC = TC->getImmediatelyDeclaredConstraint();
  6797. if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
  6798. OldC = TC->getImmediatelyDeclaredConstraint();
  6799. auto Diagnose = [&] {
  6800. S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
  6801. diag::err_template_different_type_constraint);
  6802. S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
  6803. diag::note_template_prev_declaration) << /*declaration*/0;
  6804. };
  6805. if (!NewC != !OldC) {
  6806. if (Complain)
  6807. Diagnose();
  6808. return false;
  6809. }
  6810. if (NewC) {
  6811. llvm::FoldingSetNodeID OldCID, NewCID;
  6812. OldC->Profile(OldCID, S.Context, /*Canonical=*/true);
  6813. NewC->Profile(NewCID, S.Context, /*Canonical=*/true);
  6814. if (OldCID != NewCID) {
  6815. if (Complain)
  6816. Diagnose();
  6817. return false;
  6818. }
  6819. }
  6820. }
  6821. return true;
  6822. }
  6823. /// Diagnose a known arity mismatch when comparing template argument
  6824. /// lists.
  6825. static
  6826. void DiagnoseTemplateParameterListArityMismatch(Sema &S,
  6827. TemplateParameterList *New,
  6828. TemplateParameterList *Old,
  6829. Sema::TemplateParameterListEqualKind Kind,
  6830. SourceLocation TemplateArgLoc) {
  6831. unsigned NextDiag = diag::err_template_param_list_different_arity;
  6832. if (TemplateArgLoc.isValid()) {
  6833. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  6834. NextDiag = diag::note_template_param_list_different_arity;
  6835. }
  6836. S.Diag(New->getTemplateLoc(), NextDiag)
  6837. << (New->size() > Old->size())
  6838. << (Kind != Sema::TPL_TemplateMatch)
  6839. << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
  6840. S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
  6841. << (Kind != Sema::TPL_TemplateMatch)
  6842. << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
  6843. }
  6844. /// Determine whether the given template parameter lists are
  6845. /// equivalent.
  6846. ///
  6847. /// \param New The new template parameter list, typically written in the
  6848. /// source code as part of a new template declaration.
  6849. ///
  6850. /// \param Old The old template parameter list, typically found via
  6851. /// name lookup of the template declared with this template parameter
  6852. /// list.
  6853. ///
  6854. /// \param Complain If true, this routine will produce a diagnostic if
  6855. /// the template parameter lists are not equivalent.
  6856. ///
  6857. /// \param Kind describes how we are to match the template parameter lists.
  6858. ///
  6859. /// \param TemplateArgLoc If this source location is valid, then we
  6860. /// are actually checking the template parameter list of a template
  6861. /// argument (New) against the template parameter list of its
  6862. /// corresponding template template parameter (Old). We produce
  6863. /// slightly different diagnostics in this scenario.
  6864. ///
  6865. /// \returns True if the template parameter lists are equal, false
  6866. /// otherwise.
  6867. bool
  6868. Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
  6869. TemplateParameterList *Old,
  6870. bool Complain,
  6871. TemplateParameterListEqualKind Kind,
  6872. SourceLocation TemplateArgLoc) {
  6873. if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
  6874. if (Complain)
  6875. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  6876. TemplateArgLoc);
  6877. return false;
  6878. }
  6879. // C++0x [temp.arg.template]p3:
  6880. // A template-argument matches a template template-parameter (call it P)
  6881. // when each of the template parameters in the template-parameter-list of
  6882. // the template-argument's corresponding class template or alias template
  6883. // (call it A) matches the corresponding template parameter in the
  6884. // template-parameter-list of P. [...]
  6885. TemplateParameterList::iterator NewParm = New->begin();
  6886. TemplateParameterList::iterator NewParmEnd = New->end();
  6887. for (TemplateParameterList::iterator OldParm = Old->begin(),
  6888. OldParmEnd = Old->end();
  6889. OldParm != OldParmEnd; ++OldParm) {
  6890. if (Kind != TPL_TemplateTemplateArgumentMatch ||
  6891. !(*OldParm)->isTemplateParameterPack()) {
  6892. if (NewParm == NewParmEnd) {
  6893. if (Complain)
  6894. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  6895. TemplateArgLoc);
  6896. return false;
  6897. }
  6898. if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
  6899. Kind, TemplateArgLoc))
  6900. return false;
  6901. ++NewParm;
  6902. continue;
  6903. }
  6904. // C++0x [temp.arg.template]p3:
  6905. // [...] When P's template- parameter-list contains a template parameter
  6906. // pack (14.5.3), the template parameter pack will match zero or more
  6907. // template parameters or template parameter packs in the
  6908. // template-parameter-list of A with the same type and form as the
  6909. // template parameter pack in P (ignoring whether those template
  6910. // parameters are template parameter packs).
  6911. for (; NewParm != NewParmEnd; ++NewParm) {
  6912. if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
  6913. Kind, TemplateArgLoc))
  6914. return false;
  6915. }
  6916. }
  6917. // Make sure we exhausted all of the arguments.
  6918. if (NewParm != NewParmEnd) {
  6919. if (Complain)
  6920. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  6921. TemplateArgLoc);
  6922. return false;
  6923. }
  6924. if (Kind != TPL_TemplateTemplateArgumentMatch) {
  6925. const Expr *NewRC = New->getRequiresClause();
  6926. const Expr *OldRC = Old->getRequiresClause();
  6927. auto Diagnose = [&] {
  6928. Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
  6929. diag::err_template_different_requires_clause);
  6930. Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
  6931. diag::note_template_prev_declaration) << /*declaration*/0;
  6932. };
  6933. if (!NewRC != !OldRC) {
  6934. if (Complain)
  6935. Diagnose();
  6936. return false;
  6937. }
  6938. if (NewRC) {
  6939. llvm::FoldingSetNodeID OldRCID, NewRCID;
  6940. OldRC->Profile(OldRCID, Context, /*Canonical=*/true);
  6941. NewRC->Profile(NewRCID, Context, /*Canonical=*/true);
  6942. if (OldRCID != NewRCID) {
  6943. if (Complain)
  6944. Diagnose();
  6945. return false;
  6946. }
  6947. }
  6948. }
  6949. return true;
  6950. }
  6951. /// Check whether a template can be declared within this scope.
  6952. ///
  6953. /// If the template declaration is valid in this scope, returns
  6954. /// false. Otherwise, issues a diagnostic and returns true.
  6955. bool
  6956. Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
  6957. if (!S)
  6958. return false;
  6959. // Find the nearest enclosing declaration scope.
  6960. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  6961. (S->getFlags() & Scope::TemplateParamScope) != 0)
  6962. S = S->getParent();
  6963. // C++ [temp.pre]p6: [P2096]
  6964. // A template, explicit specialization, or partial specialization shall not
  6965. // have C linkage.
  6966. DeclContext *Ctx = S->getEntity();
  6967. if (Ctx && Ctx->isExternCContext()) {
  6968. Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
  6969. << TemplateParams->getSourceRange();
  6970. if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
  6971. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  6972. return true;
  6973. }
  6974. Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
  6975. // C++ [temp]p2:
  6976. // A template-declaration can appear only as a namespace scope or
  6977. // class scope declaration.
  6978. // C++ [temp.expl.spec]p3:
  6979. // An explicit specialization may be declared in any scope in which the
  6980. // corresponding primary template may be defined.
  6981. // C++ [temp.class.spec]p6: [P2096]
  6982. // A partial specialization may be declared in any scope in which the
  6983. // corresponding primary template may be defined.
  6984. if (Ctx) {
  6985. if (Ctx->isFileContext())
  6986. return false;
  6987. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
  6988. // C++ [temp.mem]p2:
  6989. // A local class shall not have member templates.
  6990. if (RD->isLocalClass())
  6991. return Diag(TemplateParams->getTemplateLoc(),
  6992. diag::err_template_inside_local_class)
  6993. << TemplateParams->getSourceRange();
  6994. else
  6995. return false;
  6996. }
  6997. }
  6998. return Diag(TemplateParams->getTemplateLoc(),
  6999. diag::err_template_outside_namespace_or_class_scope)
  7000. << TemplateParams->getSourceRange();
  7001. }
  7002. /// Determine what kind of template specialization the given declaration
  7003. /// is.
  7004. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
  7005. if (!D)
  7006. return TSK_Undeclared;
  7007. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
  7008. return Record->getTemplateSpecializationKind();
  7009. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  7010. return Function->getTemplateSpecializationKind();
  7011. if (VarDecl *Var = dyn_cast<VarDecl>(D))
  7012. return Var->getTemplateSpecializationKind();
  7013. return TSK_Undeclared;
  7014. }
  7015. /// Check whether a specialization is well-formed in the current
  7016. /// context.
  7017. ///
  7018. /// This routine determines whether a template specialization can be declared
  7019. /// in the current context (C++ [temp.expl.spec]p2).
  7020. ///
  7021. /// \param S the semantic analysis object for which this check is being
  7022. /// performed.
  7023. ///
  7024. /// \param Specialized the entity being specialized or instantiated, which
  7025. /// may be a kind of template (class template, function template, etc.) or
  7026. /// a member of a class template (member function, static data member,
  7027. /// member class).
  7028. ///
  7029. /// \param PrevDecl the previous declaration of this entity, if any.
  7030. ///
  7031. /// \param Loc the location of the explicit specialization or instantiation of
  7032. /// this entity.
  7033. ///
  7034. /// \param IsPartialSpecialization whether this is a partial specialization of
  7035. /// a class template.
  7036. ///
  7037. /// \returns true if there was an error that we cannot recover from, false
  7038. /// otherwise.
  7039. static bool CheckTemplateSpecializationScope(Sema &S,
  7040. NamedDecl *Specialized,
  7041. NamedDecl *PrevDecl,
  7042. SourceLocation Loc,
  7043. bool IsPartialSpecialization) {
  7044. // Keep these "kind" numbers in sync with the %select statements in the
  7045. // various diagnostics emitted by this routine.
  7046. int EntityKind = 0;
  7047. if (isa<ClassTemplateDecl>(Specialized))
  7048. EntityKind = IsPartialSpecialization? 1 : 0;
  7049. else if (isa<VarTemplateDecl>(Specialized))
  7050. EntityKind = IsPartialSpecialization ? 3 : 2;
  7051. else if (isa<FunctionTemplateDecl>(Specialized))
  7052. EntityKind = 4;
  7053. else if (isa<CXXMethodDecl>(Specialized))
  7054. EntityKind = 5;
  7055. else if (isa<VarDecl>(Specialized))
  7056. EntityKind = 6;
  7057. else if (isa<RecordDecl>(Specialized))
  7058. EntityKind = 7;
  7059. else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
  7060. EntityKind = 8;
  7061. else {
  7062. S.Diag(Loc, diag::err_template_spec_unknown_kind)
  7063. << S.getLangOpts().CPlusPlus11;
  7064. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  7065. return true;
  7066. }
  7067. // C++ [temp.expl.spec]p2:
  7068. // An explicit specialization may be declared in any scope in which
  7069. // the corresponding primary template may be defined.
  7070. if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7071. S.Diag(Loc, diag::err_template_spec_decl_function_scope)
  7072. << Specialized;
  7073. return true;
  7074. }
  7075. // C++ [temp.class.spec]p6:
  7076. // A class template partial specialization may be declared in any
  7077. // scope in which the primary template may be defined.
  7078. DeclContext *SpecializedContext =
  7079. Specialized->getDeclContext()->getRedeclContext();
  7080. DeclContext *DC = S.CurContext->getRedeclContext();
  7081. // Make sure that this redeclaration (or definition) occurs in the same
  7082. // scope or an enclosing namespace.
  7083. if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
  7084. : DC->Equals(SpecializedContext))) {
  7085. if (isa<TranslationUnitDecl>(SpecializedContext))
  7086. S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
  7087. << EntityKind << Specialized;
  7088. else {
  7089. auto *ND = cast<NamedDecl>(SpecializedContext);
  7090. int Diag = diag::err_template_spec_redecl_out_of_scope;
  7091. if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
  7092. Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
  7093. S.Diag(Loc, Diag) << EntityKind << Specialized
  7094. << ND << isa<CXXRecordDecl>(ND);
  7095. }
  7096. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  7097. // Don't allow specializing in the wrong class during error recovery.
  7098. // Otherwise, things can go horribly wrong.
  7099. if (DC->isRecord())
  7100. return true;
  7101. }
  7102. return false;
  7103. }
  7104. static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
  7105. if (!E->isTypeDependent())
  7106. return SourceLocation();
  7107. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  7108. Checker.TraverseStmt(E);
  7109. if (Checker.MatchLoc.isInvalid())
  7110. return E->getSourceRange();
  7111. return Checker.MatchLoc;
  7112. }
  7113. static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
  7114. if (!TL.getType()->isDependentType())
  7115. return SourceLocation();
  7116. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  7117. Checker.TraverseTypeLoc(TL);
  7118. if (Checker.MatchLoc.isInvalid())
  7119. return TL.getSourceRange();
  7120. return Checker.MatchLoc;
  7121. }
  7122. /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
  7123. /// that checks non-type template partial specialization arguments.
  7124. static bool CheckNonTypeTemplatePartialSpecializationArgs(
  7125. Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
  7126. const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
  7127. for (unsigned I = 0; I != NumArgs; ++I) {
  7128. if (Args[I].getKind() == TemplateArgument::Pack) {
  7129. if (CheckNonTypeTemplatePartialSpecializationArgs(
  7130. S, TemplateNameLoc, Param, Args[I].pack_begin(),
  7131. Args[I].pack_size(), IsDefaultArgument))
  7132. return true;
  7133. continue;
  7134. }
  7135. if (Args[I].getKind() != TemplateArgument::Expression)
  7136. continue;
  7137. Expr *ArgExpr = Args[I].getAsExpr();
  7138. // We can have a pack expansion of any of the bullets below.
  7139. if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
  7140. ArgExpr = Expansion->getPattern();
  7141. // Strip off any implicit casts we added as part of type checking.
  7142. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  7143. ArgExpr = ICE->getSubExpr();
  7144. // C++ [temp.class.spec]p8:
  7145. // A non-type argument is non-specialized if it is the name of a
  7146. // non-type parameter. All other non-type arguments are
  7147. // specialized.
  7148. //
  7149. // Below, we check the two conditions that only apply to
  7150. // specialized non-type arguments, so skip any non-specialized
  7151. // arguments.
  7152. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
  7153. if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
  7154. continue;
  7155. // C++ [temp.class.spec]p9:
  7156. // Within the argument list of a class template partial
  7157. // specialization, the following restrictions apply:
  7158. // -- A partially specialized non-type argument expression
  7159. // shall not involve a template parameter of the partial
  7160. // specialization except when the argument expression is a
  7161. // simple identifier.
  7162. // -- The type of a template parameter corresponding to a
  7163. // specialized non-type argument shall not be dependent on a
  7164. // parameter of the specialization.
  7165. // DR1315 removes the first bullet, leaving an incoherent set of rules.
  7166. // We implement a compromise between the original rules and DR1315:
  7167. // -- A specialized non-type template argument shall not be
  7168. // type-dependent and the corresponding template parameter
  7169. // shall have a non-dependent type.
  7170. SourceRange ParamUseRange =
  7171. findTemplateParameterInType(Param->getDepth(), ArgExpr);
  7172. if (ParamUseRange.isValid()) {
  7173. if (IsDefaultArgument) {
  7174. S.Diag(TemplateNameLoc,
  7175. diag::err_dependent_non_type_arg_in_partial_spec);
  7176. S.Diag(ParamUseRange.getBegin(),
  7177. diag::note_dependent_non_type_default_arg_in_partial_spec)
  7178. << ParamUseRange;
  7179. } else {
  7180. S.Diag(ParamUseRange.getBegin(),
  7181. diag::err_dependent_non_type_arg_in_partial_spec)
  7182. << ParamUseRange;
  7183. }
  7184. return true;
  7185. }
  7186. ParamUseRange = findTemplateParameter(
  7187. Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
  7188. if (ParamUseRange.isValid()) {
  7189. S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
  7190. diag::err_dependent_typed_non_type_arg_in_partial_spec)
  7191. << Param->getType();
  7192. S.Diag(Param->getLocation(), diag::note_template_param_here)
  7193. << (IsDefaultArgument ? ParamUseRange : SourceRange())
  7194. << ParamUseRange;
  7195. return true;
  7196. }
  7197. }
  7198. return false;
  7199. }
  7200. /// Check the non-type template arguments of a class template
  7201. /// partial specialization according to C++ [temp.class.spec]p9.
  7202. ///
  7203. /// \param TemplateNameLoc the location of the template name.
  7204. /// \param PrimaryTemplate the template parameters of the primary class
  7205. /// template.
  7206. /// \param NumExplicit the number of explicitly-specified template arguments.
  7207. /// \param TemplateArgs the template arguments of the class template
  7208. /// partial specialization.
  7209. ///
  7210. /// \returns \c true if there was an error, \c false otherwise.
  7211. bool Sema::CheckTemplatePartialSpecializationArgs(
  7212. SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
  7213. unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
  7214. // We have to be conservative when checking a template in a dependent
  7215. // context.
  7216. if (PrimaryTemplate->getDeclContext()->isDependentContext())
  7217. return false;
  7218. TemplateParameterList *TemplateParams =
  7219. PrimaryTemplate->getTemplateParameters();
  7220. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  7221. NonTypeTemplateParmDecl *Param
  7222. = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
  7223. if (!Param)
  7224. continue;
  7225. if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
  7226. Param, &TemplateArgs[I],
  7227. 1, I >= NumExplicit))
  7228. return true;
  7229. }
  7230. return false;
  7231. }
  7232. DeclResult Sema::ActOnClassTemplateSpecialization(
  7233. Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  7234. SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
  7235. TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
  7236. MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
  7237. assert(TUK != TUK_Reference && "References are not specializations");
  7238. // NOTE: KWLoc is the location of the tag keyword. This will instead
  7239. // store the location of the outermost template keyword in the declaration.
  7240. SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
  7241. ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
  7242. SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
  7243. SourceLocation LAngleLoc = TemplateId.LAngleLoc;
  7244. SourceLocation RAngleLoc = TemplateId.RAngleLoc;
  7245. // Find the class template we're specializing
  7246. TemplateName Name = TemplateId.Template.get();
  7247. ClassTemplateDecl *ClassTemplate
  7248. = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
  7249. if (!ClassTemplate) {
  7250. Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
  7251. << (Name.getAsTemplateDecl() &&
  7252. isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
  7253. return true;
  7254. }
  7255. bool isMemberSpecialization = false;
  7256. bool isPartialSpecialization = false;
  7257. // Check the validity of the template headers that introduce this
  7258. // template.
  7259. // FIXME: We probably shouldn't complain about these headers for
  7260. // friend declarations.
  7261. bool Invalid = false;
  7262. TemplateParameterList *TemplateParams =
  7263. MatchTemplateParametersToScopeSpecifier(
  7264. KWLoc, TemplateNameLoc, SS, &TemplateId,
  7265. TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
  7266. Invalid);
  7267. if (Invalid)
  7268. return true;
  7269. // Check that we can declare a template specialization here.
  7270. if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
  7271. return true;
  7272. if (TemplateParams && TemplateParams->size() > 0) {
  7273. isPartialSpecialization = true;
  7274. if (TUK == TUK_Friend) {
  7275. Diag(KWLoc, diag::err_partial_specialization_friend)
  7276. << SourceRange(LAngleLoc, RAngleLoc);
  7277. return true;
  7278. }
  7279. // C++ [temp.class.spec]p10:
  7280. // The template parameter list of a specialization shall not
  7281. // contain default template argument values.
  7282. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  7283. Decl *Param = TemplateParams->getParam(I);
  7284. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  7285. if (TTP->hasDefaultArgument()) {
  7286. Diag(TTP->getDefaultArgumentLoc(),
  7287. diag::err_default_arg_in_partial_spec);
  7288. TTP->removeDefaultArgument();
  7289. }
  7290. } else if (NonTypeTemplateParmDecl *NTTP
  7291. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  7292. if (Expr *DefArg = NTTP->getDefaultArgument()) {
  7293. Diag(NTTP->getDefaultArgumentLoc(),
  7294. diag::err_default_arg_in_partial_spec)
  7295. << DefArg->getSourceRange();
  7296. NTTP->removeDefaultArgument();
  7297. }
  7298. } else {
  7299. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
  7300. if (TTP->hasDefaultArgument()) {
  7301. Diag(TTP->getDefaultArgument().getLocation(),
  7302. diag::err_default_arg_in_partial_spec)
  7303. << TTP->getDefaultArgument().getSourceRange();
  7304. TTP->removeDefaultArgument();
  7305. }
  7306. }
  7307. }
  7308. } else if (TemplateParams) {
  7309. if (TUK == TUK_Friend)
  7310. Diag(KWLoc, diag::err_template_spec_friend)
  7311. << FixItHint::CreateRemoval(
  7312. SourceRange(TemplateParams->getTemplateLoc(),
  7313. TemplateParams->getRAngleLoc()))
  7314. << SourceRange(LAngleLoc, RAngleLoc);
  7315. } else {
  7316. assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
  7317. }
  7318. // Check that the specialization uses the same tag kind as the
  7319. // original template.
  7320. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7321. assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
  7322. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  7323. Kind, TUK == TUK_Definition, KWLoc,
  7324. ClassTemplate->getIdentifier())) {
  7325. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7326. << ClassTemplate
  7327. << FixItHint::CreateReplacement(KWLoc,
  7328. ClassTemplate->getTemplatedDecl()->getKindName());
  7329. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  7330. diag::note_previous_use);
  7331. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  7332. }
  7333. // Translate the parser's template argument list in our AST format.
  7334. TemplateArgumentListInfo TemplateArgs =
  7335. makeTemplateArgumentListInfo(*this, TemplateId);
  7336. // Check for unexpanded parameter packs in any of the template arguments.
  7337. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  7338. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  7339. UPPC_PartialSpecialization))
  7340. return true;
  7341. // Check that the template argument list is well-formed for this
  7342. // template.
  7343. SmallVector<TemplateArgument, 4> Converted;
  7344. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
  7345. TemplateArgs, false, Converted,
  7346. /*UpdateArgsWithConversions=*/true))
  7347. return true;
  7348. // Find the class template (partial) specialization declaration that
  7349. // corresponds to these arguments.
  7350. if (isPartialSpecialization) {
  7351. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
  7352. TemplateArgs.size(), Converted))
  7353. return true;
  7354. // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
  7355. // also do it during instantiation.
  7356. if (!Name.isDependent() &&
  7357. !TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
  7358. Converted)) {
  7359. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  7360. << ClassTemplate->getDeclName();
  7361. isPartialSpecialization = false;
  7362. }
  7363. }
  7364. void *InsertPos = nullptr;
  7365. ClassTemplateSpecializationDecl *PrevDecl = nullptr;
  7366. if (isPartialSpecialization)
  7367. PrevDecl = ClassTemplate->findPartialSpecialization(Converted,
  7368. TemplateParams,
  7369. InsertPos);
  7370. else
  7371. PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
  7372. ClassTemplateSpecializationDecl *Specialization = nullptr;
  7373. // Check whether we can declare a class template specialization in
  7374. // the current scope.
  7375. if (TUK != TUK_Friend &&
  7376. CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
  7377. TemplateNameLoc,
  7378. isPartialSpecialization))
  7379. return true;
  7380. // The canonical type
  7381. QualType CanonType;
  7382. if (isPartialSpecialization) {
  7383. // Build the canonical type that describes the converted template
  7384. // arguments of the class template partial specialization.
  7385. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  7386. CanonType = Context.getTemplateSpecializationType(CanonTemplate,
  7387. Converted);
  7388. if (Context.hasSameType(CanonType,
  7389. ClassTemplate->getInjectedClassNameSpecialization()) &&
  7390. (!Context.getLangOpts().CPlusPlus20 ||
  7391. !TemplateParams->hasAssociatedConstraints())) {
  7392. // C++ [temp.class.spec]p9b3:
  7393. //
  7394. // -- The argument list of the specialization shall not be identical
  7395. // to the implicit argument list of the primary template.
  7396. //
  7397. // This rule has since been removed, because it's redundant given DR1495,
  7398. // but we keep it because it produces better diagnostics and recovery.
  7399. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  7400. << /*class template*/0 << (TUK == TUK_Definition)
  7401. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  7402. return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
  7403. ClassTemplate->getIdentifier(),
  7404. TemplateNameLoc,
  7405. Attr,
  7406. TemplateParams,
  7407. AS_none, /*ModulePrivateLoc=*/SourceLocation(),
  7408. /*FriendLoc*/SourceLocation(),
  7409. TemplateParameterLists.size() - 1,
  7410. TemplateParameterLists.data());
  7411. }
  7412. // Create a new class template partial specialization declaration node.
  7413. ClassTemplatePartialSpecializationDecl *PrevPartial
  7414. = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
  7415. ClassTemplatePartialSpecializationDecl *Partial
  7416. = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
  7417. ClassTemplate->getDeclContext(),
  7418. KWLoc, TemplateNameLoc,
  7419. TemplateParams,
  7420. ClassTemplate,
  7421. Converted,
  7422. TemplateArgs,
  7423. CanonType,
  7424. PrevPartial);
  7425. SetNestedNameSpecifier(*this, Partial, SS);
  7426. if (TemplateParameterLists.size() > 1 && SS.isSet()) {
  7427. Partial->setTemplateParameterListsInfo(
  7428. Context, TemplateParameterLists.drop_back(1));
  7429. }
  7430. if (!PrevPartial)
  7431. ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
  7432. Specialization = Partial;
  7433. // If we are providing an explicit specialization of a member class
  7434. // template specialization, make a note of that.
  7435. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  7436. PrevPartial->setMemberSpecialization();
  7437. CheckTemplatePartialSpecialization(Partial);
  7438. } else {
  7439. // Create a new class template specialization declaration node for
  7440. // this explicit specialization or friend declaration.
  7441. Specialization
  7442. = ClassTemplateSpecializationDecl::Create(Context, Kind,
  7443. ClassTemplate->getDeclContext(),
  7444. KWLoc, TemplateNameLoc,
  7445. ClassTemplate,
  7446. Converted,
  7447. PrevDecl);
  7448. SetNestedNameSpecifier(*this, Specialization, SS);
  7449. if (TemplateParameterLists.size() > 0) {
  7450. Specialization->setTemplateParameterListsInfo(Context,
  7451. TemplateParameterLists);
  7452. }
  7453. if (!PrevDecl)
  7454. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  7455. if (CurContext->isDependentContext()) {
  7456. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  7457. CanonType = Context.getTemplateSpecializationType(
  7458. CanonTemplate, Converted);
  7459. } else {
  7460. CanonType = Context.getTypeDeclType(Specialization);
  7461. }
  7462. }
  7463. // C++ [temp.expl.spec]p6:
  7464. // If a template, a member template or the member of a class template is
  7465. // explicitly specialized then that specialization shall be declared
  7466. // before the first use of that specialization that would cause an implicit
  7467. // instantiation to take place, in every translation unit in which such a
  7468. // use occurs; no diagnostic is required.
  7469. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  7470. bool Okay = false;
  7471. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  7472. // Is there any previous explicit specialization declaration?
  7473. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  7474. Okay = true;
  7475. break;
  7476. }
  7477. }
  7478. if (!Okay) {
  7479. SourceRange Range(TemplateNameLoc, RAngleLoc);
  7480. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  7481. << Context.getTypeDeclType(Specialization) << Range;
  7482. Diag(PrevDecl->getPointOfInstantiation(),
  7483. diag::note_instantiation_required_here)
  7484. << (PrevDecl->getTemplateSpecializationKind()
  7485. != TSK_ImplicitInstantiation);
  7486. return true;
  7487. }
  7488. }
  7489. // If this is not a friend, note that this is an explicit specialization.
  7490. if (TUK != TUK_Friend)
  7491. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  7492. // Check that this isn't a redefinition of this specialization.
  7493. if (TUK == TUK_Definition) {
  7494. RecordDecl *Def = Specialization->getDefinition();
  7495. NamedDecl *Hidden = nullptr;
  7496. if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  7497. SkipBody->ShouldSkip = true;
  7498. SkipBody->Previous = Def;
  7499. makeMergedDefinitionVisible(Hidden);
  7500. } else if (Def) {
  7501. SourceRange Range(TemplateNameLoc, RAngleLoc);
  7502. Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
  7503. Diag(Def->getLocation(), diag::note_previous_definition);
  7504. Specialization->setInvalidDecl();
  7505. return true;
  7506. }
  7507. }
  7508. ProcessDeclAttributeList(S, Specialization, Attr);
  7509. // Add alignment attributes if necessary; these attributes are checked when
  7510. // the ASTContext lays out the structure.
  7511. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  7512. AddAlignmentAttributesForRecord(Specialization);
  7513. AddMsStructLayoutForRecord(Specialization);
  7514. }
  7515. if (ModulePrivateLoc.isValid())
  7516. Diag(Specialization->getLocation(), diag::err_module_private_specialization)
  7517. << (isPartialSpecialization? 1 : 0)
  7518. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7519. // Build the fully-sugared type for this class template
  7520. // specialization as the user wrote in the specialization
  7521. // itself. This means that we'll pretty-print the type retrieved
  7522. // from the specialization's declaration the way that the user
  7523. // actually wrote the specialization, rather than formatting the
  7524. // name based on the "canonical" representation used to store the
  7525. // template arguments in the specialization.
  7526. TypeSourceInfo *WrittenTy
  7527. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  7528. TemplateArgs, CanonType);
  7529. if (TUK != TUK_Friend) {
  7530. Specialization->setTypeAsWritten(WrittenTy);
  7531. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  7532. }
  7533. // C++ [temp.expl.spec]p9:
  7534. // A template explicit specialization is in the scope of the
  7535. // namespace in which the template was defined.
  7536. //
  7537. // We actually implement this paragraph where we set the semantic
  7538. // context (in the creation of the ClassTemplateSpecializationDecl),
  7539. // but we also maintain the lexical context where the actual
  7540. // definition occurs.
  7541. Specialization->setLexicalDeclContext(CurContext);
  7542. // We may be starting the definition of this specialization.
  7543. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  7544. Specialization->startDefinition();
  7545. if (TUK == TUK_Friend) {
  7546. FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
  7547. TemplateNameLoc,
  7548. WrittenTy,
  7549. /*FIXME:*/KWLoc);
  7550. Friend->setAccess(AS_public);
  7551. CurContext->addDecl(Friend);
  7552. } else {
  7553. // Add the specialization into its lexical context, so that it can
  7554. // be seen when iterating through the list of declarations in that
  7555. // context. However, specializations are not found by name lookup.
  7556. CurContext->addDecl(Specialization);
  7557. }
  7558. if (SkipBody && SkipBody->ShouldSkip)
  7559. return SkipBody->Previous;
  7560. return Specialization;
  7561. }
  7562. Decl *Sema::ActOnTemplateDeclarator(Scope *S,
  7563. MultiTemplateParamsArg TemplateParameterLists,
  7564. Declarator &D) {
  7565. Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
  7566. ActOnDocumentableDecl(NewDecl);
  7567. return NewDecl;
  7568. }
  7569. Decl *Sema::ActOnConceptDefinition(Scope *S,
  7570. MultiTemplateParamsArg TemplateParameterLists,
  7571. IdentifierInfo *Name, SourceLocation NameLoc,
  7572. Expr *ConstraintExpr) {
  7573. DeclContext *DC = CurContext;
  7574. if (!DC->getRedeclContext()->isFileContext()) {
  7575. Diag(NameLoc,
  7576. diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
  7577. return nullptr;
  7578. }
  7579. if (TemplateParameterLists.size() > 1) {
  7580. Diag(NameLoc, diag::err_concept_extra_headers);
  7581. return nullptr;
  7582. }
  7583. if (TemplateParameterLists.front()->size() == 0) {
  7584. Diag(NameLoc, diag::err_concept_no_parameters);
  7585. return nullptr;
  7586. }
  7587. if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
  7588. return nullptr;
  7589. ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
  7590. TemplateParameterLists.front(),
  7591. ConstraintExpr);
  7592. if (NewDecl->hasAssociatedConstraints()) {
  7593. // C++2a [temp.concept]p4:
  7594. // A concept shall not have associated constraints.
  7595. Diag(NameLoc, diag::err_concept_no_associated_constraints);
  7596. NewDecl->setInvalidDecl();
  7597. }
  7598. // Check for conflicting previous declaration.
  7599. DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
  7600. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  7601. ForVisibleRedeclaration);
  7602. LookupName(Previous, S);
  7603. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
  7604. /*AllowInlineNamespace*/false);
  7605. if (!Previous.empty()) {
  7606. auto *Old = Previous.getRepresentativeDecl();
  7607. Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
  7608. diag::err_redefinition_different_kind) << NewDecl->getDeclName();
  7609. Diag(Old->getLocation(), diag::note_previous_definition);
  7610. }
  7611. ActOnDocumentableDecl(NewDecl);
  7612. PushOnScopeChains(NewDecl, S);
  7613. return NewDecl;
  7614. }
  7615. /// \brief Strips various properties off an implicit instantiation
  7616. /// that has just been explicitly specialized.
  7617. static void StripImplicitInstantiation(NamedDecl *D) {
  7618. D->dropAttr<DLLImportAttr>();
  7619. D->dropAttr<DLLExportAttr>();
  7620. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7621. FD->setInlineSpecified(false);
  7622. }
  7623. /// Compute the diagnostic location for an explicit instantiation
  7624. // declaration or definition.
  7625. static SourceLocation DiagLocForExplicitInstantiation(
  7626. NamedDecl* D, SourceLocation PointOfInstantiation) {
  7627. // Explicit instantiations following a specialization have no effect and
  7628. // hence no PointOfInstantiation. In that case, walk decl backwards
  7629. // until a valid name loc is found.
  7630. SourceLocation PrevDiagLoc = PointOfInstantiation;
  7631. for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
  7632. Prev = Prev->getPreviousDecl()) {
  7633. PrevDiagLoc = Prev->getLocation();
  7634. }
  7635. assert(PrevDiagLoc.isValid() &&
  7636. "Explicit instantiation without point of instantiation?");
  7637. return PrevDiagLoc;
  7638. }
  7639. /// Diagnose cases where we have an explicit template specialization
  7640. /// before/after an explicit template instantiation, producing diagnostics
  7641. /// for those cases where they are required and determining whether the
  7642. /// new specialization/instantiation will have any effect.
  7643. ///
  7644. /// \param NewLoc the location of the new explicit specialization or
  7645. /// instantiation.
  7646. ///
  7647. /// \param NewTSK the kind of the new explicit specialization or instantiation.
  7648. ///
  7649. /// \param PrevDecl the previous declaration of the entity.
  7650. ///
  7651. /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
  7652. ///
  7653. /// \param PrevPointOfInstantiation if valid, indicates where the previous
  7654. /// declaration was instantiated (either implicitly or explicitly).
  7655. ///
  7656. /// \param HasNoEffect will be set to true to indicate that the new
  7657. /// specialization or instantiation has no effect and should be ignored.
  7658. ///
  7659. /// \returns true if there was an error that should prevent the introduction of
  7660. /// the new declaration into the AST, false otherwise.
  7661. bool
  7662. Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
  7663. TemplateSpecializationKind NewTSK,
  7664. NamedDecl *PrevDecl,
  7665. TemplateSpecializationKind PrevTSK,
  7666. SourceLocation PrevPointOfInstantiation,
  7667. bool &HasNoEffect) {
  7668. HasNoEffect = false;
  7669. switch (NewTSK) {
  7670. case TSK_Undeclared:
  7671. case TSK_ImplicitInstantiation:
  7672. assert(
  7673. (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
  7674. "previous declaration must be implicit!");
  7675. return false;
  7676. case TSK_ExplicitSpecialization:
  7677. switch (PrevTSK) {
  7678. case TSK_Undeclared:
  7679. case TSK_ExplicitSpecialization:
  7680. // Okay, we're just specializing something that is either already
  7681. // explicitly specialized or has merely been mentioned without any
  7682. // instantiation.
  7683. return false;
  7684. case TSK_ImplicitInstantiation:
  7685. if (PrevPointOfInstantiation.isInvalid()) {
  7686. // The declaration itself has not actually been instantiated, so it is
  7687. // still okay to specialize it.
  7688. StripImplicitInstantiation(PrevDecl);
  7689. return false;
  7690. }
  7691. // Fall through
  7692. LLVM_FALLTHROUGH;
  7693. case TSK_ExplicitInstantiationDeclaration:
  7694. case TSK_ExplicitInstantiationDefinition:
  7695. assert((PrevTSK == TSK_ImplicitInstantiation ||
  7696. PrevPointOfInstantiation.isValid()) &&
  7697. "Explicit instantiation without point of instantiation?");
  7698. // C++ [temp.expl.spec]p6:
  7699. // If a template, a member template or the member of a class template
  7700. // is explicitly specialized then that specialization shall be declared
  7701. // before the first use of that specialization that would cause an
  7702. // implicit instantiation to take place, in every translation unit in
  7703. // which such a use occurs; no diagnostic is required.
  7704. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  7705. // Is there any previous explicit specialization declaration?
  7706. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
  7707. return false;
  7708. }
  7709. Diag(NewLoc, diag::err_specialization_after_instantiation)
  7710. << PrevDecl;
  7711. Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
  7712. << (PrevTSK != TSK_ImplicitInstantiation);
  7713. return true;
  7714. }
  7715. llvm_unreachable("The switch over PrevTSK must be exhaustive.");
  7716. case TSK_ExplicitInstantiationDeclaration:
  7717. switch (PrevTSK) {
  7718. case TSK_ExplicitInstantiationDeclaration:
  7719. // This explicit instantiation declaration is redundant (that's okay).
  7720. HasNoEffect = true;
  7721. return false;
  7722. case TSK_Undeclared:
  7723. case TSK_ImplicitInstantiation:
  7724. // We're explicitly instantiating something that may have already been
  7725. // implicitly instantiated; that's fine.
  7726. return false;
  7727. case TSK_ExplicitSpecialization:
  7728. // C++0x [temp.explicit]p4:
  7729. // For a given set of template parameters, if an explicit instantiation
  7730. // of a template appears after a declaration of an explicit
  7731. // specialization for that template, the explicit instantiation has no
  7732. // effect.
  7733. HasNoEffect = true;
  7734. return false;
  7735. case TSK_ExplicitInstantiationDefinition:
  7736. // C++0x [temp.explicit]p10:
  7737. // If an entity is the subject of both an explicit instantiation
  7738. // declaration and an explicit instantiation definition in the same
  7739. // translation unit, the definition shall follow the declaration.
  7740. Diag(NewLoc,
  7741. diag::err_explicit_instantiation_declaration_after_definition);
  7742. // Explicit instantiations following a specialization have no effect and
  7743. // hence no PrevPointOfInstantiation. In that case, walk decl backwards
  7744. // until a valid name loc is found.
  7745. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  7746. diag::note_explicit_instantiation_definition_here);
  7747. HasNoEffect = true;
  7748. return false;
  7749. }
  7750. llvm_unreachable("Unexpected TemplateSpecializationKind!");
  7751. case TSK_ExplicitInstantiationDefinition:
  7752. switch (PrevTSK) {
  7753. case TSK_Undeclared:
  7754. case TSK_ImplicitInstantiation:
  7755. // We're explicitly instantiating something that may have already been
  7756. // implicitly instantiated; that's fine.
  7757. return false;
  7758. case TSK_ExplicitSpecialization:
  7759. // C++ DR 259, C++0x [temp.explicit]p4:
  7760. // For a given set of template parameters, if an explicit
  7761. // instantiation of a template appears after a declaration of
  7762. // an explicit specialization for that template, the explicit
  7763. // instantiation has no effect.
  7764. Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
  7765. << PrevDecl;
  7766. Diag(PrevDecl->getLocation(),
  7767. diag::note_previous_template_specialization);
  7768. HasNoEffect = true;
  7769. return false;
  7770. case TSK_ExplicitInstantiationDeclaration:
  7771. // We're explicitly instantiating a definition for something for which we
  7772. // were previously asked to suppress instantiations. That's fine.
  7773. // C++0x [temp.explicit]p4:
  7774. // For a given set of template parameters, if an explicit instantiation
  7775. // of a template appears after a declaration of an explicit
  7776. // specialization for that template, the explicit instantiation has no
  7777. // effect.
  7778. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  7779. // Is there any previous explicit specialization declaration?
  7780. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  7781. HasNoEffect = true;
  7782. break;
  7783. }
  7784. }
  7785. return false;
  7786. case TSK_ExplicitInstantiationDefinition:
  7787. // C++0x [temp.spec]p5:
  7788. // For a given template and a given set of template-arguments,
  7789. // - an explicit instantiation definition shall appear at most once
  7790. // in a program,
  7791. // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
  7792. Diag(NewLoc, (getLangOpts().MSVCCompat)
  7793. ? diag::ext_explicit_instantiation_duplicate
  7794. : diag::err_explicit_instantiation_duplicate)
  7795. << PrevDecl;
  7796. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  7797. diag::note_previous_explicit_instantiation);
  7798. HasNoEffect = true;
  7799. return false;
  7800. }
  7801. }
  7802. llvm_unreachable("Missing specialization/instantiation case?");
  7803. }
  7804. /// Perform semantic analysis for the given dependent function
  7805. /// template specialization.
  7806. ///
  7807. /// The only possible way to get a dependent function template specialization
  7808. /// is with a friend declaration, like so:
  7809. ///
  7810. /// \code
  7811. /// template \<class T> void foo(T);
  7812. /// template \<class T> class A {
  7813. /// friend void foo<>(T);
  7814. /// };
  7815. /// \endcode
  7816. ///
  7817. /// There really isn't any useful analysis we can do here, so we
  7818. /// just store the information.
  7819. bool
  7820. Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
  7821. const TemplateArgumentListInfo &ExplicitTemplateArgs,
  7822. LookupResult &Previous) {
  7823. // Remove anything from Previous that isn't a function template in
  7824. // the correct context.
  7825. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  7826. LookupResult::Filter F = Previous.makeFilter();
  7827. enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
  7828. SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
  7829. while (F.hasNext()) {
  7830. NamedDecl *D = F.next()->getUnderlyingDecl();
  7831. if (!isa<FunctionTemplateDecl>(D)) {
  7832. F.erase();
  7833. DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
  7834. continue;
  7835. }
  7836. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  7837. D->getDeclContext()->getRedeclContext())) {
  7838. F.erase();
  7839. DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
  7840. continue;
  7841. }
  7842. }
  7843. F.done();
  7844. if (Previous.empty()) {
  7845. Diag(FD->getLocation(),
  7846. diag::err_dependent_function_template_spec_no_match);
  7847. for (auto &P : DiscardedCandidates)
  7848. Diag(P.second->getLocation(),
  7849. diag::note_dependent_function_template_spec_discard_reason)
  7850. << P.first;
  7851. return true;
  7852. }
  7853. FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
  7854. ExplicitTemplateArgs);
  7855. return false;
  7856. }
  7857. /// Perform semantic analysis for the given function template
  7858. /// specialization.
  7859. ///
  7860. /// This routine performs all of the semantic analysis required for an
  7861. /// explicit function template specialization. On successful completion,
  7862. /// the function declaration \p FD will become a function template
  7863. /// specialization.
  7864. ///
  7865. /// \param FD the function declaration, which will be updated to become a
  7866. /// function template specialization.
  7867. ///
  7868. /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
  7869. /// if any. Note that this may be valid info even when 0 arguments are
  7870. /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
  7871. /// as it anyway contains info on the angle brackets locations.
  7872. ///
  7873. /// \param Previous the set of declarations that may be specialized by
  7874. /// this function specialization.
  7875. ///
  7876. /// \param QualifiedFriend whether this is a lookup for a qualified friend
  7877. /// declaration with no explicit template argument list that might be
  7878. /// befriending a function template specialization.
  7879. bool Sema::CheckFunctionTemplateSpecialization(
  7880. FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
  7881. LookupResult &Previous, bool QualifiedFriend) {
  7882. // The set of function template specializations that could match this
  7883. // explicit function template specialization.
  7884. UnresolvedSet<8> Candidates;
  7885. TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
  7886. /*ForTakingAddress=*/false);
  7887. llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
  7888. ConvertedTemplateArgs;
  7889. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  7890. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7891. I != E; ++I) {
  7892. NamedDecl *Ovl = (*I)->getUnderlyingDecl();
  7893. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
  7894. // Only consider templates found within the same semantic lookup scope as
  7895. // FD.
  7896. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  7897. Ovl->getDeclContext()->getRedeclContext()))
  7898. continue;
  7899. // When matching a constexpr member function template specialization
  7900. // against the primary template, we don't yet know whether the
  7901. // specialization has an implicit 'const' (because we don't know whether
  7902. // it will be a static member function until we know which template it
  7903. // specializes), so adjust it now assuming it specializes this template.
  7904. QualType FT = FD->getType();
  7905. if (FD->isConstexpr()) {
  7906. CXXMethodDecl *OldMD =
  7907. dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
  7908. if (OldMD && OldMD->isConst()) {
  7909. const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
  7910. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7911. EPI.TypeQuals.addConst();
  7912. FT = Context.getFunctionType(FPT->getReturnType(),
  7913. FPT->getParamTypes(), EPI);
  7914. }
  7915. }
  7916. TemplateArgumentListInfo Args;
  7917. if (ExplicitTemplateArgs)
  7918. Args = *ExplicitTemplateArgs;
  7919. // C++ [temp.expl.spec]p11:
  7920. // A trailing template-argument can be left unspecified in the
  7921. // template-id naming an explicit function template specialization
  7922. // provided it can be deduced from the function argument type.
  7923. // Perform template argument deduction to determine whether we may be
  7924. // specializing this template.
  7925. // FIXME: It is somewhat wasteful to build
  7926. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  7927. FunctionDecl *Specialization = nullptr;
  7928. if (TemplateDeductionResult TDK = DeduceTemplateArguments(
  7929. cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
  7930. ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
  7931. Info)) {
  7932. // Template argument deduction failed; record why it failed, so
  7933. // that we can provide nifty diagnostics.
  7934. FailedCandidates.addCandidate().set(
  7935. I.getPair(), FunTmpl->getTemplatedDecl(),
  7936. MakeDeductionFailureInfo(Context, TDK, Info));
  7937. (void)TDK;
  7938. continue;
  7939. }
  7940. // Target attributes are part of the cuda function signature, so
  7941. // the deduced template's cuda target must match that of the
  7942. // specialization. Given that C++ template deduction does not
  7943. // take target attributes into account, we reject candidates
  7944. // here that have a different target.
  7945. if (LangOpts.CUDA &&
  7946. IdentifyCUDATarget(Specialization,
  7947. /* IgnoreImplicitHDAttr = */ true) !=
  7948. IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
  7949. FailedCandidates.addCandidate().set(
  7950. I.getPair(), FunTmpl->getTemplatedDecl(),
  7951. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  7952. continue;
  7953. }
  7954. // Record this candidate.
  7955. if (ExplicitTemplateArgs)
  7956. ConvertedTemplateArgs[Specialization] = std::move(Args);
  7957. Candidates.addDecl(Specialization, I.getAccess());
  7958. }
  7959. }
  7960. // For a qualified friend declaration (with no explicit marker to indicate
  7961. // that a template specialization was intended), note all (template and
  7962. // non-template) candidates.
  7963. if (QualifiedFriend && Candidates.empty()) {
  7964. Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
  7965. << FD->getDeclName() << FDLookupContext;
  7966. // FIXME: We should form a single candidate list and diagnose all
  7967. // candidates at once, to get proper sorting and limiting.
  7968. for (auto *OldND : Previous) {
  7969. if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
  7970. NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
  7971. }
  7972. FailedCandidates.NoteCandidates(*this, FD->getLocation());
  7973. return true;
  7974. }
  7975. // Find the most specialized function template.
  7976. UnresolvedSetIterator Result = getMostSpecialized(
  7977. Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
  7978. PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
  7979. PDiag(diag::err_function_template_spec_ambiguous)
  7980. << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
  7981. PDiag(diag::note_function_template_spec_matched));
  7982. if (Result == Candidates.end())
  7983. return true;
  7984. // Ignore access information; it doesn't figure into redeclaration checking.
  7985. FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
  7986. FunctionTemplateSpecializationInfo *SpecInfo
  7987. = Specialization->getTemplateSpecializationInfo();
  7988. assert(SpecInfo && "Function template specialization info missing?");
  7989. // Note: do not overwrite location info if previous template
  7990. // specialization kind was explicit.
  7991. TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
  7992. if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
  7993. Specialization->setLocation(FD->getLocation());
  7994. Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
  7995. // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
  7996. // function can differ from the template declaration with respect to
  7997. // the constexpr specifier.
  7998. // FIXME: We need an update record for this AST mutation.
  7999. // FIXME: What if there are multiple such prior declarations (for instance,
  8000. // from different modules)?
  8001. Specialization->setConstexprKind(FD->getConstexprKind());
  8002. }
  8003. // FIXME: Check if the prior specialization has a point of instantiation.
  8004. // If so, we have run afoul of .
  8005. // If this is a friend declaration, then we're not really declaring
  8006. // an explicit specialization.
  8007. bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
  8008. // Check the scope of this explicit specialization.
  8009. if (!isFriend &&
  8010. CheckTemplateSpecializationScope(*this,
  8011. Specialization->getPrimaryTemplate(),
  8012. Specialization, FD->getLocation(),
  8013. false))
  8014. return true;
  8015. // C++ [temp.expl.spec]p6:
  8016. // If a template, a member template or the member of a class template is
  8017. // explicitly specialized then that specialization shall be declared
  8018. // before the first use of that specialization that would cause an implicit
  8019. // instantiation to take place, in every translation unit in which such a
  8020. // use occurs; no diagnostic is required.
  8021. bool HasNoEffect = false;
  8022. if (!isFriend &&
  8023. CheckSpecializationInstantiationRedecl(FD->getLocation(),
  8024. TSK_ExplicitSpecialization,
  8025. Specialization,
  8026. SpecInfo->getTemplateSpecializationKind(),
  8027. SpecInfo->getPointOfInstantiation(),
  8028. HasNoEffect))
  8029. return true;
  8030. // Mark the prior declaration as an explicit specialization, so that later
  8031. // clients know that this is an explicit specialization.
  8032. if (!isFriend) {
  8033. // Since explicit specializations do not inherit '=delete' from their
  8034. // primary function template - check if the 'specialization' that was
  8035. // implicitly generated (during template argument deduction for partial
  8036. // ordering) from the most specialized of all the function templates that
  8037. // 'FD' could have been specializing, has a 'deleted' definition. If so,
  8038. // first check that it was implicitly generated during template argument
  8039. // deduction by making sure it wasn't referenced, and then reset the deleted
  8040. // flag to not-deleted, so that we can inherit that information from 'FD'.
  8041. if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
  8042. !Specialization->getCanonicalDecl()->isReferenced()) {
  8043. // FIXME: This assert will not hold in the presence of modules.
  8044. assert(
  8045. Specialization->getCanonicalDecl() == Specialization &&
  8046. "This must be the only existing declaration of this specialization");
  8047. // FIXME: We need an update record for this AST mutation.
  8048. Specialization->setDeletedAsWritten(false);
  8049. }
  8050. // FIXME: We need an update record for this AST mutation.
  8051. SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  8052. MarkUnusedFileScopedDecl(Specialization);
  8053. }
  8054. // Turn the given function declaration into a function template
  8055. // specialization, with the template arguments from the previous
  8056. // specialization.
  8057. // Take copies of (semantic and syntactic) template argument lists.
  8058. const TemplateArgumentList* TemplArgs = new (Context)
  8059. TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
  8060. FD->setFunctionTemplateSpecialization(
  8061. Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
  8062. SpecInfo->getTemplateSpecializationKind(),
  8063. ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
  8064. // A function template specialization inherits the target attributes
  8065. // of its template. (We require the attributes explicitly in the
  8066. // code to match, but a template may have implicit attributes by
  8067. // virtue e.g. of being constexpr, and it passes these implicit
  8068. // attributes on to its specializations.)
  8069. if (LangOpts.CUDA)
  8070. inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
  8071. // The "previous declaration" for this function template specialization is
  8072. // the prior function template specialization.
  8073. Previous.clear();
  8074. Previous.addDecl(Specialization);
  8075. return false;
  8076. }
  8077. /// Perform semantic analysis for the given non-template member
  8078. /// specialization.
  8079. ///
  8080. /// This routine performs all of the semantic analysis required for an
  8081. /// explicit member function specialization. On successful completion,
  8082. /// the function declaration \p FD will become a member function
  8083. /// specialization.
  8084. ///
  8085. /// \param Member the member declaration, which will be updated to become a
  8086. /// specialization.
  8087. ///
  8088. /// \param Previous the set of declarations, one of which may be specialized
  8089. /// by this function specialization; the set will be modified to contain the
  8090. /// redeclared member.
  8091. bool
  8092. Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
  8093. assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
  8094. // Try to find the member we are instantiating.
  8095. NamedDecl *FoundInstantiation = nullptr;
  8096. NamedDecl *Instantiation = nullptr;
  8097. NamedDecl *InstantiatedFrom = nullptr;
  8098. MemberSpecializationInfo *MSInfo = nullptr;
  8099. if (Previous.empty()) {
  8100. // Nowhere to look anyway.
  8101. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
  8102. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8103. I != E; ++I) {
  8104. NamedDecl *D = (*I)->getUnderlyingDecl();
  8105. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  8106. QualType Adjusted = Function->getType();
  8107. if (!hasExplicitCallingConv(Adjusted))
  8108. Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
  8109. // This doesn't handle deduced return types, but both function
  8110. // declarations should be undeduced at this point.
  8111. if (Context.hasSameType(Adjusted, Method->getType())) {
  8112. FoundInstantiation = *I;
  8113. Instantiation = Method;
  8114. InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
  8115. MSInfo = Method->getMemberSpecializationInfo();
  8116. break;
  8117. }
  8118. }
  8119. }
  8120. } else if (isa<VarDecl>(Member)) {
  8121. VarDecl *PrevVar;
  8122. if (Previous.isSingleResult() &&
  8123. (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
  8124. if (PrevVar->isStaticDataMember()) {
  8125. FoundInstantiation = Previous.getRepresentativeDecl();
  8126. Instantiation = PrevVar;
  8127. InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
  8128. MSInfo = PrevVar->getMemberSpecializationInfo();
  8129. }
  8130. } else if (isa<RecordDecl>(Member)) {
  8131. CXXRecordDecl *PrevRecord;
  8132. if (Previous.isSingleResult() &&
  8133. (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
  8134. FoundInstantiation = Previous.getRepresentativeDecl();
  8135. Instantiation = PrevRecord;
  8136. InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
  8137. MSInfo = PrevRecord->getMemberSpecializationInfo();
  8138. }
  8139. } else if (isa<EnumDecl>(Member)) {
  8140. EnumDecl *PrevEnum;
  8141. if (Previous.isSingleResult() &&
  8142. (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
  8143. FoundInstantiation = Previous.getRepresentativeDecl();
  8144. Instantiation = PrevEnum;
  8145. InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
  8146. MSInfo = PrevEnum->getMemberSpecializationInfo();
  8147. }
  8148. }
  8149. if (!Instantiation) {
  8150. // There is no previous declaration that matches. Since member
  8151. // specializations are always out-of-line, the caller will complain about
  8152. // this mismatch later.
  8153. return false;
  8154. }
  8155. // A member specialization in a friend declaration isn't really declaring
  8156. // an explicit specialization, just identifying a specific (possibly implicit)
  8157. // specialization. Don't change the template specialization kind.
  8158. //
  8159. // FIXME: Is this really valid? Other compilers reject.
  8160. if (Member->getFriendObjectKind() != Decl::FOK_None) {
  8161. // Preserve instantiation information.
  8162. if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
  8163. cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
  8164. cast<CXXMethodDecl>(InstantiatedFrom),
  8165. cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
  8166. } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
  8167. cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
  8168. cast<CXXRecordDecl>(InstantiatedFrom),
  8169. cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
  8170. }
  8171. Previous.clear();
  8172. Previous.addDecl(FoundInstantiation);
  8173. return false;
  8174. }
  8175. // Make sure that this is a specialization of a member.
  8176. if (!InstantiatedFrom) {
  8177. Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
  8178. << Member;
  8179. Diag(Instantiation->getLocation(), diag::note_specialized_decl);
  8180. return true;
  8181. }
  8182. // C++ [temp.expl.spec]p6:
  8183. // If a template, a member template or the member of a class template is
  8184. // explicitly specialized then that specialization shall be declared
  8185. // before the first use of that specialization that would cause an implicit
  8186. // instantiation to take place, in every translation unit in which such a
  8187. // use occurs; no diagnostic is required.
  8188. assert(MSInfo && "Member specialization info missing?");
  8189. bool HasNoEffect = false;
  8190. if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
  8191. TSK_ExplicitSpecialization,
  8192. Instantiation,
  8193. MSInfo->getTemplateSpecializationKind(),
  8194. MSInfo->getPointOfInstantiation(),
  8195. HasNoEffect))
  8196. return true;
  8197. // Check the scope of this explicit specialization.
  8198. if (CheckTemplateSpecializationScope(*this,
  8199. InstantiatedFrom,
  8200. Instantiation, Member->getLocation(),
  8201. false))
  8202. return true;
  8203. // Note that this member specialization is an "instantiation of" the
  8204. // corresponding member of the original template.
  8205. if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
  8206. FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
  8207. if (InstantiationFunction->getTemplateSpecializationKind() ==
  8208. TSK_ImplicitInstantiation) {
  8209. // Explicit specializations of member functions of class templates do not
  8210. // inherit '=delete' from the member function they are specializing.
  8211. if (InstantiationFunction->isDeleted()) {
  8212. // FIXME: This assert will not hold in the presence of modules.
  8213. assert(InstantiationFunction->getCanonicalDecl() ==
  8214. InstantiationFunction);
  8215. // FIXME: We need an update record for this AST mutation.
  8216. InstantiationFunction->setDeletedAsWritten(false);
  8217. }
  8218. }
  8219. MemberFunction->setInstantiationOfMemberFunction(
  8220. cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8221. } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
  8222. MemberVar->setInstantiationOfStaticDataMember(
  8223. cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8224. } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
  8225. MemberClass->setInstantiationOfMemberClass(
  8226. cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8227. } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
  8228. MemberEnum->setInstantiationOfMemberEnum(
  8229. cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8230. } else {
  8231. llvm_unreachable("unknown member specialization kind");
  8232. }
  8233. // Save the caller the trouble of having to figure out which declaration
  8234. // this specialization matches.
  8235. Previous.clear();
  8236. Previous.addDecl(FoundInstantiation);
  8237. return false;
  8238. }
  8239. /// Complete the explicit specialization of a member of a class template by
  8240. /// updating the instantiated member to be marked as an explicit specialization.
  8241. ///
  8242. /// \param OrigD The member declaration instantiated from the template.
  8243. /// \param Loc The location of the explicit specialization of the member.
  8244. template<typename DeclT>
  8245. static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
  8246. SourceLocation Loc) {
  8247. if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  8248. return;
  8249. // FIXME: Inform AST mutation listeners of this AST mutation.
  8250. // FIXME: If there are multiple in-class declarations of the member (from
  8251. // multiple modules, or a declaration and later definition of a member type),
  8252. // should we update all of them?
  8253. OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  8254. OrigD->setLocation(Loc);
  8255. }
  8256. void Sema::CompleteMemberSpecialization(NamedDecl *Member,
  8257. LookupResult &Previous) {
  8258. NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
  8259. if (Instantiation == Member)
  8260. return;
  8261. if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
  8262. completeMemberSpecializationImpl(*this, Function, Member->getLocation());
  8263. else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
  8264. completeMemberSpecializationImpl(*this, Var, Member->getLocation());
  8265. else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
  8266. completeMemberSpecializationImpl(*this, Record, Member->getLocation());
  8267. else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
  8268. completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
  8269. else
  8270. llvm_unreachable("unknown member specialization kind");
  8271. }
  8272. /// Check the scope of an explicit instantiation.
  8273. ///
  8274. /// \returns true if a serious error occurs, false otherwise.
  8275. static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
  8276. SourceLocation InstLoc,
  8277. bool WasQualifiedName) {
  8278. DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
  8279. DeclContext *CurContext = S.CurContext->getRedeclContext();
  8280. if (CurContext->isRecord()) {
  8281. S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
  8282. << D;
  8283. return true;
  8284. }
  8285. // C++11 [temp.explicit]p3:
  8286. // An explicit instantiation shall appear in an enclosing namespace of its
  8287. // template. If the name declared in the explicit instantiation is an
  8288. // unqualified name, the explicit instantiation shall appear in the
  8289. // namespace where its template is declared or, if that namespace is inline
  8290. // (7.3.1), any namespace from its enclosing namespace set.
  8291. //
  8292. // This is DR275, which we do not retroactively apply to C++98/03.
  8293. if (WasQualifiedName) {
  8294. if (CurContext->Encloses(OrigContext))
  8295. return false;
  8296. } else {
  8297. if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
  8298. return false;
  8299. }
  8300. if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
  8301. if (WasQualifiedName)
  8302. S.Diag(InstLoc,
  8303. S.getLangOpts().CPlusPlus11?
  8304. diag::err_explicit_instantiation_out_of_scope :
  8305. diag::warn_explicit_instantiation_out_of_scope_0x)
  8306. << D << NS;
  8307. else
  8308. S.Diag(InstLoc,
  8309. S.getLangOpts().CPlusPlus11?
  8310. diag::err_explicit_instantiation_unqualified_wrong_namespace :
  8311. diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
  8312. << D << NS;
  8313. } else
  8314. S.Diag(InstLoc,
  8315. S.getLangOpts().CPlusPlus11?
  8316. diag::err_explicit_instantiation_must_be_global :
  8317. diag::warn_explicit_instantiation_must_be_global_0x)
  8318. << D;
  8319. S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
  8320. return false;
  8321. }
  8322. /// Common checks for whether an explicit instantiation of \p D is valid.
  8323. static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
  8324. SourceLocation InstLoc,
  8325. bool WasQualifiedName,
  8326. TemplateSpecializationKind TSK) {
  8327. // C++ [temp.explicit]p13:
  8328. // An explicit instantiation declaration shall not name a specialization of
  8329. // a template with internal linkage.
  8330. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  8331. D->getFormalLinkage() == InternalLinkage) {
  8332. S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
  8333. return true;
  8334. }
  8335. // C++11 [temp.explicit]p3: [DR 275]
  8336. // An explicit instantiation shall appear in an enclosing namespace of its
  8337. // template.
  8338. if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
  8339. return true;
  8340. return false;
  8341. }
  8342. /// Determine whether the given scope specifier has a template-id in it.
  8343. static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
  8344. if (!SS.isSet())
  8345. return false;
  8346. // C++11 [temp.explicit]p3:
  8347. // If the explicit instantiation is for a member function, a member class
  8348. // or a static data member of a class template specialization, the name of
  8349. // the class template specialization in the qualified-id for the member
  8350. // name shall be a simple-template-id.
  8351. //
  8352. // C++98 has the same restriction, just worded differently.
  8353. for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
  8354. NNS = NNS->getPrefix())
  8355. if (const Type *T = NNS->getAsType())
  8356. if (isa<TemplateSpecializationType>(T))
  8357. return true;
  8358. return false;
  8359. }
  8360. /// Make a dllexport or dllimport attr on a class template specialization take
  8361. /// effect.
  8362. static void dllExportImportClassTemplateSpecialization(
  8363. Sema &S, ClassTemplateSpecializationDecl *Def) {
  8364. auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
  8365. assert(A && "dllExportImportClassTemplateSpecialization called "
  8366. "on Def without dllexport or dllimport");
  8367. // We reject explicit instantiations in class scope, so there should
  8368. // never be any delayed exported classes to worry about.
  8369. assert(S.DelayedDllExportClasses.empty() &&
  8370. "delayed exports present at explicit instantiation");
  8371. S.checkClassLevelDLLAttribute(Def);
  8372. // Propagate attribute to base class templates.
  8373. for (auto &B : Def->bases()) {
  8374. if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  8375. B.getType()->getAsCXXRecordDecl()))
  8376. S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
  8377. }
  8378. S.referenceDLLExportedClassMethods();
  8379. }
  8380. // Explicit instantiation of a class template specialization
  8381. DeclResult Sema::ActOnExplicitInstantiation(
  8382. Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
  8383. unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
  8384. TemplateTy TemplateD, SourceLocation TemplateNameLoc,
  8385. SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
  8386. SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
  8387. // Find the class template we're specializing
  8388. TemplateName Name = TemplateD.get();
  8389. TemplateDecl *TD = Name.getAsTemplateDecl();
  8390. // Check that the specialization uses the same tag kind as the
  8391. // original template.
  8392. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  8393. assert(Kind != TTK_Enum &&
  8394. "Invalid enum tag in class template explicit instantiation!");
  8395. ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
  8396. if (!ClassTemplate) {
  8397. NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
  8398. Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
  8399. Diag(TD->getLocation(), diag::note_previous_use);
  8400. return true;
  8401. }
  8402. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  8403. Kind, /*isDefinition*/false, KWLoc,
  8404. ClassTemplate->getIdentifier())) {
  8405. Diag(KWLoc, diag::err_use_with_wrong_tag)
  8406. << ClassTemplate
  8407. << FixItHint::CreateReplacement(KWLoc,
  8408. ClassTemplate->getTemplatedDecl()->getKindName());
  8409. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  8410. diag::note_previous_use);
  8411. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  8412. }
  8413. // C++0x [temp.explicit]p2:
  8414. // There are two forms of explicit instantiation: an explicit instantiation
  8415. // definition and an explicit instantiation declaration. An explicit
  8416. // instantiation declaration begins with the extern keyword. [...]
  8417. TemplateSpecializationKind TSK = ExternLoc.isInvalid()
  8418. ? TSK_ExplicitInstantiationDefinition
  8419. : TSK_ExplicitInstantiationDeclaration;
  8420. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  8421. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  8422. // Check for dllexport class template instantiation declarations,
  8423. // except for MinGW mode.
  8424. for (const ParsedAttr &AL : Attr) {
  8425. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  8426. Diag(ExternLoc,
  8427. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  8428. Diag(AL.getLoc(), diag::note_attribute);
  8429. break;
  8430. }
  8431. }
  8432. if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
  8433. Diag(ExternLoc,
  8434. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  8435. Diag(A->getLocation(), diag::note_attribute);
  8436. }
  8437. }
  8438. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  8439. // instantiation declarations for most purposes.
  8440. bool DLLImportExplicitInstantiationDef = false;
  8441. if (TSK == TSK_ExplicitInstantiationDefinition &&
  8442. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  8443. // Check for dllimport class template instantiation definitions.
  8444. bool DLLImport =
  8445. ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
  8446. for (const ParsedAttr &AL : Attr) {
  8447. if (AL.getKind() == ParsedAttr::AT_DLLImport)
  8448. DLLImport = true;
  8449. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  8450. // dllexport trumps dllimport here.
  8451. DLLImport = false;
  8452. break;
  8453. }
  8454. }
  8455. if (DLLImport) {
  8456. TSK = TSK_ExplicitInstantiationDeclaration;
  8457. DLLImportExplicitInstantiationDef = true;
  8458. }
  8459. }
  8460. // Translate the parser's template argument list in our AST format.
  8461. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  8462. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  8463. // Check that the template argument list is well-formed for this
  8464. // template.
  8465. SmallVector<TemplateArgument, 4> Converted;
  8466. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
  8467. TemplateArgs, false, Converted,
  8468. /*UpdateArgsWithConversions=*/true))
  8469. return true;
  8470. // Find the class template specialization declaration that
  8471. // corresponds to these arguments.
  8472. void *InsertPos = nullptr;
  8473. ClassTemplateSpecializationDecl *PrevDecl
  8474. = ClassTemplate->findSpecialization(Converted, InsertPos);
  8475. TemplateSpecializationKind PrevDecl_TSK
  8476. = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
  8477. if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
  8478. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  8479. // Check for dllexport class template instantiation definitions in MinGW
  8480. // mode, if a previous declaration of the instantiation was seen.
  8481. for (const ParsedAttr &AL : Attr) {
  8482. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  8483. Diag(AL.getLoc(),
  8484. diag::warn_attribute_dllexport_explicit_instantiation_def);
  8485. break;
  8486. }
  8487. }
  8488. }
  8489. if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
  8490. SS.isSet(), TSK))
  8491. return true;
  8492. ClassTemplateSpecializationDecl *Specialization = nullptr;
  8493. bool HasNoEffect = false;
  8494. if (PrevDecl) {
  8495. if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
  8496. PrevDecl, PrevDecl_TSK,
  8497. PrevDecl->getPointOfInstantiation(),
  8498. HasNoEffect))
  8499. return PrevDecl;
  8500. // Even though HasNoEffect == true means that this explicit instantiation
  8501. // has no effect on semantics, we go on to put its syntax in the AST.
  8502. if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
  8503. PrevDecl_TSK == TSK_Undeclared) {
  8504. // Since the only prior class template specialization with these
  8505. // arguments was referenced but not declared, reuse that
  8506. // declaration node as our own, updating the source location
  8507. // for the template name to reflect our new declaration.
  8508. // (Other source locations will be updated later.)
  8509. Specialization = PrevDecl;
  8510. Specialization->setLocation(TemplateNameLoc);
  8511. PrevDecl = nullptr;
  8512. }
  8513. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  8514. DLLImportExplicitInstantiationDef) {
  8515. // The new specialization might add a dllimport attribute.
  8516. HasNoEffect = false;
  8517. }
  8518. }
  8519. if (!Specialization) {
  8520. // Create a new class template specialization declaration node for
  8521. // this explicit specialization.
  8522. Specialization
  8523. = ClassTemplateSpecializationDecl::Create(Context, Kind,
  8524. ClassTemplate->getDeclContext(),
  8525. KWLoc, TemplateNameLoc,
  8526. ClassTemplate,
  8527. Converted,
  8528. PrevDecl);
  8529. SetNestedNameSpecifier(*this, Specialization, SS);
  8530. if (!HasNoEffect && !PrevDecl) {
  8531. // Insert the new specialization.
  8532. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  8533. }
  8534. }
  8535. // Build the fully-sugared type for this explicit instantiation as
  8536. // the user wrote in the explicit instantiation itself. This means
  8537. // that we'll pretty-print the type retrieved from the
  8538. // specialization's declaration the way that the user actually wrote
  8539. // the explicit instantiation, rather than formatting the name based
  8540. // on the "canonical" representation used to store the template
  8541. // arguments in the specialization.
  8542. TypeSourceInfo *WrittenTy
  8543. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  8544. TemplateArgs,
  8545. Context.getTypeDeclType(Specialization));
  8546. Specialization->setTypeAsWritten(WrittenTy);
  8547. // Set source locations for keywords.
  8548. Specialization->setExternLoc(ExternLoc);
  8549. Specialization->setTemplateKeywordLoc(TemplateLoc);
  8550. Specialization->setBraceRange(SourceRange());
  8551. bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
  8552. ProcessDeclAttributeList(S, Specialization, Attr);
  8553. // Add the explicit instantiation into its lexical context. However,
  8554. // since explicit instantiations are never found by name lookup, we
  8555. // just put it into the declaration context directly.
  8556. Specialization->setLexicalDeclContext(CurContext);
  8557. CurContext->addDecl(Specialization);
  8558. // Syntax is now OK, so return if it has no other effect on semantics.
  8559. if (HasNoEffect) {
  8560. // Set the template specialization kind.
  8561. Specialization->setTemplateSpecializationKind(TSK);
  8562. return Specialization;
  8563. }
  8564. // C++ [temp.explicit]p3:
  8565. // A definition of a class template or class member template
  8566. // shall be in scope at the point of the explicit instantiation of
  8567. // the class template or class member template.
  8568. //
  8569. // This check comes when we actually try to perform the
  8570. // instantiation.
  8571. ClassTemplateSpecializationDecl *Def
  8572. = cast_or_null<ClassTemplateSpecializationDecl>(
  8573. Specialization->getDefinition());
  8574. if (!Def)
  8575. InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
  8576. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  8577. MarkVTableUsed(TemplateNameLoc, Specialization, true);
  8578. Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
  8579. }
  8580. // Instantiate the members of this class template specialization.
  8581. Def = cast_or_null<ClassTemplateSpecializationDecl>(
  8582. Specialization->getDefinition());
  8583. if (Def) {
  8584. TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
  8585. // Fix a TSK_ExplicitInstantiationDeclaration followed by a
  8586. // TSK_ExplicitInstantiationDefinition
  8587. if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
  8588. (TSK == TSK_ExplicitInstantiationDefinition ||
  8589. DLLImportExplicitInstantiationDef)) {
  8590. // FIXME: Need to notify the ASTMutationListener that we did this.
  8591. Def->setTemplateSpecializationKind(TSK);
  8592. if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
  8593. (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  8594. !Context.getTargetInfo().getTriple().isPS4CPU())) {
  8595. // An explicit instantiation definition can add a dll attribute to a
  8596. // template with a previous instantiation declaration. MinGW doesn't
  8597. // allow this.
  8598. auto *A = cast<InheritableAttr>(
  8599. getDLLAttr(Specialization)->clone(getASTContext()));
  8600. A->setInherited(true);
  8601. Def->addAttr(A);
  8602. dllExportImportClassTemplateSpecialization(*this, Def);
  8603. }
  8604. }
  8605. // Fix a TSK_ImplicitInstantiation followed by a
  8606. // TSK_ExplicitInstantiationDefinition
  8607. bool NewlyDLLExported =
  8608. !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
  8609. if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
  8610. (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  8611. !Context.getTargetInfo().getTriple().isPS4CPU())) {
  8612. // An explicit instantiation definition can add a dll attribute to a
  8613. // template with a previous implicit instantiation. MinGW doesn't allow
  8614. // this. We limit clang to only adding dllexport, to avoid potentially
  8615. // strange codegen behavior. For example, if we extend this conditional
  8616. // to dllimport, and we have a source file calling a method on an
  8617. // implicitly instantiated template class instance and then declaring a
  8618. // dllimport explicit instantiation definition for the same template
  8619. // class, the codegen for the method call will not respect the dllimport,
  8620. // while it will with cl. The Def will already have the DLL attribute,
  8621. // since the Def and Specialization will be the same in the case of
  8622. // Old_TSK == TSK_ImplicitInstantiation, and we already added the
  8623. // attribute to the Specialization; we just need to make it take effect.
  8624. assert(Def == Specialization &&
  8625. "Def and Specialization should match for implicit instantiation");
  8626. dllExportImportClassTemplateSpecialization(*this, Def);
  8627. }
  8628. // In MinGW mode, export the template instantiation if the declaration
  8629. // was marked dllexport.
  8630. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  8631. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
  8632. PrevDecl->hasAttr<DLLExportAttr>()) {
  8633. dllExportImportClassTemplateSpecialization(*this, Def);
  8634. }
  8635. if (Def->hasAttr<MSInheritanceAttr>()) {
  8636. Specialization->addAttr(Def->getAttr<MSInheritanceAttr>());
  8637. Consumer.AssignInheritanceModel(Specialization);
  8638. }
  8639. // Set the template specialization kind. Make sure it is set before
  8640. // instantiating the members which will trigger ASTConsumer callbacks.
  8641. Specialization->setTemplateSpecializationKind(TSK);
  8642. InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
  8643. } else {
  8644. // Set the template specialization kind.
  8645. Specialization->setTemplateSpecializationKind(TSK);
  8646. }
  8647. return Specialization;
  8648. }
  8649. // Explicit instantiation of a member class of a class template.
  8650. DeclResult
  8651. Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
  8652. SourceLocation TemplateLoc, unsigned TagSpec,
  8653. SourceLocation KWLoc, CXXScopeSpec &SS,
  8654. IdentifierInfo *Name, SourceLocation NameLoc,
  8655. const ParsedAttributesView &Attr) {
  8656. bool Owned = false;
  8657. bool IsDependent = false;
  8658. Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
  8659. KWLoc, SS, Name, NameLoc, Attr, AS_none,
  8660. /*ModulePrivateLoc=*/SourceLocation(),
  8661. MultiTemplateParamsArg(), Owned, IsDependent,
  8662. SourceLocation(), false, TypeResult(),
  8663. /*IsTypeSpecifier*/false,
  8664. /*IsTemplateParamOrArg*/false);
  8665. assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
  8666. if (!TagD)
  8667. return true;
  8668. TagDecl *Tag = cast<TagDecl>(TagD);
  8669. assert(!Tag->isEnum() && "shouldn't see enumerations here");
  8670. if (Tag->isInvalidDecl())
  8671. return true;
  8672. CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
  8673. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  8674. if (!Pattern) {
  8675. Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
  8676. << Context.getTypeDeclType(Record);
  8677. Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
  8678. return true;
  8679. }
  8680. // C++0x [temp.explicit]p2:
  8681. // If the explicit instantiation is for a class or member class, the
  8682. // elaborated-type-specifier in the declaration shall include a
  8683. // simple-template-id.
  8684. //
  8685. // C++98 has the same restriction, just worded differently.
  8686. if (!ScopeSpecifierHasTemplateId(SS))
  8687. Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
  8688. << Record << SS.getRange();
  8689. // C++0x [temp.explicit]p2:
  8690. // There are two forms of explicit instantiation: an explicit instantiation
  8691. // definition and an explicit instantiation declaration. An explicit
  8692. // instantiation declaration begins with the extern keyword. [...]
  8693. TemplateSpecializationKind TSK
  8694. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  8695. : TSK_ExplicitInstantiationDeclaration;
  8696. CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
  8697. // Verify that it is okay to explicitly instantiate here.
  8698. CXXRecordDecl *PrevDecl
  8699. = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
  8700. if (!PrevDecl && Record->getDefinition())
  8701. PrevDecl = Record;
  8702. if (PrevDecl) {
  8703. MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
  8704. bool HasNoEffect = false;
  8705. assert(MSInfo && "No member specialization information?");
  8706. if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
  8707. PrevDecl,
  8708. MSInfo->getTemplateSpecializationKind(),
  8709. MSInfo->getPointOfInstantiation(),
  8710. HasNoEffect))
  8711. return true;
  8712. if (HasNoEffect)
  8713. return TagD;
  8714. }
  8715. CXXRecordDecl *RecordDef
  8716. = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  8717. if (!RecordDef) {
  8718. // C++ [temp.explicit]p3:
  8719. // A definition of a member class of a class template shall be in scope
  8720. // at the point of an explicit instantiation of the member class.
  8721. CXXRecordDecl *Def
  8722. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  8723. if (!Def) {
  8724. Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
  8725. << 0 << Record->getDeclName() << Record->getDeclContext();
  8726. Diag(Pattern->getLocation(), diag::note_forward_declaration)
  8727. << Pattern;
  8728. return true;
  8729. } else {
  8730. if (InstantiateClass(NameLoc, Record, Def,
  8731. getTemplateInstantiationArgs(Record),
  8732. TSK))
  8733. return true;
  8734. RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  8735. if (!RecordDef)
  8736. return true;
  8737. }
  8738. }
  8739. // Instantiate all of the members of the class.
  8740. InstantiateClassMembers(NameLoc, RecordDef,
  8741. getTemplateInstantiationArgs(Record), TSK);
  8742. if (TSK == TSK_ExplicitInstantiationDefinition)
  8743. MarkVTableUsed(NameLoc, RecordDef, true);
  8744. // FIXME: We don't have any representation for explicit instantiations of
  8745. // member classes. Such a representation is not needed for compilation, but it
  8746. // should be available for clients that want to see all of the declarations in
  8747. // the source code.
  8748. return TagD;
  8749. }
  8750. DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
  8751. SourceLocation ExternLoc,
  8752. SourceLocation TemplateLoc,
  8753. Declarator &D) {
  8754. // Explicit instantiations always require a name.
  8755. // TODO: check if/when DNInfo should replace Name.
  8756. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  8757. DeclarationName Name = NameInfo.getName();
  8758. if (!Name) {
  8759. if (!D.isInvalidType())
  8760. Diag(D.getDeclSpec().getBeginLoc(),
  8761. diag::err_explicit_instantiation_requires_name)
  8762. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  8763. return true;
  8764. }
  8765. // The scope passed in may not be a decl scope. Zip up the scope tree until
  8766. // we find one that is.
  8767. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  8768. (S->getFlags() & Scope::TemplateParamScope) != 0)
  8769. S = S->getParent();
  8770. // Determine the type of the declaration.
  8771. TypeSourceInfo *T = GetTypeForDeclarator(D, S);
  8772. QualType R = T->getType();
  8773. if (R.isNull())
  8774. return true;
  8775. // C++ [dcl.stc]p1:
  8776. // A storage-class-specifier shall not be specified in [...] an explicit
  8777. // instantiation (14.7.2) directive.
  8778. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  8779. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
  8780. << Name;
  8781. return true;
  8782. } else if (D.getDeclSpec().getStorageClassSpec()
  8783. != DeclSpec::SCS_unspecified) {
  8784. // Complain about then remove the storage class specifier.
  8785. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
  8786. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  8787. D.getMutableDeclSpec().ClearStorageClassSpecs();
  8788. }
  8789. // C++0x [temp.explicit]p1:
  8790. // [...] An explicit instantiation of a function template shall not use the
  8791. // inline or constexpr specifiers.
  8792. // Presumably, this also applies to member functions of class templates as
  8793. // well.
  8794. if (D.getDeclSpec().isInlineSpecified())
  8795. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8796. getLangOpts().CPlusPlus11 ?
  8797. diag::err_explicit_instantiation_inline :
  8798. diag::warn_explicit_instantiation_inline_0x)
  8799. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  8800. if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
  8801. // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
  8802. // not already specified.
  8803. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  8804. diag::err_explicit_instantiation_constexpr);
  8805. // A deduction guide is not on the list of entities that can be explicitly
  8806. // instantiated.
  8807. if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  8808. Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
  8809. << /*explicit instantiation*/ 0;
  8810. return true;
  8811. }
  8812. // C++0x [temp.explicit]p2:
  8813. // There are two forms of explicit instantiation: an explicit instantiation
  8814. // definition and an explicit instantiation declaration. An explicit
  8815. // instantiation declaration begins with the extern keyword. [...]
  8816. TemplateSpecializationKind TSK
  8817. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  8818. : TSK_ExplicitInstantiationDeclaration;
  8819. LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
  8820. LookupParsedName(Previous, S, &D.getCXXScopeSpec());
  8821. if (!R->isFunctionType()) {
  8822. // C++ [temp.explicit]p1:
  8823. // A [...] static data member of a class template can be explicitly
  8824. // instantiated from the member definition associated with its class
  8825. // template.
  8826. // C++1y [temp.explicit]p1:
  8827. // A [...] variable [...] template specialization can be explicitly
  8828. // instantiated from its template.
  8829. if (Previous.isAmbiguous())
  8830. return true;
  8831. VarDecl *Prev = Previous.getAsSingle<VarDecl>();
  8832. VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
  8833. if (!PrevTemplate) {
  8834. if (!Prev || !Prev->isStaticDataMember()) {
  8835. // We expect to see a static data member here.
  8836. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
  8837. << Name;
  8838. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  8839. P != PEnd; ++P)
  8840. Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
  8841. return true;
  8842. }
  8843. if (!Prev->getInstantiatedFromStaticDataMember()) {
  8844. // FIXME: Check for explicit specialization?
  8845. Diag(D.getIdentifierLoc(),
  8846. diag::err_explicit_instantiation_data_member_not_instantiated)
  8847. << Prev;
  8848. Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
  8849. // FIXME: Can we provide a note showing where this was declared?
  8850. return true;
  8851. }
  8852. } else {
  8853. // Explicitly instantiate a variable template.
  8854. // C++1y [dcl.spec.auto]p6:
  8855. // ... A program that uses auto or decltype(auto) in a context not
  8856. // explicitly allowed in this section is ill-formed.
  8857. //
  8858. // This includes auto-typed variable template instantiations.
  8859. if (R->isUndeducedType()) {
  8860. Diag(T->getTypeLoc().getBeginLoc(),
  8861. diag::err_auto_not_allowed_var_inst);
  8862. return true;
  8863. }
  8864. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  8865. // C++1y [temp.explicit]p3:
  8866. // If the explicit instantiation is for a variable, the unqualified-id
  8867. // in the declaration shall be a template-id.
  8868. Diag(D.getIdentifierLoc(),
  8869. diag::err_explicit_instantiation_without_template_id)
  8870. << PrevTemplate;
  8871. Diag(PrevTemplate->getLocation(),
  8872. diag::note_explicit_instantiation_here);
  8873. return true;
  8874. }
  8875. // Translate the parser's template argument list into our AST format.
  8876. TemplateArgumentListInfo TemplateArgs =
  8877. makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  8878. DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
  8879. D.getIdentifierLoc(), TemplateArgs);
  8880. if (Res.isInvalid())
  8881. return true;
  8882. if (!Res.isUsable()) {
  8883. // We somehow specified dependent template arguments in an explicit
  8884. // instantiation. This should probably only happen during error
  8885. // recovery.
  8886. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
  8887. return true;
  8888. }
  8889. // Ignore access control bits, we don't need them for redeclaration
  8890. // checking.
  8891. Prev = cast<VarDecl>(Res.get());
  8892. }
  8893. // C++0x [temp.explicit]p2:
  8894. // If the explicit instantiation is for a member function, a member class
  8895. // or a static data member of a class template specialization, the name of
  8896. // the class template specialization in the qualified-id for the member
  8897. // name shall be a simple-template-id.
  8898. //
  8899. // C++98 has the same restriction, just worded differently.
  8900. //
  8901. // This does not apply to variable template specializations, where the
  8902. // template-id is in the unqualified-id instead.
  8903. if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
  8904. Diag(D.getIdentifierLoc(),
  8905. diag::ext_explicit_instantiation_without_qualified_id)
  8906. << Prev << D.getCXXScopeSpec().getRange();
  8907. CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
  8908. // Verify that it is okay to explicitly instantiate here.
  8909. TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
  8910. SourceLocation POI = Prev->getPointOfInstantiation();
  8911. bool HasNoEffect = false;
  8912. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
  8913. PrevTSK, POI, HasNoEffect))
  8914. return true;
  8915. if (!HasNoEffect) {
  8916. // Instantiate static data member or variable template.
  8917. Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  8918. // Merge attributes.
  8919. ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
  8920. if (TSK == TSK_ExplicitInstantiationDefinition)
  8921. InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
  8922. }
  8923. // Check the new variable specialization against the parsed input.
  8924. if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
  8925. Diag(T->getTypeLoc().getBeginLoc(),
  8926. diag::err_invalid_var_template_spec_type)
  8927. << 0 << PrevTemplate << R << Prev->getType();
  8928. Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
  8929. << 2 << PrevTemplate->getDeclName();
  8930. return true;
  8931. }
  8932. // FIXME: Create an ExplicitInstantiation node?
  8933. return (Decl*) nullptr;
  8934. }
  8935. // If the declarator is a template-id, translate the parser's template
  8936. // argument list into our AST format.
  8937. bool HasExplicitTemplateArgs = false;
  8938. TemplateArgumentListInfo TemplateArgs;
  8939. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8940. TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  8941. HasExplicitTemplateArgs = true;
  8942. }
  8943. // C++ [temp.explicit]p1:
  8944. // A [...] function [...] can be explicitly instantiated from its template.
  8945. // A member function [...] of a class template can be explicitly
  8946. // instantiated from the member definition associated with its class
  8947. // template.
  8948. UnresolvedSet<8> TemplateMatches;
  8949. FunctionDecl *NonTemplateMatch = nullptr;
  8950. TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
  8951. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  8952. P != PEnd; ++P) {
  8953. NamedDecl *Prev = *P;
  8954. if (!HasExplicitTemplateArgs) {
  8955. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
  8956. QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
  8957. /*AdjustExceptionSpec*/true);
  8958. if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
  8959. if (Method->getPrimaryTemplate()) {
  8960. TemplateMatches.addDecl(Method, P.getAccess());
  8961. } else {
  8962. // FIXME: Can this assert ever happen? Needs a test.
  8963. assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
  8964. NonTemplateMatch = Method;
  8965. }
  8966. }
  8967. }
  8968. }
  8969. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
  8970. if (!FunTmpl)
  8971. continue;
  8972. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  8973. FunctionDecl *Specialization = nullptr;
  8974. if (TemplateDeductionResult TDK
  8975. = DeduceTemplateArguments(FunTmpl,
  8976. (HasExplicitTemplateArgs ? &TemplateArgs
  8977. : nullptr),
  8978. R, Specialization, Info)) {
  8979. // Keep track of almost-matches.
  8980. FailedCandidates.addCandidate()
  8981. .set(P.getPair(), FunTmpl->getTemplatedDecl(),
  8982. MakeDeductionFailureInfo(Context, TDK, Info));
  8983. (void)TDK;
  8984. continue;
  8985. }
  8986. // Target attributes are part of the cuda function signature, so
  8987. // the cuda target of the instantiated function must match that of its
  8988. // template. Given that C++ template deduction does not take
  8989. // target attributes into account, we reject candidates here that
  8990. // have a different target.
  8991. if (LangOpts.CUDA &&
  8992. IdentifyCUDATarget(Specialization,
  8993. /* IgnoreImplicitHDAttr = */ true) !=
  8994. IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
  8995. FailedCandidates.addCandidate().set(
  8996. P.getPair(), FunTmpl->getTemplatedDecl(),
  8997. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  8998. continue;
  8999. }
  9000. TemplateMatches.addDecl(Specialization, P.getAccess());
  9001. }
  9002. FunctionDecl *Specialization = NonTemplateMatch;
  9003. if (!Specialization) {
  9004. // Find the most specialized function template specialization.
  9005. UnresolvedSetIterator Result = getMostSpecialized(
  9006. TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
  9007. D.getIdentifierLoc(),
  9008. PDiag(diag::err_explicit_instantiation_not_known) << Name,
  9009. PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
  9010. PDiag(diag::note_explicit_instantiation_candidate));
  9011. if (Result == TemplateMatches.end())
  9012. return true;
  9013. // Ignore access control bits, we don't need them for redeclaration checking.
  9014. Specialization = cast<FunctionDecl>(*Result);
  9015. }
  9016. // C++11 [except.spec]p4
  9017. // In an explicit instantiation an exception-specification may be specified,
  9018. // but is not required.
  9019. // If an exception-specification is specified in an explicit instantiation
  9020. // directive, it shall be compatible with the exception-specifications of
  9021. // other declarations of that function.
  9022. if (auto *FPT = R->getAs<FunctionProtoType>())
  9023. if (FPT->hasExceptionSpec()) {
  9024. unsigned DiagID =
  9025. diag::err_mismatched_exception_spec_explicit_instantiation;
  9026. if (getLangOpts().MicrosoftExt)
  9027. DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
  9028. bool Result = CheckEquivalentExceptionSpec(
  9029. PDiag(DiagID) << Specialization->getType(),
  9030. PDiag(diag::note_explicit_instantiation_here),
  9031. Specialization->getType()->getAs<FunctionProtoType>(),
  9032. Specialization->getLocation(), FPT, D.getBeginLoc());
  9033. // In Microsoft mode, mismatching exception specifications just cause a
  9034. // warning.
  9035. if (!getLangOpts().MicrosoftExt && Result)
  9036. return true;
  9037. }
  9038. if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
  9039. Diag(D.getIdentifierLoc(),
  9040. diag::err_explicit_instantiation_member_function_not_instantiated)
  9041. << Specialization
  9042. << (Specialization->getTemplateSpecializationKind() ==
  9043. TSK_ExplicitSpecialization);
  9044. Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
  9045. return true;
  9046. }
  9047. FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
  9048. if (!PrevDecl && Specialization->isThisDeclarationADefinition())
  9049. PrevDecl = Specialization;
  9050. if (PrevDecl) {
  9051. bool HasNoEffect = false;
  9052. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
  9053. PrevDecl,
  9054. PrevDecl->getTemplateSpecializationKind(),
  9055. PrevDecl->getPointOfInstantiation(),
  9056. HasNoEffect))
  9057. return true;
  9058. // FIXME: We may still want to build some representation of this
  9059. // explicit specialization.
  9060. if (HasNoEffect)
  9061. return (Decl*) nullptr;
  9062. }
  9063. // HACK: libc++ has a bug where it attempts to explicitly instantiate the
  9064. // functions
  9065. // valarray<size_t>::valarray(size_t) and
  9066. // valarray<size_t>::~valarray()
  9067. // that it declared to have internal linkage with the internal_linkage
  9068. // attribute. Ignore the explicit instantiation declaration in this case.
  9069. if (Specialization->hasAttr<InternalLinkageAttr>() &&
  9070. TSK == TSK_ExplicitInstantiationDeclaration) {
  9071. if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
  9072. if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
  9073. RD->isInStdNamespace())
  9074. return (Decl*) nullptr;
  9075. }
  9076. ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
  9077. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  9078. // instantiation declarations.
  9079. if (TSK == TSK_ExplicitInstantiationDefinition &&
  9080. Specialization->hasAttr<DLLImportAttr>() &&
  9081. Context.getTargetInfo().getCXXABI().isMicrosoft())
  9082. TSK = TSK_ExplicitInstantiationDeclaration;
  9083. Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  9084. if (Specialization->isDefined()) {
  9085. // Let the ASTConsumer know that this function has been explicitly
  9086. // instantiated now, and its linkage might have changed.
  9087. Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
  9088. } else if (TSK == TSK_ExplicitInstantiationDefinition)
  9089. InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
  9090. // C++0x [temp.explicit]p2:
  9091. // If the explicit instantiation is for a member function, a member class
  9092. // or a static data member of a class template specialization, the name of
  9093. // the class template specialization in the qualified-id for the member
  9094. // name shall be a simple-template-id.
  9095. //
  9096. // C++98 has the same restriction, just worded differently.
  9097. FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
  9098. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
  9099. D.getCXXScopeSpec().isSet() &&
  9100. !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
  9101. Diag(D.getIdentifierLoc(),
  9102. diag::ext_explicit_instantiation_without_qualified_id)
  9103. << Specialization << D.getCXXScopeSpec().getRange();
  9104. CheckExplicitInstantiation(
  9105. *this,
  9106. FunTmpl ? (NamedDecl *)FunTmpl
  9107. : Specialization->getInstantiatedFromMemberFunction(),
  9108. D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
  9109. // FIXME: Create some kind of ExplicitInstantiationDecl here.
  9110. return (Decl*) nullptr;
  9111. }
  9112. TypeResult
  9113. Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  9114. const CXXScopeSpec &SS, IdentifierInfo *Name,
  9115. SourceLocation TagLoc, SourceLocation NameLoc) {
  9116. // This has to hold, because SS is expected to be defined.
  9117. assert(Name && "Expected a name in a dependent tag");
  9118. NestedNameSpecifier *NNS = SS.getScopeRep();
  9119. if (!NNS)
  9120. return true;
  9121. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  9122. if (TUK == TUK_Declaration || TUK == TUK_Definition) {
  9123. Diag(NameLoc, diag::err_dependent_tag_decl)
  9124. << (TUK == TUK_Definition) << Kind << SS.getRange();
  9125. return true;
  9126. }
  9127. // Create the resulting type.
  9128. ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  9129. QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
  9130. // Create type-source location information for this type.
  9131. TypeLocBuilder TLB;
  9132. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
  9133. TL.setElaboratedKeywordLoc(TagLoc);
  9134. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  9135. TL.setNameLoc(NameLoc);
  9136. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  9137. }
  9138. TypeResult
  9139. Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
  9140. const CXXScopeSpec &SS, const IdentifierInfo &II,
  9141. SourceLocation IdLoc) {
  9142. if (SS.isInvalid())
  9143. return true;
  9144. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  9145. Diag(TypenameLoc,
  9146. getLangOpts().CPlusPlus11 ?
  9147. diag::warn_cxx98_compat_typename_outside_of_template :
  9148. diag::ext_typename_outside_of_template)
  9149. << FixItHint::CreateRemoval(TypenameLoc);
  9150. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  9151. TypeSourceInfo *TSI = nullptr;
  9152. QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
  9153. TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
  9154. /*DeducedTSTContext=*/true);
  9155. if (T.isNull())
  9156. return true;
  9157. return CreateParsedType(T, TSI);
  9158. }
  9159. TypeResult
  9160. Sema::ActOnTypenameType(Scope *S,
  9161. SourceLocation TypenameLoc,
  9162. const CXXScopeSpec &SS,
  9163. SourceLocation TemplateKWLoc,
  9164. TemplateTy TemplateIn,
  9165. IdentifierInfo *TemplateII,
  9166. SourceLocation TemplateIILoc,
  9167. SourceLocation LAngleLoc,
  9168. ASTTemplateArgsPtr TemplateArgsIn,
  9169. SourceLocation RAngleLoc) {
  9170. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  9171. Diag(TypenameLoc,
  9172. getLangOpts().CPlusPlus11 ?
  9173. diag::warn_cxx98_compat_typename_outside_of_template :
  9174. diag::ext_typename_outside_of_template)
  9175. << FixItHint::CreateRemoval(TypenameLoc);
  9176. // Strangely, non-type results are not ignored by this lookup, so the
  9177. // program is ill-formed if it finds an injected-class-name.
  9178. if (TypenameLoc.isValid()) {
  9179. auto *LookupRD =
  9180. dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
  9181. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  9182. Diag(TemplateIILoc,
  9183. diag::ext_out_of_line_qualified_id_type_names_constructor)
  9184. << TemplateII << 0 /*injected-class-name used as template name*/
  9185. << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
  9186. }
  9187. }
  9188. // Translate the parser's template argument list in our AST format.
  9189. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  9190. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  9191. TemplateName Template = TemplateIn.get();
  9192. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  9193. // Construct a dependent template specialization type.
  9194. assert(DTN && "dependent template has non-dependent name?");
  9195. assert(DTN->getQualifier() == SS.getScopeRep());
  9196. QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
  9197. DTN->getQualifier(),
  9198. DTN->getIdentifier(),
  9199. TemplateArgs);
  9200. // Create source-location information for this type.
  9201. TypeLocBuilder Builder;
  9202. DependentTemplateSpecializationTypeLoc SpecTL
  9203. = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
  9204. SpecTL.setElaboratedKeywordLoc(TypenameLoc);
  9205. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  9206. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  9207. SpecTL.setTemplateNameLoc(TemplateIILoc);
  9208. SpecTL.setLAngleLoc(LAngleLoc);
  9209. SpecTL.setRAngleLoc(RAngleLoc);
  9210. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  9211. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  9212. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  9213. }
  9214. QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  9215. if (T.isNull())
  9216. return true;
  9217. // Provide source-location information for the template specialization type.
  9218. TypeLocBuilder Builder;
  9219. TemplateSpecializationTypeLoc SpecTL
  9220. = Builder.push<TemplateSpecializationTypeLoc>(T);
  9221. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  9222. SpecTL.setTemplateNameLoc(TemplateIILoc);
  9223. SpecTL.setLAngleLoc(LAngleLoc);
  9224. SpecTL.setRAngleLoc(RAngleLoc);
  9225. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  9226. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  9227. T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
  9228. ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
  9229. TL.setElaboratedKeywordLoc(TypenameLoc);
  9230. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  9231. TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
  9232. return CreateParsedType(T, TSI);
  9233. }
  9234. /// Determine whether this failed name lookup should be treated as being
  9235. /// disabled by a usage of std::enable_if.
  9236. static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
  9237. SourceRange &CondRange, Expr *&Cond) {
  9238. // We must be looking for a ::type...
  9239. if (!II.isStr("type"))
  9240. return false;
  9241. // ... within an explicitly-written template specialization...
  9242. if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
  9243. return false;
  9244. TypeLoc EnableIfTy = NNS.getTypeLoc();
  9245. TemplateSpecializationTypeLoc EnableIfTSTLoc =
  9246. EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
  9247. if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
  9248. return false;
  9249. const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
  9250. // ... which names a complete class template declaration...
  9251. const TemplateDecl *EnableIfDecl =
  9252. EnableIfTST->getTemplateName().getAsTemplateDecl();
  9253. if (!EnableIfDecl || EnableIfTST->isIncompleteType())
  9254. return false;
  9255. // ... called "enable_if".
  9256. const IdentifierInfo *EnableIfII =
  9257. EnableIfDecl->getDeclName().getAsIdentifierInfo();
  9258. if (!EnableIfII || !EnableIfII->isStr("enable_if"))
  9259. return false;
  9260. // Assume the first template argument is the condition.
  9261. CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
  9262. // Dig out the condition.
  9263. Cond = nullptr;
  9264. if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
  9265. != TemplateArgument::Expression)
  9266. return true;
  9267. Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
  9268. // Ignore Boolean literals; they add no value.
  9269. if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
  9270. Cond = nullptr;
  9271. return true;
  9272. }
  9273. QualType
  9274. Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
  9275. SourceLocation KeywordLoc,
  9276. NestedNameSpecifierLoc QualifierLoc,
  9277. const IdentifierInfo &II,
  9278. SourceLocation IILoc,
  9279. TypeSourceInfo **TSI,
  9280. bool DeducedTSTContext) {
  9281. QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
  9282. DeducedTSTContext);
  9283. if (T.isNull())
  9284. return QualType();
  9285. *TSI = Context.CreateTypeSourceInfo(T);
  9286. if (isa<DependentNameType>(T)) {
  9287. DependentNameTypeLoc TL =
  9288. (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
  9289. TL.setElaboratedKeywordLoc(KeywordLoc);
  9290. TL.setQualifierLoc(QualifierLoc);
  9291. TL.setNameLoc(IILoc);
  9292. } else {
  9293. ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
  9294. TL.setElaboratedKeywordLoc(KeywordLoc);
  9295. TL.setQualifierLoc(QualifierLoc);
  9296. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
  9297. }
  9298. return T;
  9299. }
  9300. /// Build the type that describes a C++ typename specifier,
  9301. /// e.g., "typename T::type".
  9302. QualType
  9303. Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
  9304. SourceLocation KeywordLoc,
  9305. NestedNameSpecifierLoc QualifierLoc,
  9306. const IdentifierInfo &II,
  9307. SourceLocation IILoc, bool DeducedTSTContext) {
  9308. CXXScopeSpec SS;
  9309. SS.Adopt(QualifierLoc);
  9310. DeclContext *Ctx = nullptr;
  9311. if (QualifierLoc) {
  9312. Ctx = computeDeclContext(SS);
  9313. if (!Ctx) {
  9314. // If the nested-name-specifier is dependent and couldn't be
  9315. // resolved to a type, build a typename type.
  9316. assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
  9317. return Context.getDependentNameType(Keyword,
  9318. QualifierLoc.getNestedNameSpecifier(),
  9319. &II);
  9320. }
  9321. // If the nested-name-specifier refers to the current instantiation,
  9322. // the "typename" keyword itself is superfluous. In C++03, the
  9323. // program is actually ill-formed. However, DR 382 (in C++0x CD1)
  9324. // allows such extraneous "typename" keywords, and we retroactively
  9325. // apply this DR to C++03 code with only a warning. In any case we continue.
  9326. if (RequireCompleteDeclContext(SS, Ctx))
  9327. return QualType();
  9328. }
  9329. DeclarationName Name(&II);
  9330. LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
  9331. if (Ctx)
  9332. LookupQualifiedName(Result, Ctx, SS);
  9333. else
  9334. LookupName(Result, CurScope);
  9335. unsigned DiagID = 0;
  9336. Decl *Referenced = nullptr;
  9337. switch (Result.getResultKind()) {
  9338. case LookupResult::NotFound: {
  9339. // If we're looking up 'type' within a template named 'enable_if', produce
  9340. // a more specific diagnostic.
  9341. SourceRange CondRange;
  9342. Expr *Cond = nullptr;
  9343. if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
  9344. // If we have a condition, narrow it down to the specific failed
  9345. // condition.
  9346. if (Cond) {
  9347. Expr *FailedCond;
  9348. std::string FailedDescription;
  9349. std::tie(FailedCond, FailedDescription) =
  9350. findFailedBooleanCondition(Cond);
  9351. Diag(FailedCond->getExprLoc(),
  9352. diag::err_typename_nested_not_found_requirement)
  9353. << FailedDescription
  9354. << FailedCond->getSourceRange();
  9355. return QualType();
  9356. }
  9357. Diag(CondRange.getBegin(),
  9358. diag::err_typename_nested_not_found_enable_if)
  9359. << Ctx << CondRange;
  9360. return QualType();
  9361. }
  9362. DiagID = Ctx ? diag::err_typename_nested_not_found
  9363. : diag::err_unknown_typename;
  9364. break;
  9365. }
  9366. case LookupResult::FoundUnresolvedValue: {
  9367. // We found a using declaration that is a value. Most likely, the using
  9368. // declaration itself is meant to have the 'typename' keyword.
  9369. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  9370. IILoc);
  9371. Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
  9372. << Name << Ctx << FullRange;
  9373. if (UnresolvedUsingValueDecl *Using
  9374. = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
  9375. SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
  9376. Diag(Loc, diag::note_using_value_decl_missing_typename)
  9377. << FixItHint::CreateInsertion(Loc, "typename ");
  9378. }
  9379. }
  9380. // Fall through to create a dependent typename type, from which we can recover
  9381. // better.
  9382. LLVM_FALLTHROUGH;
  9383. case LookupResult::NotFoundInCurrentInstantiation:
  9384. // Okay, it's a member of an unknown instantiation.
  9385. return Context.getDependentNameType(Keyword,
  9386. QualifierLoc.getNestedNameSpecifier(),
  9387. &II);
  9388. case LookupResult::Found:
  9389. if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
  9390. // C++ [class.qual]p2:
  9391. // In a lookup in which function names are not ignored and the
  9392. // nested-name-specifier nominates a class C, if the name specified
  9393. // after the nested-name-specifier, when looked up in C, is the
  9394. // injected-class-name of C [...] then the name is instead considered
  9395. // to name the constructor of class C.
  9396. //
  9397. // Unlike in an elaborated-type-specifier, function names are not ignored
  9398. // in typename-specifier lookup. However, they are ignored in all the
  9399. // contexts where we form a typename type with no keyword (that is, in
  9400. // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
  9401. //
  9402. // FIXME: That's not strictly true: mem-initializer-id lookup does not
  9403. // ignore functions, but that appears to be an oversight.
  9404. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
  9405. auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
  9406. if (Keyword == ETK_Typename && LookupRD && FoundRD &&
  9407. FoundRD->isInjectedClassName() &&
  9408. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  9409. Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
  9410. << &II << 1 << 0 /*'typename' keyword used*/;
  9411. // We found a type. Build an ElaboratedType, since the
  9412. // typename-specifier was just sugar.
  9413. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  9414. return Context.getElaboratedType(Keyword,
  9415. QualifierLoc.getNestedNameSpecifier(),
  9416. Context.getTypeDeclType(Type));
  9417. }
  9418. // C++ [dcl.type.simple]p2:
  9419. // A type-specifier of the form
  9420. // typename[opt] nested-name-specifier[opt] template-name
  9421. // is a placeholder for a deduced class type [...].
  9422. if (getLangOpts().CPlusPlus17) {
  9423. if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
  9424. if (!DeducedTSTContext) {
  9425. QualType T(QualifierLoc
  9426. ? QualifierLoc.getNestedNameSpecifier()->getAsType()
  9427. : nullptr, 0);
  9428. if (!T.isNull())
  9429. Diag(IILoc, diag::err_dependent_deduced_tst)
  9430. << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
  9431. else
  9432. Diag(IILoc, diag::err_deduced_tst)
  9433. << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
  9434. Diag(TD->getLocation(), diag::note_template_decl_here);
  9435. return QualType();
  9436. }
  9437. return Context.getElaboratedType(
  9438. Keyword, QualifierLoc.getNestedNameSpecifier(),
  9439. Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  9440. QualType(), false));
  9441. }
  9442. }
  9443. DiagID = Ctx ? diag::err_typename_nested_not_type
  9444. : diag::err_typename_not_type;
  9445. Referenced = Result.getFoundDecl();
  9446. break;
  9447. case LookupResult::FoundOverloaded:
  9448. DiagID = Ctx ? diag::err_typename_nested_not_type
  9449. : diag::err_typename_not_type;
  9450. Referenced = *Result.begin();
  9451. break;
  9452. case LookupResult::Ambiguous:
  9453. return QualType();
  9454. }
  9455. // If we get here, it's because name lookup did not find a
  9456. // type. Emit an appropriate diagnostic and return an error.
  9457. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  9458. IILoc);
  9459. if (Ctx)
  9460. Diag(IILoc, DiagID) << FullRange << Name << Ctx;
  9461. else
  9462. Diag(IILoc, DiagID) << FullRange << Name;
  9463. if (Referenced)
  9464. Diag(Referenced->getLocation(),
  9465. Ctx ? diag::note_typename_member_refers_here
  9466. : diag::note_typename_refers_here)
  9467. << Name;
  9468. return QualType();
  9469. }
  9470. namespace {
  9471. // See Sema::RebuildTypeInCurrentInstantiation
  9472. class CurrentInstantiationRebuilder
  9473. : public TreeTransform<CurrentInstantiationRebuilder> {
  9474. SourceLocation Loc;
  9475. DeclarationName Entity;
  9476. public:
  9477. typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
  9478. CurrentInstantiationRebuilder(Sema &SemaRef,
  9479. SourceLocation Loc,
  9480. DeclarationName Entity)
  9481. : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
  9482. Loc(Loc), Entity(Entity) { }
  9483. /// Determine whether the given type \p T has already been
  9484. /// transformed.
  9485. ///
  9486. /// For the purposes of type reconstruction, a type has already been
  9487. /// transformed if it is NULL or if it is not dependent.
  9488. bool AlreadyTransformed(QualType T) {
  9489. return T.isNull() || !T->isInstantiationDependentType();
  9490. }
  9491. /// Returns the location of the entity whose type is being
  9492. /// rebuilt.
  9493. SourceLocation getBaseLocation() { return Loc; }
  9494. /// Returns the name of the entity whose type is being rebuilt.
  9495. DeclarationName getBaseEntity() { return Entity; }
  9496. /// Sets the "base" location and entity when that
  9497. /// information is known based on another transformation.
  9498. void setBase(SourceLocation Loc, DeclarationName Entity) {
  9499. this->Loc = Loc;
  9500. this->Entity = Entity;
  9501. }
  9502. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  9503. // Lambdas never need to be transformed.
  9504. return E;
  9505. }
  9506. };
  9507. } // end anonymous namespace
  9508. /// Rebuilds a type within the context of the current instantiation.
  9509. ///
  9510. /// The type \p T is part of the type of an out-of-line member definition of
  9511. /// a class template (or class template partial specialization) that was parsed
  9512. /// and constructed before we entered the scope of the class template (or
  9513. /// partial specialization thereof). This routine will rebuild that type now
  9514. /// that we have entered the declarator's scope, which may produce different
  9515. /// canonical types, e.g.,
  9516. ///
  9517. /// \code
  9518. /// template<typename T>
  9519. /// struct X {
  9520. /// typedef T* pointer;
  9521. /// pointer data();
  9522. /// };
  9523. ///
  9524. /// template<typename T>
  9525. /// typename X<T>::pointer X<T>::data() { ... }
  9526. /// \endcode
  9527. ///
  9528. /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
  9529. /// since we do not know that we can look into X<T> when we parsed the type.
  9530. /// This function will rebuild the type, performing the lookup of "pointer"
  9531. /// in X<T> and returning an ElaboratedType whose canonical type is the same
  9532. /// as the canonical type of T*, allowing the return types of the out-of-line
  9533. /// definition and the declaration to match.
  9534. TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
  9535. SourceLocation Loc,
  9536. DeclarationName Name) {
  9537. if (!T || !T->getType()->isInstantiationDependentType())
  9538. return T;
  9539. CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
  9540. return Rebuilder.TransformType(T);
  9541. }
  9542. ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
  9543. CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
  9544. DeclarationName());
  9545. return Rebuilder.TransformExpr(E);
  9546. }
  9547. bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
  9548. if (SS.isInvalid())
  9549. return true;
  9550. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  9551. CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
  9552. DeclarationName());
  9553. NestedNameSpecifierLoc Rebuilt
  9554. = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
  9555. if (!Rebuilt)
  9556. return true;
  9557. SS.Adopt(Rebuilt);
  9558. return false;
  9559. }
  9560. /// Rebuild the template parameters now that we know we're in a current
  9561. /// instantiation.
  9562. bool Sema::RebuildTemplateParamsInCurrentInstantiation(
  9563. TemplateParameterList *Params) {
  9564. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  9565. Decl *Param = Params->getParam(I);
  9566. // There is nothing to rebuild in a type parameter.
  9567. if (isa<TemplateTypeParmDecl>(Param))
  9568. continue;
  9569. // Rebuild the template parameter list of a template template parameter.
  9570. if (TemplateTemplateParmDecl *TTP
  9571. = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  9572. if (RebuildTemplateParamsInCurrentInstantiation(
  9573. TTP->getTemplateParameters()))
  9574. return true;
  9575. continue;
  9576. }
  9577. // Rebuild the type of a non-type template parameter.
  9578. NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
  9579. TypeSourceInfo *NewTSI
  9580. = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
  9581. NTTP->getLocation(),
  9582. NTTP->getDeclName());
  9583. if (!NewTSI)
  9584. return true;
  9585. if (NewTSI->getType()->isUndeducedType()) {
  9586. // C++17 [temp.dep.expr]p3:
  9587. // An id-expression is type-dependent if it contains
  9588. // - an identifier associated by name lookup with a non-type
  9589. // template-parameter declared with a type that contains a
  9590. // placeholder type (7.1.7.4),
  9591. NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
  9592. }
  9593. if (NewTSI != NTTP->getTypeSourceInfo()) {
  9594. NTTP->setTypeSourceInfo(NewTSI);
  9595. NTTP->setType(NewTSI->getType());
  9596. }
  9597. }
  9598. return false;
  9599. }
  9600. /// Produces a formatted string that describes the binding of
  9601. /// template parameters to template arguments.
  9602. std::string
  9603. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  9604. const TemplateArgumentList &Args) {
  9605. return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
  9606. }
  9607. std::string
  9608. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  9609. const TemplateArgument *Args,
  9610. unsigned NumArgs) {
  9611. SmallString<128> Str;
  9612. llvm::raw_svector_ostream Out(Str);
  9613. if (!Params || Params->size() == 0 || NumArgs == 0)
  9614. return std::string();
  9615. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  9616. if (I >= NumArgs)
  9617. break;
  9618. if (I == 0)
  9619. Out << "[with ";
  9620. else
  9621. Out << ", ";
  9622. if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
  9623. Out << Id->getName();
  9624. } else {
  9625. Out << '$' << I;
  9626. }
  9627. Out << " = ";
  9628. Args[I].print(getPrintingPolicy(), Out,
  9629. TemplateParameterList::shouldIncludeTypeForArgument(
  9630. getPrintingPolicy(), Params, I));
  9631. }
  9632. Out << ']';
  9633. return std::string(Out.str());
  9634. }
  9635. void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
  9636. CachedTokens &Toks) {
  9637. if (!FD)
  9638. return;
  9639. auto LPT = std::make_unique<LateParsedTemplate>();
  9640. // Take tokens to avoid allocations
  9641. LPT->Toks.swap(Toks);
  9642. LPT->D = FnD;
  9643. LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
  9644. FD->setLateTemplateParsed(true);
  9645. }
  9646. void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
  9647. if (!FD)
  9648. return;
  9649. FD->setLateTemplateParsed(false);
  9650. }
  9651. bool Sema::IsInsideALocalClassWithinATemplateFunction() {
  9652. DeclContext *DC = CurContext;
  9653. while (DC) {
  9654. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
  9655. const FunctionDecl *FD = RD->isLocalClass();
  9656. return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
  9657. } else if (DC->isTranslationUnit() || DC->isNamespace())
  9658. return false;
  9659. DC = DC->getParent();
  9660. }
  9661. return false;
  9662. }
  9663. namespace {
  9664. /// Walk the path from which a declaration was instantiated, and check
  9665. /// that every explicit specialization along that path is visible. This enforces
  9666. /// C++ [temp.expl.spec]/6:
  9667. ///
  9668. /// If a template, a member template or a member of a class template is
  9669. /// explicitly specialized then that specialization shall be declared before
  9670. /// the first use of that specialization that would cause an implicit
  9671. /// instantiation to take place, in every translation unit in which such a
  9672. /// use occurs; no diagnostic is required.
  9673. ///
  9674. /// and also C++ [temp.class.spec]/1:
  9675. ///
  9676. /// A partial specialization shall be declared before the first use of a
  9677. /// class template specialization that would make use of the partial
  9678. /// specialization as the result of an implicit or explicit instantiation
  9679. /// in every translation unit in which such a use occurs; no diagnostic is
  9680. /// required.
  9681. class ExplicitSpecializationVisibilityChecker {
  9682. Sema &S;
  9683. SourceLocation Loc;
  9684. llvm::SmallVector<Module *, 8> Modules;
  9685. public:
  9686. ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
  9687. : S(S), Loc(Loc) {}
  9688. void check(NamedDecl *ND) {
  9689. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  9690. return checkImpl(FD);
  9691. if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
  9692. return checkImpl(RD);
  9693. if (auto *VD = dyn_cast<VarDecl>(ND))
  9694. return checkImpl(VD);
  9695. if (auto *ED = dyn_cast<EnumDecl>(ND))
  9696. return checkImpl(ED);
  9697. }
  9698. private:
  9699. void diagnose(NamedDecl *D, bool IsPartialSpec) {
  9700. auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
  9701. : Sema::MissingImportKind::ExplicitSpecialization;
  9702. const bool Recover = true;
  9703. // If we got a custom set of modules (because only a subset of the
  9704. // declarations are interesting), use them, otherwise let
  9705. // diagnoseMissingImport intelligently pick some.
  9706. if (Modules.empty())
  9707. S.diagnoseMissingImport(Loc, D, Kind, Recover);
  9708. else
  9709. S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
  9710. }
  9711. // Check a specific declaration. There are three problematic cases:
  9712. //
  9713. // 1) The declaration is an explicit specialization of a template
  9714. // specialization.
  9715. // 2) The declaration is an explicit specialization of a member of an
  9716. // templated class.
  9717. // 3) The declaration is an instantiation of a template, and that template
  9718. // is an explicit specialization of a member of a templated class.
  9719. //
  9720. // We don't need to go any deeper than that, as the instantiation of the
  9721. // surrounding class / etc is not triggered by whatever triggered this
  9722. // instantiation, and thus should be checked elsewhere.
  9723. template<typename SpecDecl>
  9724. void checkImpl(SpecDecl *Spec) {
  9725. bool IsHiddenExplicitSpecialization = false;
  9726. if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
  9727. IsHiddenExplicitSpecialization =
  9728. Spec->getMemberSpecializationInfo()
  9729. ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
  9730. : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
  9731. } else {
  9732. checkInstantiated(Spec);
  9733. }
  9734. if (IsHiddenExplicitSpecialization)
  9735. diagnose(Spec->getMostRecentDecl(), false);
  9736. }
  9737. void checkInstantiated(FunctionDecl *FD) {
  9738. if (auto *TD = FD->getPrimaryTemplate())
  9739. checkTemplate(TD);
  9740. }
  9741. void checkInstantiated(CXXRecordDecl *RD) {
  9742. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
  9743. if (!SD)
  9744. return;
  9745. auto From = SD->getSpecializedTemplateOrPartial();
  9746. if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
  9747. checkTemplate(TD);
  9748. else if (auto *TD =
  9749. From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  9750. if (!S.hasVisibleDeclaration(TD))
  9751. diagnose(TD, true);
  9752. checkTemplate(TD);
  9753. }
  9754. }
  9755. void checkInstantiated(VarDecl *RD) {
  9756. auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
  9757. if (!SD)
  9758. return;
  9759. auto From = SD->getSpecializedTemplateOrPartial();
  9760. if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
  9761. checkTemplate(TD);
  9762. else if (auto *TD =
  9763. From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  9764. if (!S.hasVisibleDeclaration(TD))
  9765. diagnose(TD, true);
  9766. checkTemplate(TD);
  9767. }
  9768. }
  9769. void checkInstantiated(EnumDecl *FD) {}
  9770. template<typename TemplDecl>
  9771. void checkTemplate(TemplDecl *TD) {
  9772. if (TD->isMemberSpecialization()) {
  9773. if (!S.hasVisibleMemberSpecialization(TD, &Modules))
  9774. diagnose(TD->getMostRecentDecl(), false);
  9775. }
  9776. }
  9777. };
  9778. } // end anonymous namespace
  9779. void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
  9780. if (!getLangOpts().Modules)
  9781. return;
  9782. ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
  9783. }