SemaTemplateDeduction.cpp 243 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091
  1. //===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
  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. //
  9. // This file implements C++ template argument deduction.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/TemplateDeduction.h"
  13. #include "TreeTransform.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclAccessPair.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/NestedNameSpecifier.h"
  26. #include "clang/AST/RecursiveASTVisitor.h"
  27. #include "clang/AST/TemplateBase.h"
  28. #include "clang/AST/TemplateName.h"
  29. #include "clang/AST/Type.h"
  30. #include "clang/AST/TypeLoc.h"
  31. #include "clang/AST/UnresolvedSet.h"
  32. #include "clang/Basic/AddressSpaces.h"
  33. #include "clang/Basic/ExceptionSpecificationType.h"
  34. #include "clang/Basic/LLVM.h"
  35. #include "clang/Basic/LangOptions.h"
  36. #include "clang/Basic/PartialDiagnostic.h"
  37. #include "clang/Basic/SourceLocation.h"
  38. #include "clang/Basic/Specifiers.h"
  39. #include "clang/Sema/Ownership.h"
  40. #include "clang/Sema/Sema.h"
  41. #include "clang/Sema/Template.h"
  42. #include "llvm/ADT/APInt.h"
  43. #include "llvm/ADT/APSInt.h"
  44. #include "llvm/ADT/ArrayRef.h"
  45. #include "llvm/ADT/DenseMap.h"
  46. #include "llvm/ADT/FoldingSet.h"
  47. #include "llvm/ADT/Optional.h"
  48. #include "llvm/ADT/SmallBitVector.h"
  49. #include "llvm/ADT/SmallPtrSet.h"
  50. #include "llvm/ADT/SmallVector.h"
  51. #include "llvm/Support/Casting.h"
  52. #include "llvm/Support/Compiler.h"
  53. #include "llvm/Support/ErrorHandling.h"
  54. #include <algorithm>
  55. #include <cassert>
  56. #include <tuple>
  57. #include <utility>
  58. namespace clang {
  59. /// Various flags that control template argument deduction.
  60. ///
  61. /// These flags can be bitwise-OR'd together.
  62. enum TemplateDeductionFlags {
  63. /// No template argument deduction flags, which indicates the
  64. /// strictest results for template argument deduction (as used for, e.g.,
  65. /// matching class template partial specializations).
  66. TDF_None = 0,
  67. /// Within template argument deduction from a function call, we are
  68. /// matching with a parameter type for which the original parameter was
  69. /// a reference.
  70. TDF_ParamWithReferenceType = 0x1,
  71. /// Within template argument deduction from a function call, we
  72. /// are matching in a case where we ignore cv-qualifiers.
  73. TDF_IgnoreQualifiers = 0x02,
  74. /// Within template argument deduction from a function call,
  75. /// we are matching in a case where we can perform template argument
  76. /// deduction from a template-id of a derived class of the argument type.
  77. TDF_DerivedClass = 0x04,
  78. /// Allow non-dependent types to differ, e.g., when performing
  79. /// template argument deduction from a function call where conversions
  80. /// may apply.
  81. TDF_SkipNonDependent = 0x08,
  82. /// Whether we are performing template argument deduction for
  83. /// parameters and arguments in a top-level template argument
  84. TDF_TopLevelParameterTypeList = 0x10,
  85. /// Within template argument deduction from overload resolution per
  86. /// C++ [over.over] allow matching function types that are compatible in
  87. /// terms of noreturn and default calling convention adjustments, or
  88. /// similarly matching a declared template specialization against a
  89. /// possible template, per C++ [temp.deduct.decl]. In either case, permit
  90. /// deduction where the parameter is a function type that can be converted
  91. /// to the argument type.
  92. TDF_AllowCompatibleFunctionType = 0x20,
  93. /// Within template argument deduction for a conversion function, we are
  94. /// matching with an argument type for which the original argument was
  95. /// a reference.
  96. TDF_ArgWithReferenceType = 0x40,
  97. };
  98. }
  99. using namespace clang;
  100. using namespace sema;
  101. /// Compare two APSInts, extending and switching the sign as
  102. /// necessary to compare their values regardless of underlying type.
  103. static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
  104. if (Y.getBitWidth() > X.getBitWidth())
  105. X = X.extend(Y.getBitWidth());
  106. else if (Y.getBitWidth() < X.getBitWidth())
  107. Y = Y.extend(X.getBitWidth());
  108. // If there is a signedness mismatch, correct it.
  109. if (X.isSigned() != Y.isSigned()) {
  110. // If the signed value is negative, then the values cannot be the same.
  111. if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
  112. return false;
  113. Y.setIsSigned(true);
  114. X.setIsSigned(true);
  115. }
  116. return X == Y;
  117. }
  118. static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
  119. Sema &S, TemplateParameterList *TemplateParams, QualType Param,
  120. QualType Arg, TemplateDeductionInfo &Info,
  121. SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
  122. bool PartialOrdering = false, bool DeducedFromArrayBound = false);
  123. static Sema::TemplateDeductionResult
  124. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  125. ArrayRef<TemplateArgument> Ps,
  126. ArrayRef<TemplateArgument> As,
  127. TemplateDeductionInfo &Info,
  128. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  129. bool NumberOfArgumentsMustMatch);
  130. static void MarkUsedTemplateParameters(ASTContext &Ctx,
  131. const TemplateArgument &TemplateArg,
  132. bool OnlyDeduced, unsigned Depth,
  133. llvm::SmallBitVector &Used);
  134. static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
  135. bool OnlyDeduced, unsigned Level,
  136. llvm::SmallBitVector &Deduced);
  137. /// If the given expression is of a form that permits the deduction
  138. /// of a non-type template parameter, return the declaration of that
  139. /// non-type template parameter.
  140. static const NonTypeTemplateParmDecl *
  141. getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
  142. // If we are within an alias template, the expression may have undergone
  143. // any number of parameter substitutions already.
  144. while (true) {
  145. if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
  146. E = IC->getSubExpr();
  147. else if (const auto *CE = dyn_cast<ConstantExpr>(E))
  148. E = CE->getSubExpr();
  149. else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
  150. E = Subst->getReplacement();
  151. else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
  152. // Look through implicit copy construction from an lvalue of the same type.
  153. if (CCE->getParenOrBraceRange().isValid())
  154. break;
  155. // Note, there could be default arguments.
  156. assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
  157. E = CCE->getArg(0);
  158. } else
  159. break;
  160. }
  161. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  162. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
  163. if (NTTP->getDepth() == Depth)
  164. return NTTP;
  165. return nullptr;
  166. }
  167. static const NonTypeTemplateParmDecl *
  168. getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
  169. return getDeducedParameterFromExpr(E, Info.getDeducedDepth());
  170. }
  171. /// Determine whether two declaration pointers refer to the same
  172. /// declaration.
  173. static bool isSameDeclaration(Decl *X, Decl *Y) {
  174. if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
  175. X = NX->getUnderlyingDecl();
  176. if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
  177. Y = NY->getUnderlyingDecl();
  178. return X->getCanonicalDecl() == Y->getCanonicalDecl();
  179. }
  180. /// Verify that the given, deduced template arguments are compatible.
  181. ///
  182. /// \returns The deduced template argument, or a NULL template argument if
  183. /// the deduced template arguments were incompatible.
  184. static DeducedTemplateArgument
  185. checkDeducedTemplateArguments(ASTContext &Context,
  186. const DeducedTemplateArgument &X,
  187. const DeducedTemplateArgument &Y) {
  188. // We have no deduction for one or both of the arguments; they're compatible.
  189. if (X.isNull())
  190. return Y;
  191. if (Y.isNull())
  192. return X;
  193. // If we have two non-type template argument values deduced for the same
  194. // parameter, they must both match the type of the parameter, and thus must
  195. // match each other's type. As we're only keeping one of them, we must check
  196. // for that now. The exception is that if either was deduced from an array
  197. // bound, the type is permitted to differ.
  198. if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
  199. QualType XType = X.getNonTypeTemplateArgumentType();
  200. if (!XType.isNull()) {
  201. QualType YType = Y.getNonTypeTemplateArgumentType();
  202. if (YType.isNull() || !Context.hasSameType(XType, YType))
  203. return DeducedTemplateArgument();
  204. }
  205. }
  206. switch (X.getKind()) {
  207. case TemplateArgument::Null:
  208. llvm_unreachable("Non-deduced template arguments handled above");
  209. case TemplateArgument::Type:
  210. // If two template type arguments have the same type, they're compatible.
  211. if (Y.getKind() == TemplateArgument::Type &&
  212. Context.hasSameType(X.getAsType(), Y.getAsType()))
  213. return X;
  214. // If one of the two arguments was deduced from an array bound, the other
  215. // supersedes it.
  216. if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
  217. return X.wasDeducedFromArrayBound() ? Y : X;
  218. // The arguments are not compatible.
  219. return DeducedTemplateArgument();
  220. case TemplateArgument::Integral:
  221. // If we deduced a constant in one case and either a dependent expression or
  222. // declaration in another case, keep the integral constant.
  223. // If both are integral constants with the same value, keep that value.
  224. if (Y.getKind() == TemplateArgument::Expression ||
  225. Y.getKind() == TemplateArgument::Declaration ||
  226. (Y.getKind() == TemplateArgument::Integral &&
  227. hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
  228. return X.wasDeducedFromArrayBound() ? Y : X;
  229. // All other combinations are incompatible.
  230. return DeducedTemplateArgument();
  231. case TemplateArgument::Template:
  232. if (Y.getKind() == TemplateArgument::Template &&
  233. Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
  234. return X;
  235. // All other combinations are incompatible.
  236. return DeducedTemplateArgument();
  237. case TemplateArgument::TemplateExpansion:
  238. if (Y.getKind() == TemplateArgument::TemplateExpansion &&
  239. Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
  240. Y.getAsTemplateOrTemplatePattern()))
  241. return X;
  242. // All other combinations are incompatible.
  243. return DeducedTemplateArgument();
  244. case TemplateArgument::Expression: {
  245. if (Y.getKind() != TemplateArgument::Expression)
  246. return checkDeducedTemplateArguments(Context, Y, X);
  247. // Compare the expressions for equality
  248. llvm::FoldingSetNodeID ID1, ID2;
  249. X.getAsExpr()->Profile(ID1, Context, true);
  250. Y.getAsExpr()->Profile(ID2, Context, true);
  251. if (ID1 == ID2)
  252. return X.wasDeducedFromArrayBound() ? Y : X;
  253. // Differing dependent expressions are incompatible.
  254. return DeducedTemplateArgument();
  255. }
  256. case TemplateArgument::Declaration:
  257. assert(!X.wasDeducedFromArrayBound());
  258. // If we deduced a declaration and a dependent expression, keep the
  259. // declaration.
  260. if (Y.getKind() == TemplateArgument::Expression)
  261. return X;
  262. // If we deduced a declaration and an integral constant, keep the
  263. // integral constant and whichever type did not come from an array
  264. // bound.
  265. if (Y.getKind() == TemplateArgument::Integral) {
  266. if (Y.wasDeducedFromArrayBound())
  267. return TemplateArgument(Context, Y.getAsIntegral(),
  268. X.getParamTypeForDecl());
  269. return Y;
  270. }
  271. // If we deduced two declarations, make sure that they refer to the
  272. // same declaration.
  273. if (Y.getKind() == TemplateArgument::Declaration &&
  274. isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
  275. return X;
  276. // All other combinations are incompatible.
  277. return DeducedTemplateArgument();
  278. case TemplateArgument::NullPtr:
  279. // If we deduced a null pointer and a dependent expression, keep the
  280. // null pointer.
  281. if (Y.getKind() == TemplateArgument::Expression)
  282. return X;
  283. // If we deduced a null pointer and an integral constant, keep the
  284. // integral constant.
  285. if (Y.getKind() == TemplateArgument::Integral)
  286. return Y;
  287. // If we deduced two null pointers, they are the same.
  288. if (Y.getKind() == TemplateArgument::NullPtr)
  289. return X;
  290. // All other combinations are incompatible.
  291. return DeducedTemplateArgument();
  292. case TemplateArgument::Pack: {
  293. if (Y.getKind() != TemplateArgument::Pack ||
  294. X.pack_size() != Y.pack_size())
  295. return DeducedTemplateArgument();
  296. llvm::SmallVector<TemplateArgument, 8> NewPack;
  297. for (TemplateArgument::pack_iterator XA = X.pack_begin(),
  298. XAEnd = X.pack_end(),
  299. YA = Y.pack_begin();
  300. XA != XAEnd; ++XA, ++YA) {
  301. TemplateArgument Merged = checkDeducedTemplateArguments(
  302. Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
  303. DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
  304. if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
  305. return DeducedTemplateArgument();
  306. NewPack.push_back(Merged);
  307. }
  308. return DeducedTemplateArgument(
  309. TemplateArgument::CreatePackCopy(Context, NewPack),
  310. X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
  311. }
  312. }
  313. llvm_unreachable("Invalid TemplateArgument Kind!");
  314. }
  315. /// Deduce the value of the given non-type template parameter
  316. /// as the given deduced template argument. All non-type template parameter
  317. /// deduction is funneled through here.
  318. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  319. Sema &S, TemplateParameterList *TemplateParams,
  320. const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
  321. QualType ValueType, TemplateDeductionInfo &Info,
  322. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  323. assert(NTTP->getDepth() == Info.getDeducedDepth() &&
  324. "deducing non-type template argument with wrong depth");
  325. DeducedTemplateArgument Result = checkDeducedTemplateArguments(
  326. S.Context, Deduced[NTTP->getIndex()], NewDeduced);
  327. if (Result.isNull()) {
  328. Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
  329. Info.FirstArg = Deduced[NTTP->getIndex()];
  330. Info.SecondArg = NewDeduced;
  331. return Sema::TDK_Inconsistent;
  332. }
  333. Deduced[NTTP->getIndex()] = Result;
  334. if (!S.getLangOpts().CPlusPlus17)
  335. return Sema::TDK_Success;
  336. if (NTTP->isExpandedParameterPack())
  337. // FIXME: We may still need to deduce parts of the type here! But we
  338. // don't have any way to find which slice of the type to use, and the
  339. // type stored on the NTTP itself is nonsense. Perhaps the type of an
  340. // expanded NTTP should be a pack expansion type?
  341. return Sema::TDK_Success;
  342. // Get the type of the parameter for deduction. If it's a (dependent) array
  343. // or function type, we will not have decayed it yet, so do that now.
  344. QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
  345. if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
  346. ParamType = Expansion->getPattern();
  347. // FIXME: It's not clear how deduction of a parameter of reference
  348. // type from an argument (of non-reference type) should be performed.
  349. // For now, we just remove reference types from both sides and let
  350. // the final check for matching types sort out the mess.
  351. ValueType = ValueType.getNonReferenceType();
  352. if (ParamType->isReferenceType())
  353. ParamType = ParamType.getNonReferenceType();
  354. else
  355. // Top-level cv-qualifiers are irrelevant for a non-reference type.
  356. ValueType = ValueType.getUnqualifiedType();
  357. return DeduceTemplateArgumentsByTypeMatch(
  358. S, TemplateParams, ParamType, ValueType, Info, Deduced,
  359. TDF_SkipNonDependent, /*PartialOrdering=*/false,
  360. /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
  361. }
  362. /// Deduce the value of the given non-type template parameter
  363. /// from the given integral constant.
  364. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  365. Sema &S, TemplateParameterList *TemplateParams,
  366. const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
  367. QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
  368. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  369. return DeduceNonTypeTemplateArgument(
  370. S, TemplateParams, NTTP,
  371. DeducedTemplateArgument(S.Context, Value, ValueType,
  372. DeducedFromArrayBound),
  373. ValueType, Info, Deduced);
  374. }
  375. /// Deduce the value of the given non-type template parameter
  376. /// from the given null pointer template argument type.
  377. static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
  378. Sema &S, TemplateParameterList *TemplateParams,
  379. const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
  380. TemplateDeductionInfo &Info,
  381. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  382. Expr *Value = S.ImpCastExprToType(
  383. new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy,
  384. NTTP->getLocation()),
  385. NullPtrType,
  386. NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
  387. : CK_NullToPointer)
  388. .get();
  389. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  390. DeducedTemplateArgument(Value),
  391. Value->getType(), Info, Deduced);
  392. }
  393. /// Deduce the value of the given non-type template parameter
  394. /// from the given type- or value-dependent expression.
  395. ///
  396. /// \returns true if deduction succeeded, false otherwise.
  397. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  398. Sema &S, TemplateParameterList *TemplateParams,
  399. const NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
  400. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  401. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  402. DeducedTemplateArgument(Value),
  403. Value->getType(), Info, Deduced);
  404. }
  405. /// Deduce the value of the given non-type template parameter
  406. /// from the given declaration.
  407. ///
  408. /// \returns true if deduction succeeded, false otherwise.
  409. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  410. Sema &S, TemplateParameterList *TemplateParams,
  411. const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
  412. TemplateDeductionInfo &Info,
  413. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  414. D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
  415. TemplateArgument New(D, T);
  416. return DeduceNonTypeTemplateArgument(
  417. S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
  418. }
  419. static Sema::TemplateDeductionResult
  420. DeduceTemplateArguments(Sema &S,
  421. TemplateParameterList *TemplateParams,
  422. TemplateName Param,
  423. TemplateName Arg,
  424. TemplateDeductionInfo &Info,
  425. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  426. TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
  427. if (!ParamDecl) {
  428. // The parameter type is dependent and is not a template template parameter,
  429. // so there is nothing that we can deduce.
  430. return Sema::TDK_Success;
  431. }
  432. if (TemplateTemplateParmDecl *TempParam
  433. = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
  434. // If we're not deducing at this depth, there's nothing to deduce.
  435. if (TempParam->getDepth() != Info.getDeducedDepth())
  436. return Sema::TDK_Success;
  437. DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
  438. DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
  439. Deduced[TempParam->getIndex()],
  440. NewDeduced);
  441. if (Result.isNull()) {
  442. Info.Param = TempParam;
  443. Info.FirstArg = Deduced[TempParam->getIndex()];
  444. Info.SecondArg = NewDeduced;
  445. return Sema::TDK_Inconsistent;
  446. }
  447. Deduced[TempParam->getIndex()] = Result;
  448. return Sema::TDK_Success;
  449. }
  450. // Verify that the two template names are equivalent.
  451. if (S.Context.hasSameTemplateName(Param, Arg))
  452. return Sema::TDK_Success;
  453. // Mismatch of non-dependent template parameter to argument.
  454. Info.FirstArg = TemplateArgument(Param);
  455. Info.SecondArg = TemplateArgument(Arg);
  456. return Sema::TDK_NonDeducedMismatch;
  457. }
  458. /// Deduce the template arguments by comparing the template parameter
  459. /// type (which is a template-id) with the template argument type.
  460. ///
  461. /// \param S the Sema
  462. ///
  463. /// \param TemplateParams the template parameters that we are deducing
  464. ///
  465. /// \param Param the parameter type
  466. ///
  467. /// \param Arg the argument type
  468. ///
  469. /// \param Info information about the template argument deduction itself
  470. ///
  471. /// \param Deduced the deduced template arguments
  472. ///
  473. /// \returns the result of template argument deduction so far. Note that a
  474. /// "success" result means that template argument deduction has not yet failed,
  475. /// but it may still fail, later, for other reasons.
  476. static Sema::TemplateDeductionResult
  477. DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams,
  478. const QualType P, QualType A,
  479. TemplateDeductionInfo &Info,
  480. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  481. QualType UP = P;
  482. if (const auto *IP = P->getAs<InjectedClassNameType>())
  483. UP = IP->getInjectedSpecializationType();
  484. // FIXME: Try to preserve type sugar here, which is hard
  485. // because of the unresolved template arguments.
  486. const auto *TP = UP.getCanonicalType()->castAs<TemplateSpecializationType>();
  487. ArrayRef<TemplateArgument> PResolved = TP->template_arguments();
  488. QualType UA = A;
  489. // Treat an injected-class-name as its underlying template-id.
  490. if (const auto *Injected = A->getAs<InjectedClassNameType>())
  491. UA = Injected->getInjectedSpecializationType();
  492. // Check whether the template argument is a dependent template-id.
  493. // FIXME: Should not lose sugar here.
  494. if (const auto *SA =
  495. dyn_cast<TemplateSpecializationType>(UA.getCanonicalType())) {
  496. // Perform template argument deduction for the template name.
  497. if (auto Result =
  498. DeduceTemplateArguments(S, TemplateParams, TP->getTemplateName(),
  499. SA->getTemplateName(), Info, Deduced))
  500. return Result;
  501. // Perform template argument deduction on each template
  502. // argument. Ignore any missing/extra arguments, since they could be
  503. // filled in by default arguments.
  504. return DeduceTemplateArguments(S, TemplateParams, PResolved,
  505. SA->template_arguments(), Info, Deduced,
  506. /*NumberOfArgumentsMustMatch=*/false);
  507. }
  508. // If the argument type is a class template specialization, we
  509. // perform template argument deduction using its template
  510. // arguments.
  511. const auto *RA = UA->getAs<RecordType>();
  512. const auto *SA =
  513. RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
  514. if (!SA) {
  515. Info.FirstArg = TemplateArgument(P);
  516. Info.SecondArg = TemplateArgument(A);
  517. return Sema::TDK_NonDeducedMismatch;
  518. }
  519. // Perform template argument deduction for the template name.
  520. if (auto Result = DeduceTemplateArguments(
  521. S, TemplateParams, TP->getTemplateName(),
  522. TemplateName(SA->getSpecializedTemplate()), Info, Deduced))
  523. return Result;
  524. // Perform template argument deduction for the template arguments.
  525. return DeduceTemplateArguments(S, TemplateParams, PResolved,
  526. SA->getTemplateArgs().asArray(), Info, Deduced,
  527. /*NumberOfArgumentsMustMatch=*/true);
  528. }
  529. static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) {
  530. assert(T->isCanonicalUnqualified());
  531. switch (T->getTypeClass()) {
  532. case Type::TypeOfExpr:
  533. case Type::TypeOf:
  534. case Type::DependentName:
  535. case Type::Decltype:
  536. case Type::UnresolvedUsing:
  537. case Type::TemplateTypeParm:
  538. return true;
  539. case Type::ConstantArray:
  540. case Type::IncompleteArray:
  541. case Type::VariableArray:
  542. case Type::DependentSizedArray:
  543. return IsPossiblyOpaquelyQualifiedTypeInternal(
  544. cast<ArrayType>(T)->getElementType().getTypePtr());
  545. default:
  546. return false;
  547. }
  548. }
  549. /// Determines whether the given type is an opaque type that
  550. /// might be more qualified when instantiated.
  551. static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
  552. return IsPossiblyOpaquelyQualifiedTypeInternal(
  553. T->getCanonicalTypeInternal().getTypePtr());
  554. }
  555. /// Helper function to build a TemplateParameter when we don't
  556. /// know its type statically.
  557. static TemplateParameter makeTemplateParameter(Decl *D) {
  558. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
  559. return TemplateParameter(TTP);
  560. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
  561. return TemplateParameter(NTTP);
  562. return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
  563. }
  564. /// A pack that we're currently deducing.
  565. struct clang::DeducedPack {
  566. // The index of the pack.
  567. unsigned Index;
  568. // The old value of the pack before we started deducing it.
  569. DeducedTemplateArgument Saved;
  570. // A deferred value of this pack from an inner deduction, that couldn't be
  571. // deduced because this deduction hadn't happened yet.
  572. DeducedTemplateArgument DeferredDeduction;
  573. // The new value of the pack.
  574. SmallVector<DeducedTemplateArgument, 4> New;
  575. // The outer deduction for this pack, if any.
  576. DeducedPack *Outer = nullptr;
  577. DeducedPack(unsigned Index) : Index(Index) {}
  578. };
  579. namespace {
  580. /// A scope in which we're performing pack deduction.
  581. class PackDeductionScope {
  582. public:
  583. /// Prepare to deduce the packs named within Pattern.
  584. PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
  585. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  586. TemplateDeductionInfo &Info, TemplateArgument Pattern)
  587. : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
  588. unsigned NumNamedPacks = addPacks(Pattern);
  589. finishConstruction(NumNamedPacks);
  590. }
  591. /// Prepare to directly deduce arguments of the parameter with index \p Index.
  592. PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
  593. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  594. TemplateDeductionInfo &Info, unsigned Index)
  595. : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
  596. addPack(Index);
  597. finishConstruction(1);
  598. }
  599. private:
  600. void addPack(unsigned Index) {
  601. // Save the deduced template argument for the parameter pack expanded
  602. // by this pack expansion, then clear out the deduction.
  603. DeducedPack Pack(Index);
  604. Pack.Saved = Deduced[Index];
  605. Deduced[Index] = TemplateArgument();
  606. // FIXME: What if we encounter multiple packs with different numbers of
  607. // pre-expanded expansions? (This should already have been diagnosed
  608. // during substitution.)
  609. if (Optional<unsigned> ExpandedPackExpansions =
  610. getExpandedPackSize(TemplateParams->getParam(Index)))
  611. FixedNumExpansions = ExpandedPackExpansions;
  612. Packs.push_back(Pack);
  613. }
  614. unsigned addPacks(TemplateArgument Pattern) {
  615. // Compute the set of template parameter indices that correspond to
  616. // parameter packs expanded by the pack expansion.
  617. llvm::SmallBitVector SawIndices(TemplateParams->size());
  618. llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
  619. auto AddPack = [&](unsigned Index) {
  620. if (SawIndices[Index])
  621. return;
  622. SawIndices[Index] = true;
  623. addPack(Index);
  624. // Deducing a parameter pack that is a pack expansion also constrains the
  625. // packs appearing in that parameter to have the same deduced arity. Also,
  626. // in C++17 onwards, deducing a non-type template parameter deduces its
  627. // type, so we need to collect the pending deduced values for those packs.
  628. if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
  629. TemplateParams->getParam(Index))) {
  630. if (!NTTP->isExpandedParameterPack())
  631. if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
  632. ExtraDeductions.push_back(Expansion->getPattern());
  633. }
  634. // FIXME: Also collect the unexpanded packs in any type and template
  635. // parameter packs that are pack expansions.
  636. };
  637. auto Collect = [&](TemplateArgument Pattern) {
  638. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  639. S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  640. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  641. unsigned Depth, Index;
  642. std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
  643. if (Depth == Info.getDeducedDepth())
  644. AddPack(Index);
  645. }
  646. };
  647. // Look for unexpanded packs in the pattern.
  648. Collect(Pattern);
  649. assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
  650. unsigned NumNamedPacks = Packs.size();
  651. // Also look for unexpanded packs that are indirectly deduced by deducing
  652. // the sizes of the packs in this pattern.
  653. while (!ExtraDeductions.empty())
  654. Collect(ExtraDeductions.pop_back_val());
  655. return NumNamedPacks;
  656. }
  657. void finishConstruction(unsigned NumNamedPacks) {
  658. // Dig out the partially-substituted pack, if there is one.
  659. const TemplateArgument *PartialPackArgs = nullptr;
  660. unsigned NumPartialPackArgs = 0;
  661. std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
  662. if (auto *Scope = S.CurrentInstantiationScope)
  663. if (auto *Partial = Scope->getPartiallySubstitutedPack(
  664. &PartialPackArgs, &NumPartialPackArgs))
  665. PartialPackDepthIndex = getDepthAndIndex(Partial);
  666. // This pack expansion will have been partially or fully expanded if
  667. // it only names explicitly-specified parameter packs (including the
  668. // partially-substituted one, if any).
  669. bool IsExpanded = true;
  670. for (unsigned I = 0; I != NumNamedPacks; ++I) {
  671. if (Packs[I].Index >= Info.getNumExplicitArgs()) {
  672. IsExpanded = false;
  673. IsPartiallyExpanded = false;
  674. break;
  675. }
  676. if (PartialPackDepthIndex ==
  677. std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
  678. IsPartiallyExpanded = true;
  679. }
  680. }
  681. // Skip over the pack elements that were expanded into separate arguments.
  682. // If we partially expanded, this is the number of partial arguments.
  683. if (IsPartiallyExpanded)
  684. PackElements += NumPartialPackArgs;
  685. else if (IsExpanded)
  686. PackElements += *FixedNumExpansions;
  687. for (auto &Pack : Packs) {
  688. if (Info.PendingDeducedPacks.size() > Pack.Index)
  689. Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
  690. else
  691. Info.PendingDeducedPacks.resize(Pack.Index + 1);
  692. Info.PendingDeducedPacks[Pack.Index] = &Pack;
  693. if (PartialPackDepthIndex ==
  694. std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
  695. Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
  696. // We pre-populate the deduced value of the partially-substituted
  697. // pack with the specified value. This is not entirely correct: the
  698. // value is supposed to have been substituted, not deduced, but the
  699. // cases where this is observable require an exact type match anyway.
  700. //
  701. // FIXME: If we could represent a "depth i, index j, pack elem k"
  702. // parameter, we could substitute the partially-substituted pack
  703. // everywhere and avoid this.
  704. if (!IsPartiallyExpanded)
  705. Deduced[Pack.Index] = Pack.New[PackElements];
  706. }
  707. }
  708. }
  709. public:
  710. ~PackDeductionScope() {
  711. for (auto &Pack : Packs)
  712. Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
  713. }
  714. /// Determine whether this pack has already been partially expanded into a
  715. /// sequence of (prior) function parameters / template arguments.
  716. bool isPartiallyExpanded() { return IsPartiallyExpanded; }
  717. /// Determine whether this pack expansion scope has a known, fixed arity.
  718. /// This happens if it involves a pack from an outer template that has
  719. /// (notionally) already been expanded.
  720. bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
  721. /// Determine whether the next element of the argument is still part of this
  722. /// pack. This is the case unless the pack is already expanded to a fixed
  723. /// length.
  724. bool hasNextElement() {
  725. return !FixedNumExpansions || *FixedNumExpansions > PackElements;
  726. }
  727. /// Move to deducing the next element in each pack that is being deduced.
  728. void nextPackElement() {
  729. // Capture the deduced template arguments for each parameter pack expanded
  730. // by this pack expansion, add them to the list of arguments we've deduced
  731. // for that pack, then clear out the deduced argument.
  732. for (auto &Pack : Packs) {
  733. DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
  734. if (!Pack.New.empty() || !DeducedArg.isNull()) {
  735. while (Pack.New.size() < PackElements)
  736. Pack.New.push_back(DeducedTemplateArgument());
  737. if (Pack.New.size() == PackElements)
  738. Pack.New.push_back(DeducedArg);
  739. else
  740. Pack.New[PackElements] = DeducedArg;
  741. DeducedArg = Pack.New.size() > PackElements + 1
  742. ? Pack.New[PackElements + 1]
  743. : DeducedTemplateArgument();
  744. }
  745. }
  746. ++PackElements;
  747. }
  748. /// Finish template argument deduction for a set of argument packs,
  749. /// producing the argument packs and checking for consistency with prior
  750. /// deductions.
  751. Sema::TemplateDeductionResult finish() {
  752. // Build argument packs for each of the parameter packs expanded by this
  753. // pack expansion.
  754. for (auto &Pack : Packs) {
  755. // Put back the old value for this pack.
  756. Deduced[Pack.Index] = Pack.Saved;
  757. // Always make sure the size of this pack is correct, even if we didn't
  758. // deduce any values for it.
  759. //
  760. // FIXME: This isn't required by the normative wording, but substitution
  761. // and post-substitution checking will always fail if the arity of any
  762. // pack is not equal to the number of elements we processed. (Either that
  763. // or something else has gone *very* wrong.) We're permitted to skip any
  764. // hard errors from those follow-on steps by the intent (but not the
  765. // wording) of C++ [temp.inst]p8:
  766. //
  767. // If the function selected by overload resolution can be determined
  768. // without instantiating a class template definition, it is unspecified
  769. // whether that instantiation actually takes place
  770. Pack.New.resize(PackElements);
  771. // Build or find a new value for this pack.
  772. DeducedTemplateArgument NewPack;
  773. if (Pack.New.empty()) {
  774. // If we deduced an empty argument pack, create it now.
  775. NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
  776. } else {
  777. TemplateArgument *ArgumentPack =
  778. new (S.Context) TemplateArgument[Pack.New.size()];
  779. std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
  780. NewPack = DeducedTemplateArgument(
  781. TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
  782. // FIXME: This is wrong, it's possible that some pack elements are
  783. // deduced from an array bound and others are not:
  784. // template<typename ...T, T ...V> void g(const T (&...p)[V]);
  785. // g({1, 2, 3}, {{}, {}});
  786. // ... should deduce T = {int, size_t (from array bound)}.
  787. Pack.New[0].wasDeducedFromArrayBound());
  788. }
  789. // Pick where we're going to put the merged pack.
  790. DeducedTemplateArgument *Loc;
  791. if (Pack.Outer) {
  792. if (Pack.Outer->DeferredDeduction.isNull()) {
  793. // Defer checking this pack until we have a complete pack to compare
  794. // it against.
  795. Pack.Outer->DeferredDeduction = NewPack;
  796. continue;
  797. }
  798. Loc = &Pack.Outer->DeferredDeduction;
  799. } else {
  800. Loc = &Deduced[Pack.Index];
  801. }
  802. // Check the new pack matches any previous value.
  803. DeducedTemplateArgument OldPack = *Loc;
  804. DeducedTemplateArgument Result =
  805. checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
  806. // If we deferred a deduction of this pack, check that one now too.
  807. if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
  808. OldPack = Result;
  809. NewPack = Pack.DeferredDeduction;
  810. Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
  811. }
  812. NamedDecl *Param = TemplateParams->getParam(Pack.Index);
  813. if (Result.isNull()) {
  814. Info.Param = makeTemplateParameter(Param);
  815. Info.FirstArg = OldPack;
  816. Info.SecondArg = NewPack;
  817. return Sema::TDK_Inconsistent;
  818. }
  819. // If we have a pre-expanded pack and we didn't deduce enough elements
  820. // for it, fail deduction.
  821. if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
  822. if (*Expansions != PackElements) {
  823. Info.Param = makeTemplateParameter(Param);
  824. Info.FirstArg = Result;
  825. return Sema::TDK_IncompletePack;
  826. }
  827. }
  828. *Loc = Result;
  829. }
  830. return Sema::TDK_Success;
  831. }
  832. private:
  833. Sema &S;
  834. TemplateParameterList *TemplateParams;
  835. SmallVectorImpl<DeducedTemplateArgument> &Deduced;
  836. TemplateDeductionInfo &Info;
  837. unsigned PackElements = 0;
  838. bool IsPartiallyExpanded = false;
  839. /// The number of expansions, if we have a fully-expanded pack in this scope.
  840. Optional<unsigned> FixedNumExpansions;
  841. SmallVector<DeducedPack, 2> Packs;
  842. };
  843. } // namespace
  844. /// Deduce the template arguments by comparing the list of parameter
  845. /// types to the list of argument types, as in the parameter-type-lists of
  846. /// function types (C++ [temp.deduct.type]p10).
  847. ///
  848. /// \param S The semantic analysis object within which we are deducing
  849. ///
  850. /// \param TemplateParams The template parameters that we are deducing
  851. ///
  852. /// \param Params The list of parameter types
  853. ///
  854. /// \param NumParams The number of types in \c Params
  855. ///
  856. /// \param Args The list of argument types
  857. ///
  858. /// \param NumArgs The number of types in \c Args
  859. ///
  860. /// \param Info information about the template argument deduction itself
  861. ///
  862. /// \param Deduced the deduced template arguments
  863. ///
  864. /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
  865. /// how template argument deduction is performed.
  866. ///
  867. /// \param PartialOrdering If true, we are performing template argument
  868. /// deduction for during partial ordering for a call
  869. /// (C++0x [temp.deduct.partial]).
  870. ///
  871. /// \returns the result of template argument deduction so far. Note that a
  872. /// "success" result means that template argument deduction has not yet failed,
  873. /// but it may still fail, later, for other reasons.
  874. static Sema::TemplateDeductionResult
  875. DeduceTemplateArguments(Sema &S,
  876. TemplateParameterList *TemplateParams,
  877. const QualType *Params, unsigned NumParams,
  878. const QualType *Args, unsigned NumArgs,
  879. TemplateDeductionInfo &Info,
  880. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  881. unsigned TDF,
  882. bool PartialOrdering = false) {
  883. // C++0x [temp.deduct.type]p10:
  884. // Similarly, if P has a form that contains (T), then each parameter type
  885. // Pi of the respective parameter-type- list of P is compared with the
  886. // corresponding parameter type Ai of the corresponding parameter-type-list
  887. // of A. [...]
  888. unsigned ArgIdx = 0, ParamIdx = 0;
  889. for (; ParamIdx != NumParams; ++ParamIdx) {
  890. // Check argument types.
  891. const PackExpansionType *Expansion
  892. = dyn_cast<PackExpansionType>(Params[ParamIdx]);
  893. if (!Expansion) {
  894. // Simple case: compare the parameter and argument types at this point.
  895. // Make sure we have an argument.
  896. if (ArgIdx >= NumArgs)
  897. return Sema::TDK_MiscellaneousDeductionFailure;
  898. if (isa<PackExpansionType>(Args[ArgIdx])) {
  899. // C++0x [temp.deduct.type]p22:
  900. // If the original function parameter associated with A is a function
  901. // parameter pack and the function parameter associated with P is not
  902. // a function parameter pack, then template argument deduction fails.
  903. return Sema::TDK_MiscellaneousDeductionFailure;
  904. }
  905. if (Sema::TemplateDeductionResult Result =
  906. DeduceTemplateArgumentsByTypeMatch(
  907. S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
  908. Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
  909. PartialOrdering,
  910. /*DeducedFromArrayBound=*/false))
  911. return Result;
  912. ++ArgIdx;
  913. continue;
  914. }
  915. // C++0x [temp.deduct.type]p10:
  916. // If the parameter-declaration corresponding to Pi is a function
  917. // parameter pack, then the type of its declarator- id is compared with
  918. // each remaining parameter type in the parameter-type-list of A. Each
  919. // comparison deduces template arguments for subsequent positions in the
  920. // template parameter packs expanded by the function parameter pack.
  921. QualType Pattern = Expansion->getPattern();
  922. PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
  923. // A pack scope with fixed arity is not really a pack any more, so is not
  924. // a non-deduced context.
  925. if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
  926. for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
  927. // Deduce template arguments from the pattern.
  928. if (Sema::TemplateDeductionResult Result =
  929. DeduceTemplateArgumentsByTypeMatch(
  930. S, TemplateParams, Pattern.getUnqualifiedType(),
  931. Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
  932. PartialOrdering, /*DeducedFromArrayBound=*/false))
  933. return Result;
  934. PackScope.nextPackElement();
  935. }
  936. } else {
  937. // C++0x [temp.deduct.type]p5:
  938. // The non-deduced contexts are:
  939. // - A function parameter pack that does not occur at the end of the
  940. // parameter-declaration-clause.
  941. //
  942. // FIXME: There is no wording to say what we should do in this case. We
  943. // choose to resolve this by applying the same rule that is applied for a
  944. // function call: that is, deduce all contained packs to their
  945. // explicitly-specified values (or to <> if there is no such value).
  946. //
  947. // This is seemingly-arbitrarily different from the case of a template-id
  948. // with a non-trailing pack-expansion in its arguments, which renders the
  949. // entire template-argument-list a non-deduced context.
  950. // If the parameter type contains an explicitly-specified pack that we
  951. // could not expand, skip the number of parameters notionally created
  952. // by the expansion.
  953. Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
  954. if (NumExpansions && !PackScope.isPartiallyExpanded()) {
  955. for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
  956. ++I, ++ArgIdx)
  957. PackScope.nextPackElement();
  958. }
  959. }
  960. // Build argument packs for each of the parameter packs expanded by this
  961. // pack expansion.
  962. if (auto Result = PackScope.finish())
  963. return Result;
  964. }
  965. // Make sure we don't have any extra arguments.
  966. if (ArgIdx < NumArgs)
  967. return Sema::TDK_MiscellaneousDeductionFailure;
  968. return Sema::TDK_Success;
  969. }
  970. /// Determine whether the parameter has qualifiers that the argument
  971. /// lacks. Put another way, determine whether there is no way to add
  972. /// a deduced set of qualifiers to the ParamType that would result in
  973. /// its qualifiers matching those of the ArgType.
  974. static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
  975. QualType ArgType) {
  976. Qualifiers ParamQs = ParamType.getQualifiers();
  977. Qualifiers ArgQs = ArgType.getQualifiers();
  978. if (ParamQs == ArgQs)
  979. return false;
  980. // Mismatched (but not missing) Objective-C GC attributes.
  981. if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
  982. ParamQs.hasObjCGCAttr())
  983. return true;
  984. // Mismatched (but not missing) address spaces.
  985. if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
  986. ParamQs.hasAddressSpace())
  987. return true;
  988. // Mismatched (but not missing) Objective-C lifetime qualifiers.
  989. if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
  990. ParamQs.hasObjCLifetime())
  991. return true;
  992. // CVR qualifiers inconsistent or a superset.
  993. return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
  994. }
  995. /// Compare types for equality with respect to possibly compatible
  996. /// function types (noreturn adjustment, implicit calling conventions). If any
  997. /// of parameter and argument is not a function, just perform type comparison.
  998. ///
  999. /// \param P the template parameter type.
  1000. ///
  1001. /// \param A the argument type.
  1002. bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) {
  1003. const FunctionType *PF = P->getAs<FunctionType>(),
  1004. *AF = A->getAs<FunctionType>();
  1005. // Just compare if not functions.
  1006. if (!PF || !AF)
  1007. return Context.hasSameType(P, A);
  1008. // Noreturn and noexcept adjustment.
  1009. QualType AdjustedParam;
  1010. if (IsFunctionConversion(P, A, AdjustedParam))
  1011. return Context.hasSameType(AdjustedParam, A);
  1012. // FIXME: Compatible calling conventions.
  1013. return Context.hasSameType(P, A);
  1014. }
  1015. /// Get the index of the first template parameter that was originally from the
  1016. /// innermost template-parameter-list. This is 0 except when we concatenate
  1017. /// the template parameter lists of a class template and a constructor template
  1018. /// when forming an implicit deduction guide.
  1019. static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
  1020. auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
  1021. if (!Guide || !Guide->isImplicit())
  1022. return 0;
  1023. return Guide->getDeducedTemplate()->getTemplateParameters()->size();
  1024. }
  1025. /// Determine whether a type denotes a forwarding reference.
  1026. static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
  1027. // C++1z [temp.deduct.call]p3:
  1028. // A forwarding reference is an rvalue reference to a cv-unqualified
  1029. // template parameter that does not represent a template parameter of a
  1030. // class template.
  1031. if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
  1032. if (ParamRef->getPointeeType().getQualifiers())
  1033. return false;
  1034. auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
  1035. return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
  1036. }
  1037. return false;
  1038. }
  1039. static CXXRecordDecl *getCanonicalRD(QualType T) {
  1040. return cast<CXXRecordDecl>(
  1041. T->castAs<RecordType>()->getDecl()->getCanonicalDecl());
  1042. }
  1043. /// Attempt to deduce the template arguments by checking the base types
  1044. /// according to (C++20 [temp.deduct.call] p4b3.
  1045. ///
  1046. /// \param S the semantic analysis object within which we are deducing.
  1047. ///
  1048. /// \param RecordT the top level record object we are deducing against.
  1049. ///
  1050. /// \param TemplateParams the template parameters that we are deducing.
  1051. ///
  1052. /// \param SpecParam the template specialization parameter type.
  1053. ///
  1054. /// \param Info information about the template argument deduction itself.
  1055. ///
  1056. /// \param Deduced the deduced template arguments.
  1057. ///
  1058. /// \returns the result of template argument deduction with the bases. "invalid"
  1059. /// means no matches, "success" found a single item, and the
  1060. /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
  1061. static Sema::TemplateDeductionResult
  1062. DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
  1063. TemplateParameterList *TemplateParams, QualType P,
  1064. TemplateDeductionInfo &Info,
  1065. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  1066. // C++14 [temp.deduct.call] p4b3:
  1067. // If P is a class and P has the form simple-template-id, then the
  1068. // transformed A can be a derived class of the deduced A. Likewise if
  1069. // P is a pointer to a class of the form simple-template-id, the
  1070. // transformed A can be a pointer to a derived class pointed to by the
  1071. // deduced A. However, if there is a class C that is a (direct or
  1072. // indirect) base class of D and derived (directly or indirectly) from a
  1073. // class B and that would be a valid deduced A, the deduced A cannot be
  1074. // B or pointer to B, respectively.
  1075. //
  1076. // These alternatives are considered only if type deduction would
  1077. // otherwise fail. If they yield more than one possible deduced A, the
  1078. // type deduction fails.
  1079. // Use a breadth-first search through the bases to collect the set of
  1080. // successful matches. Visited contains the set of nodes we have already
  1081. // visited, while ToVisit is our stack of records that we still need to
  1082. // visit. Matches contains a list of matches that have yet to be
  1083. // disqualified.
  1084. llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited;
  1085. SmallVector<QualType, 8> ToVisit;
  1086. // We iterate over this later, so we have to use MapVector to ensure
  1087. // determinism.
  1088. llvm::MapVector<const CXXRecordDecl *,
  1089. SmallVector<DeducedTemplateArgument, 8>>
  1090. Matches;
  1091. auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
  1092. for (const auto &Base : RD->bases()) {
  1093. QualType T = Base.getType();
  1094. assert(T->isRecordType() && "Base class that isn't a record?");
  1095. if (Visited.insert(::getCanonicalRD(T)).second)
  1096. ToVisit.push_back(T);
  1097. }
  1098. };
  1099. // Set up the loop by adding all the bases.
  1100. AddBases(RD);
  1101. // Search each path of bases until we either run into a successful match
  1102. // (where all bases of it are invalid), or we run out of bases.
  1103. while (!ToVisit.empty()) {
  1104. QualType NextT = ToVisit.pop_back_val();
  1105. SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
  1106. Deduced.end());
  1107. TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
  1108. Sema::TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments(
  1109. S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
  1110. // If this was a successful deduction, add it to the list of matches,
  1111. // otherwise we need to continue searching its bases.
  1112. const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
  1113. if (BaseResult == Sema::TDK_Success)
  1114. Matches.insert({RD, DeducedCopy});
  1115. else
  1116. AddBases(RD);
  1117. }
  1118. // At this point, 'Matches' contains a list of seemingly valid bases, however
  1119. // in the event that we have more than 1 match, it is possible that the base
  1120. // of one of the matches might be disqualified for being a base of another
  1121. // valid match. We can count on cyclical instantiations being invalid to
  1122. // simplify the disqualifications. That is, if A & B are both matches, and B
  1123. // inherits from A (disqualifying A), we know that A cannot inherit from B.
  1124. if (Matches.size() > 1) {
  1125. Visited.clear();
  1126. for (const auto &Match : Matches)
  1127. AddBases(Match.first);
  1128. // We can give up once we have a single item (or have run out of things to
  1129. // search) since cyclical inheritance isn't valid.
  1130. while (Matches.size() > 1 && !ToVisit.empty()) {
  1131. const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
  1132. Matches.erase(RD);
  1133. // Always add all bases, since the inheritance tree can contain
  1134. // disqualifications for multiple matches.
  1135. AddBases(RD);
  1136. }
  1137. }
  1138. if (Matches.empty())
  1139. return Sema::TDK_Invalid;
  1140. if (Matches.size() > 1)
  1141. return Sema::TDK_MiscellaneousDeductionFailure;
  1142. std::swap(Matches.front().second, Deduced);
  1143. return Sema::TDK_Success;
  1144. }
  1145. /// Deduce the template arguments by comparing the parameter type and
  1146. /// the argument type (C++ [temp.deduct.type]).
  1147. ///
  1148. /// \param S the semantic analysis object within which we are deducing
  1149. ///
  1150. /// \param TemplateParams the template parameters that we are deducing
  1151. ///
  1152. /// \param ParamIn the parameter type
  1153. ///
  1154. /// \param ArgIn the argument type
  1155. ///
  1156. /// \param Info information about the template argument deduction itself
  1157. ///
  1158. /// \param Deduced the deduced template arguments
  1159. ///
  1160. /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
  1161. /// how template argument deduction is performed.
  1162. ///
  1163. /// \param PartialOrdering Whether we're performing template argument deduction
  1164. /// in the context of partial ordering (C++0x [temp.deduct.partial]).
  1165. ///
  1166. /// \returns the result of template argument deduction so far. Note that a
  1167. /// "success" result means that template argument deduction has not yet failed,
  1168. /// but it may still fail, later, for other reasons.
  1169. static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
  1170. Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
  1171. TemplateDeductionInfo &Info,
  1172. SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
  1173. bool PartialOrdering, bool DeducedFromArrayBound) {
  1174. // If the argument type is a pack expansion, look at its pattern.
  1175. // This isn't explicitly called out
  1176. if (const auto *AExp = dyn_cast<PackExpansionType>(A))
  1177. A = AExp->getPattern();
  1178. assert(!isa<PackExpansionType>(A.getCanonicalType()));
  1179. if (PartialOrdering) {
  1180. // C++11 [temp.deduct.partial]p5:
  1181. // Before the partial ordering is done, certain transformations are
  1182. // performed on the types used for partial ordering:
  1183. // - If P is a reference type, P is replaced by the type referred to.
  1184. const ReferenceType *PRef = P->getAs<ReferenceType>();
  1185. if (PRef)
  1186. P = PRef->getPointeeType();
  1187. // - If A is a reference type, A is replaced by the type referred to.
  1188. const ReferenceType *ARef = A->getAs<ReferenceType>();
  1189. if (ARef)
  1190. A = A->getPointeeType();
  1191. if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
  1192. // C++11 [temp.deduct.partial]p9:
  1193. // If, for a given type, deduction succeeds in both directions (i.e.,
  1194. // the types are identical after the transformations above) and both
  1195. // P and A were reference types [...]:
  1196. // - if [one type] was an lvalue reference and [the other type] was
  1197. // not, [the other type] is not considered to be at least as
  1198. // specialized as [the first type]
  1199. // - if [one type] is more cv-qualified than [the other type],
  1200. // [the other type] is not considered to be at least as specialized
  1201. // as [the first type]
  1202. // Objective-C ARC adds:
  1203. // - [one type] has non-trivial lifetime, [the other type] has
  1204. // __unsafe_unretained lifetime, and the types are otherwise
  1205. // identical
  1206. //
  1207. // A is "considered to be at least as specialized" as P iff deduction
  1208. // succeeds, so we model this as a deduction failure. Note that
  1209. // [the first type] is P and [the other type] is A here; the standard
  1210. // gets this backwards.
  1211. Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
  1212. if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
  1213. PQuals.isStrictSupersetOf(AQuals) ||
  1214. (PQuals.hasNonTrivialObjCLifetime() &&
  1215. AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
  1216. PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
  1217. Info.FirstArg = TemplateArgument(P);
  1218. Info.SecondArg = TemplateArgument(A);
  1219. return Sema::TDK_NonDeducedMismatch;
  1220. }
  1221. }
  1222. Qualifiers DiscardedQuals;
  1223. // C++11 [temp.deduct.partial]p7:
  1224. // Remove any top-level cv-qualifiers:
  1225. // - If P is a cv-qualified type, P is replaced by the cv-unqualified
  1226. // version of P.
  1227. P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
  1228. // - If A is a cv-qualified type, A is replaced by the cv-unqualified
  1229. // version of A.
  1230. A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
  1231. } else {
  1232. // C++0x [temp.deduct.call]p4 bullet 1:
  1233. // - If the original P is a reference type, the deduced A (i.e., the type
  1234. // referred to by the reference) can be more cv-qualified than the
  1235. // transformed A.
  1236. if (TDF & TDF_ParamWithReferenceType) {
  1237. Qualifiers Quals;
  1238. QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
  1239. Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers());
  1240. P = S.Context.getQualifiedType(UnqualP, Quals);
  1241. }
  1242. if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
  1243. // C++0x [temp.deduct.type]p10:
  1244. // If P and A are function types that originated from deduction when
  1245. // taking the address of a function template (14.8.2.2) or when deducing
  1246. // template arguments from a function declaration (14.8.2.6) and Pi and
  1247. // Ai are parameters of the top-level parameter-type-list of P and A,
  1248. // respectively, Pi is adjusted if it is a forwarding reference and Ai
  1249. // is an lvalue reference, in
  1250. // which case the type of Pi is changed to be the template parameter
  1251. // type (i.e., T&& is changed to simply T). [ Note: As a result, when
  1252. // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
  1253. // deduced as X&. - end note ]
  1254. TDF &= ~TDF_TopLevelParameterTypeList;
  1255. if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
  1256. A->isLValueReferenceType())
  1257. P = P->getPointeeType();
  1258. }
  1259. }
  1260. // C++ [temp.deduct.type]p9:
  1261. // A template type argument T, a template template argument TT or a
  1262. // template non-type argument i can be deduced if P and A have one of
  1263. // the following forms:
  1264. //
  1265. // T
  1266. // cv-list T
  1267. if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
  1268. // Just skip any attempts to deduce from a placeholder type or a parameter
  1269. // at a different depth.
  1270. if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
  1271. return Sema::TDK_Success;
  1272. unsigned Index = TTP->getIndex();
  1273. // If the argument type is an array type, move the qualifiers up to the
  1274. // top level, so they can be matched with the qualifiers on the parameter.
  1275. if (A->isArrayType()) {
  1276. Qualifiers Quals;
  1277. A = S.Context.getUnqualifiedArrayType(A, Quals);
  1278. if (Quals)
  1279. A = S.Context.getQualifiedType(A, Quals);
  1280. }
  1281. // The argument type can not be less qualified than the parameter
  1282. // type.
  1283. if (!(TDF & TDF_IgnoreQualifiers) &&
  1284. hasInconsistentOrSupersetQualifiersOf(P, A)) {
  1285. Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
  1286. Info.FirstArg = TemplateArgument(P);
  1287. Info.SecondArg = TemplateArgument(A);
  1288. return Sema::TDK_Underqualified;
  1289. }
  1290. // Do not match a function type with a cv-qualified type.
  1291. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
  1292. if (A->isFunctionType() && P.hasQualifiers())
  1293. return Sema::TDK_NonDeducedMismatch;
  1294. assert(TTP->getDepth() == Info.getDeducedDepth() &&
  1295. "saw template type parameter with wrong depth");
  1296. assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
  1297. "Unresolved overloaded function");
  1298. QualType DeducedType = A;
  1299. // Remove any qualifiers on the parameter from the deduced type.
  1300. // We checked the qualifiers for consistency above.
  1301. Qualifiers DeducedQs = DeducedType.getQualifiers();
  1302. Qualifiers ParamQs = P.getQualifiers();
  1303. DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
  1304. if (ParamQs.hasObjCGCAttr())
  1305. DeducedQs.removeObjCGCAttr();
  1306. if (ParamQs.hasAddressSpace())
  1307. DeducedQs.removeAddressSpace();
  1308. if (ParamQs.hasObjCLifetime())
  1309. DeducedQs.removeObjCLifetime();
  1310. // Objective-C ARC:
  1311. // If template deduction would produce a lifetime qualifier on a type
  1312. // that is not a lifetime type, template argument deduction fails.
  1313. if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
  1314. !DeducedType->isDependentType()) {
  1315. Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
  1316. Info.FirstArg = TemplateArgument(P);
  1317. Info.SecondArg = TemplateArgument(A);
  1318. return Sema::TDK_Underqualified;
  1319. }
  1320. // Objective-C ARC:
  1321. // If template deduction would produce an argument type with lifetime type
  1322. // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
  1323. if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
  1324. !DeducedQs.hasObjCLifetime())
  1325. DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
  1326. DeducedType =
  1327. S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
  1328. DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
  1329. DeducedTemplateArgument Result =
  1330. checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
  1331. if (Result.isNull()) {
  1332. Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
  1333. Info.FirstArg = Deduced[Index];
  1334. Info.SecondArg = NewDeduced;
  1335. return Sema::TDK_Inconsistent;
  1336. }
  1337. Deduced[Index] = Result;
  1338. return Sema::TDK_Success;
  1339. }
  1340. // Set up the template argument deduction information for a failure.
  1341. Info.FirstArg = TemplateArgument(P);
  1342. Info.SecondArg = TemplateArgument(A);
  1343. // If the parameter is an already-substituted template parameter
  1344. // pack, do nothing: we don't know which of its arguments to look
  1345. // at, so we have to wait until all of the parameter packs in this
  1346. // expansion have arguments.
  1347. if (P->getAs<SubstTemplateTypeParmPackType>())
  1348. return Sema::TDK_Success;
  1349. // Check the cv-qualifiers on the parameter and argument types.
  1350. if (!(TDF & TDF_IgnoreQualifiers)) {
  1351. if (TDF & TDF_ParamWithReferenceType) {
  1352. if (hasInconsistentOrSupersetQualifiersOf(P, A))
  1353. return Sema::TDK_NonDeducedMismatch;
  1354. } else if (TDF & TDF_ArgWithReferenceType) {
  1355. // C++ [temp.deduct.conv]p4:
  1356. // If the original A is a reference type, A can be more cv-qualified
  1357. // than the deduced A
  1358. if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
  1359. return Sema::TDK_NonDeducedMismatch;
  1360. // Strip out all extra qualifiers from the argument to figure out the
  1361. // type we're converting to, prior to the qualification conversion.
  1362. Qualifiers Quals;
  1363. A = S.Context.getUnqualifiedArrayType(A, Quals);
  1364. A = S.Context.getQualifiedType(A, P.getQualifiers());
  1365. } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
  1366. if (P.getCVRQualifiers() != A.getCVRQualifiers())
  1367. return Sema::TDK_NonDeducedMismatch;
  1368. }
  1369. }
  1370. // If the parameter type is not dependent, there is nothing to deduce.
  1371. if (!P->isDependentType()) {
  1372. if (TDF & TDF_SkipNonDependent)
  1373. return Sema::TDK_Success;
  1374. if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(P, A)
  1375. : S.Context.hasSameType(P, A))
  1376. return Sema::TDK_Success;
  1377. if (TDF & TDF_AllowCompatibleFunctionType &&
  1378. S.isSameOrCompatibleFunctionType(P, A))
  1379. return Sema::TDK_Success;
  1380. if (!(TDF & TDF_IgnoreQualifiers))
  1381. return Sema::TDK_NonDeducedMismatch;
  1382. // Otherwise, when ignoring qualifiers, the types not having the same
  1383. // unqualified type does not mean they do not match, so in this case we
  1384. // must keep going and analyze with a non-dependent parameter type.
  1385. }
  1386. switch (P.getCanonicalType()->getTypeClass()) {
  1387. // Non-canonical types cannot appear here.
  1388. #define NON_CANONICAL_TYPE(Class, Base) \
  1389. case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
  1390. #define TYPE(Class, Base)
  1391. #include "clang/AST/TypeNodes.inc"
  1392. case Type::TemplateTypeParm:
  1393. case Type::SubstTemplateTypeParmPack:
  1394. llvm_unreachable("Type nodes handled above");
  1395. case Type::Auto:
  1396. // FIXME: Implement deduction in dependent case.
  1397. if (P->isDependentType())
  1398. return Sema::TDK_Success;
  1399. LLVM_FALLTHROUGH;
  1400. case Type::Builtin:
  1401. case Type::VariableArray:
  1402. case Type::Vector:
  1403. case Type::FunctionNoProto:
  1404. case Type::Record:
  1405. case Type::Enum:
  1406. case Type::ObjCObject:
  1407. case Type::ObjCInterface:
  1408. case Type::ObjCObjectPointer:
  1409. case Type::BitInt:
  1410. return (TDF & TDF_SkipNonDependent) ||
  1411. ((TDF & TDF_IgnoreQualifiers)
  1412. ? S.Context.hasSameUnqualifiedType(P, A)
  1413. : S.Context.hasSameType(P, A))
  1414. ? Sema::TDK_Success
  1415. : Sema::TDK_NonDeducedMismatch;
  1416. // _Complex T [placeholder extension]
  1417. case Type::Complex: {
  1418. const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
  1419. if (!CA)
  1420. return Sema::TDK_NonDeducedMismatch;
  1421. return DeduceTemplateArgumentsByTypeMatch(
  1422. S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
  1423. Deduced, TDF);
  1424. }
  1425. // _Atomic T [extension]
  1426. case Type::Atomic: {
  1427. const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
  1428. if (!AA)
  1429. return Sema::TDK_NonDeducedMismatch;
  1430. return DeduceTemplateArgumentsByTypeMatch(
  1431. S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
  1432. Deduced, TDF);
  1433. }
  1434. // T *
  1435. case Type::Pointer: {
  1436. QualType PointeeType;
  1437. if (const auto *PA = A->getAs<PointerType>()) {
  1438. PointeeType = PA->getPointeeType();
  1439. } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
  1440. PointeeType = PA->getPointeeType();
  1441. } else {
  1442. return Sema::TDK_NonDeducedMismatch;
  1443. }
  1444. return DeduceTemplateArgumentsByTypeMatch(
  1445. S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
  1446. PointeeType, Info, Deduced,
  1447. TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass));
  1448. }
  1449. // T &
  1450. case Type::LValueReference: {
  1451. const auto *RP = P->castAs<LValueReferenceType>(),
  1452. *RA = A->getAs<LValueReferenceType>();
  1453. if (!RA)
  1454. return Sema::TDK_NonDeducedMismatch;
  1455. return DeduceTemplateArgumentsByTypeMatch(
  1456. S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
  1457. Deduced, 0);
  1458. }
  1459. // T && [C++0x]
  1460. case Type::RValueReference: {
  1461. const auto *RP = P->castAs<RValueReferenceType>(),
  1462. *RA = A->getAs<RValueReferenceType>();
  1463. if (!RA)
  1464. return Sema::TDK_NonDeducedMismatch;
  1465. return DeduceTemplateArgumentsByTypeMatch(
  1466. S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
  1467. Deduced, 0);
  1468. }
  1469. // T [] (implied, but not stated explicitly)
  1470. case Type::IncompleteArray: {
  1471. const auto *IAA = S.Context.getAsIncompleteArrayType(A);
  1472. if (!IAA)
  1473. return Sema::TDK_NonDeducedMismatch;
  1474. return DeduceTemplateArgumentsByTypeMatch(
  1475. S, TemplateParams,
  1476. S.Context.getAsIncompleteArrayType(P)->getElementType(),
  1477. IAA->getElementType(), Info, Deduced, TDF & TDF_IgnoreQualifiers);
  1478. }
  1479. // T [integer-constant]
  1480. case Type::ConstantArray: {
  1481. const auto *CAA = S.Context.getAsConstantArrayType(A),
  1482. *CAP = S.Context.getAsConstantArrayType(P);
  1483. assert(CAP);
  1484. if (!CAA || CAA->getSize() != CAP->getSize())
  1485. return Sema::TDK_NonDeducedMismatch;
  1486. return DeduceTemplateArgumentsByTypeMatch(
  1487. S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
  1488. Deduced, TDF & TDF_IgnoreQualifiers);
  1489. }
  1490. // type [i]
  1491. case Type::DependentSizedArray: {
  1492. const auto *AA = S.Context.getAsArrayType(A);
  1493. if (!AA)
  1494. return Sema::TDK_NonDeducedMismatch;
  1495. // Check the element type of the arrays
  1496. const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
  1497. assert(DAP);
  1498. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1499. S, TemplateParams, DAP->getElementType(), AA->getElementType(),
  1500. Info, Deduced, TDF & TDF_IgnoreQualifiers))
  1501. return Result;
  1502. // Determine the array bound is something we can deduce.
  1503. const NonTypeTemplateParmDecl *NTTP =
  1504. getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
  1505. if (!NTTP)
  1506. return Sema::TDK_Success;
  1507. // We can perform template argument deduction for the given non-type
  1508. // template parameter.
  1509. assert(NTTP->getDepth() == Info.getDeducedDepth() &&
  1510. "saw non-type template parameter with wrong depth");
  1511. if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
  1512. llvm::APSInt Size(CAA->getSize());
  1513. return DeduceNonTypeTemplateArgument(
  1514. S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
  1515. /*ArrayBound=*/true, Info, Deduced);
  1516. }
  1517. if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
  1518. if (DAA->getSizeExpr())
  1519. return DeduceNonTypeTemplateArgument(
  1520. S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
  1521. // Incomplete type does not match a dependently-sized array type
  1522. return Sema::TDK_NonDeducedMismatch;
  1523. }
  1524. // type(*)(T)
  1525. // T(*)()
  1526. // T(*)(T)
  1527. case Type::FunctionProto: {
  1528. const auto *FPP = P->castAs<FunctionProtoType>(),
  1529. *FPA = A->getAs<FunctionProtoType>();
  1530. if (!FPA)
  1531. return Sema::TDK_NonDeducedMismatch;
  1532. if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
  1533. FPP->getRefQualifier() != FPA->getRefQualifier() ||
  1534. FPP->isVariadic() != FPA->isVariadic())
  1535. return Sema::TDK_NonDeducedMismatch;
  1536. // Check return types.
  1537. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1538. S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
  1539. Info, Deduced, 0,
  1540. /*PartialOrdering=*/false,
  1541. /*DeducedFromArrayBound=*/false))
  1542. return Result;
  1543. // Check parameter types.
  1544. if (auto Result = DeduceTemplateArguments(
  1545. S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
  1546. FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
  1547. TDF & TDF_TopLevelParameterTypeList))
  1548. return Result;
  1549. if (TDF & TDF_AllowCompatibleFunctionType)
  1550. return Sema::TDK_Success;
  1551. // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
  1552. // deducing through the noexcept-specifier if it's part of the canonical
  1553. // type. libstdc++ relies on this.
  1554. Expr *NoexceptExpr = FPP->getNoexceptExpr();
  1555. if (const NonTypeTemplateParmDecl *NTTP =
  1556. NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
  1557. : nullptr) {
  1558. assert(NTTP->getDepth() == Info.getDeducedDepth() &&
  1559. "saw non-type template parameter with wrong depth");
  1560. llvm::APSInt Noexcept(1);
  1561. switch (FPA->canThrow()) {
  1562. case CT_Cannot:
  1563. Noexcept = 1;
  1564. LLVM_FALLTHROUGH;
  1565. case CT_Can:
  1566. // We give E in noexcept(E) the "deduced from array bound" treatment.
  1567. // FIXME: Should we?
  1568. return DeduceNonTypeTemplateArgument(
  1569. S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
  1570. /*DeducedFromArrayBound=*/true, Info, Deduced);
  1571. case CT_Dependent:
  1572. if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
  1573. return DeduceNonTypeTemplateArgument(
  1574. S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
  1575. // Can't deduce anything from throw(T...).
  1576. break;
  1577. }
  1578. }
  1579. // FIXME: Detect non-deduced exception specification mismatches?
  1580. //
  1581. // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
  1582. // top-level differences in noexcept-specifications.
  1583. return Sema::TDK_Success;
  1584. }
  1585. case Type::InjectedClassName:
  1586. // Treat a template's injected-class-name as if the template
  1587. // specialization type had been used.
  1588. // template-name<T> (where template-name refers to a class template)
  1589. // template-name<i>
  1590. // TT<T>
  1591. // TT<i>
  1592. // TT<>
  1593. case Type::TemplateSpecialization: {
  1594. // When Arg cannot be a derived class, we can just try to deduce template
  1595. // arguments from the template-id.
  1596. if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
  1597. return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
  1598. Deduced);
  1599. SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
  1600. Deduced.end());
  1601. auto Result =
  1602. DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
  1603. if (Result == Sema::TDK_Success)
  1604. return Result;
  1605. // We cannot inspect base classes as part of deduction when the type
  1606. // is incomplete, so either instantiate any templates necessary to
  1607. // complete the type, or skip over it if it cannot be completed.
  1608. if (!S.isCompleteType(Info.getLocation(), A))
  1609. return Result;
  1610. // Reset the incorrectly deduced argument from above.
  1611. Deduced = DeducedOrig;
  1612. // Check bases according to C++14 [temp.deduct.call] p4b3:
  1613. auto BaseResult = DeduceTemplateBases(S, getCanonicalRD(A),
  1614. TemplateParams, P, Info, Deduced);
  1615. return BaseResult != Sema::TDK_Invalid ? BaseResult : Result;
  1616. }
  1617. // T type::*
  1618. // T T::*
  1619. // T (type::*)()
  1620. // type (T::*)()
  1621. // type (type::*)(T)
  1622. // type (T::*)(T)
  1623. // T (type::*)(T)
  1624. // T (T::*)()
  1625. // T (T::*)(T)
  1626. case Type::MemberPointer: {
  1627. const auto *MPP = P->castAs<MemberPointerType>(),
  1628. *MPA = A->getAs<MemberPointerType>();
  1629. if (!MPA)
  1630. return Sema::TDK_NonDeducedMismatch;
  1631. QualType PPT = MPP->getPointeeType();
  1632. if (PPT->isFunctionType())
  1633. S.adjustMemberFunctionCC(PPT, /*IsStatic=*/true,
  1634. /*IsCtorOrDtor=*/false, Info.getLocation());
  1635. QualType APT = MPA->getPointeeType();
  1636. if (APT->isFunctionType())
  1637. S.adjustMemberFunctionCC(APT, /*IsStatic=*/true,
  1638. /*IsCtorOrDtor=*/false, Info.getLocation());
  1639. unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
  1640. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1641. S, TemplateParams, PPT, APT, Info, Deduced, SubTDF))
  1642. return Result;
  1643. return DeduceTemplateArgumentsByTypeMatch(
  1644. S, TemplateParams, QualType(MPP->getClass(), 0),
  1645. QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
  1646. }
  1647. // (clang extension)
  1648. //
  1649. // type(^)(T)
  1650. // T(^)()
  1651. // T(^)(T)
  1652. case Type::BlockPointer: {
  1653. const auto *BPP = P->castAs<BlockPointerType>(),
  1654. *BPA = A->getAs<BlockPointerType>();
  1655. if (!BPA)
  1656. return Sema::TDK_NonDeducedMismatch;
  1657. return DeduceTemplateArgumentsByTypeMatch(
  1658. S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
  1659. Deduced, 0);
  1660. }
  1661. // (clang extension)
  1662. //
  1663. // T __attribute__(((ext_vector_type(<integral constant>))))
  1664. case Type::ExtVector: {
  1665. const auto *VP = P->castAs<ExtVectorType>();
  1666. QualType ElementType;
  1667. if (const auto *VA = A->getAs<ExtVectorType>()) {
  1668. // Make sure that the vectors have the same number of elements.
  1669. if (VP->getNumElements() != VA->getNumElements())
  1670. return Sema::TDK_NonDeducedMismatch;
  1671. ElementType = VA->getElementType();
  1672. } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
  1673. // We can't check the number of elements, since the argument has a
  1674. // dependent number of elements. This can only occur during partial
  1675. // ordering.
  1676. ElementType = VA->getElementType();
  1677. } else {
  1678. return Sema::TDK_NonDeducedMismatch;
  1679. }
  1680. // Perform deduction on the element types.
  1681. return DeduceTemplateArgumentsByTypeMatch(
  1682. S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
  1683. TDF);
  1684. }
  1685. case Type::DependentVector: {
  1686. const auto *VP = P->castAs<DependentVectorType>();
  1687. if (const auto *VA = A->getAs<VectorType>()) {
  1688. // Perform deduction on the element types.
  1689. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1690. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1691. Info, Deduced, TDF))
  1692. return Result;
  1693. // Perform deduction on the vector size, if we can.
  1694. const NonTypeTemplateParmDecl *NTTP =
  1695. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1696. if (!NTTP)
  1697. return Sema::TDK_Success;
  1698. llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
  1699. ArgSize = VA->getNumElements();
  1700. // Note that we use the "array bound" rules here; just like in that
  1701. // case, we don't have any particular type for the vector size, but
  1702. // we can provide one if necessary.
  1703. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
  1704. S.Context.UnsignedIntTy, true,
  1705. Info, Deduced);
  1706. }
  1707. if (const auto *VA = A->getAs<DependentVectorType>()) {
  1708. // Perform deduction on the element types.
  1709. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1710. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1711. Info, Deduced, TDF))
  1712. return Result;
  1713. // Perform deduction on the vector size, if we can.
  1714. const NonTypeTemplateParmDecl *NTTP =
  1715. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1716. if (!NTTP)
  1717. return Sema::TDK_Success;
  1718. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1719. VA->getSizeExpr(), Info, Deduced);
  1720. }
  1721. return Sema::TDK_NonDeducedMismatch;
  1722. }
  1723. // (clang extension)
  1724. //
  1725. // T __attribute__(((ext_vector_type(N))))
  1726. case Type::DependentSizedExtVector: {
  1727. const auto *VP = P->castAs<DependentSizedExtVectorType>();
  1728. if (const auto *VA = A->getAs<ExtVectorType>()) {
  1729. // Perform deduction on the element types.
  1730. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1731. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1732. Info, Deduced, TDF))
  1733. return Result;
  1734. // Perform deduction on the vector size, if we can.
  1735. const NonTypeTemplateParmDecl *NTTP =
  1736. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1737. if (!NTTP)
  1738. return Sema::TDK_Success;
  1739. llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
  1740. ArgSize = VA->getNumElements();
  1741. // Note that we use the "array bound" rules here; just like in that
  1742. // case, we don't have any particular type for the vector size, but
  1743. // we can provide one if necessary.
  1744. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
  1745. S.Context.IntTy, true, Info,
  1746. Deduced);
  1747. }
  1748. if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
  1749. // Perform deduction on the element types.
  1750. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1751. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1752. Info, Deduced, TDF))
  1753. return Result;
  1754. // Perform deduction on the vector size, if we can.
  1755. const NonTypeTemplateParmDecl *NTTP =
  1756. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1757. if (!NTTP)
  1758. return Sema::TDK_Success;
  1759. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1760. VA->getSizeExpr(), Info, Deduced);
  1761. }
  1762. return Sema::TDK_NonDeducedMismatch;
  1763. }
  1764. // (clang extension)
  1765. //
  1766. // T __attribute__((matrix_type(<integral constant>,
  1767. // <integral constant>)))
  1768. case Type::ConstantMatrix: {
  1769. const auto *MP = P->castAs<ConstantMatrixType>(),
  1770. *MA = A->getAs<ConstantMatrixType>();
  1771. if (!MA)
  1772. return Sema::TDK_NonDeducedMismatch;
  1773. // Check that the dimensions are the same
  1774. if (MP->getNumRows() != MA->getNumRows() ||
  1775. MP->getNumColumns() != MA->getNumColumns()) {
  1776. return Sema::TDK_NonDeducedMismatch;
  1777. }
  1778. // Perform deduction on element types.
  1779. return DeduceTemplateArgumentsByTypeMatch(
  1780. S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
  1781. Deduced, TDF);
  1782. }
  1783. case Type::DependentSizedMatrix: {
  1784. const auto *MP = P->castAs<DependentSizedMatrixType>();
  1785. const auto *MA = A->getAs<MatrixType>();
  1786. if (!MA)
  1787. return Sema::TDK_NonDeducedMismatch;
  1788. // Check the element type of the matrixes.
  1789. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1790. S, TemplateParams, MP->getElementType(), MA->getElementType(),
  1791. Info, Deduced, TDF))
  1792. return Result;
  1793. // Try to deduce a matrix dimension.
  1794. auto DeduceMatrixArg =
  1795. [&S, &Info, &Deduced, &TemplateParams](
  1796. Expr *ParamExpr, const MatrixType *A,
  1797. unsigned (ConstantMatrixType::*GetArgDimension)() const,
  1798. Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
  1799. const auto *ACM = dyn_cast<ConstantMatrixType>(A);
  1800. const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
  1801. if (!ParamExpr->isValueDependent()) {
  1802. Optional<llvm::APSInt> ParamConst =
  1803. ParamExpr->getIntegerConstantExpr(S.Context);
  1804. if (!ParamConst)
  1805. return Sema::TDK_NonDeducedMismatch;
  1806. if (ACM) {
  1807. if ((ACM->*GetArgDimension)() == *ParamConst)
  1808. return Sema::TDK_Success;
  1809. return Sema::TDK_NonDeducedMismatch;
  1810. }
  1811. Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
  1812. if (Optional<llvm::APSInt> ArgConst =
  1813. ArgExpr->getIntegerConstantExpr(S.Context))
  1814. if (*ArgConst == *ParamConst)
  1815. return Sema::TDK_Success;
  1816. return Sema::TDK_NonDeducedMismatch;
  1817. }
  1818. const NonTypeTemplateParmDecl *NTTP =
  1819. getDeducedParameterFromExpr(Info, ParamExpr);
  1820. if (!NTTP)
  1821. return Sema::TDK_Success;
  1822. if (ACM) {
  1823. llvm::APSInt ArgConst(
  1824. S.Context.getTypeSize(S.Context.getSizeType()));
  1825. ArgConst = (ACM->*GetArgDimension)();
  1826. return DeduceNonTypeTemplateArgument(
  1827. S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
  1828. /*ArrayBound=*/true, Info, Deduced);
  1829. }
  1830. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1831. (ADM->*GetArgDimensionExpr)(),
  1832. Info, Deduced);
  1833. };
  1834. if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
  1835. &ConstantMatrixType::getNumRows,
  1836. &DependentSizedMatrixType::getRowExpr))
  1837. return Result;
  1838. return DeduceMatrixArg(MP->getColumnExpr(), MA,
  1839. &ConstantMatrixType::getNumColumns,
  1840. &DependentSizedMatrixType::getColumnExpr);
  1841. }
  1842. // (clang extension)
  1843. //
  1844. // T __attribute__(((address_space(N))))
  1845. case Type::DependentAddressSpace: {
  1846. const auto *ASP = P->castAs<DependentAddressSpaceType>();
  1847. if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
  1848. // Perform deduction on the pointer type.
  1849. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1850. S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
  1851. Info, Deduced, TDF))
  1852. return Result;
  1853. // Perform deduction on the address space, if we can.
  1854. const NonTypeTemplateParmDecl *NTTP =
  1855. getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
  1856. if (!NTTP)
  1857. return Sema::TDK_Success;
  1858. return DeduceNonTypeTemplateArgument(
  1859. S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
  1860. }
  1861. if (isTargetAddressSpace(A.getAddressSpace())) {
  1862. llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
  1863. false);
  1864. ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
  1865. // Perform deduction on the pointer types.
  1866. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1867. S, TemplateParams, ASP->getPointeeType(),
  1868. S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF))
  1869. return Result;
  1870. // Perform deduction on the address space, if we can.
  1871. const NonTypeTemplateParmDecl *NTTP =
  1872. getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
  1873. if (!NTTP)
  1874. return Sema::TDK_Success;
  1875. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1876. ArgAddressSpace, S.Context.IntTy,
  1877. true, Info, Deduced);
  1878. }
  1879. return Sema::TDK_NonDeducedMismatch;
  1880. }
  1881. case Type::DependentBitInt: {
  1882. const auto *IP = P->castAs<DependentBitIntType>();
  1883. if (const auto *IA = A->getAs<BitIntType>()) {
  1884. if (IP->isUnsigned() != IA->isUnsigned())
  1885. return Sema::TDK_NonDeducedMismatch;
  1886. const NonTypeTemplateParmDecl *NTTP =
  1887. getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
  1888. if (!NTTP)
  1889. return Sema::TDK_Success;
  1890. llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
  1891. ArgSize = IA->getNumBits();
  1892. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
  1893. S.Context.IntTy, true, Info,
  1894. Deduced);
  1895. }
  1896. if (const auto *IA = A->getAs<DependentBitIntType>()) {
  1897. if (IP->isUnsigned() != IA->isUnsigned())
  1898. return Sema::TDK_NonDeducedMismatch;
  1899. return Sema::TDK_Success;
  1900. }
  1901. return Sema::TDK_NonDeducedMismatch;
  1902. }
  1903. case Type::TypeOfExpr:
  1904. case Type::TypeOf:
  1905. case Type::DependentName:
  1906. case Type::UnresolvedUsing:
  1907. case Type::Decltype:
  1908. case Type::UnaryTransform:
  1909. case Type::DeducedTemplateSpecialization:
  1910. case Type::DependentTemplateSpecialization:
  1911. case Type::PackExpansion:
  1912. case Type::Pipe:
  1913. // No template argument deduction for these types
  1914. return Sema::TDK_Success;
  1915. }
  1916. llvm_unreachable("Invalid Type Class!");
  1917. }
  1918. static Sema::TemplateDeductionResult
  1919. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  1920. const TemplateArgument &P, TemplateArgument A,
  1921. TemplateDeductionInfo &Info,
  1922. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  1923. // If the template argument is a pack expansion, perform template argument
  1924. // deduction against the pattern of that expansion. This only occurs during
  1925. // partial ordering.
  1926. if (A.isPackExpansion())
  1927. A = A.getPackExpansionPattern();
  1928. switch (P.getKind()) {
  1929. case TemplateArgument::Null:
  1930. llvm_unreachable("Null template argument in parameter list");
  1931. case TemplateArgument::Type:
  1932. if (A.getKind() == TemplateArgument::Type)
  1933. return DeduceTemplateArgumentsByTypeMatch(
  1934. S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
  1935. Info.FirstArg = P;
  1936. Info.SecondArg = A;
  1937. return Sema::TDK_NonDeducedMismatch;
  1938. case TemplateArgument::Template:
  1939. if (A.getKind() == TemplateArgument::Template)
  1940. return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
  1941. A.getAsTemplate(), Info, Deduced);
  1942. Info.FirstArg = P;
  1943. Info.SecondArg = A;
  1944. return Sema::TDK_NonDeducedMismatch;
  1945. case TemplateArgument::TemplateExpansion:
  1946. llvm_unreachable("caller should handle pack expansions");
  1947. case TemplateArgument::Declaration:
  1948. if (A.getKind() == TemplateArgument::Declaration &&
  1949. isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
  1950. return Sema::TDK_Success;
  1951. Info.FirstArg = P;
  1952. Info.SecondArg = A;
  1953. return Sema::TDK_NonDeducedMismatch;
  1954. case TemplateArgument::NullPtr:
  1955. if (A.getKind() == TemplateArgument::NullPtr &&
  1956. S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
  1957. return Sema::TDK_Success;
  1958. Info.FirstArg = P;
  1959. Info.SecondArg = A;
  1960. return Sema::TDK_NonDeducedMismatch;
  1961. case TemplateArgument::Integral:
  1962. if (A.getKind() == TemplateArgument::Integral) {
  1963. if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
  1964. return Sema::TDK_Success;
  1965. }
  1966. Info.FirstArg = P;
  1967. Info.SecondArg = A;
  1968. return Sema::TDK_NonDeducedMismatch;
  1969. case TemplateArgument::Expression:
  1970. if (const NonTypeTemplateParmDecl *NTTP =
  1971. getDeducedParameterFromExpr(Info, P.getAsExpr())) {
  1972. if (A.getKind() == TemplateArgument::Integral)
  1973. return DeduceNonTypeTemplateArgument(
  1974. S, TemplateParams, NTTP, A.getAsIntegral(), A.getIntegralType(),
  1975. /*ArrayBound=*/false, Info, Deduced);
  1976. if (A.getKind() == TemplateArgument::NullPtr)
  1977. return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
  1978. A.getNullPtrType(), Info, Deduced);
  1979. if (A.getKind() == TemplateArgument::Expression)
  1980. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1981. A.getAsExpr(), Info, Deduced);
  1982. if (A.getKind() == TemplateArgument::Declaration)
  1983. return DeduceNonTypeTemplateArgument(
  1984. S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
  1985. Info, Deduced);
  1986. Info.FirstArg = P;
  1987. Info.SecondArg = A;
  1988. return Sema::TDK_NonDeducedMismatch;
  1989. }
  1990. // Can't deduce anything, but that's okay.
  1991. return Sema::TDK_Success;
  1992. case TemplateArgument::Pack:
  1993. llvm_unreachable("Argument packs should be expanded by the caller!");
  1994. }
  1995. llvm_unreachable("Invalid TemplateArgument Kind!");
  1996. }
  1997. /// Determine whether there is a template argument to be used for
  1998. /// deduction.
  1999. ///
  2000. /// This routine "expands" argument packs in-place, overriding its input
  2001. /// parameters so that \c Args[ArgIdx] will be the available template argument.
  2002. ///
  2003. /// \returns true if there is another template argument (which will be at
  2004. /// \c Args[ArgIdx]), false otherwise.
  2005. static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
  2006. unsigned &ArgIdx) {
  2007. if (ArgIdx == Args.size())
  2008. return false;
  2009. const TemplateArgument &Arg = Args[ArgIdx];
  2010. if (Arg.getKind() != TemplateArgument::Pack)
  2011. return true;
  2012. assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
  2013. Args = Arg.pack_elements();
  2014. ArgIdx = 0;
  2015. return ArgIdx < Args.size();
  2016. }
  2017. /// Determine whether the given set of template arguments has a pack
  2018. /// expansion that is not the last template argument.
  2019. static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
  2020. bool FoundPackExpansion = false;
  2021. for (const auto &A : Args) {
  2022. if (FoundPackExpansion)
  2023. return true;
  2024. if (A.getKind() == TemplateArgument::Pack)
  2025. return hasPackExpansionBeforeEnd(A.pack_elements());
  2026. // FIXME: If this is a fixed-arity pack expansion from an outer level of
  2027. // templates, it should not be treated as a pack expansion.
  2028. if (A.isPackExpansion())
  2029. FoundPackExpansion = true;
  2030. }
  2031. return false;
  2032. }
  2033. static Sema::TemplateDeductionResult
  2034. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  2035. ArrayRef<TemplateArgument> Ps,
  2036. ArrayRef<TemplateArgument> As,
  2037. TemplateDeductionInfo &Info,
  2038. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2039. bool NumberOfArgumentsMustMatch) {
  2040. // C++0x [temp.deduct.type]p9:
  2041. // If the template argument list of P contains a pack expansion that is not
  2042. // the last template argument, the entire template argument list is a
  2043. // non-deduced context.
  2044. if (hasPackExpansionBeforeEnd(Ps))
  2045. return Sema::TDK_Success;
  2046. // C++0x [temp.deduct.type]p9:
  2047. // If P has a form that contains <T> or <i>, then each argument Pi of the
  2048. // respective template argument list P is compared with the corresponding
  2049. // argument Ai of the corresponding template argument list of A.
  2050. unsigned ArgIdx = 0, ParamIdx = 0;
  2051. for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
  2052. const TemplateArgument &P = Ps[ParamIdx];
  2053. if (!P.isPackExpansion()) {
  2054. // The simple case: deduce template arguments by matching Pi and Ai.
  2055. // Check whether we have enough arguments.
  2056. if (!hasTemplateArgumentForDeduction(As, ArgIdx))
  2057. return NumberOfArgumentsMustMatch
  2058. ? Sema::TDK_MiscellaneousDeductionFailure
  2059. : Sema::TDK_Success;
  2060. // C++1z [temp.deduct.type]p9:
  2061. // During partial ordering, if Ai was originally a pack expansion [and]
  2062. // Pi is not a pack expansion, template argument deduction fails.
  2063. if (As[ArgIdx].isPackExpansion())
  2064. return Sema::TDK_MiscellaneousDeductionFailure;
  2065. // Perform deduction for this Pi/Ai pair.
  2066. if (auto Result = DeduceTemplateArguments(S, TemplateParams, P,
  2067. As[ArgIdx], Info, Deduced))
  2068. return Result;
  2069. // Move to the next argument.
  2070. ++ArgIdx;
  2071. continue;
  2072. }
  2073. // The parameter is a pack expansion.
  2074. // C++0x [temp.deduct.type]p9:
  2075. // If Pi is a pack expansion, then the pattern of Pi is compared with
  2076. // each remaining argument in the template argument list of A. Each
  2077. // comparison deduces template arguments for subsequent positions in the
  2078. // template parameter packs expanded by Pi.
  2079. TemplateArgument Pattern = P.getPackExpansionPattern();
  2080. // Prepare to deduce the packs within the pattern.
  2081. PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
  2082. // Keep track of the deduced template arguments for each parameter pack
  2083. // expanded by this pack expansion (the outer index) and for each
  2084. // template argument (the inner SmallVectors).
  2085. for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
  2086. PackScope.hasNextElement();
  2087. ++ArgIdx) {
  2088. // Deduce template arguments from the pattern.
  2089. if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pattern,
  2090. As[ArgIdx], Info, Deduced))
  2091. return Result;
  2092. PackScope.nextPackElement();
  2093. }
  2094. // Build argument packs for each of the parameter packs expanded by this
  2095. // pack expansion.
  2096. if (auto Result = PackScope.finish())
  2097. return Result;
  2098. }
  2099. return Sema::TDK_Success;
  2100. }
  2101. static Sema::TemplateDeductionResult
  2102. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  2103. const TemplateArgumentList &ParamList,
  2104. const TemplateArgumentList &ArgList,
  2105. TemplateDeductionInfo &Info,
  2106. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  2107. return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
  2108. ArgList.asArray(), Info, Deduced,
  2109. /*NumberOfArgumentsMustMatch=*/false);
  2110. }
  2111. /// Determine whether two template arguments are the same.
  2112. static bool isSameTemplateArg(ASTContext &Context,
  2113. TemplateArgument X,
  2114. const TemplateArgument &Y,
  2115. bool PackExpansionMatchesPack = false) {
  2116. // If we're checking deduced arguments (X) against original arguments (Y),
  2117. // we will have flattened packs to non-expansions in X.
  2118. if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
  2119. X = X.getPackExpansionPattern();
  2120. if (X.getKind() != Y.getKind())
  2121. return false;
  2122. switch (X.getKind()) {
  2123. case TemplateArgument::Null:
  2124. llvm_unreachable("Comparing NULL template argument");
  2125. case TemplateArgument::Type:
  2126. return Context.getCanonicalType(X.getAsType()) ==
  2127. Context.getCanonicalType(Y.getAsType());
  2128. case TemplateArgument::Declaration:
  2129. return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
  2130. case TemplateArgument::NullPtr:
  2131. return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
  2132. case TemplateArgument::Template:
  2133. case TemplateArgument::TemplateExpansion:
  2134. return Context.getCanonicalTemplateName(
  2135. X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
  2136. Context.getCanonicalTemplateName(
  2137. Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
  2138. case TemplateArgument::Integral:
  2139. return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
  2140. case TemplateArgument::Expression: {
  2141. llvm::FoldingSetNodeID XID, YID;
  2142. X.getAsExpr()->Profile(XID, Context, true);
  2143. Y.getAsExpr()->Profile(YID, Context, true);
  2144. return XID == YID;
  2145. }
  2146. case TemplateArgument::Pack:
  2147. if (X.pack_size() != Y.pack_size())
  2148. return false;
  2149. for (TemplateArgument::pack_iterator XP = X.pack_begin(),
  2150. XPEnd = X.pack_end(),
  2151. YP = Y.pack_begin();
  2152. XP != XPEnd; ++XP, ++YP)
  2153. if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
  2154. return false;
  2155. return true;
  2156. }
  2157. llvm_unreachable("Invalid TemplateArgument Kind!");
  2158. }
  2159. /// Allocate a TemplateArgumentLoc where all locations have
  2160. /// been initialized to the given location.
  2161. ///
  2162. /// \param Arg The template argument we are producing template argument
  2163. /// location information for.
  2164. ///
  2165. /// \param NTTPType For a declaration template argument, the type of
  2166. /// the non-type template parameter that corresponds to this template
  2167. /// argument. Can be null if no type sugar is available to add to the
  2168. /// type from the template argument.
  2169. ///
  2170. /// \param Loc The source location to use for the resulting template
  2171. /// argument.
  2172. TemplateArgumentLoc
  2173. Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
  2174. QualType NTTPType, SourceLocation Loc) {
  2175. switch (Arg.getKind()) {
  2176. case TemplateArgument::Null:
  2177. llvm_unreachable("Can't get a NULL template argument here");
  2178. case TemplateArgument::Type:
  2179. return TemplateArgumentLoc(
  2180. Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
  2181. case TemplateArgument::Declaration: {
  2182. if (NTTPType.isNull())
  2183. NTTPType = Arg.getParamTypeForDecl();
  2184. Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
  2185. .getAs<Expr>();
  2186. return TemplateArgumentLoc(TemplateArgument(E), E);
  2187. }
  2188. case TemplateArgument::NullPtr: {
  2189. if (NTTPType.isNull())
  2190. NTTPType = Arg.getNullPtrType();
  2191. Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
  2192. .getAs<Expr>();
  2193. return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
  2194. E);
  2195. }
  2196. case TemplateArgument::Integral: {
  2197. Expr *E =
  2198. BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
  2199. return TemplateArgumentLoc(TemplateArgument(E), E);
  2200. }
  2201. case TemplateArgument::Template:
  2202. case TemplateArgument::TemplateExpansion: {
  2203. NestedNameSpecifierLocBuilder Builder;
  2204. TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
  2205. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
  2206. Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
  2207. else if (QualifiedTemplateName *QTN =
  2208. Template.getAsQualifiedTemplateName())
  2209. Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
  2210. if (Arg.getKind() == TemplateArgument::Template)
  2211. return TemplateArgumentLoc(Context, Arg,
  2212. Builder.getWithLocInContext(Context), Loc);
  2213. return TemplateArgumentLoc(
  2214. Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
  2215. }
  2216. case TemplateArgument::Expression:
  2217. return TemplateArgumentLoc(Arg, Arg.getAsExpr());
  2218. case TemplateArgument::Pack:
  2219. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
  2220. }
  2221. llvm_unreachable("Invalid TemplateArgument Kind!");
  2222. }
  2223. TemplateArgumentLoc
  2224. Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
  2225. SourceLocation Location) {
  2226. return getTrivialTemplateArgumentLoc(
  2227. Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
  2228. }
  2229. /// Convert the given deduced template argument and add it to the set of
  2230. /// fully-converted template arguments.
  2231. static bool
  2232. ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
  2233. DeducedTemplateArgument Arg,
  2234. NamedDecl *Template,
  2235. TemplateDeductionInfo &Info,
  2236. bool IsDeduced,
  2237. SmallVectorImpl<TemplateArgument> &Output) {
  2238. auto ConvertArg = [&](DeducedTemplateArgument Arg,
  2239. unsigned ArgumentPackIndex) {
  2240. // Convert the deduced template argument into a template
  2241. // argument that we can check, almost as if the user had written
  2242. // the template argument explicitly.
  2243. TemplateArgumentLoc ArgLoc =
  2244. S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
  2245. // Check the template argument, converting it as necessary.
  2246. return S.CheckTemplateArgument(
  2247. Param, ArgLoc, Template, Template->getLocation(),
  2248. Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
  2249. IsDeduced
  2250. ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
  2251. : Sema::CTAK_Deduced)
  2252. : Sema::CTAK_Specified);
  2253. };
  2254. if (Arg.getKind() == TemplateArgument::Pack) {
  2255. // This is a template argument pack, so check each of its arguments against
  2256. // the template parameter.
  2257. SmallVector<TemplateArgument, 2> PackedArgsBuilder;
  2258. for (const auto &P : Arg.pack_elements()) {
  2259. // When converting the deduced template argument, append it to the
  2260. // general output list. We need to do this so that the template argument
  2261. // checking logic has all of the prior template arguments available.
  2262. DeducedTemplateArgument InnerArg(P);
  2263. InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
  2264. assert(InnerArg.getKind() != TemplateArgument::Pack &&
  2265. "deduced nested pack");
  2266. if (P.isNull()) {
  2267. // We deduced arguments for some elements of this pack, but not for
  2268. // all of them. This happens if we get a conditionally-non-deduced
  2269. // context in a pack expansion (such as an overload set in one of the
  2270. // arguments).
  2271. S.Diag(Param->getLocation(),
  2272. diag::err_template_arg_deduced_incomplete_pack)
  2273. << Arg << Param;
  2274. return true;
  2275. }
  2276. if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
  2277. return true;
  2278. // Move the converted template argument into our argument pack.
  2279. PackedArgsBuilder.push_back(Output.pop_back_val());
  2280. }
  2281. // If the pack is empty, we still need to substitute into the parameter
  2282. // itself, in case that substitution fails.
  2283. if (PackedArgsBuilder.empty()) {
  2284. LocalInstantiationScope Scope(S);
  2285. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
  2286. MultiLevelTemplateArgumentList Args(TemplateArgs);
  2287. if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  2288. Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
  2289. NTTP, Output,
  2290. Template->getSourceRange());
  2291. if (Inst.isInvalid() ||
  2292. S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
  2293. NTTP->getDeclName()).isNull())
  2294. return true;
  2295. } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  2296. Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
  2297. TTP, Output,
  2298. Template->getSourceRange());
  2299. if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
  2300. return true;
  2301. }
  2302. // For type parameters, no substitution is ever required.
  2303. }
  2304. // Create the resulting argument pack.
  2305. Output.push_back(
  2306. TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
  2307. return false;
  2308. }
  2309. return ConvertArg(Arg, 0);
  2310. }
  2311. // FIXME: This should not be a template, but
  2312. // ClassTemplatePartialSpecializationDecl sadly does not derive from
  2313. // TemplateDecl.
  2314. template<typename TemplateDeclT>
  2315. static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
  2316. Sema &S, TemplateDeclT *Template, bool IsDeduced,
  2317. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2318. TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
  2319. LocalInstantiationScope *CurrentInstantiationScope = nullptr,
  2320. unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
  2321. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  2322. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  2323. NamedDecl *Param = TemplateParams->getParam(I);
  2324. // C++0x [temp.arg.explicit]p3:
  2325. // A trailing template parameter pack (14.5.3) not otherwise deduced will
  2326. // be deduced to an empty sequence of template arguments.
  2327. // FIXME: Where did the word "trailing" come from?
  2328. if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
  2329. if (auto Result =
  2330. PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
  2331. return Result;
  2332. }
  2333. if (!Deduced[I].isNull()) {
  2334. if (I < NumAlreadyConverted) {
  2335. // We may have had explicitly-specified template arguments for a
  2336. // template parameter pack (that may or may not have been extended
  2337. // via additional deduced arguments).
  2338. if (Param->isParameterPack() && CurrentInstantiationScope &&
  2339. CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
  2340. // Forget the partially-substituted pack; its substitution is now
  2341. // complete.
  2342. CurrentInstantiationScope->ResetPartiallySubstitutedPack();
  2343. // We still need to check the argument in case it was extended by
  2344. // deduction.
  2345. } else {
  2346. // We have already fully type-checked and converted this
  2347. // argument, because it was explicitly-specified. Just record the
  2348. // presence of this argument.
  2349. Builder.push_back(Deduced[I]);
  2350. continue;
  2351. }
  2352. }
  2353. // We may have deduced this argument, so it still needs to be
  2354. // checked and converted.
  2355. if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
  2356. IsDeduced, Builder)) {
  2357. Info.Param = makeTemplateParameter(Param);
  2358. // FIXME: These template arguments are temporary. Free them!
  2359. Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
  2360. return Sema::TDK_SubstitutionFailure;
  2361. }
  2362. continue;
  2363. }
  2364. // Substitute into the default template argument, if available.
  2365. bool HasDefaultArg = false;
  2366. TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
  2367. if (!TD) {
  2368. assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
  2369. isa<VarTemplatePartialSpecializationDecl>(Template));
  2370. return Sema::TDK_Incomplete;
  2371. }
  2372. TemplateArgumentLoc DefArg;
  2373. {
  2374. Qualifiers ThisTypeQuals;
  2375. CXXRecordDecl *ThisContext = nullptr;
  2376. if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
  2377. if (Rec->isLambda())
  2378. if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
  2379. ThisContext = Method->getParent();
  2380. ThisTypeQuals = Method->getMethodQualifiers();
  2381. }
  2382. Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
  2383. S.getLangOpts().CPlusPlus17);
  2384. DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
  2385. TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
  2386. HasDefaultArg);
  2387. }
  2388. // If there was no default argument, deduction is incomplete.
  2389. if (DefArg.getArgument().isNull()) {
  2390. Info.Param = makeTemplateParameter(
  2391. const_cast<NamedDecl *>(TemplateParams->getParam(I)));
  2392. Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
  2393. if (PartialOverloading) break;
  2394. return HasDefaultArg ? Sema::TDK_SubstitutionFailure
  2395. : Sema::TDK_Incomplete;
  2396. }
  2397. // Check whether we can actually use the default argument.
  2398. if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
  2399. TD->getSourceRange().getEnd(), 0, Builder,
  2400. Sema::CTAK_Specified)) {
  2401. Info.Param = makeTemplateParameter(
  2402. const_cast<NamedDecl *>(TemplateParams->getParam(I)));
  2403. // FIXME: These template arguments are temporary. Free them!
  2404. Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
  2405. return Sema::TDK_SubstitutionFailure;
  2406. }
  2407. // If we get here, we successfully used the default template argument.
  2408. }
  2409. return Sema::TDK_Success;
  2410. }
  2411. static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
  2412. if (auto *DC = dyn_cast<DeclContext>(D))
  2413. return DC;
  2414. return D->getDeclContext();
  2415. }
  2416. template<typename T> struct IsPartialSpecialization {
  2417. static constexpr bool value = false;
  2418. };
  2419. template<>
  2420. struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
  2421. static constexpr bool value = true;
  2422. };
  2423. template<>
  2424. struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
  2425. static constexpr bool value = true;
  2426. };
  2427. template<typename TemplateDeclT>
  2428. static Sema::TemplateDeductionResult
  2429. CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template,
  2430. ArrayRef<TemplateArgument> DeducedArgs,
  2431. TemplateDeductionInfo& Info) {
  2432. llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
  2433. Template->getAssociatedConstraints(AssociatedConstraints);
  2434. if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
  2435. DeducedArgs, Info.getLocation(),
  2436. Info.AssociatedConstraintsSatisfaction) ||
  2437. !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
  2438. Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
  2439. return Sema::TDK_ConstraintsNotSatisfied;
  2440. }
  2441. return Sema::TDK_Success;
  2442. }
  2443. /// Complete template argument deduction for a partial specialization.
  2444. template <typename T>
  2445. static std::enable_if_t<IsPartialSpecialization<T>::value,
  2446. Sema::TemplateDeductionResult>
  2447. FinishTemplateArgumentDeduction(
  2448. Sema &S, T *Partial, bool IsPartialOrdering,
  2449. const TemplateArgumentList &TemplateArgs,
  2450. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2451. TemplateDeductionInfo &Info) {
  2452. // Unevaluated SFINAE context.
  2453. EnterExpressionEvaluationContext Unevaluated(
  2454. S, Sema::ExpressionEvaluationContext::Unevaluated);
  2455. Sema::SFINAETrap Trap(S);
  2456. Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
  2457. // C++ [temp.deduct.type]p2:
  2458. // [...] or if any template argument remains neither deduced nor
  2459. // explicitly specified, template argument deduction fails.
  2460. SmallVector<TemplateArgument, 4> Builder;
  2461. if (auto Result = ConvertDeducedTemplateArguments(
  2462. S, Partial, IsPartialOrdering, Deduced, Info, Builder))
  2463. return Result;
  2464. // Form the template argument list from the deduced template arguments.
  2465. TemplateArgumentList *DeducedArgumentList
  2466. = TemplateArgumentList::CreateCopy(S.Context, Builder);
  2467. Info.reset(DeducedArgumentList);
  2468. // Substitute the deduced template arguments into the template
  2469. // arguments of the class template partial specialization, and
  2470. // verify that the instantiated template arguments are both valid
  2471. // and are equivalent to the template arguments originally provided
  2472. // to the class template.
  2473. LocalInstantiationScope InstScope(S);
  2474. auto *Template = Partial->getSpecializedTemplate();
  2475. const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
  2476. Partial->getTemplateArgsAsWritten();
  2477. TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
  2478. PartialTemplArgInfo->RAngleLoc);
  2479. if (S.SubstTemplateArguments(
  2480. PartialTemplArgInfo->arguments(),
  2481. MultiLevelTemplateArgumentList(*DeducedArgumentList), InstArgs)) {
  2482. unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
  2483. if (ParamIdx >= Partial->getTemplateParameters()->size())
  2484. ParamIdx = Partial->getTemplateParameters()->size() - 1;
  2485. Decl *Param = const_cast<NamedDecl *>(
  2486. Partial->getTemplateParameters()->getParam(ParamIdx));
  2487. Info.Param = makeTemplateParameter(Param);
  2488. Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
  2489. return Sema::TDK_SubstitutionFailure;
  2490. }
  2491. bool ConstraintsNotSatisfied;
  2492. SmallVector<TemplateArgument, 4> ConvertedInstArgs;
  2493. if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
  2494. false, ConvertedInstArgs,
  2495. /*UpdateArgsWithConversions=*/true,
  2496. &ConstraintsNotSatisfied))
  2497. return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied :
  2498. Sema::TDK_SubstitutionFailure;
  2499. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  2500. for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
  2501. TemplateArgument InstArg = ConvertedInstArgs.data()[I];
  2502. if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
  2503. Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
  2504. Info.FirstArg = TemplateArgs[I];
  2505. Info.SecondArg = InstArg;
  2506. return Sema::TDK_NonDeducedMismatch;
  2507. }
  2508. }
  2509. if (Trap.hasErrorOccurred())
  2510. return Sema::TDK_SubstitutionFailure;
  2511. if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info))
  2512. return Result;
  2513. return Sema::TDK_Success;
  2514. }
  2515. /// Complete template argument deduction for a class or variable template,
  2516. /// when partial ordering against a partial specialization.
  2517. // FIXME: Factor out duplication with partial specialization version above.
  2518. static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
  2519. Sema &S, TemplateDecl *Template, bool PartialOrdering,
  2520. const TemplateArgumentList &TemplateArgs,
  2521. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2522. TemplateDeductionInfo &Info) {
  2523. // Unevaluated SFINAE context.
  2524. EnterExpressionEvaluationContext Unevaluated(
  2525. S, Sema::ExpressionEvaluationContext::Unevaluated);
  2526. Sema::SFINAETrap Trap(S);
  2527. Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
  2528. // C++ [temp.deduct.type]p2:
  2529. // [...] or if any template argument remains neither deduced nor
  2530. // explicitly specified, template argument deduction fails.
  2531. SmallVector<TemplateArgument, 4> Builder;
  2532. if (auto Result = ConvertDeducedTemplateArguments(
  2533. S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
  2534. return Result;
  2535. // Check that we produced the correct argument list.
  2536. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  2537. for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
  2538. TemplateArgument InstArg = Builder[I];
  2539. if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
  2540. /*PackExpansionMatchesPack*/true)) {
  2541. Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
  2542. Info.FirstArg = TemplateArgs[I];
  2543. Info.SecondArg = InstArg;
  2544. return Sema::TDK_NonDeducedMismatch;
  2545. }
  2546. }
  2547. if (Trap.hasErrorOccurred())
  2548. return Sema::TDK_SubstitutionFailure;
  2549. if (auto Result = CheckDeducedArgumentConstraints(S, Template, Builder,
  2550. Info))
  2551. return Result;
  2552. return Sema::TDK_Success;
  2553. }
  2554. /// Perform template argument deduction to determine whether
  2555. /// the given template arguments match the given class template
  2556. /// partial specialization per C++ [temp.class.spec.match].
  2557. Sema::TemplateDeductionResult
  2558. Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
  2559. const TemplateArgumentList &TemplateArgs,
  2560. TemplateDeductionInfo &Info) {
  2561. if (Partial->isInvalidDecl())
  2562. return TDK_Invalid;
  2563. // C++ [temp.class.spec.match]p2:
  2564. // A partial specialization matches a given actual template
  2565. // argument list if the template arguments of the partial
  2566. // specialization can be deduced from the actual template argument
  2567. // list (14.8.2).
  2568. // Unevaluated SFINAE context.
  2569. EnterExpressionEvaluationContext Unevaluated(
  2570. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2571. SFINAETrap Trap(*this);
  2572. // This deduction has no relation to any outer instantiation we might be
  2573. // performing.
  2574. LocalInstantiationScope InstantiationScope(*this);
  2575. SmallVector<DeducedTemplateArgument, 4> Deduced;
  2576. Deduced.resize(Partial->getTemplateParameters()->size());
  2577. if (TemplateDeductionResult Result
  2578. = ::DeduceTemplateArguments(*this,
  2579. Partial->getTemplateParameters(),
  2580. Partial->getTemplateArgs(),
  2581. TemplateArgs, Info, Deduced))
  2582. return Result;
  2583. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
  2584. InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
  2585. Info);
  2586. if (Inst.isInvalid())
  2587. return TDK_InstantiationDepth;
  2588. if (Trap.hasErrorOccurred())
  2589. return Sema::TDK_SubstitutionFailure;
  2590. TemplateDeductionResult Result;
  2591. runWithSufficientStackSpace(Info.getLocation(), [&] {
  2592. Result = ::FinishTemplateArgumentDeduction(*this, Partial,
  2593. /*IsPartialOrdering=*/false,
  2594. TemplateArgs, Deduced, Info);
  2595. });
  2596. return Result;
  2597. }
  2598. /// Perform template argument deduction to determine whether
  2599. /// the given template arguments match the given variable template
  2600. /// partial specialization per C++ [temp.class.spec.match].
  2601. Sema::TemplateDeductionResult
  2602. Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
  2603. const TemplateArgumentList &TemplateArgs,
  2604. TemplateDeductionInfo &Info) {
  2605. if (Partial->isInvalidDecl())
  2606. return TDK_Invalid;
  2607. // C++ [temp.class.spec.match]p2:
  2608. // A partial specialization matches a given actual template
  2609. // argument list if the template arguments of the partial
  2610. // specialization can be deduced from the actual template argument
  2611. // list (14.8.2).
  2612. // Unevaluated SFINAE context.
  2613. EnterExpressionEvaluationContext Unevaluated(
  2614. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2615. SFINAETrap Trap(*this);
  2616. // This deduction has no relation to any outer instantiation we might be
  2617. // performing.
  2618. LocalInstantiationScope InstantiationScope(*this);
  2619. SmallVector<DeducedTemplateArgument, 4> Deduced;
  2620. Deduced.resize(Partial->getTemplateParameters()->size());
  2621. if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
  2622. *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
  2623. TemplateArgs, Info, Deduced))
  2624. return Result;
  2625. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
  2626. InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
  2627. Info);
  2628. if (Inst.isInvalid())
  2629. return TDK_InstantiationDepth;
  2630. if (Trap.hasErrorOccurred())
  2631. return Sema::TDK_SubstitutionFailure;
  2632. TemplateDeductionResult Result;
  2633. runWithSufficientStackSpace(Info.getLocation(), [&] {
  2634. Result = ::FinishTemplateArgumentDeduction(*this, Partial,
  2635. /*IsPartialOrdering=*/false,
  2636. TemplateArgs, Deduced, Info);
  2637. });
  2638. return Result;
  2639. }
  2640. /// Determine whether the given type T is a simple-template-id type.
  2641. static bool isSimpleTemplateIdType(QualType T) {
  2642. if (const TemplateSpecializationType *Spec
  2643. = T->getAs<TemplateSpecializationType>())
  2644. return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
  2645. // C++17 [temp.local]p2:
  2646. // the injected-class-name [...] is equivalent to the template-name followed
  2647. // by the template-arguments of the class template specialization or partial
  2648. // specialization enclosed in <>
  2649. // ... which means it's equivalent to a simple-template-id.
  2650. //
  2651. // This only arises during class template argument deduction for a copy
  2652. // deduction candidate, where it permits slicing.
  2653. if (T->getAs<InjectedClassNameType>())
  2654. return true;
  2655. return false;
  2656. }
  2657. /// Substitute the explicitly-provided template arguments into the
  2658. /// given function template according to C++ [temp.arg.explicit].
  2659. ///
  2660. /// \param FunctionTemplate the function template into which the explicit
  2661. /// template arguments will be substituted.
  2662. ///
  2663. /// \param ExplicitTemplateArgs the explicitly-specified template
  2664. /// arguments.
  2665. ///
  2666. /// \param Deduced the deduced template arguments, which will be populated
  2667. /// with the converted and checked explicit template arguments.
  2668. ///
  2669. /// \param ParamTypes will be populated with the instantiated function
  2670. /// parameters.
  2671. ///
  2672. /// \param FunctionType if non-NULL, the result type of the function template
  2673. /// will also be instantiated and the pointed-to value will be updated with
  2674. /// the instantiated function type.
  2675. ///
  2676. /// \param Info if substitution fails for any reason, this object will be
  2677. /// populated with more information about the failure.
  2678. ///
  2679. /// \returns TDK_Success if substitution was successful, or some failure
  2680. /// condition.
  2681. Sema::TemplateDeductionResult
  2682. Sema::SubstituteExplicitTemplateArguments(
  2683. FunctionTemplateDecl *FunctionTemplate,
  2684. TemplateArgumentListInfo &ExplicitTemplateArgs,
  2685. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2686. SmallVectorImpl<QualType> &ParamTypes,
  2687. QualType *FunctionType,
  2688. TemplateDeductionInfo &Info) {
  2689. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  2690. TemplateParameterList *TemplateParams
  2691. = FunctionTemplate->getTemplateParameters();
  2692. if (ExplicitTemplateArgs.size() == 0) {
  2693. // No arguments to substitute; just copy over the parameter types and
  2694. // fill in the function type.
  2695. for (auto P : Function->parameters())
  2696. ParamTypes.push_back(P->getType());
  2697. if (FunctionType)
  2698. *FunctionType = Function->getType();
  2699. return TDK_Success;
  2700. }
  2701. // Unevaluated SFINAE context.
  2702. EnterExpressionEvaluationContext Unevaluated(
  2703. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2704. SFINAETrap Trap(*this);
  2705. // C++ [temp.arg.explicit]p3:
  2706. // Template arguments that are present shall be specified in the
  2707. // declaration order of their corresponding template-parameters. The
  2708. // template argument list shall not specify more template-arguments than
  2709. // there are corresponding template-parameters.
  2710. SmallVector<TemplateArgument, 4> Builder;
  2711. // Enter a new template instantiation context where we check the
  2712. // explicitly-specified template arguments against this function template,
  2713. // and then substitute them into the function parameter types.
  2714. SmallVector<TemplateArgument, 4> DeducedArgs;
  2715. InstantiatingTemplate Inst(
  2716. *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
  2717. CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
  2718. if (Inst.isInvalid())
  2719. return TDK_InstantiationDepth;
  2720. if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
  2721. ExplicitTemplateArgs, true, Builder, false) ||
  2722. Trap.hasErrorOccurred()) {
  2723. unsigned Index = Builder.size();
  2724. if (Index >= TemplateParams->size())
  2725. return TDK_SubstitutionFailure;
  2726. Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
  2727. return TDK_InvalidExplicitArguments;
  2728. }
  2729. // Form the template argument list from the explicitly-specified
  2730. // template arguments.
  2731. TemplateArgumentList *ExplicitArgumentList
  2732. = TemplateArgumentList::CreateCopy(Context, Builder);
  2733. Info.setExplicitArgs(ExplicitArgumentList);
  2734. // Template argument deduction and the final substitution should be
  2735. // done in the context of the templated declaration. Explicit
  2736. // argument substitution, on the other hand, needs to happen in the
  2737. // calling context.
  2738. ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
  2739. // If we deduced template arguments for a template parameter pack,
  2740. // note that the template argument pack is partially substituted and record
  2741. // the explicit template arguments. They'll be used as part of deduction
  2742. // for this template parameter pack.
  2743. unsigned PartiallySubstitutedPackIndex = -1u;
  2744. if (!Builder.empty()) {
  2745. const TemplateArgument &Arg = Builder.back();
  2746. if (Arg.getKind() == TemplateArgument::Pack) {
  2747. auto *Param = TemplateParams->getParam(Builder.size() - 1);
  2748. // If this is a fully-saturated fixed-size pack, it should be
  2749. // fully-substituted, not partially-substituted.
  2750. Optional<unsigned> Expansions = getExpandedPackSize(Param);
  2751. if (!Expansions || Arg.pack_size() < *Expansions) {
  2752. PartiallySubstitutedPackIndex = Builder.size() - 1;
  2753. CurrentInstantiationScope->SetPartiallySubstitutedPack(
  2754. Param, Arg.pack_begin(), Arg.pack_size());
  2755. }
  2756. }
  2757. }
  2758. const FunctionProtoType *Proto
  2759. = Function->getType()->getAs<FunctionProtoType>();
  2760. assert(Proto && "Function template does not have a prototype?");
  2761. // Isolate our substituted parameters from our caller.
  2762. LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
  2763. ExtParameterInfoBuilder ExtParamInfos;
  2764. // Instantiate the types of each of the function parameters given the
  2765. // explicitly-specified template arguments. If the function has a trailing
  2766. // return type, substitute it after the arguments to ensure we substitute
  2767. // in lexical order.
  2768. if (Proto->hasTrailingReturn()) {
  2769. if (SubstParmTypes(Function->getLocation(), Function->parameters(),
  2770. Proto->getExtParameterInfosOrNull(),
  2771. MultiLevelTemplateArgumentList(*ExplicitArgumentList),
  2772. ParamTypes, /*params*/ nullptr, ExtParamInfos))
  2773. return TDK_SubstitutionFailure;
  2774. }
  2775. // Instantiate the return type.
  2776. QualType ResultType;
  2777. {
  2778. // C++11 [expr.prim.general]p3:
  2779. // If a declaration declares a member function or member function
  2780. // template of a class X, the expression this is a prvalue of type
  2781. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  2782. // and the end of the function-definition, member-declarator, or
  2783. // declarator.
  2784. Qualifiers ThisTypeQuals;
  2785. CXXRecordDecl *ThisContext = nullptr;
  2786. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  2787. ThisContext = Method->getParent();
  2788. ThisTypeQuals = Method->getMethodQualifiers();
  2789. }
  2790. CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
  2791. getLangOpts().CPlusPlus11);
  2792. ResultType =
  2793. SubstType(Proto->getReturnType(),
  2794. MultiLevelTemplateArgumentList(*ExplicitArgumentList),
  2795. Function->getTypeSpecStartLoc(), Function->getDeclName());
  2796. if (ResultType.isNull() || Trap.hasErrorOccurred())
  2797. return TDK_SubstitutionFailure;
  2798. // CUDA: Kernel function must have 'void' return type.
  2799. if (getLangOpts().CUDA)
  2800. if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
  2801. Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
  2802. << Function->getType() << Function->getSourceRange();
  2803. return TDK_SubstitutionFailure;
  2804. }
  2805. }
  2806. // Instantiate the types of each of the function parameters given the
  2807. // explicitly-specified template arguments if we didn't do so earlier.
  2808. if (!Proto->hasTrailingReturn() &&
  2809. SubstParmTypes(Function->getLocation(), Function->parameters(),
  2810. Proto->getExtParameterInfosOrNull(),
  2811. MultiLevelTemplateArgumentList(*ExplicitArgumentList),
  2812. ParamTypes, /*params*/ nullptr, ExtParamInfos))
  2813. return TDK_SubstitutionFailure;
  2814. if (FunctionType) {
  2815. auto EPI = Proto->getExtProtoInfo();
  2816. EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
  2817. // In C++1z onwards, exception specifications are part of the function type,
  2818. // so substitution into the type must also substitute into the exception
  2819. // specification.
  2820. SmallVector<QualType, 4> ExceptionStorage;
  2821. if (getLangOpts().CPlusPlus17 &&
  2822. SubstExceptionSpec(
  2823. Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
  2824. MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
  2825. return TDK_SubstitutionFailure;
  2826. *FunctionType = BuildFunctionType(ResultType, ParamTypes,
  2827. Function->getLocation(),
  2828. Function->getDeclName(),
  2829. EPI);
  2830. if (FunctionType->isNull() || Trap.hasErrorOccurred())
  2831. return TDK_SubstitutionFailure;
  2832. }
  2833. // C++ [temp.arg.explicit]p2:
  2834. // Trailing template arguments that can be deduced (14.8.2) may be
  2835. // omitted from the list of explicit template-arguments. If all of the
  2836. // template arguments can be deduced, they may all be omitted; in this
  2837. // case, the empty template argument list <> itself may also be omitted.
  2838. //
  2839. // Take all of the explicitly-specified arguments and put them into
  2840. // the set of deduced template arguments. The partially-substituted
  2841. // parameter pack, however, will be set to NULL since the deduction
  2842. // mechanism handles the partially-substituted argument pack directly.
  2843. Deduced.reserve(TemplateParams->size());
  2844. for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
  2845. const TemplateArgument &Arg = ExplicitArgumentList->get(I);
  2846. if (I == PartiallySubstitutedPackIndex)
  2847. Deduced.push_back(DeducedTemplateArgument());
  2848. else
  2849. Deduced.push_back(Arg);
  2850. }
  2851. return TDK_Success;
  2852. }
  2853. /// Check whether the deduced argument type for a call to a function
  2854. /// template matches the actual argument type per C++ [temp.deduct.call]p4.
  2855. static Sema::TemplateDeductionResult
  2856. CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
  2857. Sema::OriginalCallArg OriginalArg,
  2858. QualType DeducedA) {
  2859. ASTContext &Context = S.Context;
  2860. auto Failed = [&]() -> Sema::TemplateDeductionResult {
  2861. Info.FirstArg = TemplateArgument(DeducedA);
  2862. Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
  2863. Info.CallArgIndex = OriginalArg.ArgIdx;
  2864. return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
  2865. : Sema::TDK_DeducedMismatch;
  2866. };
  2867. QualType A = OriginalArg.OriginalArgType;
  2868. QualType OriginalParamType = OriginalArg.OriginalParamType;
  2869. // Check for type equality (top-level cv-qualifiers are ignored).
  2870. if (Context.hasSameUnqualifiedType(A, DeducedA))
  2871. return Sema::TDK_Success;
  2872. // Strip off references on the argument types; they aren't needed for
  2873. // the following checks.
  2874. if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
  2875. DeducedA = DeducedARef->getPointeeType();
  2876. if (const ReferenceType *ARef = A->getAs<ReferenceType>())
  2877. A = ARef->getPointeeType();
  2878. // C++ [temp.deduct.call]p4:
  2879. // [...] However, there are three cases that allow a difference:
  2880. // - If the original P is a reference type, the deduced A (i.e., the
  2881. // type referred to by the reference) can be more cv-qualified than
  2882. // the transformed A.
  2883. if (const ReferenceType *OriginalParamRef
  2884. = OriginalParamType->getAs<ReferenceType>()) {
  2885. // We don't want to keep the reference around any more.
  2886. OriginalParamType = OriginalParamRef->getPointeeType();
  2887. // FIXME: Resolve core issue (no number yet): if the original P is a
  2888. // reference type and the transformed A is function type "noexcept F",
  2889. // the deduced A can be F.
  2890. QualType Tmp;
  2891. if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
  2892. return Sema::TDK_Success;
  2893. Qualifiers AQuals = A.getQualifiers();
  2894. Qualifiers DeducedAQuals = DeducedA.getQualifiers();
  2895. // Under Objective-C++ ARC, the deduced type may have implicitly
  2896. // been given strong or (when dealing with a const reference)
  2897. // unsafe_unretained lifetime. If so, update the original
  2898. // qualifiers to include this lifetime.
  2899. if (S.getLangOpts().ObjCAutoRefCount &&
  2900. ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
  2901. AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
  2902. (DeducedAQuals.hasConst() &&
  2903. DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
  2904. AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
  2905. }
  2906. if (AQuals == DeducedAQuals) {
  2907. // Qualifiers match; there's nothing to do.
  2908. } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
  2909. return Failed();
  2910. } else {
  2911. // Qualifiers are compatible, so have the argument type adopt the
  2912. // deduced argument type's qualifiers as if we had performed the
  2913. // qualification conversion.
  2914. A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
  2915. }
  2916. }
  2917. // - The transformed A can be another pointer or pointer to member
  2918. // type that can be converted to the deduced A via a function pointer
  2919. // conversion and/or a qualification conversion.
  2920. //
  2921. // Also allow conversions which merely strip __attribute__((noreturn)) from
  2922. // function types (recursively).
  2923. bool ObjCLifetimeConversion = false;
  2924. QualType ResultTy;
  2925. if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
  2926. (S.IsQualificationConversion(A, DeducedA, false,
  2927. ObjCLifetimeConversion) ||
  2928. S.IsFunctionConversion(A, DeducedA, ResultTy)))
  2929. return Sema::TDK_Success;
  2930. // - If P is a class and P has the form simple-template-id, then the
  2931. // transformed A can be a derived class of the deduced A. [...]
  2932. // [...] Likewise, if P is a pointer to a class of the form
  2933. // simple-template-id, the transformed A can be a pointer to a
  2934. // derived class pointed to by the deduced A.
  2935. if (const PointerType *OriginalParamPtr
  2936. = OriginalParamType->getAs<PointerType>()) {
  2937. if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
  2938. if (const PointerType *APtr = A->getAs<PointerType>()) {
  2939. if (A->getPointeeType()->isRecordType()) {
  2940. OriginalParamType = OriginalParamPtr->getPointeeType();
  2941. DeducedA = DeducedAPtr->getPointeeType();
  2942. A = APtr->getPointeeType();
  2943. }
  2944. }
  2945. }
  2946. }
  2947. if (Context.hasSameUnqualifiedType(A, DeducedA))
  2948. return Sema::TDK_Success;
  2949. if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
  2950. S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
  2951. return Sema::TDK_Success;
  2952. return Failed();
  2953. }
  2954. /// Find the pack index for a particular parameter index in an instantiation of
  2955. /// a function template with specific arguments.
  2956. ///
  2957. /// \return The pack index for whichever pack produced this parameter, or -1
  2958. /// if this was not produced by a parameter. Intended to be used as the
  2959. /// ArgumentPackSubstitutionIndex for further substitutions.
  2960. // FIXME: We should track this in OriginalCallArgs so we don't need to
  2961. // reconstruct it here.
  2962. static unsigned getPackIndexForParam(Sema &S,
  2963. FunctionTemplateDecl *FunctionTemplate,
  2964. const MultiLevelTemplateArgumentList &Args,
  2965. unsigned ParamIdx) {
  2966. unsigned Idx = 0;
  2967. for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
  2968. if (PD->isParameterPack()) {
  2969. unsigned NumExpansions =
  2970. S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
  2971. if (Idx + NumExpansions > ParamIdx)
  2972. return ParamIdx - Idx;
  2973. Idx += NumExpansions;
  2974. } else {
  2975. if (Idx == ParamIdx)
  2976. return -1; // Not a pack expansion
  2977. ++Idx;
  2978. }
  2979. }
  2980. llvm_unreachable("parameter index would not be produced from template");
  2981. }
  2982. /// Finish template argument deduction for a function template,
  2983. /// checking the deduced template arguments for completeness and forming
  2984. /// the function template specialization.
  2985. ///
  2986. /// \param OriginalCallArgs If non-NULL, the original call arguments against
  2987. /// which the deduced argument types should be compared.
  2988. Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
  2989. FunctionTemplateDecl *FunctionTemplate,
  2990. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2991. unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
  2992. TemplateDeductionInfo &Info,
  2993. SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
  2994. bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
  2995. // Unevaluated SFINAE context.
  2996. EnterExpressionEvaluationContext Unevaluated(
  2997. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2998. SFINAETrap Trap(*this);
  2999. // Enter a new template instantiation context while we instantiate the
  3000. // actual function declaration.
  3001. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
  3002. InstantiatingTemplate Inst(
  3003. *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
  3004. CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
  3005. if (Inst.isInvalid())
  3006. return TDK_InstantiationDepth;
  3007. ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
  3008. // C++ [temp.deduct.type]p2:
  3009. // [...] or if any template argument remains neither deduced nor
  3010. // explicitly specified, template argument deduction fails.
  3011. SmallVector<TemplateArgument, 4> Builder;
  3012. if (auto Result = ConvertDeducedTemplateArguments(
  3013. *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
  3014. CurrentInstantiationScope, NumExplicitlySpecified,
  3015. PartialOverloading))
  3016. return Result;
  3017. // C++ [temp.deduct.call]p10: [DR1391]
  3018. // If deduction succeeds for all parameters that contain
  3019. // template-parameters that participate in template argument deduction,
  3020. // and all template arguments are explicitly specified, deduced, or
  3021. // obtained from default template arguments, remaining parameters are then
  3022. // compared with the corresponding arguments. For each remaining parameter
  3023. // P with a type that was non-dependent before substitution of any
  3024. // explicitly-specified template arguments, if the corresponding argument
  3025. // A cannot be implicitly converted to P, deduction fails.
  3026. if (CheckNonDependent())
  3027. return TDK_NonDependentConversionFailure;
  3028. // Form the template argument list from the deduced template arguments.
  3029. TemplateArgumentList *DeducedArgumentList
  3030. = TemplateArgumentList::CreateCopy(Context, Builder);
  3031. Info.reset(DeducedArgumentList);
  3032. // Substitute the deduced template arguments into the function template
  3033. // declaration to produce the function template specialization.
  3034. DeclContext *Owner = FunctionTemplate->getDeclContext();
  3035. if (FunctionTemplate->getFriendObjectKind())
  3036. Owner = FunctionTemplate->getLexicalDeclContext();
  3037. MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
  3038. Specialization = cast_or_null<FunctionDecl>(
  3039. SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
  3040. if (!Specialization || Specialization->isInvalidDecl())
  3041. return TDK_SubstitutionFailure;
  3042. assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  3043. FunctionTemplate->getCanonicalDecl());
  3044. // If the template argument list is owned by the function template
  3045. // specialization, release it.
  3046. if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
  3047. !Trap.hasErrorOccurred())
  3048. Info.take();
  3049. // There may have been an error that did not prevent us from constructing a
  3050. // declaration. Mark the declaration invalid and return with a substitution
  3051. // failure.
  3052. if (Trap.hasErrorOccurred()) {
  3053. Specialization->setInvalidDecl(true);
  3054. return TDK_SubstitutionFailure;
  3055. }
  3056. // C++2a [temp.deduct]p5
  3057. // [...] When all template arguments have been deduced [...] all uses of
  3058. // template parameters [...] are replaced with the corresponding deduced
  3059. // or default argument values.
  3060. // [...] If the function template has associated constraints
  3061. // ([temp.constr.decl]), those constraints are checked for satisfaction
  3062. // ([temp.constr.constr]). If the constraints are not satisfied, type
  3063. // deduction fails.
  3064. if (!PartialOverloading ||
  3065. (Builder.size() == FunctionTemplate->getTemplateParameters()->size())) {
  3066. if (CheckInstantiatedFunctionTemplateConstraints(Info.getLocation(),
  3067. Specialization, Builder, Info.AssociatedConstraintsSatisfaction))
  3068. return TDK_MiscellaneousDeductionFailure;
  3069. if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
  3070. Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
  3071. return TDK_ConstraintsNotSatisfied;
  3072. }
  3073. }
  3074. if (OriginalCallArgs) {
  3075. // C++ [temp.deduct.call]p4:
  3076. // In general, the deduction process attempts to find template argument
  3077. // values that will make the deduced A identical to A (after the type A
  3078. // is transformed as described above). [...]
  3079. llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
  3080. for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
  3081. OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
  3082. auto ParamIdx = OriginalArg.ArgIdx;
  3083. if (ParamIdx >= Specialization->getNumParams())
  3084. // FIXME: This presumably means a pack ended up smaller than we
  3085. // expected while deducing. Should this not result in deduction
  3086. // failure? Can it even happen?
  3087. continue;
  3088. QualType DeducedA;
  3089. if (!OriginalArg.DecomposedParam) {
  3090. // P is one of the function parameters, just look up its substituted
  3091. // type.
  3092. DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
  3093. } else {
  3094. // P is a decomposed element of a parameter corresponding to a
  3095. // braced-init-list argument. Substitute back into P to find the
  3096. // deduced A.
  3097. QualType &CacheEntry =
  3098. DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
  3099. if (CacheEntry.isNull()) {
  3100. ArgumentPackSubstitutionIndexRAII PackIndex(
  3101. *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
  3102. ParamIdx));
  3103. CacheEntry =
  3104. SubstType(OriginalArg.OriginalParamType, SubstArgs,
  3105. Specialization->getTypeSpecStartLoc(),
  3106. Specialization->getDeclName());
  3107. }
  3108. DeducedA = CacheEntry;
  3109. }
  3110. if (auto TDK =
  3111. CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
  3112. return TDK;
  3113. }
  3114. }
  3115. // If we suppressed any diagnostics while performing template argument
  3116. // deduction, and if we haven't already instantiated this declaration,
  3117. // keep track of these diagnostics. They'll be emitted if this specialization
  3118. // is actually used.
  3119. if (Info.diag_begin() != Info.diag_end()) {
  3120. SuppressedDiagnosticsMap::iterator
  3121. Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
  3122. if (Pos == SuppressedDiagnostics.end())
  3123. SuppressedDiagnostics[Specialization->getCanonicalDecl()]
  3124. .append(Info.diag_begin(), Info.diag_end());
  3125. }
  3126. return TDK_Success;
  3127. }
  3128. /// Gets the type of a function for template-argument-deducton
  3129. /// purposes when it's considered as part of an overload set.
  3130. static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
  3131. FunctionDecl *Fn) {
  3132. // We may need to deduce the return type of the function now.
  3133. if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
  3134. S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
  3135. return {};
  3136. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  3137. if (Method->isInstance()) {
  3138. // An instance method that's referenced in a form that doesn't
  3139. // look like a member pointer is just invalid.
  3140. if (!R.HasFormOfMemberPointer)
  3141. return {};
  3142. return S.Context.getMemberPointerType(Fn->getType(),
  3143. S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
  3144. }
  3145. if (!R.IsAddressOfOperand) return Fn->getType();
  3146. return S.Context.getPointerType(Fn->getType());
  3147. }
  3148. /// Apply the deduction rules for overload sets.
  3149. ///
  3150. /// \return the null type if this argument should be treated as an
  3151. /// undeduced context
  3152. static QualType
  3153. ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
  3154. Expr *Arg, QualType ParamType,
  3155. bool ParamWasReference) {
  3156. OverloadExpr::FindResult R = OverloadExpr::find(Arg);
  3157. OverloadExpr *Ovl = R.Expression;
  3158. // C++0x [temp.deduct.call]p4
  3159. unsigned TDF = 0;
  3160. if (ParamWasReference)
  3161. TDF |= TDF_ParamWithReferenceType;
  3162. if (R.IsAddressOfOperand)
  3163. TDF |= TDF_IgnoreQualifiers;
  3164. // C++0x [temp.deduct.call]p6:
  3165. // When P is a function type, pointer to function type, or pointer
  3166. // to member function type:
  3167. if (!ParamType->isFunctionType() &&
  3168. !ParamType->isFunctionPointerType() &&
  3169. !ParamType->isMemberFunctionPointerType()) {
  3170. if (Ovl->hasExplicitTemplateArgs()) {
  3171. // But we can still look for an explicit specialization.
  3172. if (FunctionDecl *ExplicitSpec
  3173. = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
  3174. return GetTypeOfFunction(S, R, ExplicitSpec);
  3175. }
  3176. DeclAccessPair DAP;
  3177. if (FunctionDecl *Viable =
  3178. S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
  3179. return GetTypeOfFunction(S, R, Viable);
  3180. return {};
  3181. }
  3182. // Gather the explicit template arguments, if any.
  3183. TemplateArgumentListInfo ExplicitTemplateArgs;
  3184. if (Ovl->hasExplicitTemplateArgs())
  3185. Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
  3186. QualType Match;
  3187. for (UnresolvedSetIterator I = Ovl->decls_begin(),
  3188. E = Ovl->decls_end(); I != E; ++I) {
  3189. NamedDecl *D = (*I)->getUnderlyingDecl();
  3190. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
  3191. // - If the argument is an overload set containing one or more
  3192. // function templates, the parameter is treated as a
  3193. // non-deduced context.
  3194. if (!Ovl->hasExplicitTemplateArgs())
  3195. return {};
  3196. // Otherwise, see if we can resolve a function type
  3197. FunctionDecl *Specialization = nullptr;
  3198. TemplateDeductionInfo Info(Ovl->getNameLoc());
  3199. if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
  3200. Specialization, Info))
  3201. continue;
  3202. D = Specialization;
  3203. }
  3204. FunctionDecl *Fn = cast<FunctionDecl>(D);
  3205. QualType ArgType = GetTypeOfFunction(S, R, Fn);
  3206. if (ArgType.isNull()) continue;
  3207. // Function-to-pointer conversion.
  3208. if (!ParamWasReference && ParamType->isPointerType() &&
  3209. ArgType->isFunctionType())
  3210. ArgType = S.Context.getPointerType(ArgType);
  3211. // - If the argument is an overload set (not containing function
  3212. // templates), trial argument deduction is attempted using each
  3213. // of the members of the set. If deduction succeeds for only one
  3214. // of the overload set members, that member is used as the
  3215. // argument value for the deduction. If deduction succeeds for
  3216. // more than one member of the overload set the parameter is
  3217. // treated as a non-deduced context.
  3218. // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
  3219. // Type deduction is done independently for each P/A pair, and
  3220. // the deduced template argument values are then combined.
  3221. // So we do not reject deductions which were made elsewhere.
  3222. SmallVector<DeducedTemplateArgument, 8>
  3223. Deduced(TemplateParams->size());
  3224. TemplateDeductionInfo Info(Ovl->getNameLoc());
  3225. Sema::TemplateDeductionResult Result
  3226. = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
  3227. ArgType, Info, Deduced, TDF);
  3228. if (Result) continue;
  3229. if (!Match.isNull())
  3230. return {};
  3231. Match = ArgType;
  3232. }
  3233. return Match;
  3234. }
  3235. /// Perform the adjustments to the parameter and argument types
  3236. /// described in C++ [temp.deduct.call].
  3237. ///
  3238. /// \returns true if the caller should not attempt to perform any template
  3239. /// argument deduction based on this P/A pair because the argument is an
  3240. /// overloaded function set that could not be resolved.
  3241. static bool AdjustFunctionParmAndArgTypesForDeduction(
  3242. Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
  3243. QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
  3244. // C++0x [temp.deduct.call]p3:
  3245. // If P is a cv-qualified type, the top level cv-qualifiers of P's type
  3246. // are ignored for type deduction.
  3247. if (ParamType.hasQualifiers())
  3248. ParamType = ParamType.getUnqualifiedType();
  3249. // [...] If P is a reference type, the type referred to by P is
  3250. // used for type deduction.
  3251. const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
  3252. if (ParamRefType)
  3253. ParamType = ParamRefType->getPointeeType();
  3254. // Overload sets usually make this parameter an undeduced context,
  3255. // but there are sometimes special circumstances. Typically
  3256. // involving a template-id-expr.
  3257. if (ArgType == S.Context.OverloadTy) {
  3258. ArgType = ResolveOverloadForDeduction(S, TemplateParams,
  3259. Arg, ParamType,
  3260. ParamRefType != nullptr);
  3261. if (ArgType.isNull())
  3262. return true;
  3263. }
  3264. if (ParamRefType) {
  3265. // If the argument has incomplete array type, try to complete its type.
  3266. if (ArgType->isIncompleteArrayType())
  3267. ArgType = S.getCompletedType(Arg);
  3268. // C++1z [temp.deduct.call]p3:
  3269. // If P is a forwarding reference and the argument is an lvalue, the type
  3270. // "lvalue reference to A" is used in place of A for type deduction.
  3271. if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
  3272. Arg->isLValue()) {
  3273. if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
  3274. ArgType = S.Context.getAddrSpaceQualType(
  3275. ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
  3276. ArgType = S.Context.getLValueReferenceType(ArgType);
  3277. }
  3278. } else {
  3279. // C++ [temp.deduct.call]p2:
  3280. // If P is not a reference type:
  3281. // - If A is an array type, the pointer type produced by the
  3282. // array-to-pointer standard conversion (4.2) is used in place of
  3283. // A for type deduction; otherwise,
  3284. if (ArgType->isArrayType())
  3285. ArgType = S.Context.getArrayDecayedType(ArgType);
  3286. // - If A is a function type, the pointer type produced by the
  3287. // function-to-pointer standard conversion (4.3) is used in place
  3288. // of A for type deduction; otherwise,
  3289. else if (ArgType->isFunctionType())
  3290. ArgType = S.Context.getPointerType(ArgType);
  3291. else {
  3292. // - If A is a cv-qualified type, the top level cv-qualifiers of A's
  3293. // type are ignored for type deduction.
  3294. ArgType = ArgType.getUnqualifiedType();
  3295. }
  3296. }
  3297. // C++0x [temp.deduct.call]p4:
  3298. // In general, the deduction process attempts to find template argument
  3299. // values that will make the deduced A identical to A (after the type A
  3300. // is transformed as described above). [...]
  3301. TDF = TDF_SkipNonDependent;
  3302. // - If the original P is a reference type, the deduced A (i.e., the
  3303. // type referred to by the reference) can be more cv-qualified than
  3304. // the transformed A.
  3305. if (ParamRefType)
  3306. TDF |= TDF_ParamWithReferenceType;
  3307. // - The transformed A can be another pointer or pointer to member
  3308. // type that can be converted to the deduced A via a qualification
  3309. // conversion (4.4).
  3310. if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
  3311. ArgType->isObjCObjectPointerType())
  3312. TDF |= TDF_IgnoreQualifiers;
  3313. // - If P is a class and P has the form simple-template-id, then the
  3314. // transformed A can be a derived class of the deduced A. Likewise,
  3315. // if P is a pointer to a class of the form simple-template-id, the
  3316. // transformed A can be a pointer to a derived class pointed to by
  3317. // the deduced A.
  3318. if (isSimpleTemplateIdType(ParamType) ||
  3319. (isa<PointerType>(ParamType) &&
  3320. isSimpleTemplateIdType(
  3321. ParamType->castAs<PointerType>()->getPointeeType())))
  3322. TDF |= TDF_DerivedClass;
  3323. return false;
  3324. }
  3325. static bool
  3326. hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
  3327. QualType T);
  3328. static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
  3329. Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
  3330. QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
  3331. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3332. SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
  3333. bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
  3334. /// Attempt template argument deduction from an initializer list
  3335. /// deemed to be an argument in a function call.
  3336. static Sema::TemplateDeductionResult DeduceFromInitializerList(
  3337. Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
  3338. InitListExpr *ILE, TemplateDeductionInfo &Info,
  3339. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3340. SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
  3341. unsigned TDF) {
  3342. // C++ [temp.deduct.call]p1: (CWG 1591)
  3343. // If removing references and cv-qualifiers from P gives
  3344. // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
  3345. // a non-empty initializer list, then deduction is performed instead for
  3346. // each element of the initializer list, taking P0 as a function template
  3347. // parameter type and the initializer element as its argument
  3348. //
  3349. // We've already removed references and cv-qualifiers here.
  3350. if (!ILE->getNumInits())
  3351. return Sema::TDK_Success;
  3352. QualType ElTy;
  3353. auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
  3354. if (ArrTy)
  3355. ElTy = ArrTy->getElementType();
  3356. else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
  3357. // Otherwise, an initializer list argument causes the parameter to be
  3358. // considered a non-deduced context
  3359. return Sema::TDK_Success;
  3360. }
  3361. // Resolving a core issue: a braced-init-list containing any designators is
  3362. // a non-deduced context.
  3363. for (Expr *E : ILE->inits())
  3364. if (isa<DesignatedInitExpr>(E))
  3365. return Sema::TDK_Success;
  3366. // Deduction only needs to be done for dependent types.
  3367. if (ElTy->isDependentType()) {
  3368. for (Expr *E : ILE->inits()) {
  3369. if (auto Result = DeduceTemplateArgumentsFromCallArgument(
  3370. S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
  3371. ArgIdx, TDF))
  3372. return Result;
  3373. }
  3374. }
  3375. // in the P0[N] case, if N is a non-type template parameter, N is deduced
  3376. // from the length of the initializer list.
  3377. if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
  3378. // Determine the array bound is something we can deduce.
  3379. if (const NonTypeTemplateParmDecl *NTTP =
  3380. getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
  3381. // We can perform template argument deduction for the given non-type
  3382. // template parameter.
  3383. // C++ [temp.deduct.type]p13:
  3384. // The type of N in the type T[N] is std::size_t.
  3385. QualType T = S.Context.getSizeType();
  3386. llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
  3387. if (auto Result = DeduceNonTypeTemplateArgument(
  3388. S, TemplateParams, NTTP, llvm::APSInt(Size), T,
  3389. /*ArrayBound=*/true, Info, Deduced))
  3390. return Result;
  3391. }
  3392. }
  3393. return Sema::TDK_Success;
  3394. }
  3395. /// Perform template argument deduction per [temp.deduct.call] for a
  3396. /// single parameter / argument pair.
  3397. static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
  3398. Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
  3399. QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
  3400. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3401. SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
  3402. bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
  3403. QualType ArgType = Arg->getType();
  3404. QualType OrigParamType = ParamType;
  3405. // If P is a reference type [...]
  3406. // If P is a cv-qualified type [...]
  3407. if (AdjustFunctionParmAndArgTypesForDeduction(
  3408. S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
  3409. return Sema::TDK_Success;
  3410. // If [...] the argument is a non-empty initializer list [...]
  3411. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
  3412. return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
  3413. Deduced, OriginalCallArgs, ArgIdx, TDF);
  3414. // [...] the deduction process attempts to find template argument values
  3415. // that will make the deduced A identical to A
  3416. //
  3417. // Keep track of the argument type and corresponding parameter index,
  3418. // so we can check for compatibility between the deduced A and A.
  3419. OriginalCallArgs.push_back(
  3420. Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
  3421. return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
  3422. ArgType, Info, Deduced, TDF);
  3423. }
  3424. /// Perform template argument deduction from a function call
  3425. /// (C++ [temp.deduct.call]).
  3426. ///
  3427. /// \param FunctionTemplate the function template for which we are performing
  3428. /// template argument deduction.
  3429. ///
  3430. /// \param ExplicitTemplateArgs the explicit template arguments provided
  3431. /// for this call.
  3432. ///
  3433. /// \param Args the function call arguments
  3434. ///
  3435. /// \param Specialization if template argument deduction was successful,
  3436. /// this will be set to the function template specialization produced by
  3437. /// template argument deduction.
  3438. ///
  3439. /// \param Info the argument will be updated to provide additional information
  3440. /// about template argument deduction.
  3441. ///
  3442. /// \param CheckNonDependent A callback to invoke to check conversions for
  3443. /// non-dependent parameters, between deduction and substitution, per DR1391.
  3444. /// If this returns true, substitution will be skipped and we return
  3445. /// TDK_NonDependentConversionFailure. The callback is passed the parameter
  3446. /// types (after substituting explicit template arguments).
  3447. ///
  3448. /// \returns the result of template argument deduction.
  3449. Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
  3450. FunctionTemplateDecl *FunctionTemplate,
  3451. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3452. FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
  3453. bool PartialOverloading,
  3454. llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
  3455. if (FunctionTemplate->isInvalidDecl())
  3456. return TDK_Invalid;
  3457. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  3458. unsigned NumParams = Function->getNumParams();
  3459. unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
  3460. // C++ [temp.deduct.call]p1:
  3461. // Template argument deduction is done by comparing each function template
  3462. // parameter type (call it P) with the type of the corresponding argument
  3463. // of the call (call it A) as described below.
  3464. if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
  3465. return TDK_TooFewArguments;
  3466. else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
  3467. const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
  3468. if (Proto->isTemplateVariadic())
  3469. /* Do nothing */;
  3470. else if (!Proto->isVariadic())
  3471. return TDK_TooManyArguments;
  3472. }
  3473. // The types of the parameters from which we will perform template argument
  3474. // deduction.
  3475. LocalInstantiationScope InstScope(*this);
  3476. TemplateParameterList *TemplateParams
  3477. = FunctionTemplate->getTemplateParameters();
  3478. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3479. SmallVector<QualType, 8> ParamTypes;
  3480. unsigned NumExplicitlySpecified = 0;
  3481. if (ExplicitTemplateArgs) {
  3482. TemplateDeductionResult Result;
  3483. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3484. Result = SubstituteExplicitTemplateArguments(
  3485. FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
  3486. Info);
  3487. });
  3488. if (Result)
  3489. return Result;
  3490. NumExplicitlySpecified = Deduced.size();
  3491. } else {
  3492. // Just fill in the parameter types from the function declaration.
  3493. for (unsigned I = 0; I != NumParams; ++I)
  3494. ParamTypes.push_back(Function->getParamDecl(I)->getType());
  3495. }
  3496. SmallVector<OriginalCallArg, 8> OriginalCallArgs;
  3497. // Deduce an argument of type ParamType from an expression with index ArgIdx.
  3498. auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
  3499. // C++ [demp.deduct.call]p1: (DR1391)
  3500. // Template argument deduction is done by comparing each function template
  3501. // parameter that contains template-parameters that participate in
  3502. // template argument deduction ...
  3503. if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
  3504. return Sema::TDK_Success;
  3505. // ... with the type of the corresponding argument
  3506. return DeduceTemplateArgumentsFromCallArgument(
  3507. *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
  3508. OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
  3509. };
  3510. // Deduce template arguments from the function parameters.
  3511. Deduced.resize(TemplateParams->size());
  3512. SmallVector<QualType, 8> ParamTypesForArgChecking;
  3513. for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
  3514. ParamIdx != NumParamTypes; ++ParamIdx) {
  3515. QualType ParamType = ParamTypes[ParamIdx];
  3516. const PackExpansionType *ParamExpansion =
  3517. dyn_cast<PackExpansionType>(ParamType);
  3518. if (!ParamExpansion) {
  3519. // Simple case: matching a function parameter to a function argument.
  3520. if (ArgIdx >= Args.size())
  3521. break;
  3522. ParamTypesForArgChecking.push_back(ParamType);
  3523. if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
  3524. return Result;
  3525. continue;
  3526. }
  3527. QualType ParamPattern = ParamExpansion->getPattern();
  3528. PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
  3529. ParamPattern);
  3530. // C++0x [temp.deduct.call]p1:
  3531. // For a function parameter pack that occurs at the end of the
  3532. // parameter-declaration-list, the type A of each remaining argument of
  3533. // the call is compared with the type P of the declarator-id of the
  3534. // function parameter pack. Each comparison deduces template arguments
  3535. // for subsequent positions in the template parameter packs expanded by
  3536. // the function parameter pack. When a function parameter pack appears
  3537. // in a non-deduced context [not at the end of the list], the type of
  3538. // that parameter pack is never deduced.
  3539. //
  3540. // FIXME: The above rule allows the size of the parameter pack to change
  3541. // after we skip it (in the non-deduced case). That makes no sense, so
  3542. // we instead notionally deduce the pack against N arguments, where N is
  3543. // the length of the explicitly-specified pack if it's expanded by the
  3544. // parameter pack and 0 otherwise, and we treat each deduction as a
  3545. // non-deduced context.
  3546. if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
  3547. for (; ArgIdx < Args.size() && PackScope.hasNextElement();
  3548. PackScope.nextPackElement(), ++ArgIdx) {
  3549. ParamTypesForArgChecking.push_back(ParamPattern);
  3550. if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
  3551. return Result;
  3552. }
  3553. } else {
  3554. // If the parameter type contains an explicitly-specified pack that we
  3555. // could not expand, skip the number of parameters notionally created
  3556. // by the expansion.
  3557. Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
  3558. if (NumExpansions && !PackScope.isPartiallyExpanded()) {
  3559. for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
  3560. ++I, ++ArgIdx) {
  3561. ParamTypesForArgChecking.push_back(ParamPattern);
  3562. // FIXME: Should we add OriginalCallArgs for these? What if the
  3563. // corresponding argument is a list?
  3564. PackScope.nextPackElement();
  3565. }
  3566. }
  3567. }
  3568. // Build argument packs for each of the parameter packs expanded by this
  3569. // pack expansion.
  3570. if (auto Result = PackScope.finish())
  3571. return Result;
  3572. }
  3573. // Capture the context in which the function call is made. This is the context
  3574. // that is needed when the accessibility of template arguments is checked.
  3575. DeclContext *CallingCtx = CurContext;
  3576. TemplateDeductionResult Result;
  3577. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3578. Result = FinishTemplateArgumentDeduction(
  3579. FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
  3580. &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
  3581. ContextRAII SavedContext(*this, CallingCtx);
  3582. return CheckNonDependent(ParamTypesForArgChecking);
  3583. });
  3584. });
  3585. return Result;
  3586. }
  3587. QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
  3588. QualType FunctionType,
  3589. bool AdjustExceptionSpec) {
  3590. if (ArgFunctionType.isNull())
  3591. return ArgFunctionType;
  3592. const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
  3593. const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
  3594. FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
  3595. bool Rebuild = false;
  3596. CallingConv CC = FunctionTypeP->getCallConv();
  3597. if (EPI.ExtInfo.getCC() != CC) {
  3598. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
  3599. Rebuild = true;
  3600. }
  3601. bool NoReturn = FunctionTypeP->getNoReturnAttr();
  3602. if (EPI.ExtInfo.getNoReturn() != NoReturn) {
  3603. EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
  3604. Rebuild = true;
  3605. }
  3606. if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
  3607. ArgFunctionTypeP->hasExceptionSpec())) {
  3608. EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
  3609. Rebuild = true;
  3610. }
  3611. if (!Rebuild)
  3612. return ArgFunctionType;
  3613. return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
  3614. ArgFunctionTypeP->getParamTypes(), EPI);
  3615. }
  3616. /// Deduce template arguments when taking the address of a function
  3617. /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
  3618. /// a template.
  3619. ///
  3620. /// \param FunctionTemplate the function template for which we are performing
  3621. /// template argument deduction.
  3622. ///
  3623. /// \param ExplicitTemplateArgs the explicitly-specified template
  3624. /// arguments.
  3625. ///
  3626. /// \param ArgFunctionType the function type that will be used as the
  3627. /// "argument" type (A) when performing template argument deduction from the
  3628. /// function template's function type. This type may be NULL, if there is no
  3629. /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
  3630. ///
  3631. /// \param Specialization if template argument deduction was successful,
  3632. /// this will be set to the function template specialization produced by
  3633. /// template argument deduction.
  3634. ///
  3635. /// \param Info the argument will be updated to provide additional information
  3636. /// about template argument deduction.
  3637. ///
  3638. /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
  3639. /// the address of a function template per [temp.deduct.funcaddr] and
  3640. /// [over.over]. If \c false, we are looking up a function template
  3641. /// specialization based on its signature, per [temp.deduct.decl].
  3642. ///
  3643. /// \returns the result of template argument deduction.
  3644. Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
  3645. FunctionTemplateDecl *FunctionTemplate,
  3646. TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
  3647. FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
  3648. bool IsAddressOfFunction) {
  3649. if (FunctionTemplate->isInvalidDecl())
  3650. return TDK_Invalid;
  3651. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  3652. TemplateParameterList *TemplateParams
  3653. = FunctionTemplate->getTemplateParameters();
  3654. QualType FunctionType = Function->getType();
  3655. // Substitute any explicit template arguments.
  3656. LocalInstantiationScope InstScope(*this);
  3657. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3658. unsigned NumExplicitlySpecified = 0;
  3659. SmallVector<QualType, 4> ParamTypes;
  3660. if (ExplicitTemplateArgs) {
  3661. TemplateDeductionResult Result;
  3662. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3663. Result = SubstituteExplicitTemplateArguments(
  3664. FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
  3665. &FunctionType, Info);
  3666. });
  3667. if (Result)
  3668. return Result;
  3669. NumExplicitlySpecified = Deduced.size();
  3670. }
  3671. // When taking the address of a function, we require convertibility of
  3672. // the resulting function type. Otherwise, we allow arbitrary mismatches
  3673. // of calling convention and noreturn.
  3674. if (!IsAddressOfFunction)
  3675. ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
  3676. /*AdjustExceptionSpec*/false);
  3677. // Unevaluated SFINAE context.
  3678. EnterExpressionEvaluationContext Unevaluated(
  3679. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  3680. SFINAETrap Trap(*this);
  3681. Deduced.resize(TemplateParams->size());
  3682. // If the function has a deduced return type, substitute it for a dependent
  3683. // type so that we treat it as a non-deduced context in what follows. If we
  3684. // are looking up by signature, the signature type should also have a deduced
  3685. // return type, which we instead expect to exactly match.
  3686. bool HasDeducedReturnType = false;
  3687. if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
  3688. Function->getReturnType()->getContainedAutoType()) {
  3689. FunctionType = SubstAutoTypeDependent(FunctionType);
  3690. HasDeducedReturnType = true;
  3691. }
  3692. if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
  3693. unsigned TDF =
  3694. TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
  3695. // Deduce template arguments from the function type.
  3696. if (TemplateDeductionResult Result
  3697. = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
  3698. FunctionType, ArgFunctionType,
  3699. Info, Deduced, TDF))
  3700. return Result;
  3701. }
  3702. TemplateDeductionResult Result;
  3703. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3704. Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
  3705. NumExplicitlySpecified,
  3706. Specialization, Info);
  3707. });
  3708. if (Result)
  3709. return Result;
  3710. // If the function has a deduced return type, deduce it now, so we can check
  3711. // that the deduced function type matches the requested type.
  3712. if (HasDeducedReturnType &&
  3713. Specialization->getReturnType()->isUndeducedType() &&
  3714. DeduceReturnType(Specialization, Info.getLocation(), false))
  3715. return TDK_MiscellaneousDeductionFailure;
  3716. // If the function has a dependent exception specification, resolve it now,
  3717. // so we can check that the exception specification matches.
  3718. auto *SpecializationFPT =
  3719. Specialization->getType()->castAs<FunctionProtoType>();
  3720. if (getLangOpts().CPlusPlus17 &&
  3721. isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
  3722. !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
  3723. return TDK_MiscellaneousDeductionFailure;
  3724. // Adjust the exception specification of the argument to match the
  3725. // substituted and resolved type we just formed. (Calling convention and
  3726. // noreturn can't be dependent, so we don't actually need this for them
  3727. // right now.)
  3728. QualType SpecializationType = Specialization->getType();
  3729. if (!IsAddressOfFunction)
  3730. ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
  3731. /*AdjustExceptionSpec*/true);
  3732. // If the requested function type does not match the actual type of the
  3733. // specialization with respect to arguments of compatible pointer to function
  3734. // types, template argument deduction fails.
  3735. if (!ArgFunctionType.isNull()) {
  3736. if (IsAddressOfFunction &&
  3737. !isSameOrCompatibleFunctionType(
  3738. Context.getCanonicalType(SpecializationType),
  3739. Context.getCanonicalType(ArgFunctionType)))
  3740. return TDK_MiscellaneousDeductionFailure;
  3741. if (!IsAddressOfFunction &&
  3742. !Context.hasSameType(SpecializationType, ArgFunctionType))
  3743. return TDK_MiscellaneousDeductionFailure;
  3744. }
  3745. return TDK_Success;
  3746. }
  3747. /// Deduce template arguments for a templated conversion
  3748. /// function (C++ [temp.deduct.conv]) and, if successful, produce a
  3749. /// conversion function template specialization.
  3750. Sema::TemplateDeductionResult
  3751. Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
  3752. QualType ToType,
  3753. CXXConversionDecl *&Specialization,
  3754. TemplateDeductionInfo &Info) {
  3755. if (ConversionTemplate->isInvalidDecl())
  3756. return TDK_Invalid;
  3757. CXXConversionDecl *ConversionGeneric
  3758. = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
  3759. QualType FromType = ConversionGeneric->getConversionType();
  3760. // Canonicalize the types for deduction.
  3761. QualType P = Context.getCanonicalType(FromType);
  3762. QualType A = Context.getCanonicalType(ToType);
  3763. // C++0x [temp.deduct.conv]p2:
  3764. // If P is a reference type, the type referred to by P is used for
  3765. // type deduction.
  3766. if (const ReferenceType *PRef = P->getAs<ReferenceType>())
  3767. P = PRef->getPointeeType();
  3768. // C++0x [temp.deduct.conv]p4:
  3769. // [...] If A is a reference type, the type referred to by A is used
  3770. // for type deduction.
  3771. if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
  3772. A = ARef->getPointeeType();
  3773. // We work around a defect in the standard here: cv-qualifiers are also
  3774. // removed from P and A in this case, unless P was a reference type. This
  3775. // seems to mostly match what other compilers are doing.
  3776. if (!FromType->getAs<ReferenceType>()) {
  3777. A = A.getUnqualifiedType();
  3778. P = P.getUnqualifiedType();
  3779. }
  3780. // C++ [temp.deduct.conv]p3:
  3781. //
  3782. // If A is not a reference type:
  3783. } else {
  3784. assert(!A->isReferenceType() && "Reference types were handled above");
  3785. // - If P is an array type, the pointer type produced by the
  3786. // array-to-pointer standard conversion (4.2) is used in place
  3787. // of P for type deduction; otherwise,
  3788. if (P->isArrayType())
  3789. P = Context.getArrayDecayedType(P);
  3790. // - If P is a function type, the pointer type produced by the
  3791. // function-to-pointer standard conversion (4.3) is used in
  3792. // place of P for type deduction; otherwise,
  3793. else if (P->isFunctionType())
  3794. P = Context.getPointerType(P);
  3795. // - If P is a cv-qualified type, the top level cv-qualifiers of
  3796. // P's type are ignored for type deduction.
  3797. else
  3798. P = P.getUnqualifiedType();
  3799. // C++0x [temp.deduct.conv]p4:
  3800. // If A is a cv-qualified type, the top level cv-qualifiers of A's
  3801. // type are ignored for type deduction. If A is a reference type, the type
  3802. // referred to by A is used for type deduction.
  3803. A = A.getUnqualifiedType();
  3804. }
  3805. // Unevaluated SFINAE context.
  3806. EnterExpressionEvaluationContext Unevaluated(
  3807. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  3808. SFINAETrap Trap(*this);
  3809. // C++ [temp.deduct.conv]p1:
  3810. // Template argument deduction is done by comparing the return
  3811. // type of the template conversion function (call it P) with the
  3812. // type that is required as the result of the conversion (call it
  3813. // A) as described in 14.8.2.4.
  3814. TemplateParameterList *TemplateParams
  3815. = ConversionTemplate->getTemplateParameters();
  3816. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3817. Deduced.resize(TemplateParams->size());
  3818. // C++0x [temp.deduct.conv]p4:
  3819. // In general, the deduction process attempts to find template
  3820. // argument values that will make the deduced A identical to
  3821. // A. However, there are two cases that allow a difference:
  3822. unsigned TDF = 0;
  3823. // - If the original A is a reference type, A can be more
  3824. // cv-qualified than the deduced A (i.e., the type referred to
  3825. // by the reference)
  3826. if (ToType->isReferenceType())
  3827. TDF |= TDF_ArgWithReferenceType;
  3828. // - The deduced A can be another pointer or pointer to member
  3829. // type that can be converted to A via a qualification
  3830. // conversion.
  3831. //
  3832. // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
  3833. // both P and A are pointers or member pointers. In this case, we
  3834. // just ignore cv-qualifiers completely).
  3835. if ((P->isPointerType() && A->isPointerType()) ||
  3836. (P->isMemberPointerType() && A->isMemberPointerType()))
  3837. TDF |= TDF_IgnoreQualifiers;
  3838. if (TemplateDeductionResult Result
  3839. = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
  3840. P, A, Info, Deduced, TDF))
  3841. return Result;
  3842. // Create an Instantiation Scope for finalizing the operator.
  3843. LocalInstantiationScope InstScope(*this);
  3844. // Finish template argument deduction.
  3845. FunctionDecl *ConversionSpecialized = nullptr;
  3846. TemplateDeductionResult Result;
  3847. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3848. Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
  3849. ConversionSpecialized, Info);
  3850. });
  3851. Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
  3852. return Result;
  3853. }
  3854. /// Deduce template arguments for a function template when there is
  3855. /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
  3856. ///
  3857. /// \param FunctionTemplate the function template for which we are performing
  3858. /// template argument deduction.
  3859. ///
  3860. /// \param ExplicitTemplateArgs the explicitly-specified template
  3861. /// arguments.
  3862. ///
  3863. /// \param Specialization if template argument deduction was successful,
  3864. /// this will be set to the function template specialization produced by
  3865. /// template argument deduction.
  3866. ///
  3867. /// \param Info the argument will be updated to provide additional information
  3868. /// about template argument deduction.
  3869. ///
  3870. /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
  3871. /// the address of a function template in a context where we do not have a
  3872. /// target type, per [over.over]. If \c false, we are looking up a function
  3873. /// template specialization based on its signature, which only happens when
  3874. /// deducing a function parameter type from an argument that is a template-id
  3875. /// naming a function template specialization.
  3876. ///
  3877. /// \returns the result of template argument deduction.
  3878. Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
  3879. FunctionTemplateDecl *FunctionTemplate,
  3880. TemplateArgumentListInfo *ExplicitTemplateArgs,
  3881. FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
  3882. bool IsAddressOfFunction) {
  3883. return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
  3884. QualType(), Specialization, Info,
  3885. IsAddressOfFunction);
  3886. }
  3887. namespace {
  3888. struct DependentAuto { bool IsPack; };
  3889. /// Substitute the 'auto' specifier or deduced template specialization type
  3890. /// specifier within a type for a given replacement type.
  3891. class SubstituteDeducedTypeTransform :
  3892. public TreeTransform<SubstituteDeducedTypeTransform> {
  3893. QualType Replacement;
  3894. bool ReplacementIsPack;
  3895. bool UseTypeSugar;
  3896. public:
  3897. SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
  3898. : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
  3899. ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
  3900. SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
  3901. bool UseTypeSugar = true)
  3902. : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
  3903. Replacement(Replacement), ReplacementIsPack(false),
  3904. UseTypeSugar(UseTypeSugar) {}
  3905. QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
  3906. assert(isa<TemplateTypeParmType>(Replacement) &&
  3907. "unexpected unsugared replacement kind");
  3908. QualType Result = Replacement;
  3909. TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
  3910. NewTL.setNameLoc(TL.getNameLoc());
  3911. return Result;
  3912. }
  3913. QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
  3914. // If we're building the type pattern to deduce against, don't wrap the
  3915. // substituted type in an AutoType. Certain template deduction rules
  3916. // apply only when a template type parameter appears directly (and not if
  3917. // the parameter is found through desugaring). For instance:
  3918. // auto &&lref = lvalue;
  3919. // must transform into "rvalue reference to T" not "rvalue reference to
  3920. // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
  3921. //
  3922. // FIXME: Is this still necessary?
  3923. if (!UseTypeSugar)
  3924. return TransformDesugared(TLB, TL);
  3925. QualType Result = SemaRef.Context.getAutoType(
  3926. Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
  3927. ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
  3928. TL.getTypePtr()->getTypeConstraintArguments());
  3929. auto NewTL = TLB.push<AutoTypeLoc>(Result);
  3930. NewTL.copy(TL);
  3931. return Result;
  3932. }
  3933. QualType TransformDeducedTemplateSpecializationType(
  3934. TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
  3935. if (!UseTypeSugar)
  3936. return TransformDesugared(TLB, TL);
  3937. QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
  3938. TL.getTypePtr()->getTemplateName(),
  3939. Replacement, Replacement.isNull());
  3940. auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
  3941. NewTL.setNameLoc(TL.getNameLoc());
  3942. return Result;
  3943. }
  3944. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  3945. // Lambdas never need to be transformed.
  3946. return E;
  3947. }
  3948. QualType Apply(TypeLoc TL) {
  3949. // Create some scratch storage for the transformed type locations.
  3950. // FIXME: We're just going to throw this information away. Don't build it.
  3951. TypeLocBuilder TLB;
  3952. TLB.reserve(TL.getFullDataSize());
  3953. return TransformType(TLB, TL);
  3954. }
  3955. };
  3956. } // namespace
  3957. Sema::DeduceAutoResult
  3958. Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
  3959. Optional<unsigned> DependentDeductionDepth,
  3960. bool IgnoreConstraints) {
  3961. return DeduceAutoType(Type->getTypeLoc(), Init, Result,
  3962. DependentDeductionDepth, IgnoreConstraints);
  3963. }
  3964. /// Attempt to produce an informative diagostic explaining why auto deduction
  3965. /// failed.
  3966. /// \return \c true if diagnosed, \c false if not.
  3967. static bool diagnoseAutoDeductionFailure(Sema &S,
  3968. Sema::TemplateDeductionResult TDK,
  3969. TemplateDeductionInfo &Info,
  3970. ArrayRef<SourceRange> Ranges) {
  3971. switch (TDK) {
  3972. case Sema::TDK_Inconsistent: {
  3973. // Inconsistent deduction means we were deducing from an initializer list.
  3974. auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
  3975. D << Info.FirstArg << Info.SecondArg;
  3976. for (auto R : Ranges)
  3977. D << R;
  3978. return true;
  3979. }
  3980. // FIXME: Are there other cases for which a custom diagnostic is more useful
  3981. // than the basic "types don't match" diagnostic?
  3982. default:
  3983. return false;
  3984. }
  3985. }
  3986. static Sema::DeduceAutoResult
  3987. CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
  3988. AutoTypeLoc TypeLoc, QualType Deduced) {
  3989. ConstraintSatisfaction Satisfaction;
  3990. ConceptDecl *Concept = Type.getTypeConstraintConcept();
  3991. TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
  3992. TypeLoc.getRAngleLoc());
  3993. TemplateArgs.addArgument(
  3994. TemplateArgumentLoc(TemplateArgument(Deduced),
  3995. S.Context.getTrivialTypeSourceInfo(
  3996. Deduced, TypeLoc.getNameLoc())));
  3997. for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
  3998. TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
  3999. llvm::SmallVector<TemplateArgument, 4> Converted;
  4000. if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
  4001. /*PartialTemplateArgs=*/false, Converted))
  4002. return Sema::DAR_FailedAlreadyDiagnosed;
  4003. if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
  4004. Converted, TypeLoc.getLocalSourceRange(),
  4005. Satisfaction))
  4006. return Sema::DAR_FailedAlreadyDiagnosed;
  4007. if (!Satisfaction.IsSatisfied) {
  4008. std::string Buf;
  4009. llvm::raw_string_ostream OS(Buf);
  4010. OS << "'" << Concept->getName();
  4011. if (TypeLoc.hasExplicitTemplateArgs()) {
  4012. printTemplateArgumentList(
  4013. OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
  4014. Type.getTypeConstraintConcept()->getTemplateParameters());
  4015. }
  4016. OS << "'";
  4017. OS.flush();
  4018. S.Diag(TypeLoc.getConceptNameLoc(),
  4019. diag::err_placeholder_constraints_not_satisfied)
  4020. << Deduced << Buf << TypeLoc.getLocalSourceRange();
  4021. S.DiagnoseUnsatisfiedConstraint(Satisfaction);
  4022. return Sema::DAR_FailedAlreadyDiagnosed;
  4023. }
  4024. return Sema::DAR_Succeeded;
  4025. }
  4026. /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
  4027. ///
  4028. /// Note that this is done even if the initializer is dependent. (This is
  4029. /// necessary to support partial ordering of templates using 'auto'.)
  4030. /// A dependent type will be produced when deducing from a dependent type.
  4031. ///
  4032. /// \param Type the type pattern using the auto type-specifier.
  4033. /// \param Init the initializer for the variable whose type is to be deduced.
  4034. /// \param Result if type deduction was successful, this will be set to the
  4035. /// deduced type.
  4036. /// \param DependentDeductionDepth Set if we should permit deduction in
  4037. /// dependent cases. This is necessary for template partial ordering with
  4038. /// 'auto' template parameters. The value specified is the template
  4039. /// parameter depth at which we should perform 'auto' deduction.
  4040. /// \param IgnoreConstraints Set if we should not fail if the deduced type does
  4041. /// not satisfy the type-constraint in the auto type.
  4042. Sema::DeduceAutoResult
  4043. Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
  4044. Optional<unsigned> DependentDeductionDepth,
  4045. bool IgnoreConstraints) {
  4046. if (Init->containsErrors())
  4047. return DAR_FailedAlreadyDiagnosed;
  4048. if (Init->getType()->isNonOverloadPlaceholderType()) {
  4049. ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
  4050. if (NonPlaceholder.isInvalid())
  4051. return DAR_FailedAlreadyDiagnosed;
  4052. Init = NonPlaceholder.get();
  4053. }
  4054. DependentAuto DependentResult = {
  4055. /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
  4056. if (!DependentDeductionDepth &&
  4057. (Type.getType()->isDependentType() || Init->isTypeDependent() ||
  4058. Init->containsUnexpandedParameterPack())) {
  4059. Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
  4060. assert(!Result.isNull() && "substituting DependentTy can't fail");
  4061. return DAR_Succeeded;
  4062. }
  4063. // Find the depth of template parameter to synthesize.
  4064. unsigned Depth = DependentDeductionDepth.getValueOr(0);
  4065. // If this is a 'decltype(auto)' specifier, do the decltype dance.
  4066. // Since 'decltype(auto)' can only occur at the top of the type, we
  4067. // don't need to go digging for it.
  4068. if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
  4069. if (AT->isDecltypeAuto()) {
  4070. if (isa<InitListExpr>(Init)) {
  4071. Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
  4072. return DAR_FailedAlreadyDiagnosed;
  4073. }
  4074. ExprResult ER = CheckPlaceholderExpr(Init);
  4075. if (ER.isInvalid())
  4076. return DAR_FailedAlreadyDiagnosed;
  4077. QualType Deduced = getDecltypeForExpr(ER.get());
  4078. assert(!Deduced.isNull());
  4079. if (AT->isConstrained() && !IgnoreConstraints) {
  4080. auto ConstraintsResult =
  4081. CheckDeducedPlaceholderConstraints(*this, *AT,
  4082. Type.getContainedAutoTypeLoc(),
  4083. Deduced);
  4084. if (ConstraintsResult != DAR_Succeeded)
  4085. return ConstraintsResult;
  4086. }
  4087. Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
  4088. if (Result.isNull())
  4089. return DAR_FailedAlreadyDiagnosed;
  4090. return DAR_Succeeded;
  4091. } else if (!getLangOpts().CPlusPlus) {
  4092. if (isa<InitListExpr>(Init)) {
  4093. Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
  4094. return DAR_FailedAlreadyDiagnosed;
  4095. }
  4096. }
  4097. }
  4098. SourceLocation Loc = Init->getExprLoc();
  4099. LocalInstantiationScope InstScope(*this);
  4100. // Build template<class TemplParam> void Func(FuncParam);
  4101. TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
  4102. Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false,
  4103. false);
  4104. QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
  4105. NamedDecl *TemplParamPtr = TemplParam;
  4106. FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
  4107. Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
  4108. QualType FuncParam =
  4109. SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/ true)
  4110. .Apply(Type);
  4111. assert(!FuncParam.isNull() &&
  4112. "substituting template parameter for 'auto' failed");
  4113. // Deduce type of TemplParam in Func(Init)
  4114. SmallVector<DeducedTemplateArgument, 1> Deduced;
  4115. Deduced.resize(1);
  4116. TemplateDeductionInfo Info(Loc, Depth);
  4117. // If deduction failed, don't diagnose if the initializer is dependent; it
  4118. // might acquire a matching type in the instantiation.
  4119. auto DeductionFailed = [&](TemplateDeductionResult TDK,
  4120. ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
  4121. if (Init->isTypeDependent()) {
  4122. Result =
  4123. SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
  4124. assert(!Result.isNull() && "substituting DependentTy can't fail");
  4125. return DAR_Succeeded;
  4126. }
  4127. if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
  4128. return DAR_FailedAlreadyDiagnosed;
  4129. return DAR_Failed;
  4130. };
  4131. SmallVector<OriginalCallArg, 4> OriginalCallArgs;
  4132. InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
  4133. if (InitList) {
  4134. // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
  4135. // against that. Such deduction only succeeds if removing cv-qualifiers and
  4136. // references results in std::initializer_list<T>.
  4137. if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
  4138. return DAR_Failed;
  4139. // Resolving a core issue: a braced-init-list containing any designators is
  4140. // a non-deduced context.
  4141. for (Expr *E : InitList->inits())
  4142. if (isa<DesignatedInitExpr>(E))
  4143. return DAR_Failed;
  4144. SourceRange DeducedFromInitRange;
  4145. for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
  4146. Expr *Init = InitList->getInit(i);
  4147. if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
  4148. *this, TemplateParamsSt.get(), 0, TemplArg, Init,
  4149. Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
  4150. /*ArgIdx*/ 0, /*TDF*/ 0))
  4151. return DeductionFailed(TDK, {DeducedFromInitRange,
  4152. Init->getSourceRange()});
  4153. if (DeducedFromInitRange.isInvalid() &&
  4154. Deduced[0].getKind() != TemplateArgument::Null)
  4155. DeducedFromInitRange = Init->getSourceRange();
  4156. }
  4157. } else {
  4158. if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
  4159. Diag(Loc, diag::err_auto_bitfield);
  4160. return DAR_FailedAlreadyDiagnosed;
  4161. }
  4162. if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
  4163. *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
  4164. OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
  4165. return DeductionFailed(TDK, {});
  4166. }
  4167. // Could be null if somehow 'auto' appears in a non-deduced context.
  4168. if (Deduced[0].getKind() != TemplateArgument::Type)
  4169. return DeductionFailed(TDK_Incomplete, {});
  4170. QualType DeducedType = Deduced[0].getAsType();
  4171. if (InitList) {
  4172. DeducedType = BuildStdInitializerList(DeducedType, Loc);
  4173. if (DeducedType.isNull())
  4174. return DAR_FailedAlreadyDiagnosed;
  4175. }
  4176. if (const auto *AT = Type.getType()->getAs<AutoType>()) {
  4177. if (AT->isConstrained() && !IgnoreConstraints) {
  4178. auto ConstraintsResult =
  4179. CheckDeducedPlaceholderConstraints(*this, *AT,
  4180. Type.getContainedAutoTypeLoc(),
  4181. DeducedType);
  4182. if (ConstraintsResult != DAR_Succeeded)
  4183. return ConstraintsResult;
  4184. }
  4185. }
  4186. Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
  4187. if (Result.isNull())
  4188. return DAR_FailedAlreadyDiagnosed;
  4189. // Check that the deduced argument type is compatible with the original
  4190. // argument type per C++ [temp.deduct.call]p4.
  4191. QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
  4192. for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
  4193. assert((bool)InitList == OriginalArg.DecomposedParam &&
  4194. "decomposed non-init-list in auto deduction?");
  4195. if (auto TDK =
  4196. CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
  4197. Result = QualType();
  4198. return DeductionFailed(TDK, {});
  4199. }
  4200. }
  4201. return DAR_Succeeded;
  4202. }
  4203. QualType Sema::SubstAutoType(QualType TypeWithAuto,
  4204. QualType TypeToReplaceAuto) {
  4205. assert(TypeToReplaceAuto != Context.DependentTy);
  4206. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
  4207. .TransformType(TypeWithAuto);
  4208. }
  4209. TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
  4210. QualType TypeToReplaceAuto) {
  4211. assert(TypeToReplaceAuto != Context.DependentTy);
  4212. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
  4213. .TransformType(TypeWithAuto);
  4214. }
  4215. QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) {
  4216. return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
  4217. .TransformType(TypeWithAuto);
  4218. }
  4219. TypeSourceInfo *
  4220. Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) {
  4221. return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
  4222. .TransformType(TypeWithAuto);
  4223. }
  4224. QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
  4225. QualType TypeToReplaceAuto) {
  4226. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
  4227. /*UseTypeSugar*/ false)
  4228. .TransformType(TypeWithAuto);
  4229. }
  4230. TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
  4231. QualType TypeToReplaceAuto) {
  4232. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
  4233. /*UseTypeSugar*/ false)
  4234. .TransformType(TypeWithAuto);
  4235. }
  4236. void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
  4237. if (isa<InitListExpr>(Init))
  4238. Diag(VDecl->getLocation(),
  4239. VDecl->isInitCapture()
  4240. ? diag::err_init_capture_deduction_failure_from_init_list
  4241. : diag::err_auto_var_deduction_failure_from_init_list)
  4242. << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
  4243. else
  4244. Diag(VDecl->getLocation(),
  4245. VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
  4246. : diag::err_auto_var_deduction_failure)
  4247. << VDecl->getDeclName() << VDecl->getType() << Init->getType()
  4248. << Init->getSourceRange();
  4249. }
  4250. bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
  4251. bool Diagnose) {
  4252. assert(FD->getReturnType()->isUndeducedType());
  4253. // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
  4254. // within the return type from the call operator's type.
  4255. if (isLambdaConversionOperator(FD)) {
  4256. CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
  4257. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  4258. // For a generic lambda, instantiate the call operator if needed.
  4259. if (auto *Args = FD->getTemplateSpecializationArgs()) {
  4260. CallOp = InstantiateFunctionDeclaration(
  4261. CallOp->getDescribedFunctionTemplate(), Args, Loc);
  4262. if (!CallOp || CallOp->isInvalidDecl())
  4263. return true;
  4264. // We might need to deduce the return type by instantiating the definition
  4265. // of the operator() function.
  4266. if (CallOp->getReturnType()->isUndeducedType()) {
  4267. runWithSufficientStackSpace(Loc, [&] {
  4268. InstantiateFunctionDefinition(Loc, CallOp);
  4269. });
  4270. }
  4271. }
  4272. if (CallOp->isInvalidDecl())
  4273. return true;
  4274. assert(!CallOp->getReturnType()->isUndeducedType() &&
  4275. "failed to deduce lambda return type");
  4276. // Build the new return type from scratch.
  4277. CallingConv RetTyCC = FD->getReturnType()
  4278. ->getPointeeType()
  4279. ->castAs<FunctionType>()
  4280. ->getCallConv();
  4281. QualType RetType = getLambdaConversionFunctionResultType(
  4282. CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
  4283. if (FD->getReturnType()->getAs<PointerType>())
  4284. RetType = Context.getPointerType(RetType);
  4285. else {
  4286. assert(FD->getReturnType()->getAs<BlockPointerType>());
  4287. RetType = Context.getBlockPointerType(RetType);
  4288. }
  4289. Context.adjustDeducedFunctionResultType(FD, RetType);
  4290. return false;
  4291. }
  4292. if (FD->getTemplateInstantiationPattern()) {
  4293. runWithSufficientStackSpace(Loc, [&] {
  4294. InstantiateFunctionDefinition(Loc, FD);
  4295. });
  4296. }
  4297. bool StillUndeduced = FD->getReturnType()->isUndeducedType();
  4298. if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
  4299. Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
  4300. Diag(FD->getLocation(), diag::note_callee_decl) << FD;
  4301. }
  4302. return StillUndeduced;
  4303. }
  4304. /// If this is a non-static member function,
  4305. static void
  4306. AddImplicitObjectParameterType(ASTContext &Context,
  4307. CXXMethodDecl *Method,
  4308. SmallVectorImpl<QualType> &ArgTypes) {
  4309. // C++11 [temp.func.order]p3:
  4310. // [...] The new parameter is of type "reference to cv A," where cv are
  4311. // the cv-qualifiers of the function template (if any) and A is
  4312. // the class of which the function template is a member.
  4313. //
  4314. // The standard doesn't say explicitly, but we pick the appropriate kind of
  4315. // reference type based on [over.match.funcs]p4.
  4316. QualType ArgTy = Context.getTypeDeclType(Method->getParent());
  4317. ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
  4318. if (Method->getRefQualifier() == RQ_RValue)
  4319. ArgTy = Context.getRValueReferenceType(ArgTy);
  4320. else
  4321. ArgTy = Context.getLValueReferenceType(ArgTy);
  4322. ArgTypes.push_back(ArgTy);
  4323. }
  4324. /// Determine whether the function template \p FT1 is at least as
  4325. /// specialized as \p FT2.
  4326. static bool isAtLeastAsSpecializedAs(Sema &S,
  4327. SourceLocation Loc,
  4328. FunctionTemplateDecl *FT1,
  4329. FunctionTemplateDecl *FT2,
  4330. TemplatePartialOrderingContext TPOC,
  4331. unsigned NumCallArguments1,
  4332. bool Reversed) {
  4333. assert(!Reversed || TPOC == TPOC_Call);
  4334. FunctionDecl *FD1 = FT1->getTemplatedDecl();
  4335. FunctionDecl *FD2 = FT2->getTemplatedDecl();
  4336. const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
  4337. const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
  4338. assert(Proto1 && Proto2 && "Function templates must have prototypes");
  4339. TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
  4340. SmallVector<DeducedTemplateArgument, 4> Deduced;
  4341. Deduced.resize(TemplateParams->size());
  4342. // C++0x [temp.deduct.partial]p3:
  4343. // The types used to determine the ordering depend on the context in which
  4344. // the partial ordering is done:
  4345. TemplateDeductionInfo Info(Loc);
  4346. SmallVector<QualType, 4> Args2;
  4347. switch (TPOC) {
  4348. case TPOC_Call: {
  4349. // - In the context of a function call, the function parameter types are
  4350. // used.
  4351. CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
  4352. CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
  4353. // C++11 [temp.func.order]p3:
  4354. // [...] If only one of the function templates is a non-static
  4355. // member, that function template is considered to have a new
  4356. // first parameter inserted in its function parameter list. The
  4357. // new parameter is of type "reference to cv A," where cv are
  4358. // the cv-qualifiers of the function template (if any) and A is
  4359. // the class of which the function template is a member.
  4360. //
  4361. // Note that we interpret this to mean "if one of the function
  4362. // templates is a non-static member and the other is a non-member";
  4363. // otherwise, the ordering rules for static functions against non-static
  4364. // functions don't make any sense.
  4365. //
  4366. // C++98/03 doesn't have this provision but we've extended DR532 to cover
  4367. // it as wording was broken prior to it.
  4368. SmallVector<QualType, 4> Args1;
  4369. unsigned NumComparedArguments = NumCallArguments1;
  4370. if (!Method2 && Method1 && !Method1->isStatic()) {
  4371. // Compare 'this' from Method1 against first parameter from Method2.
  4372. AddImplicitObjectParameterType(S.Context, Method1, Args1);
  4373. ++NumComparedArguments;
  4374. } else if (!Method1 && Method2 && !Method2->isStatic()) {
  4375. // Compare 'this' from Method2 against first parameter from Method1.
  4376. AddImplicitObjectParameterType(S.Context, Method2, Args2);
  4377. } else if (Method1 && Method2 && Reversed) {
  4378. // Compare 'this' from Method1 against second parameter from Method2
  4379. // and 'this' from Method2 against second parameter from Method1.
  4380. AddImplicitObjectParameterType(S.Context, Method1, Args1);
  4381. AddImplicitObjectParameterType(S.Context, Method2, Args2);
  4382. ++NumComparedArguments;
  4383. }
  4384. Args1.insert(Args1.end(), Proto1->param_type_begin(),
  4385. Proto1->param_type_end());
  4386. Args2.insert(Args2.end(), Proto2->param_type_begin(),
  4387. Proto2->param_type_end());
  4388. // C++ [temp.func.order]p5:
  4389. // The presence of unused ellipsis and default arguments has no effect on
  4390. // the partial ordering of function templates.
  4391. if (Args1.size() > NumComparedArguments)
  4392. Args1.resize(NumComparedArguments);
  4393. if (Args2.size() > NumComparedArguments)
  4394. Args2.resize(NumComparedArguments);
  4395. if (Reversed)
  4396. std::reverse(Args2.begin(), Args2.end());
  4397. if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
  4398. Args1.data(), Args1.size(), Info, Deduced,
  4399. TDF_None, /*PartialOrdering=*/true))
  4400. return false;
  4401. break;
  4402. }
  4403. case TPOC_Conversion:
  4404. // - In the context of a call to a conversion operator, the return types
  4405. // of the conversion function templates are used.
  4406. if (DeduceTemplateArgumentsByTypeMatch(
  4407. S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
  4408. Info, Deduced, TDF_None,
  4409. /*PartialOrdering=*/true))
  4410. return false;
  4411. break;
  4412. case TPOC_Other:
  4413. // - In other contexts (14.6.6.2) the function template's function type
  4414. // is used.
  4415. if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
  4416. FD2->getType(), FD1->getType(),
  4417. Info, Deduced, TDF_None,
  4418. /*PartialOrdering=*/true))
  4419. return false;
  4420. break;
  4421. }
  4422. // C++0x [temp.deduct.partial]p11:
  4423. // In most cases, all template parameters must have values in order for
  4424. // deduction to succeed, but for partial ordering purposes a template
  4425. // parameter may remain without a value provided it is not used in the
  4426. // types being used for partial ordering. [ Note: a template parameter used
  4427. // in a non-deduced context is considered used. -end note]
  4428. unsigned ArgIdx = 0, NumArgs = Deduced.size();
  4429. for (; ArgIdx != NumArgs; ++ArgIdx)
  4430. if (Deduced[ArgIdx].isNull())
  4431. break;
  4432. // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
  4433. // to substitute the deduced arguments back into the template and check that
  4434. // we get the right type.
  4435. if (ArgIdx == NumArgs) {
  4436. // All template arguments were deduced. FT1 is at least as specialized
  4437. // as FT2.
  4438. return true;
  4439. }
  4440. // Figure out which template parameters were used.
  4441. llvm::SmallBitVector UsedParameters(TemplateParams->size());
  4442. switch (TPOC) {
  4443. case TPOC_Call:
  4444. for (unsigned I = 0, N = Args2.size(); I != N; ++I)
  4445. ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
  4446. TemplateParams->getDepth(),
  4447. UsedParameters);
  4448. break;
  4449. case TPOC_Conversion:
  4450. ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
  4451. TemplateParams->getDepth(), UsedParameters);
  4452. break;
  4453. case TPOC_Other:
  4454. ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
  4455. TemplateParams->getDepth(),
  4456. UsedParameters);
  4457. break;
  4458. }
  4459. for (; ArgIdx != NumArgs; ++ArgIdx)
  4460. // If this argument had no value deduced but was used in one of the types
  4461. // used for partial ordering, then deduction fails.
  4462. if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
  4463. return false;
  4464. return true;
  4465. }
  4466. /// Determine whether this a function template whose parameter-type-list
  4467. /// ends with a function parameter pack.
  4468. static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
  4469. FunctionDecl *Function = FunTmpl->getTemplatedDecl();
  4470. unsigned NumParams = Function->getNumParams();
  4471. if (NumParams == 0)
  4472. return false;
  4473. ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
  4474. if (!Last->isParameterPack())
  4475. return false;
  4476. // Make sure that no previous parameter is a parameter pack.
  4477. while (--NumParams > 0) {
  4478. if (Function->getParamDecl(NumParams - 1)->isParameterPack())
  4479. return false;
  4480. }
  4481. return true;
  4482. }
  4483. /// Returns the more specialized function template according
  4484. /// to the rules of function template partial ordering (C++ [temp.func.order]).
  4485. ///
  4486. /// \param FT1 the first function template
  4487. ///
  4488. /// \param FT2 the second function template
  4489. ///
  4490. /// \param TPOC the context in which we are performing partial ordering of
  4491. /// function templates.
  4492. ///
  4493. /// \param NumCallArguments1 The number of arguments in the call to FT1, used
  4494. /// only when \c TPOC is \c TPOC_Call.
  4495. ///
  4496. /// \param NumCallArguments2 The number of arguments in the call to FT2, used
  4497. /// only when \c TPOC is \c TPOC_Call.
  4498. ///
  4499. /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
  4500. /// candidate with a reversed parameter order. In this case, the corresponding
  4501. /// P/A pairs between FT1 and FT2 are reversed.
  4502. ///
  4503. /// \returns the more specialized function template. If neither
  4504. /// template is more specialized, returns NULL.
  4505. FunctionTemplateDecl *
  4506. Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
  4507. FunctionTemplateDecl *FT2,
  4508. SourceLocation Loc,
  4509. TemplatePartialOrderingContext TPOC,
  4510. unsigned NumCallArguments1,
  4511. unsigned NumCallArguments2,
  4512. bool Reversed) {
  4513. auto JudgeByConstraints = [&] () -> FunctionTemplateDecl * {
  4514. llvm::SmallVector<const Expr *, 3> AC1, AC2;
  4515. FT1->getAssociatedConstraints(AC1);
  4516. FT2->getAssociatedConstraints(AC2);
  4517. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  4518. if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
  4519. return nullptr;
  4520. if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
  4521. return nullptr;
  4522. if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
  4523. return nullptr;
  4524. return AtLeastAsConstrained1 ? FT1 : FT2;
  4525. };
  4526. bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
  4527. NumCallArguments1, Reversed);
  4528. bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
  4529. NumCallArguments2, Reversed);
  4530. if (Better1 != Better2) // We have a clear winner
  4531. return Better1 ? FT1 : FT2;
  4532. if (!Better1 && !Better2) // Neither is better than the other
  4533. return JudgeByConstraints();
  4534. // FIXME: This mimics what GCC implements, but doesn't match up with the
  4535. // proposed resolution for core issue 692. This area needs to be sorted out,
  4536. // but for now we attempt to maintain compatibility.
  4537. bool Variadic1 = isVariadicFunctionTemplate(FT1);
  4538. bool Variadic2 = isVariadicFunctionTemplate(FT2);
  4539. if (Variadic1 != Variadic2)
  4540. return Variadic1? FT2 : FT1;
  4541. return JudgeByConstraints();
  4542. }
  4543. /// Determine if the two templates are equivalent.
  4544. static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
  4545. if (T1 == T2)
  4546. return true;
  4547. if (!T1 || !T2)
  4548. return false;
  4549. return T1->getCanonicalDecl() == T2->getCanonicalDecl();
  4550. }
  4551. /// Retrieve the most specialized of the given function template
  4552. /// specializations.
  4553. ///
  4554. /// \param SpecBegin the start iterator of the function template
  4555. /// specializations that we will be comparing.
  4556. ///
  4557. /// \param SpecEnd the end iterator of the function template
  4558. /// specializations, paired with \p SpecBegin.
  4559. ///
  4560. /// \param Loc the location where the ambiguity or no-specializations
  4561. /// diagnostic should occur.
  4562. ///
  4563. /// \param NoneDiag partial diagnostic used to diagnose cases where there are
  4564. /// no matching candidates.
  4565. ///
  4566. /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
  4567. /// occurs.
  4568. ///
  4569. /// \param CandidateDiag partial diagnostic used for each function template
  4570. /// specialization that is a candidate in the ambiguous ordering. One parameter
  4571. /// in this diagnostic should be unbound, which will correspond to the string
  4572. /// describing the template arguments for the function template specialization.
  4573. ///
  4574. /// \returns the most specialized function template specialization, if
  4575. /// found. Otherwise, returns SpecEnd.
  4576. UnresolvedSetIterator Sema::getMostSpecialized(
  4577. UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
  4578. TemplateSpecCandidateSet &FailedCandidates,
  4579. SourceLocation Loc, const PartialDiagnostic &NoneDiag,
  4580. const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
  4581. bool Complain, QualType TargetType) {
  4582. if (SpecBegin == SpecEnd) {
  4583. if (Complain) {
  4584. Diag(Loc, NoneDiag);
  4585. FailedCandidates.NoteCandidates(*this, Loc);
  4586. }
  4587. return SpecEnd;
  4588. }
  4589. if (SpecBegin + 1 == SpecEnd)
  4590. return SpecBegin;
  4591. // Find the function template that is better than all of the templates it
  4592. // has been compared to.
  4593. UnresolvedSetIterator Best = SpecBegin;
  4594. FunctionTemplateDecl *BestTemplate
  4595. = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
  4596. assert(BestTemplate && "Not a function template specialization?");
  4597. for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
  4598. FunctionTemplateDecl *Challenger
  4599. = cast<FunctionDecl>(*I)->getPrimaryTemplate();
  4600. assert(Challenger && "Not a function template specialization?");
  4601. if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
  4602. Loc, TPOC_Other, 0, 0),
  4603. Challenger)) {
  4604. Best = I;
  4605. BestTemplate = Challenger;
  4606. }
  4607. }
  4608. // Make sure that the "best" function template is more specialized than all
  4609. // of the others.
  4610. bool Ambiguous = false;
  4611. for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
  4612. FunctionTemplateDecl *Challenger
  4613. = cast<FunctionDecl>(*I)->getPrimaryTemplate();
  4614. if (I != Best &&
  4615. !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
  4616. Loc, TPOC_Other, 0, 0),
  4617. BestTemplate)) {
  4618. Ambiguous = true;
  4619. break;
  4620. }
  4621. }
  4622. if (!Ambiguous) {
  4623. // We found an answer. Return it.
  4624. return Best;
  4625. }
  4626. // Diagnose the ambiguity.
  4627. if (Complain) {
  4628. Diag(Loc, AmbigDiag);
  4629. // FIXME: Can we order the candidates in some sane way?
  4630. for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
  4631. PartialDiagnostic PD = CandidateDiag;
  4632. const auto *FD = cast<FunctionDecl>(*I);
  4633. PD << FD << getTemplateArgumentBindingsText(
  4634. FD->getPrimaryTemplate()->getTemplateParameters(),
  4635. *FD->getTemplateSpecializationArgs());
  4636. if (!TargetType.isNull())
  4637. HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
  4638. Diag((*I)->getLocation(), PD);
  4639. }
  4640. }
  4641. return SpecEnd;
  4642. }
  4643. /// Determine whether one partial specialization, P1, is at least as
  4644. /// specialized than another, P2.
  4645. ///
  4646. /// \tparam TemplateLikeDecl The kind of P2, which must be a
  4647. /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
  4648. /// \param T1 The injected-class-name of P1 (faked for a variable template).
  4649. /// \param T2 The injected-class-name of P2 (faked for a variable template).
  4650. template<typename TemplateLikeDecl>
  4651. static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
  4652. TemplateLikeDecl *P2,
  4653. TemplateDeductionInfo &Info) {
  4654. // C++ [temp.class.order]p1:
  4655. // For two class template partial specializations, the first is at least as
  4656. // specialized as the second if, given the following rewrite to two
  4657. // function templates, the first function template is at least as
  4658. // specialized as the second according to the ordering rules for function
  4659. // templates (14.6.6.2):
  4660. // - the first function template has the same template parameters as the
  4661. // first partial specialization and has a single function parameter
  4662. // whose type is a class template specialization with the template
  4663. // arguments of the first partial specialization, and
  4664. // - the second function template has the same template parameters as the
  4665. // second partial specialization and has a single function parameter
  4666. // whose type is a class template specialization with the template
  4667. // arguments of the second partial specialization.
  4668. //
  4669. // Rather than synthesize function templates, we merely perform the
  4670. // equivalent partial ordering by performing deduction directly on
  4671. // the template arguments of the class template partial
  4672. // specializations. This computation is slightly simpler than the
  4673. // general problem of function template partial ordering, because
  4674. // class template partial specializations are more constrained. We
  4675. // know that every template parameter is deducible from the class
  4676. // template partial specialization's template arguments, for
  4677. // example.
  4678. SmallVector<DeducedTemplateArgument, 4> Deduced;
  4679. // Determine whether P1 is at least as specialized as P2.
  4680. Deduced.resize(P2->getTemplateParameters()->size());
  4681. if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
  4682. T2, T1, Info, Deduced, TDF_None,
  4683. /*PartialOrdering=*/true))
  4684. return false;
  4685. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
  4686. Deduced.end());
  4687. Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
  4688. Info);
  4689. if (Inst.isInvalid())
  4690. return false;
  4691. auto *TST1 = T1->castAs<TemplateSpecializationType>();
  4692. bool AtLeastAsSpecialized;
  4693. S.runWithSufficientStackSpace(Info.getLocation(), [&] {
  4694. AtLeastAsSpecialized = !FinishTemplateArgumentDeduction(
  4695. S, P2, /*IsPartialOrdering=*/true,
  4696. TemplateArgumentList(TemplateArgumentList::OnStack,
  4697. TST1->template_arguments()),
  4698. Deduced, Info);
  4699. });
  4700. return AtLeastAsSpecialized;
  4701. }
  4702. /// Returns the more specialized class template partial specialization
  4703. /// according to the rules of partial ordering of class template partial
  4704. /// specializations (C++ [temp.class.order]).
  4705. ///
  4706. /// \param PS1 the first class template partial specialization
  4707. ///
  4708. /// \param PS2 the second class template partial specialization
  4709. ///
  4710. /// \returns the more specialized class template partial specialization. If
  4711. /// neither partial specialization is more specialized, returns NULL.
  4712. ClassTemplatePartialSpecializationDecl *
  4713. Sema::getMoreSpecializedPartialSpecialization(
  4714. ClassTemplatePartialSpecializationDecl *PS1,
  4715. ClassTemplatePartialSpecializationDecl *PS2,
  4716. SourceLocation Loc) {
  4717. QualType PT1 = PS1->getInjectedSpecializationType();
  4718. QualType PT2 = PS2->getInjectedSpecializationType();
  4719. TemplateDeductionInfo Info(Loc);
  4720. bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
  4721. bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
  4722. if (!Better1 && !Better2)
  4723. return nullptr;
  4724. if (Better1 && Better2) {
  4725. llvm::SmallVector<const Expr *, 3> AC1, AC2;
  4726. PS1->getAssociatedConstraints(AC1);
  4727. PS2->getAssociatedConstraints(AC2);
  4728. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  4729. if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1))
  4730. return nullptr;
  4731. if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2))
  4732. return nullptr;
  4733. if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
  4734. return nullptr;
  4735. return AtLeastAsConstrained1 ? PS1 : PS2;
  4736. }
  4737. return Better1 ? PS1 : PS2;
  4738. }
  4739. bool Sema::isMoreSpecializedThanPrimary(
  4740. ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
  4741. ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
  4742. QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
  4743. QualType PartialT = Spec->getInjectedSpecializationType();
  4744. if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
  4745. return false;
  4746. if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info))
  4747. return true;
  4748. Info.clearSFINAEDiagnostic();
  4749. llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC;
  4750. Primary->getAssociatedConstraints(PrimaryAC);
  4751. Spec->getAssociatedConstraints(SpecAC);
  4752. bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec;
  4753. if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC,
  4754. AtLeastAsConstrainedSpec))
  4755. return false;
  4756. if (!AtLeastAsConstrainedSpec)
  4757. return false;
  4758. if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC,
  4759. AtLeastAsConstrainedPrimary))
  4760. return false;
  4761. return !AtLeastAsConstrainedPrimary;
  4762. }
  4763. VarTemplatePartialSpecializationDecl *
  4764. Sema::getMoreSpecializedPartialSpecialization(
  4765. VarTemplatePartialSpecializationDecl *PS1,
  4766. VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
  4767. // Pretend the variable template specializations are class template
  4768. // specializations and form a fake injected class name type for comparison.
  4769. assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
  4770. "the partial specializations being compared should specialize"
  4771. " the same template.");
  4772. TemplateName Name(PS1->getSpecializedTemplate());
  4773. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  4774. QualType PT1 = Context.getTemplateSpecializationType(
  4775. CanonTemplate, PS1->getTemplateArgs().asArray());
  4776. QualType PT2 = Context.getTemplateSpecializationType(
  4777. CanonTemplate, PS2->getTemplateArgs().asArray());
  4778. TemplateDeductionInfo Info(Loc);
  4779. bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
  4780. bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
  4781. if (!Better1 && !Better2)
  4782. return nullptr;
  4783. if (Better1 && Better2) {
  4784. llvm::SmallVector<const Expr *, 3> AC1, AC2;
  4785. PS1->getAssociatedConstraints(AC1);
  4786. PS2->getAssociatedConstraints(AC2);
  4787. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  4788. if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1))
  4789. return nullptr;
  4790. if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2))
  4791. return nullptr;
  4792. if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
  4793. return nullptr;
  4794. return AtLeastAsConstrained1 ? PS1 : PS2;
  4795. }
  4796. return Better1 ? PS1 : PS2;
  4797. }
  4798. bool Sema::isMoreSpecializedThanPrimary(
  4799. VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
  4800. TemplateDecl *Primary = Spec->getSpecializedTemplate();
  4801. // FIXME: Cache the injected template arguments rather than recomputing
  4802. // them for each partial specialization.
  4803. SmallVector<TemplateArgument, 8> PrimaryArgs;
  4804. Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
  4805. PrimaryArgs);
  4806. TemplateName CanonTemplate =
  4807. Context.getCanonicalTemplateName(TemplateName(Primary));
  4808. QualType PrimaryT = Context.getTemplateSpecializationType(
  4809. CanonTemplate, PrimaryArgs);
  4810. QualType PartialT = Context.getTemplateSpecializationType(
  4811. CanonTemplate, Spec->getTemplateArgs().asArray());
  4812. if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
  4813. return false;
  4814. if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info))
  4815. return true;
  4816. Info.clearSFINAEDiagnostic();
  4817. llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC;
  4818. Primary->getAssociatedConstraints(PrimaryAC);
  4819. Spec->getAssociatedConstraints(SpecAC);
  4820. bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec;
  4821. if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC,
  4822. AtLeastAsConstrainedSpec))
  4823. return false;
  4824. if (!AtLeastAsConstrainedSpec)
  4825. return false;
  4826. if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC,
  4827. AtLeastAsConstrainedPrimary))
  4828. return false;
  4829. return !AtLeastAsConstrainedPrimary;
  4830. }
  4831. bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
  4832. TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
  4833. // C++1z [temp.arg.template]p4: (DR 150)
  4834. // A template template-parameter P is at least as specialized as a
  4835. // template template-argument A if, given the following rewrite to two
  4836. // function templates...
  4837. // Rather than synthesize function templates, we merely perform the
  4838. // equivalent partial ordering by performing deduction directly on
  4839. // the template parameter lists of the template template parameters.
  4840. //
  4841. // Given an invented class template X with the template parameter list of
  4842. // A (including default arguments):
  4843. TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
  4844. TemplateParameterList *A = AArg->getTemplateParameters();
  4845. // - Each function template has a single function parameter whose type is
  4846. // a specialization of X with template arguments corresponding to the
  4847. // template parameters from the respective function template
  4848. SmallVector<TemplateArgument, 8> AArgs;
  4849. Context.getInjectedTemplateArgs(A, AArgs);
  4850. // Check P's arguments against A's parameter list. This will fill in default
  4851. // template arguments as needed. AArgs are already correct by construction.
  4852. // We can't just use CheckTemplateIdType because that will expand alias
  4853. // templates.
  4854. SmallVector<TemplateArgument, 4> PArgs;
  4855. {
  4856. SFINAETrap Trap(*this);
  4857. Context.getInjectedTemplateArgs(P, PArgs);
  4858. TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
  4859. P->getRAngleLoc());
  4860. for (unsigned I = 0, N = P->size(); I != N; ++I) {
  4861. // Unwrap packs that getInjectedTemplateArgs wrapped around pack
  4862. // expansions, to form an "as written" argument list.
  4863. TemplateArgument Arg = PArgs[I];
  4864. if (Arg.getKind() == TemplateArgument::Pack) {
  4865. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
  4866. Arg = *Arg.pack_begin();
  4867. }
  4868. PArgList.addArgument(getTrivialTemplateArgumentLoc(
  4869. Arg, QualType(), P->getParam(I)->getLocation()));
  4870. }
  4871. PArgs.clear();
  4872. // C++1z [temp.arg.template]p3:
  4873. // If the rewrite produces an invalid type, then P is not at least as
  4874. // specialized as A.
  4875. if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
  4876. Trap.hasErrorOccurred())
  4877. return false;
  4878. }
  4879. QualType AType = Context.getTemplateSpecializationType(X, AArgs);
  4880. QualType PType = Context.getTemplateSpecializationType(X, PArgs);
  4881. // ... the function template corresponding to P is at least as specialized
  4882. // as the function template corresponding to A according to the partial
  4883. // ordering rules for function templates.
  4884. TemplateDeductionInfo Info(Loc, A->getDepth());
  4885. return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
  4886. }
  4887. namespace {
  4888. struct MarkUsedTemplateParameterVisitor :
  4889. RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
  4890. llvm::SmallBitVector &Used;
  4891. unsigned Depth;
  4892. MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
  4893. unsigned Depth)
  4894. : Used(Used), Depth(Depth) { }
  4895. bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
  4896. if (T->getDepth() == Depth)
  4897. Used[T->getIndex()] = true;
  4898. return true;
  4899. }
  4900. bool TraverseTemplateName(TemplateName Template) {
  4901. if (auto *TTP =
  4902. dyn_cast<TemplateTemplateParmDecl>(Template.getAsTemplateDecl()))
  4903. if (TTP->getDepth() == Depth)
  4904. Used[TTP->getIndex()] = true;
  4905. RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>::
  4906. TraverseTemplateName(Template);
  4907. return true;
  4908. }
  4909. bool VisitDeclRefExpr(DeclRefExpr *E) {
  4910. if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
  4911. if (NTTP->getDepth() == Depth)
  4912. Used[NTTP->getIndex()] = true;
  4913. return true;
  4914. }
  4915. };
  4916. }
  4917. /// Mark the template parameters that are used by the given
  4918. /// expression.
  4919. static void
  4920. MarkUsedTemplateParameters(ASTContext &Ctx,
  4921. const Expr *E,
  4922. bool OnlyDeduced,
  4923. unsigned Depth,
  4924. llvm::SmallBitVector &Used) {
  4925. if (!OnlyDeduced) {
  4926. MarkUsedTemplateParameterVisitor(Used, Depth)
  4927. .TraverseStmt(const_cast<Expr *>(E));
  4928. return;
  4929. }
  4930. // We can deduce from a pack expansion.
  4931. if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
  4932. E = Expansion->getPattern();
  4933. const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth);
  4934. if (!NTTP)
  4935. return;
  4936. if (NTTP->getDepth() == Depth)
  4937. Used[NTTP->getIndex()] = true;
  4938. // In C++17 mode, additional arguments may be deduced from the type of a
  4939. // non-type argument.
  4940. if (Ctx.getLangOpts().CPlusPlus17)
  4941. MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
  4942. }
  4943. /// Mark the template parameters that are used by the given
  4944. /// nested name specifier.
  4945. static void
  4946. MarkUsedTemplateParameters(ASTContext &Ctx,
  4947. NestedNameSpecifier *NNS,
  4948. bool OnlyDeduced,
  4949. unsigned Depth,
  4950. llvm::SmallBitVector &Used) {
  4951. if (!NNS)
  4952. return;
  4953. MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
  4954. Used);
  4955. MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
  4956. OnlyDeduced, Depth, Used);
  4957. }
  4958. /// Mark the template parameters that are used by the given
  4959. /// template name.
  4960. static void
  4961. MarkUsedTemplateParameters(ASTContext &Ctx,
  4962. TemplateName Name,
  4963. bool OnlyDeduced,
  4964. unsigned Depth,
  4965. llvm::SmallBitVector &Used) {
  4966. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  4967. if (TemplateTemplateParmDecl *TTP
  4968. = dyn_cast<TemplateTemplateParmDecl>(Template)) {
  4969. if (TTP->getDepth() == Depth)
  4970. Used[TTP->getIndex()] = true;
  4971. }
  4972. return;
  4973. }
  4974. if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
  4975. MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
  4976. Depth, Used);
  4977. if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
  4978. MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
  4979. Depth, Used);
  4980. }
  4981. /// Mark the template parameters that are used by the given
  4982. /// type.
  4983. static void
  4984. MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
  4985. bool OnlyDeduced,
  4986. unsigned Depth,
  4987. llvm::SmallBitVector &Used) {
  4988. if (T.isNull())
  4989. return;
  4990. // Non-dependent types have nothing deducible
  4991. if (!T->isDependentType())
  4992. return;
  4993. T = Ctx.getCanonicalType(T);
  4994. switch (T->getTypeClass()) {
  4995. case Type::Pointer:
  4996. MarkUsedTemplateParameters(Ctx,
  4997. cast<PointerType>(T)->getPointeeType(),
  4998. OnlyDeduced,
  4999. Depth,
  5000. Used);
  5001. break;
  5002. case Type::BlockPointer:
  5003. MarkUsedTemplateParameters(Ctx,
  5004. cast<BlockPointerType>(T)->getPointeeType(),
  5005. OnlyDeduced,
  5006. Depth,
  5007. Used);
  5008. break;
  5009. case Type::LValueReference:
  5010. case Type::RValueReference:
  5011. MarkUsedTemplateParameters(Ctx,
  5012. cast<ReferenceType>(T)->getPointeeType(),
  5013. OnlyDeduced,
  5014. Depth,
  5015. Used);
  5016. break;
  5017. case Type::MemberPointer: {
  5018. const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
  5019. MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
  5020. Depth, Used);
  5021. MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
  5022. OnlyDeduced, Depth, Used);
  5023. break;
  5024. }
  5025. case Type::DependentSizedArray:
  5026. MarkUsedTemplateParameters(Ctx,
  5027. cast<DependentSizedArrayType>(T)->getSizeExpr(),
  5028. OnlyDeduced, Depth, Used);
  5029. // Fall through to check the element type
  5030. LLVM_FALLTHROUGH;
  5031. case Type::ConstantArray:
  5032. case Type::IncompleteArray:
  5033. MarkUsedTemplateParameters(Ctx,
  5034. cast<ArrayType>(T)->getElementType(),
  5035. OnlyDeduced, Depth, Used);
  5036. break;
  5037. case Type::Vector:
  5038. case Type::ExtVector:
  5039. MarkUsedTemplateParameters(Ctx,
  5040. cast<VectorType>(T)->getElementType(),
  5041. OnlyDeduced, Depth, Used);
  5042. break;
  5043. case Type::DependentVector: {
  5044. const auto *VecType = cast<DependentVectorType>(T);
  5045. MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
  5046. Depth, Used);
  5047. MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
  5048. Used);
  5049. break;
  5050. }
  5051. case Type::DependentSizedExtVector: {
  5052. const DependentSizedExtVectorType *VecType
  5053. = cast<DependentSizedExtVectorType>(T);
  5054. MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
  5055. Depth, Used);
  5056. MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
  5057. Depth, Used);
  5058. break;
  5059. }
  5060. case Type::DependentAddressSpace: {
  5061. const DependentAddressSpaceType *DependentASType =
  5062. cast<DependentAddressSpaceType>(T);
  5063. MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
  5064. OnlyDeduced, Depth, Used);
  5065. MarkUsedTemplateParameters(Ctx,
  5066. DependentASType->getAddrSpaceExpr(),
  5067. OnlyDeduced, Depth, Used);
  5068. break;
  5069. }
  5070. case Type::ConstantMatrix: {
  5071. const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
  5072. MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
  5073. Depth, Used);
  5074. break;
  5075. }
  5076. case Type::DependentSizedMatrix: {
  5077. const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
  5078. MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
  5079. Depth, Used);
  5080. MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
  5081. Used);
  5082. MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
  5083. Depth, Used);
  5084. break;
  5085. }
  5086. case Type::FunctionProto: {
  5087. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  5088. MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
  5089. Used);
  5090. for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
  5091. // C++17 [temp.deduct.type]p5:
  5092. // The non-deduced contexts are: [...]
  5093. // -- A function parameter pack that does not occur at the end of the
  5094. // parameter-declaration-list.
  5095. if (!OnlyDeduced || I + 1 == N ||
  5096. !Proto->getParamType(I)->getAs<PackExpansionType>()) {
  5097. MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
  5098. Depth, Used);
  5099. } else {
  5100. // FIXME: C++17 [temp.deduct.call]p1:
  5101. // When a function parameter pack appears in a non-deduced context,
  5102. // the type of that pack is never deduced.
  5103. //
  5104. // We should also track a set of "never deduced" parameters, and
  5105. // subtract that from the list of deduced parameters after marking.
  5106. }
  5107. }
  5108. if (auto *E = Proto->getNoexceptExpr())
  5109. MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
  5110. break;
  5111. }
  5112. case Type::TemplateTypeParm: {
  5113. const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
  5114. if (TTP->getDepth() == Depth)
  5115. Used[TTP->getIndex()] = true;
  5116. break;
  5117. }
  5118. case Type::SubstTemplateTypeParmPack: {
  5119. const SubstTemplateTypeParmPackType *Subst
  5120. = cast<SubstTemplateTypeParmPackType>(T);
  5121. MarkUsedTemplateParameters(Ctx,
  5122. QualType(Subst->getReplacedParameter(), 0),
  5123. OnlyDeduced, Depth, Used);
  5124. MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
  5125. OnlyDeduced, Depth, Used);
  5126. break;
  5127. }
  5128. case Type::InjectedClassName:
  5129. T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
  5130. LLVM_FALLTHROUGH;
  5131. case Type::TemplateSpecialization: {
  5132. const TemplateSpecializationType *Spec
  5133. = cast<TemplateSpecializationType>(T);
  5134. MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
  5135. Depth, Used);
  5136. // C++0x [temp.deduct.type]p9:
  5137. // If the template argument list of P contains a pack expansion that is
  5138. // not the last template argument, the entire template argument list is a
  5139. // non-deduced context.
  5140. if (OnlyDeduced &&
  5141. hasPackExpansionBeforeEnd(Spec->template_arguments()))
  5142. break;
  5143. for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
  5144. MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
  5145. Used);
  5146. break;
  5147. }
  5148. case Type::Complex:
  5149. if (!OnlyDeduced)
  5150. MarkUsedTemplateParameters(Ctx,
  5151. cast<ComplexType>(T)->getElementType(),
  5152. OnlyDeduced, Depth, Used);
  5153. break;
  5154. case Type::Atomic:
  5155. if (!OnlyDeduced)
  5156. MarkUsedTemplateParameters(Ctx,
  5157. cast<AtomicType>(T)->getValueType(),
  5158. OnlyDeduced, Depth, Used);
  5159. break;
  5160. case Type::DependentName:
  5161. if (!OnlyDeduced)
  5162. MarkUsedTemplateParameters(Ctx,
  5163. cast<DependentNameType>(T)->getQualifier(),
  5164. OnlyDeduced, Depth, Used);
  5165. break;
  5166. case Type::DependentTemplateSpecialization: {
  5167. // C++14 [temp.deduct.type]p5:
  5168. // The non-deduced contexts are:
  5169. // -- The nested-name-specifier of a type that was specified using a
  5170. // qualified-id
  5171. //
  5172. // C++14 [temp.deduct.type]p6:
  5173. // When a type name is specified in a way that includes a non-deduced
  5174. // context, all of the types that comprise that type name are also
  5175. // non-deduced.
  5176. if (OnlyDeduced)
  5177. break;
  5178. const DependentTemplateSpecializationType *Spec
  5179. = cast<DependentTemplateSpecializationType>(T);
  5180. MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
  5181. OnlyDeduced, Depth, Used);
  5182. for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
  5183. MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
  5184. Used);
  5185. break;
  5186. }
  5187. case Type::TypeOf:
  5188. if (!OnlyDeduced)
  5189. MarkUsedTemplateParameters(Ctx,
  5190. cast<TypeOfType>(T)->getUnderlyingType(),
  5191. OnlyDeduced, Depth, Used);
  5192. break;
  5193. case Type::TypeOfExpr:
  5194. if (!OnlyDeduced)
  5195. MarkUsedTemplateParameters(Ctx,
  5196. cast<TypeOfExprType>(T)->getUnderlyingExpr(),
  5197. OnlyDeduced, Depth, Used);
  5198. break;
  5199. case Type::Decltype:
  5200. if (!OnlyDeduced)
  5201. MarkUsedTemplateParameters(Ctx,
  5202. cast<DecltypeType>(T)->getUnderlyingExpr(),
  5203. OnlyDeduced, Depth, Used);
  5204. break;
  5205. case Type::UnaryTransform:
  5206. if (!OnlyDeduced)
  5207. MarkUsedTemplateParameters(Ctx,
  5208. cast<UnaryTransformType>(T)->getUnderlyingType(),
  5209. OnlyDeduced, Depth, Used);
  5210. break;
  5211. case Type::PackExpansion:
  5212. MarkUsedTemplateParameters(Ctx,
  5213. cast<PackExpansionType>(T)->getPattern(),
  5214. OnlyDeduced, Depth, Used);
  5215. break;
  5216. case Type::Auto:
  5217. case Type::DeducedTemplateSpecialization:
  5218. MarkUsedTemplateParameters(Ctx,
  5219. cast<DeducedType>(T)->getDeducedType(),
  5220. OnlyDeduced, Depth, Used);
  5221. break;
  5222. case Type::DependentBitInt:
  5223. MarkUsedTemplateParameters(Ctx,
  5224. cast<DependentBitIntType>(T)->getNumBitsExpr(),
  5225. OnlyDeduced, Depth, Used);
  5226. break;
  5227. // None of these types have any template parameters in them.
  5228. case Type::Builtin:
  5229. case Type::VariableArray:
  5230. case Type::FunctionNoProto:
  5231. case Type::Record:
  5232. case Type::Enum:
  5233. case Type::ObjCInterface:
  5234. case Type::ObjCObject:
  5235. case Type::ObjCObjectPointer:
  5236. case Type::UnresolvedUsing:
  5237. case Type::Pipe:
  5238. case Type::BitInt:
  5239. #define TYPE(Class, Base)
  5240. #define ABSTRACT_TYPE(Class, Base)
  5241. #define DEPENDENT_TYPE(Class, Base)
  5242. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  5243. #include "clang/AST/TypeNodes.inc"
  5244. break;
  5245. }
  5246. }
  5247. /// Mark the template parameters that are used by this
  5248. /// template argument.
  5249. static void
  5250. MarkUsedTemplateParameters(ASTContext &Ctx,
  5251. const TemplateArgument &TemplateArg,
  5252. bool OnlyDeduced,
  5253. unsigned Depth,
  5254. llvm::SmallBitVector &Used) {
  5255. switch (TemplateArg.getKind()) {
  5256. case TemplateArgument::Null:
  5257. case TemplateArgument::Integral:
  5258. case TemplateArgument::Declaration:
  5259. break;
  5260. case TemplateArgument::NullPtr:
  5261. MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
  5262. Depth, Used);
  5263. break;
  5264. case TemplateArgument::Type:
  5265. MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
  5266. Depth, Used);
  5267. break;
  5268. case TemplateArgument::Template:
  5269. case TemplateArgument::TemplateExpansion:
  5270. MarkUsedTemplateParameters(Ctx,
  5271. TemplateArg.getAsTemplateOrTemplatePattern(),
  5272. OnlyDeduced, Depth, Used);
  5273. break;
  5274. case TemplateArgument::Expression:
  5275. MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
  5276. Depth, Used);
  5277. break;
  5278. case TemplateArgument::Pack:
  5279. for (const auto &P : TemplateArg.pack_elements())
  5280. MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
  5281. break;
  5282. }
  5283. }
  5284. /// Mark which template parameters are used in a given expression.
  5285. ///
  5286. /// \param E the expression from which template parameters will be deduced.
  5287. ///
  5288. /// \param Used a bit vector whose elements will be set to \c true
  5289. /// to indicate when the corresponding template parameter will be
  5290. /// deduced.
  5291. void
  5292. Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
  5293. unsigned Depth,
  5294. llvm::SmallBitVector &Used) {
  5295. ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
  5296. }
  5297. /// Mark which template parameters can be deduced from a given
  5298. /// template argument list.
  5299. ///
  5300. /// \param TemplateArgs the template argument list from which template
  5301. /// parameters will be deduced.
  5302. ///
  5303. /// \param Used a bit vector whose elements will be set to \c true
  5304. /// to indicate when the corresponding template parameter will be
  5305. /// deduced.
  5306. void
  5307. Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
  5308. bool OnlyDeduced, unsigned Depth,
  5309. llvm::SmallBitVector &Used) {
  5310. // C++0x [temp.deduct.type]p9:
  5311. // If the template argument list of P contains a pack expansion that is not
  5312. // the last template argument, the entire template argument list is a
  5313. // non-deduced context.
  5314. if (OnlyDeduced &&
  5315. hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
  5316. return;
  5317. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  5318. ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
  5319. Depth, Used);
  5320. }
  5321. /// Marks all of the template parameters that will be deduced by a
  5322. /// call to the given function template.
  5323. void Sema::MarkDeducedTemplateParameters(
  5324. ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
  5325. llvm::SmallBitVector &Deduced) {
  5326. TemplateParameterList *TemplateParams
  5327. = FunctionTemplate->getTemplateParameters();
  5328. Deduced.clear();
  5329. Deduced.resize(TemplateParams->size());
  5330. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  5331. for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
  5332. ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
  5333. true, TemplateParams->getDepth(), Deduced);
  5334. }
  5335. bool hasDeducibleTemplateParameters(Sema &S,
  5336. FunctionTemplateDecl *FunctionTemplate,
  5337. QualType T) {
  5338. if (!T->isDependentType())
  5339. return false;
  5340. TemplateParameterList *TemplateParams
  5341. = FunctionTemplate->getTemplateParameters();
  5342. llvm::SmallBitVector Deduced(TemplateParams->size());
  5343. ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
  5344. Deduced);
  5345. return Deduced.any();
  5346. }