SemaOverload.cpp 556 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955
  1. //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
  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 provides Sema routines for C++ overloading.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/Overload.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/CXXInheritance.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/ExprObjC.h"
  19. #include "clang/AST/TypeOrdering.h"
  20. #include "clang/Basic/Diagnostic.h"
  21. #include "clang/Basic/DiagnosticOptions.h"
  22. #include "clang/Basic/PartialDiagnostic.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Sema/Initialization.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/SemaInternal.h"
  27. #include "clang/Sema/Template.h"
  28. #include "clang/Sema/TemplateDeduction.h"
  29. #include "llvm/ADT/DenseSet.h"
  30. #include "llvm/ADT/Optional.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include "llvm/ADT/SmallPtrSet.h"
  33. #include "llvm/ADT/SmallString.h"
  34. #include <algorithm>
  35. #include <cstdlib>
  36. using namespace clang;
  37. using namespace sema;
  38. static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
  39. return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
  40. return P->hasAttr<PassObjectSizeAttr>();
  41. });
  42. }
  43. /// A convenience routine for creating a decayed reference to a function.
  44. static ExprResult
  45. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
  46. const Expr *Base, bool HadMultipleCandidates,
  47. SourceLocation Loc = SourceLocation(),
  48. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  49. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  50. return ExprError();
  51. // If FoundDecl is different from Fn (such as if one is a template
  52. // and the other a specialization), make sure DiagnoseUseOfDecl is
  53. // called on both.
  54. // FIXME: This would be more comprehensively addressed by modifying
  55. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  56. // being used.
  57. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  58. return ExprError();
  59. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  60. S.ResolveExceptionSpec(Loc, FPT);
  61. DeclRefExpr *DRE = new (S.Context)
  62. DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
  63. if (HadMultipleCandidates)
  64. DRE->setHadMultipleCandidates(true);
  65. S.MarkDeclRefReferenced(DRE, Base);
  66. return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
  67. CK_FunctionToPointerDecay);
  68. }
  69. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  70. bool InOverloadResolution,
  71. StandardConversionSequence &SCS,
  72. bool CStyle,
  73. bool AllowObjCWritebackConversion);
  74. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  75. QualType &ToType,
  76. bool InOverloadResolution,
  77. StandardConversionSequence &SCS,
  78. bool CStyle);
  79. static OverloadingResult
  80. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  81. UserDefinedConversionSequence& User,
  82. OverloadCandidateSet& Conversions,
  83. bool AllowExplicit,
  84. bool AllowObjCConversionOnExplicit);
  85. static ImplicitConversionSequence::CompareKind
  86. CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
  87. const StandardConversionSequence& SCS1,
  88. const StandardConversionSequence& SCS2);
  89. static ImplicitConversionSequence::CompareKind
  90. CompareQualificationConversions(Sema &S,
  91. const StandardConversionSequence& SCS1,
  92. const StandardConversionSequence& SCS2);
  93. static ImplicitConversionSequence::CompareKind
  94. CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
  95. const StandardConversionSequence& SCS1,
  96. const StandardConversionSequence& SCS2);
  97. /// GetConversionRank - Retrieve the implicit conversion rank
  98. /// corresponding to the given implicit conversion kind.
  99. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  100. static const ImplicitConversionRank
  101. Rank[(int)ICK_Num_Conversion_Kinds] = {
  102. ICR_Exact_Match,
  103. ICR_Exact_Match,
  104. ICR_Exact_Match,
  105. ICR_Exact_Match,
  106. ICR_Exact_Match,
  107. ICR_Exact_Match,
  108. ICR_Promotion,
  109. ICR_Promotion,
  110. ICR_Promotion,
  111. ICR_Conversion,
  112. ICR_Conversion,
  113. ICR_Conversion,
  114. ICR_Conversion,
  115. ICR_Conversion,
  116. ICR_Conversion,
  117. ICR_Conversion,
  118. ICR_Conversion,
  119. ICR_Conversion,
  120. ICR_Conversion,
  121. ICR_OCL_Scalar_Widening,
  122. ICR_Complex_Real_Conversion,
  123. ICR_Conversion,
  124. ICR_Conversion,
  125. ICR_Writeback_Conversion,
  126. ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
  127. // it was omitted by the patch that added
  128. // ICK_Zero_Event_Conversion
  129. ICR_C_Conversion,
  130. ICR_C_Conversion_Extension
  131. };
  132. return Rank[(int)Kind];
  133. }
  134. /// GetImplicitConversionName - Return the name of this kind of
  135. /// implicit conversion.
  136. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  137. static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
  138. "No conversion",
  139. "Lvalue-to-rvalue",
  140. "Array-to-pointer",
  141. "Function-to-pointer",
  142. "Function pointer conversion",
  143. "Qualification",
  144. "Integral promotion",
  145. "Floating point promotion",
  146. "Complex promotion",
  147. "Integral conversion",
  148. "Floating conversion",
  149. "Complex conversion",
  150. "Floating-integral conversion",
  151. "Pointer conversion",
  152. "Pointer-to-member conversion",
  153. "Boolean conversion",
  154. "Compatible-types conversion",
  155. "Derived-to-base conversion",
  156. "Vector conversion",
  157. "Vector splat",
  158. "Complex-real conversion",
  159. "Block Pointer conversion",
  160. "Transparent Union Conversion",
  161. "Writeback conversion",
  162. "OpenCL Zero Event Conversion",
  163. "C specific type conversion",
  164. "Incompatible pointer conversion"
  165. };
  166. return Name[Kind];
  167. }
  168. /// StandardConversionSequence - Set the standard conversion
  169. /// sequence to the identity conversion.
  170. void StandardConversionSequence::setAsIdentityConversion() {
  171. First = ICK_Identity;
  172. Second = ICK_Identity;
  173. Third = ICK_Identity;
  174. DeprecatedStringLiteralToCharPtr = false;
  175. QualificationIncludesObjCLifetime = false;
  176. ReferenceBinding = false;
  177. DirectBinding = false;
  178. IsLvalueReference = true;
  179. BindsToFunctionLvalue = false;
  180. BindsToRvalue = false;
  181. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  182. ObjCLifetimeConversionBinding = false;
  183. CopyConstructor = nullptr;
  184. }
  185. /// getRank - Retrieve the rank of this standard conversion sequence
  186. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  187. /// implicit conversions.
  188. ImplicitConversionRank StandardConversionSequence::getRank() const {
  189. ImplicitConversionRank Rank = ICR_Exact_Match;
  190. if (GetConversionRank(First) > Rank)
  191. Rank = GetConversionRank(First);
  192. if (GetConversionRank(Second) > Rank)
  193. Rank = GetConversionRank(Second);
  194. if (GetConversionRank(Third) > Rank)
  195. Rank = GetConversionRank(Third);
  196. return Rank;
  197. }
  198. /// isPointerConversionToBool - Determines whether this conversion is
  199. /// a conversion of a pointer or pointer-to-member to bool. This is
  200. /// used as part of the ranking of standard conversion sequences
  201. /// (C++ 13.3.3.2p4).
  202. bool StandardConversionSequence::isPointerConversionToBool() const {
  203. // Note that FromType has not necessarily been transformed by the
  204. // array-to-pointer or function-to-pointer implicit conversions, so
  205. // check for their presence as well as checking whether FromType is
  206. // a pointer.
  207. if (getToType(1)->isBooleanType() &&
  208. (getFromType()->isPointerType() ||
  209. getFromType()->isMemberPointerType() ||
  210. getFromType()->isObjCObjectPointerType() ||
  211. getFromType()->isBlockPointerType() ||
  212. getFromType()->isNullPtrType() ||
  213. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  214. return true;
  215. return false;
  216. }
  217. /// isPointerConversionToVoidPointer - Determines whether this
  218. /// conversion is a conversion of a pointer to a void pointer. This is
  219. /// used as part of the ranking of standard conversion sequences (C++
  220. /// 13.3.3.2p4).
  221. bool
  222. StandardConversionSequence::
  223. isPointerConversionToVoidPointer(ASTContext& Context) const {
  224. QualType FromType = getFromType();
  225. QualType ToType = getToType(1);
  226. // Note that FromType has not necessarily been transformed by the
  227. // array-to-pointer implicit conversion, so check for its presence
  228. // and redo the conversion to get a pointer.
  229. if (First == ICK_Array_To_Pointer)
  230. FromType = Context.getArrayDecayedType(FromType);
  231. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  232. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  233. return ToPtrType->getPointeeType()->isVoidType();
  234. return false;
  235. }
  236. /// Skip any implicit casts which could be either part of a narrowing conversion
  237. /// or after one in an implicit conversion.
  238. static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
  239. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  240. switch (ICE->getCastKind()) {
  241. case CK_NoOp:
  242. case CK_IntegralCast:
  243. case CK_IntegralToBoolean:
  244. case CK_IntegralToFloating:
  245. case CK_BooleanToSignedIntegral:
  246. case CK_FloatingToIntegral:
  247. case CK_FloatingToBoolean:
  248. case CK_FloatingCast:
  249. Converted = ICE->getSubExpr();
  250. continue;
  251. default:
  252. return Converted;
  253. }
  254. }
  255. return Converted;
  256. }
  257. /// Check if this standard conversion sequence represents a narrowing
  258. /// conversion, according to C++11 [dcl.init.list]p7.
  259. ///
  260. /// \param Ctx The AST context.
  261. /// \param Converted The result of applying this standard conversion sequence.
  262. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  263. /// value of the expression prior to the narrowing conversion.
  264. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  265. /// type of the expression prior to the narrowing conversion.
  266. /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
  267. /// from floating point types to integral types should be ignored.
  268. NarrowingKind StandardConversionSequence::getNarrowingKind(
  269. ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
  270. QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
  271. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  272. // C++11 [dcl.init.list]p7:
  273. // A narrowing conversion is an implicit conversion ...
  274. QualType FromType = getToType(0);
  275. QualType ToType = getToType(1);
  276. // A conversion to an enumeration type is narrowing if the conversion to
  277. // the underlying type is narrowing. This only arises for expressions of
  278. // the form 'Enum{init}'.
  279. if (auto *ET = ToType->getAs<EnumType>())
  280. ToType = ET->getDecl()->getIntegerType();
  281. switch (Second) {
  282. // 'bool' is an integral type; dispatch to the right place to handle it.
  283. case ICK_Boolean_Conversion:
  284. if (FromType->isRealFloatingType())
  285. goto FloatingIntegralConversion;
  286. if (FromType->isIntegralOrUnscopedEnumerationType())
  287. goto IntegralConversion;
  288. // Boolean conversions can be from pointers and pointers to members
  289. // [conv.bool], and those aren't considered narrowing conversions.
  290. return NK_Not_Narrowing;
  291. // -- from a floating-point type to an integer type, or
  292. //
  293. // -- from an integer type or unscoped enumeration type to a floating-point
  294. // type, except where the source is a constant expression and the actual
  295. // value after conversion will fit into the target type and will produce
  296. // the original value when converted back to the original type, or
  297. case ICK_Floating_Integral:
  298. FloatingIntegralConversion:
  299. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  300. return NK_Type_Narrowing;
  301. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  302. ToType->isRealFloatingType()) {
  303. if (IgnoreFloatToIntegralConversion)
  304. return NK_Not_Narrowing;
  305. llvm::APSInt IntConstantValue;
  306. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  307. assert(Initializer && "Unknown conversion expression");
  308. // If it's value-dependent, we can't tell whether it's narrowing.
  309. if (Initializer->isValueDependent())
  310. return NK_Dependent_Narrowing;
  311. if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  312. // Convert the integer to the floating type.
  313. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  314. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  315. llvm::APFloat::rmNearestTiesToEven);
  316. // And back.
  317. llvm::APSInt ConvertedValue = IntConstantValue;
  318. bool ignored;
  319. Result.convertToInteger(ConvertedValue,
  320. llvm::APFloat::rmTowardZero, &ignored);
  321. // If the resulting value is different, this was a narrowing conversion.
  322. if (IntConstantValue != ConvertedValue) {
  323. ConstantValue = APValue(IntConstantValue);
  324. ConstantType = Initializer->getType();
  325. return NK_Constant_Narrowing;
  326. }
  327. } else {
  328. // Variables are always narrowings.
  329. return NK_Variable_Narrowing;
  330. }
  331. }
  332. return NK_Not_Narrowing;
  333. // -- from long double to double or float, or from double to float, except
  334. // where the source is a constant expression and the actual value after
  335. // conversion is within the range of values that can be represented (even
  336. // if it cannot be represented exactly), or
  337. case ICK_Floating_Conversion:
  338. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  339. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  340. // FromType is larger than ToType.
  341. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  342. // If it's value-dependent, we can't tell whether it's narrowing.
  343. if (Initializer->isValueDependent())
  344. return NK_Dependent_Narrowing;
  345. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  346. // Constant!
  347. assert(ConstantValue.isFloat());
  348. llvm::APFloat FloatVal = ConstantValue.getFloat();
  349. // Convert the source value into the target type.
  350. bool ignored;
  351. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  352. Ctx.getFloatTypeSemantics(ToType),
  353. llvm::APFloat::rmNearestTiesToEven, &ignored);
  354. // If there was no overflow, the source value is within the range of
  355. // values that can be represented.
  356. if (ConvertStatus & llvm::APFloat::opOverflow) {
  357. ConstantType = Initializer->getType();
  358. return NK_Constant_Narrowing;
  359. }
  360. } else {
  361. return NK_Variable_Narrowing;
  362. }
  363. }
  364. return NK_Not_Narrowing;
  365. // -- from an integer type or unscoped enumeration type to an integer type
  366. // that cannot represent all the values of the original type, except where
  367. // the source is a constant expression and the actual value after
  368. // conversion will fit into the target type and will produce the original
  369. // value when converted back to the original type.
  370. case ICK_Integral_Conversion:
  371. IntegralConversion: {
  372. assert(FromType->isIntegralOrUnscopedEnumerationType());
  373. assert(ToType->isIntegralOrUnscopedEnumerationType());
  374. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  375. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  376. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  377. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  378. if (FromWidth > ToWidth ||
  379. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  380. (FromSigned && !ToSigned)) {
  381. // Not all values of FromType can be represented in ToType.
  382. llvm::APSInt InitializerValue;
  383. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  384. // If it's value-dependent, we can't tell whether it's narrowing.
  385. if (Initializer->isValueDependent())
  386. return NK_Dependent_Narrowing;
  387. if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  388. // Such conversions on variables are always narrowing.
  389. return NK_Variable_Narrowing;
  390. }
  391. bool Narrowing = false;
  392. if (FromWidth < ToWidth) {
  393. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  394. // narrowing.
  395. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  396. Narrowing = true;
  397. } else {
  398. // Add a bit to the InitializerValue so we don't have to worry about
  399. // signed vs. unsigned comparisons.
  400. InitializerValue = InitializerValue.extend(
  401. InitializerValue.getBitWidth() + 1);
  402. // Convert the initializer to and from the target width and signed-ness.
  403. llvm::APSInt ConvertedValue = InitializerValue;
  404. ConvertedValue = ConvertedValue.trunc(ToWidth);
  405. ConvertedValue.setIsSigned(ToSigned);
  406. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  407. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  408. // If the result is different, this was a narrowing conversion.
  409. if (ConvertedValue != InitializerValue)
  410. Narrowing = true;
  411. }
  412. if (Narrowing) {
  413. ConstantType = Initializer->getType();
  414. ConstantValue = APValue(InitializerValue);
  415. return NK_Constant_Narrowing;
  416. }
  417. }
  418. return NK_Not_Narrowing;
  419. }
  420. default:
  421. // Other kinds of conversions are not narrowings.
  422. return NK_Not_Narrowing;
  423. }
  424. }
  425. /// dump - Print this standard conversion sequence to standard
  426. /// error. Useful for debugging overloading issues.
  427. LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
  428. raw_ostream &OS = llvm::errs();
  429. bool PrintedSomething = false;
  430. if (First != ICK_Identity) {
  431. OS << GetImplicitConversionName(First);
  432. PrintedSomething = true;
  433. }
  434. if (Second != ICK_Identity) {
  435. if (PrintedSomething) {
  436. OS << " -> ";
  437. }
  438. OS << GetImplicitConversionName(Second);
  439. if (CopyConstructor) {
  440. OS << " (by copy constructor)";
  441. } else if (DirectBinding) {
  442. OS << " (direct reference binding)";
  443. } else if (ReferenceBinding) {
  444. OS << " (reference binding)";
  445. }
  446. PrintedSomething = true;
  447. }
  448. if (Third != ICK_Identity) {
  449. if (PrintedSomething) {
  450. OS << " -> ";
  451. }
  452. OS << GetImplicitConversionName(Third);
  453. PrintedSomething = true;
  454. }
  455. if (!PrintedSomething) {
  456. OS << "No conversions required";
  457. }
  458. }
  459. /// dump - Print this user-defined conversion sequence to standard
  460. /// error. Useful for debugging overloading issues.
  461. void UserDefinedConversionSequence::dump() const {
  462. raw_ostream &OS = llvm::errs();
  463. if (Before.First || Before.Second || Before.Third) {
  464. Before.dump();
  465. OS << " -> ";
  466. }
  467. if (ConversionFunction)
  468. OS << '\'' << *ConversionFunction << '\'';
  469. else
  470. OS << "aggregate initialization";
  471. if (After.First || After.Second || After.Third) {
  472. OS << " -> ";
  473. After.dump();
  474. }
  475. }
  476. /// dump - Print this implicit conversion sequence to standard
  477. /// error. Useful for debugging overloading issues.
  478. void ImplicitConversionSequence::dump() const {
  479. raw_ostream &OS = llvm::errs();
  480. if (isStdInitializerListElement())
  481. OS << "Worst std::initializer_list element conversion: ";
  482. switch (ConversionKind) {
  483. case StandardConversion:
  484. OS << "Standard conversion: ";
  485. Standard.dump();
  486. break;
  487. case UserDefinedConversion:
  488. OS << "User-defined conversion: ";
  489. UserDefined.dump();
  490. break;
  491. case EllipsisConversion:
  492. OS << "Ellipsis conversion";
  493. break;
  494. case AmbiguousConversion:
  495. OS << "Ambiguous conversion";
  496. break;
  497. case BadConversion:
  498. OS << "Bad conversion";
  499. break;
  500. }
  501. OS << "\n";
  502. }
  503. void AmbiguousConversionSequence::construct() {
  504. new (&conversions()) ConversionSet();
  505. }
  506. void AmbiguousConversionSequence::destruct() {
  507. conversions().~ConversionSet();
  508. }
  509. void
  510. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  511. FromTypePtr = O.FromTypePtr;
  512. ToTypePtr = O.ToTypePtr;
  513. new (&conversions()) ConversionSet(O.conversions());
  514. }
  515. namespace {
  516. // Structure used by DeductionFailureInfo to store
  517. // template argument information.
  518. struct DFIArguments {
  519. TemplateArgument FirstArg;
  520. TemplateArgument SecondArg;
  521. };
  522. // Structure used by DeductionFailureInfo to store
  523. // template parameter and template argument information.
  524. struct DFIParamWithArguments : DFIArguments {
  525. TemplateParameter Param;
  526. };
  527. // Structure used by DeductionFailureInfo to store template argument
  528. // information and the index of the problematic call argument.
  529. struct DFIDeducedMismatchArgs : DFIArguments {
  530. TemplateArgumentList *TemplateArgs;
  531. unsigned CallArgIndex;
  532. };
  533. }
  534. /// Convert from Sema's representation of template deduction information
  535. /// to the form used in overload-candidate information.
  536. DeductionFailureInfo
  537. clang::MakeDeductionFailureInfo(ASTContext &Context,
  538. Sema::TemplateDeductionResult TDK,
  539. TemplateDeductionInfo &Info) {
  540. DeductionFailureInfo Result;
  541. Result.Result = static_cast<unsigned>(TDK);
  542. Result.HasDiagnostic = false;
  543. switch (TDK) {
  544. case Sema::TDK_Invalid:
  545. case Sema::TDK_InstantiationDepth:
  546. case Sema::TDK_TooManyArguments:
  547. case Sema::TDK_TooFewArguments:
  548. case Sema::TDK_MiscellaneousDeductionFailure:
  549. case Sema::TDK_CUDATargetMismatch:
  550. Result.Data = nullptr;
  551. break;
  552. case Sema::TDK_Incomplete:
  553. case Sema::TDK_InvalidExplicitArguments:
  554. Result.Data = Info.Param.getOpaqueValue();
  555. break;
  556. case Sema::TDK_DeducedMismatch:
  557. case Sema::TDK_DeducedMismatchNested: {
  558. // FIXME: Should allocate from normal heap so that we can free this later.
  559. auto *Saved = new (Context) DFIDeducedMismatchArgs;
  560. Saved->FirstArg = Info.FirstArg;
  561. Saved->SecondArg = Info.SecondArg;
  562. Saved->TemplateArgs = Info.take();
  563. Saved->CallArgIndex = Info.CallArgIndex;
  564. Result.Data = Saved;
  565. break;
  566. }
  567. case Sema::TDK_NonDeducedMismatch: {
  568. // FIXME: Should allocate from normal heap so that we can free this later.
  569. DFIArguments *Saved = new (Context) DFIArguments;
  570. Saved->FirstArg = Info.FirstArg;
  571. Saved->SecondArg = Info.SecondArg;
  572. Result.Data = Saved;
  573. break;
  574. }
  575. case Sema::TDK_IncompletePack:
  576. // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
  577. case Sema::TDK_Inconsistent:
  578. case Sema::TDK_Underqualified: {
  579. // FIXME: Should allocate from normal heap so that we can free this later.
  580. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  581. Saved->Param = Info.Param;
  582. Saved->FirstArg = Info.FirstArg;
  583. Saved->SecondArg = Info.SecondArg;
  584. Result.Data = Saved;
  585. break;
  586. }
  587. case Sema::TDK_SubstitutionFailure:
  588. Result.Data = Info.take();
  589. if (Info.hasSFINAEDiagnostic()) {
  590. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  591. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  592. Info.takeSFINAEDiagnostic(*Diag);
  593. Result.HasDiagnostic = true;
  594. }
  595. break;
  596. case Sema::TDK_Success:
  597. case Sema::TDK_NonDependentConversionFailure:
  598. llvm_unreachable("not a deduction failure");
  599. }
  600. return Result;
  601. }
  602. void DeductionFailureInfo::Destroy() {
  603. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  604. case Sema::TDK_Success:
  605. case Sema::TDK_Invalid:
  606. case Sema::TDK_InstantiationDepth:
  607. case Sema::TDK_Incomplete:
  608. case Sema::TDK_TooManyArguments:
  609. case Sema::TDK_TooFewArguments:
  610. case Sema::TDK_InvalidExplicitArguments:
  611. case Sema::TDK_CUDATargetMismatch:
  612. case Sema::TDK_NonDependentConversionFailure:
  613. break;
  614. case Sema::TDK_IncompletePack:
  615. case Sema::TDK_Inconsistent:
  616. case Sema::TDK_Underqualified:
  617. case Sema::TDK_DeducedMismatch:
  618. case Sema::TDK_DeducedMismatchNested:
  619. case Sema::TDK_NonDeducedMismatch:
  620. // FIXME: Destroy the data?
  621. Data = nullptr;
  622. break;
  623. case Sema::TDK_SubstitutionFailure:
  624. // FIXME: Destroy the template argument list?
  625. Data = nullptr;
  626. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  627. Diag->~PartialDiagnosticAt();
  628. HasDiagnostic = false;
  629. }
  630. break;
  631. // Unhandled
  632. case Sema::TDK_MiscellaneousDeductionFailure:
  633. break;
  634. }
  635. }
  636. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  637. if (HasDiagnostic)
  638. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  639. return nullptr;
  640. }
  641. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  642. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  643. case Sema::TDK_Success:
  644. case Sema::TDK_Invalid:
  645. case Sema::TDK_InstantiationDepth:
  646. case Sema::TDK_TooManyArguments:
  647. case Sema::TDK_TooFewArguments:
  648. case Sema::TDK_SubstitutionFailure:
  649. case Sema::TDK_DeducedMismatch:
  650. case Sema::TDK_DeducedMismatchNested:
  651. case Sema::TDK_NonDeducedMismatch:
  652. case Sema::TDK_CUDATargetMismatch:
  653. case Sema::TDK_NonDependentConversionFailure:
  654. return TemplateParameter();
  655. case Sema::TDK_Incomplete:
  656. case Sema::TDK_InvalidExplicitArguments:
  657. return TemplateParameter::getFromOpaqueValue(Data);
  658. case Sema::TDK_IncompletePack:
  659. case Sema::TDK_Inconsistent:
  660. case Sema::TDK_Underqualified:
  661. return static_cast<DFIParamWithArguments*>(Data)->Param;
  662. // Unhandled
  663. case Sema::TDK_MiscellaneousDeductionFailure:
  664. break;
  665. }
  666. return TemplateParameter();
  667. }
  668. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  669. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  670. case Sema::TDK_Success:
  671. case Sema::TDK_Invalid:
  672. case Sema::TDK_InstantiationDepth:
  673. case Sema::TDK_TooManyArguments:
  674. case Sema::TDK_TooFewArguments:
  675. case Sema::TDK_Incomplete:
  676. case Sema::TDK_IncompletePack:
  677. case Sema::TDK_InvalidExplicitArguments:
  678. case Sema::TDK_Inconsistent:
  679. case Sema::TDK_Underqualified:
  680. case Sema::TDK_NonDeducedMismatch:
  681. case Sema::TDK_CUDATargetMismatch:
  682. case Sema::TDK_NonDependentConversionFailure:
  683. return nullptr;
  684. case Sema::TDK_DeducedMismatch:
  685. case Sema::TDK_DeducedMismatchNested:
  686. return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
  687. case Sema::TDK_SubstitutionFailure:
  688. return static_cast<TemplateArgumentList*>(Data);
  689. // Unhandled
  690. case Sema::TDK_MiscellaneousDeductionFailure:
  691. break;
  692. }
  693. return nullptr;
  694. }
  695. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  696. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  697. case Sema::TDK_Success:
  698. case Sema::TDK_Invalid:
  699. case Sema::TDK_InstantiationDepth:
  700. case Sema::TDK_Incomplete:
  701. case Sema::TDK_TooManyArguments:
  702. case Sema::TDK_TooFewArguments:
  703. case Sema::TDK_InvalidExplicitArguments:
  704. case Sema::TDK_SubstitutionFailure:
  705. case Sema::TDK_CUDATargetMismatch:
  706. case Sema::TDK_NonDependentConversionFailure:
  707. return nullptr;
  708. case Sema::TDK_IncompletePack:
  709. case Sema::TDK_Inconsistent:
  710. case Sema::TDK_Underqualified:
  711. case Sema::TDK_DeducedMismatch:
  712. case Sema::TDK_DeducedMismatchNested:
  713. case Sema::TDK_NonDeducedMismatch:
  714. return &static_cast<DFIArguments*>(Data)->FirstArg;
  715. // Unhandled
  716. case Sema::TDK_MiscellaneousDeductionFailure:
  717. break;
  718. }
  719. return nullptr;
  720. }
  721. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  722. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  723. case Sema::TDK_Success:
  724. case Sema::TDK_Invalid:
  725. case Sema::TDK_InstantiationDepth:
  726. case Sema::TDK_Incomplete:
  727. case Sema::TDK_IncompletePack:
  728. case Sema::TDK_TooManyArguments:
  729. case Sema::TDK_TooFewArguments:
  730. case Sema::TDK_InvalidExplicitArguments:
  731. case Sema::TDK_SubstitutionFailure:
  732. case Sema::TDK_CUDATargetMismatch:
  733. case Sema::TDK_NonDependentConversionFailure:
  734. return nullptr;
  735. case Sema::TDK_Inconsistent:
  736. case Sema::TDK_Underqualified:
  737. case Sema::TDK_DeducedMismatch:
  738. case Sema::TDK_DeducedMismatchNested:
  739. case Sema::TDK_NonDeducedMismatch:
  740. return &static_cast<DFIArguments*>(Data)->SecondArg;
  741. // Unhandled
  742. case Sema::TDK_MiscellaneousDeductionFailure:
  743. break;
  744. }
  745. return nullptr;
  746. }
  747. llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
  748. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  749. case Sema::TDK_DeducedMismatch:
  750. case Sema::TDK_DeducedMismatchNested:
  751. return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
  752. default:
  753. return llvm::None;
  754. }
  755. }
  756. void OverloadCandidateSet::destroyCandidates() {
  757. for (iterator i = begin(), e = end(); i != e; ++i) {
  758. for (auto &C : i->Conversions)
  759. C.~ImplicitConversionSequence();
  760. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  761. i->DeductionFailure.Destroy();
  762. }
  763. }
  764. void OverloadCandidateSet::clear(CandidateSetKind CSK) {
  765. destroyCandidates();
  766. SlabAllocator.Reset();
  767. NumInlineBytesUsed = 0;
  768. Candidates.clear();
  769. Functions.clear();
  770. Kind = CSK;
  771. }
  772. namespace {
  773. class UnbridgedCastsSet {
  774. struct Entry {
  775. Expr **Addr;
  776. Expr *Saved;
  777. };
  778. SmallVector<Entry, 2> Entries;
  779. public:
  780. void save(Sema &S, Expr *&E) {
  781. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  782. Entry entry = { &E, E };
  783. Entries.push_back(entry);
  784. E = S.stripARCUnbridgedCast(E);
  785. }
  786. void restore() {
  787. for (SmallVectorImpl<Entry>::iterator
  788. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  789. *i->Addr = i->Saved;
  790. }
  791. };
  792. }
  793. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  794. /// preprocessing on the given expression.
  795. ///
  796. /// \param unbridgedCasts a collection to which to add unbridged casts;
  797. /// without this, they will be immediately diagnosed as errors
  798. ///
  799. /// Return true on unrecoverable error.
  800. static bool
  801. checkPlaceholderForOverload(Sema &S, Expr *&E,
  802. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  803. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  804. // We can't handle overloaded expressions here because overload
  805. // resolution might reasonably tweak them.
  806. if (placeholder->getKind() == BuiltinType::Overload) return false;
  807. // If the context potentially accepts unbridged ARC casts, strip
  808. // the unbridged cast and add it to the collection for later restoration.
  809. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  810. unbridgedCasts) {
  811. unbridgedCasts->save(S, E);
  812. return false;
  813. }
  814. // Go ahead and check everything else.
  815. ExprResult result = S.CheckPlaceholderExpr(E);
  816. if (result.isInvalid())
  817. return true;
  818. E = result.get();
  819. return false;
  820. }
  821. // Nothing to do.
  822. return false;
  823. }
  824. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  825. /// placeholders.
  826. static bool checkArgPlaceholdersForOverload(Sema &S,
  827. MultiExprArg Args,
  828. UnbridgedCastsSet &unbridged) {
  829. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  830. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  831. return true;
  832. return false;
  833. }
  834. /// Determine whether the given New declaration is an overload of the
  835. /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
  836. /// New and Old cannot be overloaded, e.g., if New has the same signature as
  837. /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
  838. /// functions (or function templates) at all. When it does return Ovl_Match or
  839. /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
  840. /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
  841. /// declaration.
  842. ///
  843. /// Example: Given the following input:
  844. ///
  845. /// void f(int, float); // #1
  846. /// void f(int, int); // #2
  847. /// int f(int, int); // #3
  848. ///
  849. /// When we process #1, there is no previous declaration of "f", so IsOverload
  850. /// will not be used.
  851. ///
  852. /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
  853. /// the parameter types, we see that #1 and #2 are overloaded (since they have
  854. /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
  855. /// unchanged.
  856. ///
  857. /// When we process #3, Old is an overload set containing #1 and #2. We compare
  858. /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
  859. /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
  860. /// functions are not part of the signature), IsOverload returns Ovl_Match and
  861. /// MatchedDecl will be set to point to the FunctionDecl for #2.
  862. ///
  863. /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
  864. /// by a using declaration. The rules for whether to hide shadow declarations
  865. /// ignore some properties which otherwise figure into a function template's
  866. /// signature.
  867. Sema::OverloadKind
  868. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  869. NamedDecl *&Match, bool NewIsUsingDecl) {
  870. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  871. I != E; ++I) {
  872. NamedDecl *OldD = *I;
  873. bool OldIsUsingDecl = false;
  874. if (isa<UsingShadowDecl>(OldD)) {
  875. OldIsUsingDecl = true;
  876. // We can always introduce two using declarations into the same
  877. // context, even if they have identical signatures.
  878. if (NewIsUsingDecl) continue;
  879. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  880. }
  881. // A using-declaration does not conflict with another declaration
  882. // if one of them is hidden.
  883. if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
  884. continue;
  885. // If either declaration was introduced by a using declaration,
  886. // we'll need to use slightly different rules for matching.
  887. // Essentially, these rules are the normal rules, except that
  888. // function templates hide function templates with different
  889. // return types or template parameter lists.
  890. bool UseMemberUsingDeclRules =
  891. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  892. !New->getFriendObjectKind();
  893. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  894. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  895. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  896. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  897. continue;
  898. }
  899. if (!isa<FunctionTemplateDecl>(OldD) &&
  900. !shouldLinkPossiblyHiddenDecl(*I, New))
  901. continue;
  902. Match = *I;
  903. return Ovl_Match;
  904. }
  905. // Builtins that have custom typechecking or have a reference should
  906. // not be overloadable or redeclarable.
  907. if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
  908. Match = *I;
  909. return Ovl_NonFunction;
  910. }
  911. } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
  912. // We can overload with these, which can show up when doing
  913. // redeclaration checks for UsingDecls.
  914. assert(Old.getLookupKind() == LookupUsingDeclName);
  915. } else if (isa<TagDecl>(OldD)) {
  916. // We can always overload with tags by hiding them.
  917. } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
  918. // Optimistically assume that an unresolved using decl will
  919. // overload; if it doesn't, we'll have to diagnose during
  920. // template instantiation.
  921. //
  922. // Exception: if the scope is dependent and this is not a class
  923. // member, the using declaration can only introduce an enumerator.
  924. if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
  925. Match = *I;
  926. return Ovl_NonFunction;
  927. }
  928. } else {
  929. // (C++ 13p1):
  930. // Only function declarations can be overloaded; object and type
  931. // declarations cannot be overloaded.
  932. Match = *I;
  933. return Ovl_NonFunction;
  934. }
  935. }
  936. // C++ [temp.friend]p1:
  937. // For a friend function declaration that is not a template declaration:
  938. // -- if the name of the friend is a qualified or unqualified template-id,
  939. // [...], otherwise
  940. // -- if the name of the friend is a qualified-id and a matching
  941. // non-template function is found in the specified class or namespace,
  942. // the friend declaration refers to that function, otherwise,
  943. // -- if the name of the friend is a qualified-id and a matching function
  944. // template is found in the specified class or namespace, the friend
  945. // declaration refers to the deduced specialization of that function
  946. // template, otherwise
  947. // -- the name shall be an unqualified-id [...]
  948. // If we get here for a qualified friend declaration, we've just reached the
  949. // third bullet. If the type of the friend is dependent, skip this lookup
  950. // until instantiation.
  951. if (New->getFriendObjectKind() && New->getQualifier() &&
  952. !New->getDescribedFunctionTemplate() &&
  953. !New->getDependentSpecializationInfo() &&
  954. !New->getType()->isDependentType()) {
  955. LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
  956. TemplateSpecResult.addAllDecls(Old);
  957. if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
  958. /*QualifiedFriend*/true)) {
  959. New->setInvalidDecl();
  960. return Ovl_Overload;
  961. }
  962. Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
  963. return Ovl_Match;
  964. }
  965. return Ovl_Overload;
  966. }
  967. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  968. bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
  969. // C++ [basic.start.main]p2: This function shall not be overloaded.
  970. if (New->isMain())
  971. return false;
  972. // MSVCRT user defined entry points cannot be overloaded.
  973. if (New->isMSVCRTEntryPoint())
  974. return false;
  975. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  976. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  977. // C++ [temp.fct]p2:
  978. // A function template can be overloaded with other function templates
  979. // and with normal (non-template) functions.
  980. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  981. return true;
  982. // Is the function New an overload of the function Old?
  983. QualType OldQType = Context.getCanonicalType(Old->getType());
  984. QualType NewQType = Context.getCanonicalType(New->getType());
  985. // Compare the signatures (C++ 1.3.10) of the two functions to
  986. // determine whether they are overloads. If we find any mismatch
  987. // in the signature, they are overloads.
  988. // If either of these functions is a K&R-style function (no
  989. // prototype), then we consider them to have matching signatures.
  990. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  991. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  992. return false;
  993. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  994. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  995. // The signature of a function includes the types of its
  996. // parameters (C++ 1.3.10), which includes the presence or absence
  997. // of the ellipsis; see C++ DR 357).
  998. if (OldQType != NewQType &&
  999. (OldType->getNumParams() != NewType->getNumParams() ||
  1000. OldType->isVariadic() != NewType->isVariadic() ||
  1001. !FunctionParamTypesAreEqual(OldType, NewType)))
  1002. return true;
  1003. // C++ [temp.over.link]p4:
  1004. // The signature of a function template consists of its function
  1005. // signature, its return type and its template parameter list. The names
  1006. // of the template parameters are significant only for establishing the
  1007. // relationship between the template parameters and the rest of the
  1008. // signature.
  1009. //
  1010. // We check the return type and template parameter lists for function
  1011. // templates first; the remaining checks follow.
  1012. //
  1013. // However, we don't consider either of these when deciding whether
  1014. // a member introduced by a shadow declaration is hidden.
  1015. if (!UseMemberUsingDeclRules && NewTemplate &&
  1016. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  1017. OldTemplate->getTemplateParameters(),
  1018. false, TPL_TemplateMatch) ||
  1019. !Context.hasSameType(Old->getDeclaredReturnType(),
  1020. New->getDeclaredReturnType())))
  1021. return true;
  1022. // If the function is a class member, its signature includes the
  1023. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  1024. //
  1025. // As part of this, also check whether one of the member functions
  1026. // is static, in which case they are not overloads (C++
  1027. // 13.1p2). While not part of the definition of the signature,
  1028. // this check is important to determine whether these functions
  1029. // can be overloaded.
  1030. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1031. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  1032. if (OldMethod && NewMethod &&
  1033. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  1034. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  1035. if (!UseMemberUsingDeclRules &&
  1036. (OldMethod->getRefQualifier() == RQ_None ||
  1037. NewMethod->getRefQualifier() == RQ_None)) {
  1038. // C++0x [over.load]p2:
  1039. // - Member function declarations with the same name and the same
  1040. // parameter-type-list as well as member function template
  1041. // declarations with the same name, the same parameter-type-list, and
  1042. // the same template parameter lists cannot be overloaded if any of
  1043. // them, but not all, have a ref-qualifier (8.3.5).
  1044. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  1045. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  1046. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  1047. }
  1048. return true;
  1049. }
  1050. // We may not have applied the implicit const for a constexpr member
  1051. // function yet (because we haven't yet resolved whether this is a static
  1052. // or non-static member function). Add it now, on the assumption that this
  1053. // is a redeclaration of OldMethod.
  1054. auto OldQuals = OldMethod->getMethodQualifiers();
  1055. auto NewQuals = NewMethod->getMethodQualifiers();
  1056. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  1057. !isa<CXXConstructorDecl>(NewMethod))
  1058. NewQuals.addConst();
  1059. // We do not allow overloading based off of '__restrict'.
  1060. OldQuals.removeRestrict();
  1061. NewQuals.removeRestrict();
  1062. if (OldQuals != NewQuals)
  1063. return true;
  1064. }
  1065. // Though pass_object_size is placed on parameters and takes an argument, we
  1066. // consider it to be a function-level modifier for the sake of function
  1067. // identity. Either the function has one or more parameters with
  1068. // pass_object_size or it doesn't.
  1069. if (functionHasPassObjectSizeParams(New) !=
  1070. functionHasPassObjectSizeParams(Old))
  1071. return true;
  1072. // enable_if attributes are an order-sensitive part of the signature.
  1073. for (specific_attr_iterator<EnableIfAttr>
  1074. NewI = New->specific_attr_begin<EnableIfAttr>(),
  1075. NewE = New->specific_attr_end<EnableIfAttr>(),
  1076. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  1077. OldE = Old->specific_attr_end<EnableIfAttr>();
  1078. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  1079. if (NewI == NewE || OldI == OldE)
  1080. return true;
  1081. llvm::FoldingSetNodeID NewID, OldID;
  1082. NewI->getCond()->Profile(NewID, Context, true);
  1083. OldI->getCond()->Profile(OldID, Context, true);
  1084. if (NewID != OldID)
  1085. return true;
  1086. }
  1087. if (getLangOpts().CUDA && ConsiderCudaAttrs) {
  1088. // Don't allow overloading of destructors. (In theory we could, but it
  1089. // would be a giant change to clang.)
  1090. if (isa<CXXDestructorDecl>(New))
  1091. return false;
  1092. CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
  1093. OldTarget = IdentifyCUDATarget(Old);
  1094. if (NewTarget == CFT_InvalidTarget)
  1095. return false;
  1096. assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
  1097. // Allow overloading of functions with same signature and different CUDA
  1098. // target attributes.
  1099. return NewTarget != OldTarget;
  1100. }
  1101. // The signatures match; this is not an overload.
  1102. return false;
  1103. }
  1104. /// Tries a user-defined conversion from From to ToType.
  1105. ///
  1106. /// Produces an implicit conversion sequence for when a standard conversion
  1107. /// is not an option. See TryImplicitConversion for more information.
  1108. static ImplicitConversionSequence
  1109. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1110. bool SuppressUserConversions,
  1111. bool AllowExplicit,
  1112. bool InOverloadResolution,
  1113. bool CStyle,
  1114. bool AllowObjCWritebackConversion,
  1115. bool AllowObjCConversionOnExplicit) {
  1116. ImplicitConversionSequence ICS;
  1117. if (SuppressUserConversions) {
  1118. // We're not in the case above, so there is no conversion that
  1119. // we can perform.
  1120. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1121. return ICS;
  1122. }
  1123. // Attempt user-defined conversion.
  1124. OverloadCandidateSet Conversions(From->getExprLoc(),
  1125. OverloadCandidateSet::CSK_Normal);
  1126. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1127. Conversions, AllowExplicit,
  1128. AllowObjCConversionOnExplicit)) {
  1129. case OR_Success:
  1130. case OR_Deleted:
  1131. ICS.setUserDefined();
  1132. // C++ [over.ics.user]p4:
  1133. // A conversion of an expression of class type to the same class
  1134. // type is given Exact Match rank, and a conversion of an
  1135. // expression of class type to a base class of that type is
  1136. // given Conversion rank, in spite of the fact that a copy
  1137. // constructor (i.e., a user-defined conversion function) is
  1138. // called for those cases.
  1139. if (CXXConstructorDecl *Constructor
  1140. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1141. QualType FromCanon
  1142. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1143. QualType ToCanon
  1144. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1145. if (Constructor->isCopyConstructor() &&
  1146. (FromCanon == ToCanon ||
  1147. S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
  1148. // Turn this into a "standard" conversion sequence, so that it
  1149. // gets ranked with standard conversion sequences.
  1150. DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
  1151. ICS.setStandard();
  1152. ICS.Standard.setAsIdentityConversion();
  1153. ICS.Standard.setFromType(From->getType());
  1154. ICS.Standard.setAllToTypes(ToType);
  1155. ICS.Standard.CopyConstructor = Constructor;
  1156. ICS.Standard.FoundCopyConstructor = Found;
  1157. if (ToCanon != FromCanon)
  1158. ICS.Standard.Second = ICK_Derived_To_Base;
  1159. }
  1160. }
  1161. break;
  1162. case OR_Ambiguous:
  1163. ICS.setAmbiguous();
  1164. ICS.Ambiguous.setFromType(From->getType());
  1165. ICS.Ambiguous.setToType(ToType);
  1166. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1167. Cand != Conversions.end(); ++Cand)
  1168. if (Cand->Viable)
  1169. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  1170. break;
  1171. // Fall through.
  1172. case OR_No_Viable_Function:
  1173. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1174. break;
  1175. }
  1176. return ICS;
  1177. }
  1178. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1179. /// from the given expression (Expr) to the given type (ToType). This
  1180. /// function returns an implicit conversion sequence that can be used
  1181. /// to perform the initialization. Given
  1182. ///
  1183. /// void f(float f);
  1184. /// void g(int i) { f(i); }
  1185. ///
  1186. /// this routine would produce an implicit conversion sequence to
  1187. /// describe the initialization of f from i, which will be a standard
  1188. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1189. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1190. //
  1191. /// Note that this routine only determines how the conversion can be
  1192. /// performed; it does not actually perform the conversion. As such,
  1193. /// it will not produce any diagnostics if no conversion is available,
  1194. /// but will instead return an implicit conversion sequence of kind
  1195. /// "BadConversion".
  1196. ///
  1197. /// If @p SuppressUserConversions, then user-defined conversions are
  1198. /// not permitted.
  1199. /// If @p AllowExplicit, then explicit user-defined conversions are
  1200. /// permitted.
  1201. ///
  1202. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1203. /// writeback conversion, which allows __autoreleasing id* parameters to
  1204. /// be initialized with __strong id* or __weak id* arguments.
  1205. static ImplicitConversionSequence
  1206. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1207. bool SuppressUserConversions,
  1208. bool AllowExplicit,
  1209. bool InOverloadResolution,
  1210. bool CStyle,
  1211. bool AllowObjCWritebackConversion,
  1212. bool AllowObjCConversionOnExplicit) {
  1213. ImplicitConversionSequence ICS;
  1214. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1215. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1216. ICS.setStandard();
  1217. return ICS;
  1218. }
  1219. if (!S.getLangOpts().CPlusPlus) {
  1220. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1221. return ICS;
  1222. }
  1223. // C++ [over.ics.user]p4:
  1224. // A conversion of an expression of class type to the same class
  1225. // type is given Exact Match rank, and a conversion of an
  1226. // expression of class type to a base class of that type is
  1227. // given Conversion rank, in spite of the fact that a copy/move
  1228. // constructor (i.e., a user-defined conversion function) is
  1229. // called for those cases.
  1230. QualType FromType = From->getType();
  1231. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1232. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1233. S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
  1234. ICS.setStandard();
  1235. ICS.Standard.setAsIdentityConversion();
  1236. ICS.Standard.setFromType(FromType);
  1237. ICS.Standard.setAllToTypes(ToType);
  1238. // We don't actually check at this point whether there is a valid
  1239. // copy/move constructor, since overloading just assumes that it
  1240. // exists. When we actually perform initialization, we'll find the
  1241. // appropriate constructor to copy the returned object, if needed.
  1242. ICS.Standard.CopyConstructor = nullptr;
  1243. // Determine whether this is considered a derived-to-base conversion.
  1244. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1245. ICS.Standard.Second = ICK_Derived_To_Base;
  1246. return ICS;
  1247. }
  1248. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1249. AllowExplicit, InOverloadResolution, CStyle,
  1250. AllowObjCWritebackConversion,
  1251. AllowObjCConversionOnExplicit);
  1252. }
  1253. ImplicitConversionSequence
  1254. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1255. bool SuppressUserConversions,
  1256. bool AllowExplicit,
  1257. bool InOverloadResolution,
  1258. bool CStyle,
  1259. bool AllowObjCWritebackConversion) {
  1260. return ::TryImplicitConversion(*this, From, ToType,
  1261. SuppressUserConversions, AllowExplicit,
  1262. InOverloadResolution, CStyle,
  1263. AllowObjCWritebackConversion,
  1264. /*AllowObjCConversionOnExplicit=*/false);
  1265. }
  1266. /// PerformImplicitConversion - Perform an implicit conversion of the
  1267. /// expression From to the type ToType. Returns the
  1268. /// converted expression. Flavor is the kind of conversion we're
  1269. /// performing, used in the error message. If @p AllowExplicit,
  1270. /// explicit user-defined conversions are permitted.
  1271. ExprResult
  1272. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1273. AssignmentAction Action, bool AllowExplicit) {
  1274. ImplicitConversionSequence ICS;
  1275. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1276. }
  1277. ExprResult
  1278. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1279. AssignmentAction Action, bool AllowExplicit,
  1280. ImplicitConversionSequence& ICS) {
  1281. if (checkPlaceholderForOverload(*this, From))
  1282. return ExprError();
  1283. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1284. bool AllowObjCWritebackConversion
  1285. = getLangOpts().ObjCAutoRefCount &&
  1286. (Action == AA_Passing || Action == AA_Sending);
  1287. if (getLangOpts().ObjC)
  1288. CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
  1289. From->getType(), From);
  1290. ICS = ::TryImplicitConversion(*this, From, ToType,
  1291. /*SuppressUserConversions=*/false,
  1292. AllowExplicit,
  1293. /*InOverloadResolution=*/false,
  1294. /*CStyle=*/false,
  1295. AllowObjCWritebackConversion,
  1296. /*AllowObjCConversionOnExplicit=*/false);
  1297. return PerformImplicitConversion(From, ToType, ICS, Action);
  1298. }
  1299. /// Determine whether the conversion from FromType to ToType is a valid
  1300. /// conversion that strips "noexcept" or "noreturn" off the nested function
  1301. /// type.
  1302. bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
  1303. QualType &ResultTy) {
  1304. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1305. return false;
  1306. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1307. // or F(t noexcept) -> F(t)
  1308. // where F adds one of the following at most once:
  1309. // - a pointer
  1310. // - a member pointer
  1311. // - a block pointer
  1312. // Changes here need matching changes in FindCompositePointerType.
  1313. CanQualType CanTo = Context.getCanonicalType(ToType);
  1314. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1315. Type::TypeClass TyClass = CanTo->getTypeClass();
  1316. if (TyClass != CanFrom->getTypeClass()) return false;
  1317. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1318. if (TyClass == Type::Pointer) {
  1319. CanTo = CanTo.getAs<PointerType>()->getPointeeType();
  1320. CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
  1321. } else if (TyClass == Type::BlockPointer) {
  1322. CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
  1323. CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
  1324. } else if (TyClass == Type::MemberPointer) {
  1325. auto ToMPT = CanTo.getAs<MemberPointerType>();
  1326. auto FromMPT = CanFrom.getAs<MemberPointerType>();
  1327. // A function pointer conversion cannot change the class of the function.
  1328. if (ToMPT->getClass() != FromMPT->getClass())
  1329. return false;
  1330. CanTo = ToMPT->getPointeeType();
  1331. CanFrom = FromMPT->getPointeeType();
  1332. } else {
  1333. return false;
  1334. }
  1335. TyClass = CanTo->getTypeClass();
  1336. if (TyClass != CanFrom->getTypeClass()) return false;
  1337. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1338. return false;
  1339. }
  1340. const auto *FromFn = cast<FunctionType>(CanFrom);
  1341. FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
  1342. const auto *ToFn = cast<FunctionType>(CanTo);
  1343. FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
  1344. bool Changed = false;
  1345. // Drop 'noreturn' if not present in target type.
  1346. if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
  1347. FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
  1348. Changed = true;
  1349. }
  1350. // Drop 'noexcept' if not present in target type.
  1351. if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
  1352. const auto *ToFPT = cast<FunctionProtoType>(ToFn);
  1353. if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
  1354. FromFn = cast<FunctionType>(
  1355. Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
  1356. EST_None)
  1357. .getTypePtr());
  1358. Changed = true;
  1359. }
  1360. // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
  1361. // only if the ExtParameterInfo lists of the two function prototypes can be
  1362. // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
  1363. SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
  1364. bool CanUseToFPT, CanUseFromFPT;
  1365. if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
  1366. CanUseFromFPT, NewParamInfos) &&
  1367. CanUseToFPT && !CanUseFromFPT) {
  1368. FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
  1369. ExtInfo.ExtParameterInfos =
  1370. NewParamInfos.empty() ? nullptr : NewParamInfos.data();
  1371. QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
  1372. FromFPT->getParamTypes(), ExtInfo);
  1373. FromFn = QT->getAs<FunctionType>();
  1374. Changed = true;
  1375. }
  1376. }
  1377. if (!Changed)
  1378. return false;
  1379. assert(QualType(FromFn, 0).isCanonical());
  1380. if (QualType(FromFn, 0) != CanTo) return false;
  1381. ResultTy = ToType;
  1382. return true;
  1383. }
  1384. /// Determine whether the conversion from FromType to ToType is a valid
  1385. /// vector conversion.
  1386. ///
  1387. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1388. /// conversion.
  1389. static bool IsVectorConversion(Sema &S, QualType FromType,
  1390. QualType ToType, ImplicitConversionKind &ICK) {
  1391. // We need at least one of these types to be a vector type to have a vector
  1392. // conversion.
  1393. if (!ToType->isVectorType() && !FromType->isVectorType())
  1394. return false;
  1395. // Identical types require no conversions.
  1396. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1397. return false;
  1398. // There are no conversions between extended vector types, only identity.
  1399. if (ToType->isExtVectorType()) {
  1400. // There are no conversions between extended vector types other than the
  1401. // identity conversion.
  1402. if (FromType->isExtVectorType())
  1403. return false;
  1404. // Vector splat from any arithmetic type to a vector.
  1405. if (FromType->isArithmeticType()) {
  1406. ICK = ICK_Vector_Splat;
  1407. return true;
  1408. }
  1409. }
  1410. // We can perform the conversion between vector types in the following cases:
  1411. // 1)vector types are equivalent AltiVec and GCC vector types
  1412. // 2)lax vector conversions are permitted and the vector types are of the
  1413. // same size
  1414. if (ToType->isVectorType() && FromType->isVectorType()) {
  1415. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1416. S.isLaxVectorConversion(FromType, ToType)) {
  1417. ICK = ICK_Vector_Conversion;
  1418. return true;
  1419. }
  1420. }
  1421. return false;
  1422. }
  1423. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1424. bool InOverloadResolution,
  1425. StandardConversionSequence &SCS,
  1426. bool CStyle);
  1427. /// IsStandardConversion - Determines whether there is a standard
  1428. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1429. /// expression From to the type ToType. Standard conversion sequences
  1430. /// only consider non-class types; for conversions that involve class
  1431. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1432. /// contain the standard conversion sequence required to perform this
  1433. /// conversion and this routine will return true. Otherwise, this
  1434. /// routine will return false and the value of SCS is unspecified.
  1435. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1436. bool InOverloadResolution,
  1437. StandardConversionSequence &SCS,
  1438. bool CStyle,
  1439. bool AllowObjCWritebackConversion) {
  1440. QualType FromType = From->getType();
  1441. // Standard conversions (C++ [conv])
  1442. SCS.setAsIdentityConversion();
  1443. SCS.IncompatibleObjC = false;
  1444. SCS.setFromType(FromType);
  1445. SCS.CopyConstructor = nullptr;
  1446. // There are no standard conversions for class types in C++, so
  1447. // abort early. When overloading in C, however, we do permit them.
  1448. if (S.getLangOpts().CPlusPlus &&
  1449. (FromType->isRecordType() || ToType->isRecordType()))
  1450. return false;
  1451. // The first conversion can be an lvalue-to-rvalue conversion,
  1452. // array-to-pointer conversion, or function-to-pointer conversion
  1453. // (C++ 4p1).
  1454. if (FromType == S.Context.OverloadTy) {
  1455. DeclAccessPair AccessPair;
  1456. if (FunctionDecl *Fn
  1457. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1458. AccessPair)) {
  1459. // We were able to resolve the address of the overloaded function,
  1460. // so we can convert to the type of that function.
  1461. FromType = Fn->getType();
  1462. SCS.setFromType(FromType);
  1463. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1464. // if the type matches (identity) or we are converting to bool
  1465. if (!S.Context.hasSameUnqualifiedType(
  1466. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1467. QualType resultTy;
  1468. // if the function type matches except for [[noreturn]], it's ok
  1469. if (!S.IsFunctionConversion(FromType,
  1470. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1471. // otherwise, only a boolean conversion is standard
  1472. if (!ToType->isBooleanType())
  1473. return false;
  1474. }
  1475. // Check if the "from" expression is taking the address of an overloaded
  1476. // function and recompute the FromType accordingly. Take advantage of the
  1477. // fact that non-static member functions *must* have such an address-of
  1478. // expression.
  1479. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1480. if (Method && !Method->isStatic()) {
  1481. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1482. "Non-unary operator on non-static member address");
  1483. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1484. == UO_AddrOf &&
  1485. "Non-address-of operator on non-static member address");
  1486. const Type *ClassType
  1487. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1488. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1489. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1490. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1491. UO_AddrOf &&
  1492. "Non-address-of operator for overloaded function expression");
  1493. FromType = S.Context.getPointerType(FromType);
  1494. }
  1495. // Check that we've computed the proper type after overload resolution.
  1496. // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
  1497. // be calling it from within an NDEBUG block.
  1498. assert(S.Context.hasSameType(
  1499. FromType,
  1500. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1501. } else {
  1502. return false;
  1503. }
  1504. }
  1505. // Lvalue-to-rvalue conversion (C++11 4.1):
  1506. // A glvalue (3.10) of a non-function, non-array type T can
  1507. // be converted to a prvalue.
  1508. bool argIsLValue = From->isGLValue();
  1509. if (argIsLValue &&
  1510. !FromType->isFunctionType() && !FromType->isArrayType() &&
  1511. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1512. SCS.First = ICK_Lvalue_To_Rvalue;
  1513. // C11 6.3.2.1p2:
  1514. // ... if the lvalue has atomic type, the value has the non-atomic version
  1515. // of the type of the lvalue ...
  1516. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1517. FromType = Atomic->getValueType();
  1518. // If T is a non-class type, the type of the rvalue is the
  1519. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1520. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1521. // just strip the qualifiers because they don't matter.
  1522. FromType = FromType.getUnqualifiedType();
  1523. } else if (FromType->isArrayType()) {
  1524. // Array-to-pointer conversion (C++ 4.2)
  1525. SCS.First = ICK_Array_To_Pointer;
  1526. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1527. // bound of T" can be converted to an rvalue of type "pointer to
  1528. // T" (C++ 4.2p1).
  1529. FromType = S.Context.getArrayDecayedType(FromType);
  1530. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1531. // This conversion is deprecated in C++03 (D.4)
  1532. SCS.DeprecatedStringLiteralToCharPtr = true;
  1533. // For the purpose of ranking in overload resolution
  1534. // (13.3.3.1.1), this conversion is considered an
  1535. // array-to-pointer conversion followed by a qualification
  1536. // conversion (4.4). (C++ 4.2p2)
  1537. SCS.Second = ICK_Identity;
  1538. SCS.Third = ICK_Qualification;
  1539. SCS.QualificationIncludesObjCLifetime = false;
  1540. SCS.setAllToTypes(FromType);
  1541. return true;
  1542. }
  1543. } else if (FromType->isFunctionType() && argIsLValue) {
  1544. // Function-to-pointer conversion (C++ 4.3).
  1545. SCS.First = ICK_Function_To_Pointer;
  1546. if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
  1547. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  1548. if (!S.checkAddressOfFunctionIsAvailable(FD))
  1549. return false;
  1550. // An lvalue of function type T can be converted to an rvalue of
  1551. // type "pointer to T." The result is a pointer to the
  1552. // function. (C++ 4.3p1).
  1553. FromType = S.Context.getPointerType(FromType);
  1554. } else {
  1555. // We don't require any conversions for the first step.
  1556. SCS.First = ICK_Identity;
  1557. }
  1558. SCS.setToType(0, FromType);
  1559. // The second conversion can be an integral promotion, floating
  1560. // point promotion, integral conversion, floating point conversion,
  1561. // floating-integral conversion, pointer conversion,
  1562. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1563. // For overloading in C, this can also be a "compatible-type"
  1564. // conversion.
  1565. bool IncompatibleObjC = false;
  1566. ImplicitConversionKind SecondICK = ICK_Identity;
  1567. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1568. // The unqualified versions of the types are the same: there's no
  1569. // conversion to do.
  1570. SCS.Second = ICK_Identity;
  1571. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1572. // Integral promotion (C++ 4.5).
  1573. SCS.Second = ICK_Integral_Promotion;
  1574. FromType = ToType.getUnqualifiedType();
  1575. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1576. // Floating point promotion (C++ 4.6).
  1577. SCS.Second = ICK_Floating_Promotion;
  1578. FromType = ToType.getUnqualifiedType();
  1579. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1580. // Complex promotion (Clang extension)
  1581. SCS.Second = ICK_Complex_Promotion;
  1582. FromType = ToType.getUnqualifiedType();
  1583. } else if (ToType->isBooleanType() &&
  1584. (FromType->isArithmeticType() ||
  1585. FromType->isAnyPointerType() ||
  1586. FromType->isBlockPointerType() ||
  1587. FromType->isMemberPointerType() ||
  1588. FromType->isNullPtrType())) {
  1589. // Boolean conversions (C++ 4.12).
  1590. SCS.Second = ICK_Boolean_Conversion;
  1591. FromType = S.Context.BoolTy;
  1592. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1593. ToType->isIntegralType(S.Context)) {
  1594. // Integral conversions (C++ 4.7).
  1595. SCS.Second = ICK_Integral_Conversion;
  1596. FromType = ToType.getUnqualifiedType();
  1597. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1598. // Complex conversions (C99 6.3.1.6)
  1599. SCS.Second = ICK_Complex_Conversion;
  1600. FromType = ToType.getUnqualifiedType();
  1601. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1602. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1603. // Complex-real conversions (C99 6.3.1.7)
  1604. SCS.Second = ICK_Complex_Real;
  1605. FromType = ToType.getUnqualifiedType();
  1606. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1607. // FIXME: disable conversions between long double and __float128 if
  1608. // their representation is different until there is back end support
  1609. // We of course allow this conversion if long double is really double.
  1610. if (&S.Context.getFloatTypeSemantics(FromType) !=
  1611. &S.Context.getFloatTypeSemantics(ToType)) {
  1612. bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
  1613. ToType == S.Context.LongDoubleTy) ||
  1614. (FromType == S.Context.LongDoubleTy &&
  1615. ToType == S.Context.Float128Ty));
  1616. if (Float128AndLongDouble &&
  1617. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  1618. &llvm::APFloat::PPCDoubleDouble()))
  1619. return false;
  1620. }
  1621. // Floating point conversions (C++ 4.8).
  1622. SCS.Second = ICK_Floating_Conversion;
  1623. FromType = ToType.getUnqualifiedType();
  1624. } else if ((FromType->isRealFloatingType() &&
  1625. ToType->isIntegralType(S.Context)) ||
  1626. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1627. ToType->isRealFloatingType())) {
  1628. // Floating-integral conversions (C++ 4.9).
  1629. SCS.Second = ICK_Floating_Integral;
  1630. FromType = ToType.getUnqualifiedType();
  1631. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1632. SCS.Second = ICK_Block_Pointer_Conversion;
  1633. } else if (AllowObjCWritebackConversion &&
  1634. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1635. SCS.Second = ICK_Writeback_Conversion;
  1636. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1637. FromType, IncompatibleObjC)) {
  1638. // Pointer conversions (C++ 4.10).
  1639. SCS.Second = ICK_Pointer_Conversion;
  1640. SCS.IncompatibleObjC = IncompatibleObjC;
  1641. FromType = FromType.getUnqualifiedType();
  1642. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1643. InOverloadResolution, FromType)) {
  1644. // Pointer to member conversions (4.11).
  1645. SCS.Second = ICK_Pointer_Member;
  1646. } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
  1647. SCS.Second = SecondICK;
  1648. FromType = ToType.getUnqualifiedType();
  1649. } else if (!S.getLangOpts().CPlusPlus &&
  1650. S.Context.typesAreCompatible(ToType, FromType)) {
  1651. // Compatible conversions (Clang extension for C function overloading)
  1652. SCS.Second = ICK_Compatible_Conversion;
  1653. FromType = ToType.getUnqualifiedType();
  1654. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1655. InOverloadResolution,
  1656. SCS, CStyle)) {
  1657. SCS.Second = ICK_TransparentUnionConversion;
  1658. FromType = ToType;
  1659. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1660. CStyle)) {
  1661. // tryAtomicConversion has updated the standard conversion sequence
  1662. // appropriately.
  1663. return true;
  1664. } else if (ToType->isEventT() &&
  1665. From->isIntegerConstantExpr(S.getASTContext()) &&
  1666. From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
  1667. SCS.Second = ICK_Zero_Event_Conversion;
  1668. FromType = ToType;
  1669. } else if (ToType->isQueueT() &&
  1670. From->isIntegerConstantExpr(S.getASTContext()) &&
  1671. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1672. SCS.Second = ICK_Zero_Queue_Conversion;
  1673. FromType = ToType;
  1674. } else if (ToType->isSamplerT() &&
  1675. From->isIntegerConstantExpr(S.getASTContext())) {
  1676. SCS.Second = ICK_Compatible_Conversion;
  1677. FromType = ToType;
  1678. } else {
  1679. // No second conversion required.
  1680. SCS.Second = ICK_Identity;
  1681. }
  1682. SCS.setToType(1, FromType);
  1683. // The third conversion can be a function pointer conversion or a
  1684. // qualification conversion (C++ [conv.fctptr], [conv.qual]).
  1685. bool ObjCLifetimeConversion;
  1686. if (S.IsFunctionConversion(FromType, ToType, FromType)) {
  1687. // Function pointer conversions (removing 'noexcept') including removal of
  1688. // 'noreturn' (Clang extension).
  1689. SCS.Third = ICK_Function_Conversion;
  1690. } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1691. ObjCLifetimeConversion)) {
  1692. SCS.Third = ICK_Qualification;
  1693. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1694. FromType = ToType;
  1695. } else {
  1696. // No conversion required
  1697. SCS.Third = ICK_Identity;
  1698. }
  1699. // C++ [over.best.ics]p6:
  1700. // [...] Any difference in top-level cv-qualification is
  1701. // subsumed by the initialization itself and does not constitute
  1702. // a conversion. [...]
  1703. QualType CanonFrom = S.Context.getCanonicalType(FromType);
  1704. QualType CanonTo = S.Context.getCanonicalType(ToType);
  1705. if (CanonFrom.getLocalUnqualifiedType()
  1706. == CanonTo.getLocalUnqualifiedType() &&
  1707. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1708. FromType = ToType;
  1709. CanonFrom = CanonTo;
  1710. }
  1711. SCS.setToType(2, FromType);
  1712. if (CanonFrom == CanonTo)
  1713. return true;
  1714. // If we have not converted the argument type to the parameter type,
  1715. // this is a bad conversion sequence, unless we're resolving an overload in C.
  1716. if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
  1717. return false;
  1718. ExprResult ER = ExprResult{From};
  1719. Sema::AssignConvertType Conv =
  1720. S.CheckSingleAssignmentConstraints(ToType, ER,
  1721. /*Diagnose=*/false,
  1722. /*DiagnoseCFAudited=*/false,
  1723. /*ConvertRHS=*/false);
  1724. ImplicitConversionKind SecondConv;
  1725. switch (Conv) {
  1726. case Sema::Compatible:
  1727. SecondConv = ICK_C_Only_Conversion;
  1728. break;
  1729. // For our purposes, discarding qualifiers is just as bad as using an
  1730. // incompatible pointer. Note that an IncompatiblePointer conversion can drop
  1731. // qualifiers, as well.
  1732. case Sema::CompatiblePointerDiscardsQualifiers:
  1733. case Sema::IncompatiblePointer:
  1734. case Sema::IncompatiblePointerSign:
  1735. SecondConv = ICK_Incompatible_Pointer_Conversion;
  1736. break;
  1737. default:
  1738. return false;
  1739. }
  1740. // First can only be an lvalue conversion, so we pretend that this was the
  1741. // second conversion. First should already be valid from earlier in the
  1742. // function.
  1743. SCS.Second = SecondConv;
  1744. SCS.setToType(1, ToType);
  1745. // Third is Identity, because Second should rank us worse than any other
  1746. // conversion. This could also be ICK_Qualification, but it's simpler to just
  1747. // lump everything in with the second conversion, and we don't gain anything
  1748. // from making this ICK_Qualification.
  1749. SCS.Third = ICK_Identity;
  1750. SCS.setToType(2, ToType);
  1751. return true;
  1752. }
  1753. static bool
  1754. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1755. QualType &ToType,
  1756. bool InOverloadResolution,
  1757. StandardConversionSequence &SCS,
  1758. bool CStyle) {
  1759. const RecordType *UT = ToType->getAsUnionType();
  1760. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1761. return false;
  1762. // The field to initialize within the transparent union.
  1763. RecordDecl *UD = UT->getDecl();
  1764. // It's compatible if the expression matches any of the fields.
  1765. for (const auto *it : UD->fields()) {
  1766. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1767. CStyle, /*AllowObjCWritebackConversion=*/false)) {
  1768. ToType = it->getType();
  1769. return true;
  1770. }
  1771. }
  1772. return false;
  1773. }
  1774. /// IsIntegralPromotion - Determines whether the conversion from the
  1775. /// expression From (whose potentially-adjusted type is FromType) to
  1776. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1777. /// sets PromotedType to the promoted type.
  1778. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1779. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1780. // All integers are built-in.
  1781. if (!To) {
  1782. return false;
  1783. }
  1784. // An rvalue of type char, signed char, unsigned char, short int, or
  1785. // unsigned short int can be converted to an rvalue of type int if
  1786. // int can represent all the values of the source type; otherwise,
  1787. // the source rvalue can be converted to an rvalue of type unsigned
  1788. // int (C++ 4.5p1).
  1789. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1790. !FromType->isEnumeralType()) {
  1791. if (// We can promote any signed, promotable integer type to an int
  1792. (FromType->isSignedIntegerType() ||
  1793. // We can promote any unsigned integer type whose size is
  1794. // less than int to an int.
  1795. Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
  1796. return To->getKind() == BuiltinType::Int;
  1797. }
  1798. return To->getKind() == BuiltinType::UInt;
  1799. }
  1800. // C++11 [conv.prom]p3:
  1801. // A prvalue of an unscoped enumeration type whose underlying type is not
  1802. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1803. // following types that can represent all the values of the enumeration
  1804. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1805. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1806. // long long int. If none of the types in that list can represent all the
  1807. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1808. // type can be converted to an rvalue a prvalue of the extended integer type
  1809. // with lowest integer conversion rank (4.13) greater than the rank of long
  1810. // long in which all the values of the enumeration can be represented. If
  1811. // there are two such extended types, the signed one is chosen.
  1812. // C++11 [conv.prom]p4:
  1813. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  1814. // can be converted to a prvalue of its underlying type. Moreover, if
  1815. // integral promotion can be applied to its underlying type, a prvalue of an
  1816. // unscoped enumeration type whose underlying type is fixed can also be
  1817. // converted to a prvalue of the promoted underlying type.
  1818. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1819. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1820. // provided for a scoped enumeration.
  1821. if (FromEnumType->getDecl()->isScoped())
  1822. return false;
  1823. // We can perform an integral promotion to the underlying type of the enum,
  1824. // even if that's not the promoted type. Note that the check for promoting
  1825. // the underlying type is based on the type alone, and does not consider
  1826. // the bitfield-ness of the actual source expression.
  1827. if (FromEnumType->getDecl()->isFixed()) {
  1828. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  1829. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  1830. IsIntegralPromotion(nullptr, Underlying, ToType);
  1831. }
  1832. // We have already pre-calculated the promotion type, so this is trivial.
  1833. if (ToType->isIntegerType() &&
  1834. isCompleteType(From->getBeginLoc(), FromType))
  1835. return Context.hasSameUnqualifiedType(
  1836. ToType, FromEnumType->getDecl()->getPromotionType());
  1837. // C++ [conv.prom]p5:
  1838. // If the bit-field has an enumerated type, it is treated as any other
  1839. // value of that type for promotion purposes.
  1840. //
  1841. // ... so do not fall through into the bit-field checks below in C++.
  1842. if (getLangOpts().CPlusPlus)
  1843. return false;
  1844. }
  1845. // C++0x [conv.prom]p2:
  1846. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1847. // to an rvalue a prvalue of the first of the following types that can
  1848. // represent all the values of its underlying type: int, unsigned int,
  1849. // long int, unsigned long int, long long int, or unsigned long long int.
  1850. // If none of the types in that list can represent all the values of its
  1851. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1852. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1853. // type.
  1854. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1855. ToType->isIntegerType()) {
  1856. // Determine whether the type we're converting from is signed or
  1857. // unsigned.
  1858. bool FromIsSigned = FromType->isSignedIntegerType();
  1859. uint64_t FromSize = Context.getTypeSize(FromType);
  1860. // The types we'll try to promote to, in the appropriate
  1861. // order. Try each of these types.
  1862. QualType PromoteTypes[6] = {
  1863. Context.IntTy, Context.UnsignedIntTy,
  1864. Context.LongTy, Context.UnsignedLongTy ,
  1865. Context.LongLongTy, Context.UnsignedLongLongTy
  1866. };
  1867. for (int Idx = 0; Idx < 6; ++Idx) {
  1868. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1869. if (FromSize < ToSize ||
  1870. (FromSize == ToSize &&
  1871. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1872. // We found the type that we can promote to. If this is the
  1873. // type we wanted, we have a promotion. Otherwise, no
  1874. // promotion.
  1875. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1876. }
  1877. }
  1878. }
  1879. // An rvalue for an integral bit-field (9.6) can be converted to an
  1880. // rvalue of type int if int can represent all the values of the
  1881. // bit-field; otherwise, it can be converted to unsigned int if
  1882. // unsigned int can represent all the values of the bit-field. If
  1883. // the bit-field is larger yet, no integral promotion applies to
  1884. // it. If the bit-field has an enumerated type, it is treated as any
  1885. // other value of that type for promotion purposes (C++ 4.5p3).
  1886. // FIXME: We should delay checking of bit-fields until we actually perform the
  1887. // conversion.
  1888. //
  1889. // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
  1890. // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
  1891. // bit-fields and those whose underlying type is larger than int) for GCC
  1892. // compatibility.
  1893. if (From) {
  1894. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  1895. llvm::APSInt BitWidth;
  1896. if (FromType->isIntegralType(Context) &&
  1897. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1898. llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1899. ToSize = Context.getTypeSize(ToType);
  1900. // Are we promoting to an int from a bitfield that fits in an int?
  1901. if (BitWidth < ToSize ||
  1902. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1903. return To->getKind() == BuiltinType::Int;
  1904. }
  1905. // Are we promoting to an unsigned int from an unsigned bitfield
  1906. // that fits into an unsigned int?
  1907. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1908. return To->getKind() == BuiltinType::UInt;
  1909. }
  1910. return false;
  1911. }
  1912. }
  1913. }
  1914. // An rvalue of type bool can be converted to an rvalue of type int,
  1915. // with false becoming zero and true becoming one (C++ 4.5p4).
  1916. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1917. return true;
  1918. }
  1919. return false;
  1920. }
  1921. /// IsFloatingPointPromotion - Determines whether the conversion from
  1922. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1923. /// returns true and sets PromotedType to the promoted type.
  1924. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1925. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1926. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1927. /// An rvalue of type float can be converted to an rvalue of type
  1928. /// double. (C++ 4.6p1).
  1929. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1930. ToBuiltin->getKind() == BuiltinType::Double)
  1931. return true;
  1932. // C99 6.3.1.5p1:
  1933. // When a float is promoted to double or long double, or a
  1934. // double is promoted to long double [...].
  1935. if (!getLangOpts().CPlusPlus &&
  1936. (FromBuiltin->getKind() == BuiltinType::Float ||
  1937. FromBuiltin->getKind() == BuiltinType::Double) &&
  1938. (ToBuiltin->getKind() == BuiltinType::LongDouble ||
  1939. ToBuiltin->getKind() == BuiltinType::Float128))
  1940. return true;
  1941. // Half can be promoted to float.
  1942. if (!getLangOpts().NativeHalfType &&
  1943. FromBuiltin->getKind() == BuiltinType::Half &&
  1944. ToBuiltin->getKind() == BuiltinType::Float)
  1945. return true;
  1946. }
  1947. return false;
  1948. }
  1949. /// Determine if a conversion is a complex promotion.
  1950. ///
  1951. /// A complex promotion is defined as a complex -> complex conversion
  1952. /// where the conversion between the underlying real types is a
  1953. /// floating-point or integral promotion.
  1954. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1955. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1956. if (!FromComplex)
  1957. return false;
  1958. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1959. if (!ToComplex)
  1960. return false;
  1961. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1962. ToComplex->getElementType()) ||
  1963. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  1964. ToComplex->getElementType());
  1965. }
  1966. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1967. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1968. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1969. /// if non-empty, will be a pointer to ToType that may or may not have
  1970. /// the right set of qualifiers on its pointee.
  1971. ///
  1972. static QualType
  1973. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  1974. QualType ToPointee, QualType ToType,
  1975. ASTContext &Context,
  1976. bool StripObjCLifetime = false) {
  1977. assert((FromPtr->getTypeClass() == Type::Pointer ||
  1978. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  1979. "Invalid similarly-qualified pointer type");
  1980. /// Conversions to 'id' subsume cv-qualifier conversions.
  1981. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  1982. return ToType.getUnqualifiedType();
  1983. QualType CanonFromPointee
  1984. = Context.getCanonicalType(FromPtr->getPointeeType());
  1985. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  1986. Qualifiers Quals = CanonFromPointee.getQualifiers();
  1987. if (StripObjCLifetime)
  1988. Quals.removeObjCLifetime();
  1989. // Exact qualifier match -> return the pointer type we're converting to.
  1990. if (CanonToPointee.getLocalQualifiers() == Quals) {
  1991. // ToType is exactly what we need. Return it.
  1992. if (!ToType.isNull())
  1993. return ToType.getUnqualifiedType();
  1994. // Build a pointer to ToPointee. It has the right qualifiers
  1995. // already.
  1996. if (isa<ObjCObjectPointerType>(ToType))
  1997. return Context.getObjCObjectPointerType(ToPointee);
  1998. return Context.getPointerType(ToPointee);
  1999. }
  2000. // Just build a canonical type that has the right qualifiers.
  2001. QualType QualifiedCanonToPointee
  2002. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  2003. if (isa<ObjCObjectPointerType>(ToType))
  2004. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  2005. return Context.getPointerType(QualifiedCanonToPointee);
  2006. }
  2007. static bool isNullPointerConstantForConversion(Expr *Expr,
  2008. bool InOverloadResolution,
  2009. ASTContext &Context) {
  2010. // Handle value-dependent integral null pointer constants correctly.
  2011. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  2012. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  2013. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  2014. return !InOverloadResolution;
  2015. return Expr->isNullPointerConstant(Context,
  2016. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2017. : Expr::NPC_ValueDependentIsNull);
  2018. }
  2019. /// IsPointerConversion - Determines whether the conversion of the
  2020. /// expression From, which has the (possibly adjusted) type FromType,
  2021. /// can be converted to the type ToType via a pointer conversion (C++
  2022. /// 4.10). If so, returns true and places the converted type (that
  2023. /// might differ from ToType in its cv-qualifiers at some level) into
  2024. /// ConvertedType.
  2025. ///
  2026. /// This routine also supports conversions to and from block pointers
  2027. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  2028. /// pointers to interfaces. FIXME: Once we've determined the
  2029. /// appropriate overloading rules for Objective-C, we may want to
  2030. /// split the Objective-C checks into a different routine; however,
  2031. /// GCC seems to consider all of these conversions to be pointer
  2032. /// conversions, so for now they live here. IncompatibleObjC will be
  2033. /// set if the conversion is an allowed Objective-C conversion that
  2034. /// should result in a warning.
  2035. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  2036. bool InOverloadResolution,
  2037. QualType& ConvertedType,
  2038. bool &IncompatibleObjC) {
  2039. IncompatibleObjC = false;
  2040. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  2041. IncompatibleObjC))
  2042. return true;
  2043. // Conversion from a null pointer constant to any Objective-C pointer type.
  2044. if (ToType->isObjCObjectPointerType() &&
  2045. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2046. ConvertedType = ToType;
  2047. return true;
  2048. }
  2049. // Blocks: Block pointers can be converted to void*.
  2050. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  2051. ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
  2052. ConvertedType = ToType;
  2053. return true;
  2054. }
  2055. // Blocks: A null pointer constant can be converted to a block
  2056. // pointer type.
  2057. if (ToType->isBlockPointerType() &&
  2058. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2059. ConvertedType = ToType;
  2060. return true;
  2061. }
  2062. // If the left-hand-side is nullptr_t, the right side can be a null
  2063. // pointer constant.
  2064. if (ToType->isNullPtrType() &&
  2065. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2066. ConvertedType = ToType;
  2067. return true;
  2068. }
  2069. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  2070. if (!ToTypePtr)
  2071. return false;
  2072. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  2073. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2074. ConvertedType = ToType;
  2075. return true;
  2076. }
  2077. // Beyond this point, both types need to be pointers
  2078. // , including objective-c pointers.
  2079. QualType ToPointeeType = ToTypePtr->getPointeeType();
  2080. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  2081. !getLangOpts().ObjCAutoRefCount) {
  2082. ConvertedType = BuildSimilarlyQualifiedPointerType(
  2083. FromType->getAs<ObjCObjectPointerType>(),
  2084. ToPointeeType,
  2085. ToType, Context);
  2086. return true;
  2087. }
  2088. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  2089. if (!FromTypePtr)
  2090. return false;
  2091. QualType FromPointeeType = FromTypePtr->getPointeeType();
  2092. // If the unqualified pointee types are the same, this can't be a
  2093. // pointer conversion, so don't do all of the work below.
  2094. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  2095. return false;
  2096. // An rvalue of type "pointer to cv T," where T is an object type,
  2097. // can be converted to an rvalue of type "pointer to cv void" (C++
  2098. // 4.10p2).
  2099. if (FromPointeeType->isIncompleteOrObjectType() &&
  2100. ToPointeeType->isVoidType()) {
  2101. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2102. ToPointeeType,
  2103. ToType, Context,
  2104. /*StripObjCLifetime=*/true);
  2105. return true;
  2106. }
  2107. // MSVC allows implicit function to void* type conversion.
  2108. if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
  2109. ToPointeeType->isVoidType()) {
  2110. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2111. ToPointeeType,
  2112. ToType, Context);
  2113. return true;
  2114. }
  2115. // When we're overloading in C, we allow a special kind of pointer
  2116. // conversion for compatible-but-not-identical pointee types.
  2117. if (!getLangOpts().CPlusPlus &&
  2118. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  2119. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2120. ToPointeeType,
  2121. ToType, Context);
  2122. return true;
  2123. }
  2124. // C++ [conv.ptr]p3:
  2125. //
  2126. // An rvalue of type "pointer to cv D," where D is a class type,
  2127. // can be converted to an rvalue of type "pointer to cv B," where
  2128. // B is a base class (clause 10) of D. If B is an inaccessible
  2129. // (clause 11) or ambiguous (10.2) base class of D, a program that
  2130. // necessitates this conversion is ill-formed. The result of the
  2131. // conversion is a pointer to the base class sub-object of the
  2132. // derived class object. The null pointer value is converted to
  2133. // the null pointer value of the destination type.
  2134. //
  2135. // Note that we do not check for ambiguity or inaccessibility
  2136. // here. That is handled by CheckPointerConversion.
  2137. if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
  2138. ToPointeeType->isRecordType() &&
  2139. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  2140. IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
  2141. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2142. ToPointeeType,
  2143. ToType, Context);
  2144. return true;
  2145. }
  2146. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  2147. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  2148. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2149. ToPointeeType,
  2150. ToType, Context);
  2151. return true;
  2152. }
  2153. return false;
  2154. }
  2155. /// Adopt the given qualifiers for the given type.
  2156. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  2157. Qualifiers TQs = T.getQualifiers();
  2158. // Check whether qualifiers already match.
  2159. if (TQs == Qs)
  2160. return T;
  2161. if (Qs.compatiblyIncludes(TQs))
  2162. return Context.getQualifiedType(T, Qs);
  2163. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  2164. }
  2165. /// isObjCPointerConversion - Determines whether this is an
  2166. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  2167. /// with the same arguments and return values.
  2168. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  2169. QualType& ConvertedType,
  2170. bool &IncompatibleObjC) {
  2171. if (!getLangOpts().ObjC)
  2172. return false;
  2173. // The set of qualifiers on the type we're converting from.
  2174. Qualifiers FromQualifiers = FromType.getQualifiers();
  2175. // First, we handle all conversions on ObjC object pointer types.
  2176. const ObjCObjectPointerType* ToObjCPtr =
  2177. ToType->getAs<ObjCObjectPointerType>();
  2178. const ObjCObjectPointerType *FromObjCPtr =
  2179. FromType->getAs<ObjCObjectPointerType>();
  2180. if (ToObjCPtr && FromObjCPtr) {
  2181. // If the pointee types are the same (ignoring qualifications),
  2182. // then this is not a pointer conversion.
  2183. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  2184. FromObjCPtr->getPointeeType()))
  2185. return false;
  2186. // Conversion between Objective-C pointers.
  2187. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  2188. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  2189. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  2190. if (getLangOpts().CPlusPlus && LHS && RHS &&
  2191. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  2192. FromObjCPtr->getPointeeType()))
  2193. return false;
  2194. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2195. ToObjCPtr->getPointeeType(),
  2196. ToType, Context);
  2197. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2198. return true;
  2199. }
  2200. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2201. // Okay: this is some kind of implicit downcast of Objective-C
  2202. // interfaces, which is permitted. However, we're going to
  2203. // complain about it.
  2204. IncompatibleObjC = true;
  2205. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2206. ToObjCPtr->getPointeeType(),
  2207. ToType, Context);
  2208. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2209. return true;
  2210. }
  2211. }
  2212. // Beyond this point, both types need to be C pointers or block pointers.
  2213. QualType ToPointeeType;
  2214. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2215. ToPointeeType = ToCPtr->getPointeeType();
  2216. else if (const BlockPointerType *ToBlockPtr =
  2217. ToType->getAs<BlockPointerType>()) {
  2218. // Objective C++: We're able to convert from a pointer to any object
  2219. // to a block pointer type.
  2220. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2221. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2222. return true;
  2223. }
  2224. ToPointeeType = ToBlockPtr->getPointeeType();
  2225. }
  2226. else if (FromType->getAs<BlockPointerType>() &&
  2227. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2228. // Objective C++: We're able to convert from a block pointer type to a
  2229. // pointer to any object.
  2230. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2231. return true;
  2232. }
  2233. else
  2234. return false;
  2235. QualType FromPointeeType;
  2236. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2237. FromPointeeType = FromCPtr->getPointeeType();
  2238. else if (const BlockPointerType *FromBlockPtr =
  2239. FromType->getAs<BlockPointerType>())
  2240. FromPointeeType = FromBlockPtr->getPointeeType();
  2241. else
  2242. return false;
  2243. // If we have pointers to pointers, recursively check whether this
  2244. // is an Objective-C conversion.
  2245. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2246. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2247. IncompatibleObjC)) {
  2248. // We always complain about this conversion.
  2249. IncompatibleObjC = true;
  2250. ConvertedType = Context.getPointerType(ConvertedType);
  2251. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2252. return true;
  2253. }
  2254. // Allow conversion of pointee being objective-c pointer to another one;
  2255. // as in I* to id.
  2256. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2257. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2258. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2259. IncompatibleObjC)) {
  2260. ConvertedType = Context.getPointerType(ConvertedType);
  2261. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2262. return true;
  2263. }
  2264. // If we have pointers to functions or blocks, check whether the only
  2265. // differences in the argument and result types are in Objective-C
  2266. // pointer conversions. If so, we permit the conversion (but
  2267. // complain about it).
  2268. const FunctionProtoType *FromFunctionType
  2269. = FromPointeeType->getAs<FunctionProtoType>();
  2270. const FunctionProtoType *ToFunctionType
  2271. = ToPointeeType->getAs<FunctionProtoType>();
  2272. if (FromFunctionType && ToFunctionType) {
  2273. // If the function types are exactly the same, this isn't an
  2274. // Objective-C pointer conversion.
  2275. if (Context.getCanonicalType(FromPointeeType)
  2276. == Context.getCanonicalType(ToPointeeType))
  2277. return false;
  2278. // Perform the quick checks that will tell us whether these
  2279. // function types are obviously different.
  2280. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2281. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2282. FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
  2283. return false;
  2284. bool HasObjCConversion = false;
  2285. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2286. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2287. // Okay, the types match exactly. Nothing to do.
  2288. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2289. ToFunctionType->getReturnType(),
  2290. ConvertedType, IncompatibleObjC)) {
  2291. // Okay, we have an Objective-C pointer conversion.
  2292. HasObjCConversion = true;
  2293. } else {
  2294. // Function types are too different. Abort.
  2295. return false;
  2296. }
  2297. // Check argument types.
  2298. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2299. ArgIdx != NumArgs; ++ArgIdx) {
  2300. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2301. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2302. if (Context.getCanonicalType(FromArgType)
  2303. == Context.getCanonicalType(ToArgType)) {
  2304. // Okay, the types match exactly. Nothing to do.
  2305. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2306. ConvertedType, IncompatibleObjC)) {
  2307. // Okay, we have an Objective-C pointer conversion.
  2308. HasObjCConversion = true;
  2309. } else {
  2310. // Argument types are too different. Abort.
  2311. return false;
  2312. }
  2313. }
  2314. if (HasObjCConversion) {
  2315. // We had an Objective-C conversion. Allow this pointer
  2316. // conversion, but complain about it.
  2317. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2318. IncompatibleObjC = true;
  2319. return true;
  2320. }
  2321. }
  2322. return false;
  2323. }
  2324. /// Determine whether this is an Objective-C writeback conversion,
  2325. /// used for parameter passing when performing automatic reference counting.
  2326. ///
  2327. /// \param FromType The type we're converting form.
  2328. ///
  2329. /// \param ToType The type we're converting to.
  2330. ///
  2331. /// \param ConvertedType The type that will be produced after applying
  2332. /// this conversion.
  2333. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2334. QualType &ConvertedType) {
  2335. if (!getLangOpts().ObjCAutoRefCount ||
  2336. Context.hasSameUnqualifiedType(FromType, ToType))
  2337. return false;
  2338. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2339. QualType ToPointee;
  2340. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2341. ToPointee = ToPointer->getPointeeType();
  2342. else
  2343. return false;
  2344. Qualifiers ToQuals = ToPointee.getQualifiers();
  2345. if (!ToPointee->isObjCLifetimeType() ||
  2346. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2347. !ToQuals.withoutObjCLifetime().empty())
  2348. return false;
  2349. // Argument must be a pointer to __strong to __weak.
  2350. QualType FromPointee;
  2351. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2352. FromPointee = FromPointer->getPointeeType();
  2353. else
  2354. return false;
  2355. Qualifiers FromQuals = FromPointee.getQualifiers();
  2356. if (!FromPointee->isObjCLifetimeType() ||
  2357. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2358. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2359. return false;
  2360. // Make sure that we have compatible qualifiers.
  2361. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2362. if (!ToQuals.compatiblyIncludes(FromQuals))
  2363. return false;
  2364. // Remove qualifiers from the pointee type we're converting from; they
  2365. // aren't used in the compatibility check belong, and we'll be adding back
  2366. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2367. FromPointee = FromPointee.getUnqualifiedType();
  2368. // The unqualified form of the pointee types must be compatible.
  2369. ToPointee = ToPointee.getUnqualifiedType();
  2370. bool IncompatibleObjC;
  2371. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2372. FromPointee = ToPointee;
  2373. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2374. IncompatibleObjC))
  2375. return false;
  2376. /// Construct the type we're converting to, which is a pointer to
  2377. /// __autoreleasing pointee.
  2378. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2379. ConvertedType = Context.getPointerType(FromPointee);
  2380. return true;
  2381. }
  2382. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2383. QualType& ConvertedType) {
  2384. QualType ToPointeeType;
  2385. if (const BlockPointerType *ToBlockPtr =
  2386. ToType->getAs<BlockPointerType>())
  2387. ToPointeeType = ToBlockPtr->getPointeeType();
  2388. else
  2389. return false;
  2390. QualType FromPointeeType;
  2391. if (const BlockPointerType *FromBlockPtr =
  2392. FromType->getAs<BlockPointerType>())
  2393. FromPointeeType = FromBlockPtr->getPointeeType();
  2394. else
  2395. return false;
  2396. // We have pointer to blocks, check whether the only
  2397. // differences in the argument and result types are in Objective-C
  2398. // pointer conversions. If so, we permit the conversion.
  2399. const FunctionProtoType *FromFunctionType
  2400. = FromPointeeType->getAs<FunctionProtoType>();
  2401. const FunctionProtoType *ToFunctionType
  2402. = ToPointeeType->getAs<FunctionProtoType>();
  2403. if (!FromFunctionType || !ToFunctionType)
  2404. return false;
  2405. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2406. return true;
  2407. // Perform the quick checks that will tell us whether these
  2408. // function types are obviously different.
  2409. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2410. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2411. return false;
  2412. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2413. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2414. if (FromEInfo != ToEInfo)
  2415. return false;
  2416. bool IncompatibleObjC = false;
  2417. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2418. ToFunctionType->getReturnType())) {
  2419. // Okay, the types match exactly. Nothing to do.
  2420. } else {
  2421. QualType RHS = FromFunctionType->getReturnType();
  2422. QualType LHS = ToFunctionType->getReturnType();
  2423. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2424. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2425. LHS = LHS.getUnqualifiedType();
  2426. if (Context.hasSameType(RHS,LHS)) {
  2427. // OK exact match.
  2428. } else if (isObjCPointerConversion(RHS, LHS,
  2429. ConvertedType, IncompatibleObjC)) {
  2430. if (IncompatibleObjC)
  2431. return false;
  2432. // Okay, we have an Objective-C pointer conversion.
  2433. }
  2434. else
  2435. return false;
  2436. }
  2437. // Check argument types.
  2438. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2439. ArgIdx != NumArgs; ++ArgIdx) {
  2440. IncompatibleObjC = false;
  2441. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2442. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2443. if (Context.hasSameType(FromArgType, ToArgType)) {
  2444. // Okay, the types match exactly. Nothing to do.
  2445. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2446. ConvertedType, IncompatibleObjC)) {
  2447. if (IncompatibleObjC)
  2448. return false;
  2449. // Okay, we have an Objective-C pointer conversion.
  2450. } else
  2451. // Argument types are too different. Abort.
  2452. return false;
  2453. }
  2454. SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
  2455. bool CanUseToFPT, CanUseFromFPT;
  2456. if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
  2457. CanUseToFPT, CanUseFromFPT,
  2458. NewParamInfos))
  2459. return false;
  2460. ConvertedType = ToType;
  2461. return true;
  2462. }
  2463. enum {
  2464. ft_default,
  2465. ft_different_class,
  2466. ft_parameter_arity,
  2467. ft_parameter_mismatch,
  2468. ft_return_type,
  2469. ft_qualifer_mismatch,
  2470. ft_noexcept
  2471. };
  2472. /// Attempts to get the FunctionProtoType from a Type. Handles
  2473. /// MemberFunctionPointers properly.
  2474. static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
  2475. if (auto *FPT = FromType->getAs<FunctionProtoType>())
  2476. return FPT;
  2477. if (auto *MPT = FromType->getAs<MemberPointerType>())
  2478. return MPT->getPointeeType()->getAs<FunctionProtoType>();
  2479. return nullptr;
  2480. }
  2481. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2482. /// function types. Catches different number of parameter, mismatch in
  2483. /// parameter types, and different return types.
  2484. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2485. QualType FromType, QualType ToType) {
  2486. // If either type is not valid, include no extra info.
  2487. if (FromType.isNull() || ToType.isNull()) {
  2488. PDiag << ft_default;
  2489. return;
  2490. }
  2491. // Get the function type from the pointers.
  2492. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2493. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2494. *ToMember = ToType->getAs<MemberPointerType>();
  2495. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2496. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2497. << QualType(FromMember->getClass(), 0);
  2498. return;
  2499. }
  2500. FromType = FromMember->getPointeeType();
  2501. ToType = ToMember->getPointeeType();
  2502. }
  2503. if (FromType->isPointerType())
  2504. FromType = FromType->getPointeeType();
  2505. if (ToType->isPointerType())
  2506. ToType = ToType->getPointeeType();
  2507. // Remove references.
  2508. FromType = FromType.getNonReferenceType();
  2509. ToType = ToType.getNonReferenceType();
  2510. // Don't print extra info for non-specialized template functions.
  2511. if (FromType->isInstantiationDependentType() &&
  2512. !FromType->getAs<TemplateSpecializationType>()) {
  2513. PDiag << ft_default;
  2514. return;
  2515. }
  2516. // No extra info for same types.
  2517. if (Context.hasSameType(FromType, ToType)) {
  2518. PDiag << ft_default;
  2519. return;
  2520. }
  2521. const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
  2522. *ToFunction = tryGetFunctionProtoType(ToType);
  2523. // Both types need to be function types.
  2524. if (!FromFunction || !ToFunction) {
  2525. PDiag << ft_default;
  2526. return;
  2527. }
  2528. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2529. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2530. << FromFunction->getNumParams();
  2531. return;
  2532. }
  2533. // Handle different parameter types.
  2534. unsigned ArgPos;
  2535. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2536. PDiag << ft_parameter_mismatch << ArgPos + 1
  2537. << ToFunction->getParamType(ArgPos)
  2538. << FromFunction->getParamType(ArgPos);
  2539. return;
  2540. }
  2541. // Handle different return type.
  2542. if (!Context.hasSameType(FromFunction->getReturnType(),
  2543. ToFunction->getReturnType())) {
  2544. PDiag << ft_return_type << ToFunction->getReturnType()
  2545. << FromFunction->getReturnType();
  2546. return;
  2547. }
  2548. if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
  2549. PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
  2550. << FromFunction->getMethodQuals();
  2551. return;
  2552. }
  2553. // Handle exception specification differences on canonical type (in C++17
  2554. // onwards).
  2555. if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
  2556. ->isNothrow() !=
  2557. cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
  2558. ->isNothrow()) {
  2559. PDiag << ft_noexcept;
  2560. return;
  2561. }
  2562. // Unable to find a difference, so add no extra info.
  2563. PDiag << ft_default;
  2564. }
  2565. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2566. /// for equality of their argument types. Caller has already checked that
  2567. /// they have same number of arguments. If the parameters are different,
  2568. /// ArgPos will have the parameter index of the first different parameter.
  2569. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2570. const FunctionProtoType *NewType,
  2571. unsigned *ArgPos) {
  2572. for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
  2573. N = NewType->param_type_begin(),
  2574. E = OldType->param_type_end();
  2575. O && (O != E); ++O, ++N) {
  2576. if (!Context.hasSameType(O->getUnqualifiedType(),
  2577. N->getUnqualifiedType())) {
  2578. if (ArgPos)
  2579. *ArgPos = O - OldType->param_type_begin();
  2580. return false;
  2581. }
  2582. }
  2583. return true;
  2584. }
  2585. /// CheckPointerConversion - Check the pointer conversion from the
  2586. /// expression From to the type ToType. This routine checks for
  2587. /// ambiguous or inaccessible derived-to-base pointer
  2588. /// conversions for which IsPointerConversion has already returned
  2589. /// true. It returns true and produces a diagnostic if there was an
  2590. /// error, or returns false otherwise.
  2591. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2592. CastKind &Kind,
  2593. CXXCastPath& BasePath,
  2594. bool IgnoreBaseAccess,
  2595. bool Diagnose) {
  2596. QualType FromType = From->getType();
  2597. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2598. Kind = CK_BitCast;
  2599. if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2600. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2601. Expr::NPCK_ZeroExpression) {
  2602. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2603. DiagRuntimeBehavior(From->getExprLoc(), From,
  2604. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2605. << ToType << From->getSourceRange());
  2606. else if (!isUnevaluatedContext())
  2607. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2608. << ToType << From->getSourceRange();
  2609. }
  2610. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2611. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2612. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2613. ToPointeeType = ToPtrType->getPointeeType();
  2614. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2615. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2616. // We must have a derived-to-base conversion. Check an
  2617. // ambiguous or inaccessible conversion.
  2618. unsigned InaccessibleID = 0;
  2619. unsigned AmbigiousID = 0;
  2620. if (Diagnose) {
  2621. InaccessibleID = diag::err_upcast_to_inaccessible_base;
  2622. AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
  2623. }
  2624. if (CheckDerivedToBaseConversion(
  2625. FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
  2626. From->getExprLoc(), From->getSourceRange(), DeclarationName(),
  2627. &BasePath, IgnoreBaseAccess))
  2628. return true;
  2629. // The conversion was successful.
  2630. Kind = CK_DerivedToBase;
  2631. }
  2632. if (Diagnose && !IsCStyleOrFunctionalCast &&
  2633. FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
  2634. assert(getLangOpts().MSVCCompat &&
  2635. "this should only be possible with MSVCCompat!");
  2636. Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
  2637. << From->getSourceRange();
  2638. }
  2639. }
  2640. } else if (const ObjCObjectPointerType *ToPtrType =
  2641. ToType->getAs<ObjCObjectPointerType>()) {
  2642. if (const ObjCObjectPointerType *FromPtrType =
  2643. FromType->getAs<ObjCObjectPointerType>()) {
  2644. // Objective-C++ conversions are always okay.
  2645. // FIXME: We should have a different class of conversions for the
  2646. // Objective-C++ implicit conversions.
  2647. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2648. return false;
  2649. } else if (FromType->isBlockPointerType()) {
  2650. Kind = CK_BlockPointerToObjCPointerCast;
  2651. } else {
  2652. Kind = CK_CPointerToObjCPointerCast;
  2653. }
  2654. } else if (ToType->isBlockPointerType()) {
  2655. if (!FromType->isBlockPointerType())
  2656. Kind = CK_AnyPointerToBlockPointerCast;
  2657. }
  2658. // We shouldn't fall into this case unless it's valid for other
  2659. // reasons.
  2660. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2661. Kind = CK_NullToPointer;
  2662. return false;
  2663. }
  2664. /// IsMemberPointerConversion - Determines whether the conversion of the
  2665. /// expression From, which has the (possibly adjusted) type FromType, can be
  2666. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2667. /// If so, returns true and places the converted type (that might differ from
  2668. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2669. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2670. QualType ToType,
  2671. bool InOverloadResolution,
  2672. QualType &ConvertedType) {
  2673. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2674. if (!ToTypePtr)
  2675. return false;
  2676. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2677. if (From->isNullPointerConstant(Context,
  2678. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2679. : Expr::NPC_ValueDependentIsNull)) {
  2680. ConvertedType = ToType;
  2681. return true;
  2682. }
  2683. // Otherwise, both types have to be member pointers.
  2684. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2685. if (!FromTypePtr)
  2686. return false;
  2687. // A pointer to member of B can be converted to a pointer to member of D,
  2688. // where D is derived from B (C++ 4.11p2).
  2689. QualType FromClass(FromTypePtr->getClass(), 0);
  2690. QualType ToClass(ToTypePtr->getClass(), 0);
  2691. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2692. IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
  2693. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2694. ToClass.getTypePtr());
  2695. return true;
  2696. }
  2697. return false;
  2698. }
  2699. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2700. /// expression From to the type ToType. This routine checks for ambiguous or
  2701. /// virtual or inaccessible base-to-derived member pointer conversions
  2702. /// for which IsMemberPointerConversion has already returned true. It returns
  2703. /// true and produces a diagnostic if there was an error, or returns false
  2704. /// otherwise.
  2705. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2706. CastKind &Kind,
  2707. CXXCastPath &BasePath,
  2708. bool IgnoreBaseAccess) {
  2709. QualType FromType = From->getType();
  2710. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2711. if (!FromPtrType) {
  2712. // This must be a null pointer to member pointer conversion
  2713. assert(From->isNullPointerConstant(Context,
  2714. Expr::NPC_ValueDependentIsNull) &&
  2715. "Expr must be null pointer constant!");
  2716. Kind = CK_NullToMemberPointer;
  2717. return false;
  2718. }
  2719. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2720. assert(ToPtrType && "No member pointer cast has a target type "
  2721. "that is not a member pointer.");
  2722. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2723. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2724. // FIXME: What about dependent types?
  2725. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2726. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2727. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2728. /*DetectVirtual=*/true);
  2729. bool DerivationOkay =
  2730. IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
  2731. assert(DerivationOkay &&
  2732. "Should not have been called if derivation isn't OK.");
  2733. (void)DerivationOkay;
  2734. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2735. getUnqualifiedType())) {
  2736. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2737. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2738. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2739. return true;
  2740. }
  2741. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2742. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2743. << FromClass << ToClass << QualType(VBase, 0)
  2744. << From->getSourceRange();
  2745. return true;
  2746. }
  2747. if (!IgnoreBaseAccess)
  2748. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2749. Paths.front(),
  2750. diag::err_downcast_from_inaccessible_base);
  2751. // Must be a base to derived member conversion.
  2752. BuildBasePathArray(Paths, BasePath);
  2753. Kind = CK_BaseToDerivedMemberPointer;
  2754. return false;
  2755. }
  2756. /// Determine whether the lifetime conversion between the two given
  2757. /// qualifiers sets is nontrivial.
  2758. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2759. Qualifiers ToQuals) {
  2760. // Converting anything to const __unsafe_unretained is trivial.
  2761. if (ToQuals.hasConst() &&
  2762. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2763. return false;
  2764. return true;
  2765. }
  2766. /// IsQualificationConversion - Determines whether the conversion from
  2767. /// an rvalue of type FromType to ToType is a qualification conversion
  2768. /// (C++ 4.4).
  2769. ///
  2770. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2771. /// when the qualification conversion involves a change in the Objective-C
  2772. /// object lifetime.
  2773. bool
  2774. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2775. bool CStyle, bool &ObjCLifetimeConversion) {
  2776. FromType = Context.getCanonicalType(FromType);
  2777. ToType = Context.getCanonicalType(ToType);
  2778. ObjCLifetimeConversion = false;
  2779. // If FromType and ToType are the same type, this is not a
  2780. // qualification conversion.
  2781. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2782. return false;
  2783. // (C++ 4.4p4):
  2784. // A conversion can add cv-qualifiers at levels other than the first
  2785. // in multi-level pointers, subject to the following rules: [...]
  2786. bool PreviousToQualsIncludeConst = true;
  2787. bool UnwrappedAnyPointer = false;
  2788. while (Context.UnwrapSimilarTypes(FromType, ToType)) {
  2789. // Within each iteration of the loop, we check the qualifiers to
  2790. // determine if this still looks like a qualification
  2791. // conversion. Then, if all is well, we unwrap one more level of
  2792. // pointers or pointers-to-members and do it all again
  2793. // until there are no more pointers or pointers-to-members left to
  2794. // unwrap.
  2795. UnwrappedAnyPointer = true;
  2796. Qualifiers FromQuals = FromType.getQualifiers();
  2797. Qualifiers ToQuals = ToType.getQualifiers();
  2798. // Ignore __unaligned qualifier if this type is void.
  2799. if (ToType.getUnqualifiedType()->isVoidType())
  2800. FromQuals.removeUnaligned();
  2801. // Objective-C ARC:
  2802. // Check Objective-C lifetime conversions.
  2803. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2804. UnwrappedAnyPointer) {
  2805. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2806. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2807. ObjCLifetimeConversion = true;
  2808. FromQuals.removeObjCLifetime();
  2809. ToQuals.removeObjCLifetime();
  2810. } else {
  2811. // Qualification conversions cannot cast between different
  2812. // Objective-C lifetime qualifiers.
  2813. return false;
  2814. }
  2815. }
  2816. // Allow addition/removal of GC attributes but not changing GC attributes.
  2817. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2818. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2819. FromQuals.removeObjCGCAttr();
  2820. ToQuals.removeObjCGCAttr();
  2821. }
  2822. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2823. // 2,j, and similarly for volatile.
  2824. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2825. return false;
  2826. // -- if the cv 1,j and cv 2,j are different, then const is in
  2827. // every cv for 0 < k < j.
  2828. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2829. && !PreviousToQualsIncludeConst)
  2830. return false;
  2831. // Keep track of whether all prior cv-qualifiers in the "to" type
  2832. // include const.
  2833. PreviousToQualsIncludeConst
  2834. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2835. }
  2836. // Allows address space promotion by language rules implemented in
  2837. // Type::Qualifiers::isAddressSpaceSupersetOf.
  2838. Qualifiers FromQuals = FromType.getQualifiers();
  2839. Qualifiers ToQuals = ToType.getQualifiers();
  2840. if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
  2841. !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
  2842. return false;
  2843. }
  2844. // We are left with FromType and ToType being the pointee types
  2845. // after unwrapping the original FromType and ToType the same number
  2846. // of types. If we unwrapped any pointers, and if FromType and
  2847. // ToType have the same unqualified type (since we checked
  2848. // qualifiers above), then this is a qualification conversion.
  2849. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2850. }
  2851. /// - Determine whether this is a conversion from a scalar type to an
  2852. /// atomic type.
  2853. ///
  2854. /// If successful, updates \c SCS's second and third steps in the conversion
  2855. /// sequence to finish the conversion.
  2856. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2857. bool InOverloadResolution,
  2858. StandardConversionSequence &SCS,
  2859. bool CStyle) {
  2860. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2861. if (!ToAtomic)
  2862. return false;
  2863. StandardConversionSequence InnerSCS;
  2864. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2865. InOverloadResolution, InnerSCS,
  2866. CStyle, /*AllowObjCWritebackConversion=*/false))
  2867. return false;
  2868. SCS.Second = InnerSCS.Second;
  2869. SCS.setToType(1, InnerSCS.getToType(1));
  2870. SCS.Third = InnerSCS.Third;
  2871. SCS.QualificationIncludesObjCLifetime
  2872. = InnerSCS.QualificationIncludesObjCLifetime;
  2873. SCS.setToType(2, InnerSCS.getToType(2));
  2874. return true;
  2875. }
  2876. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2877. CXXConstructorDecl *Constructor,
  2878. QualType Type) {
  2879. const FunctionProtoType *CtorType =
  2880. Constructor->getType()->getAs<FunctionProtoType>();
  2881. if (CtorType->getNumParams() > 0) {
  2882. QualType FirstArg = CtorType->getParamType(0);
  2883. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2884. return true;
  2885. }
  2886. return false;
  2887. }
  2888. static OverloadingResult
  2889. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2890. CXXRecordDecl *To,
  2891. UserDefinedConversionSequence &User,
  2892. OverloadCandidateSet &CandidateSet,
  2893. bool AllowExplicit) {
  2894. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  2895. for (auto *D : S.LookupConstructors(To)) {
  2896. auto Info = getConstructorInfo(D);
  2897. if (!Info)
  2898. continue;
  2899. bool Usable = !Info.Constructor->isInvalidDecl() &&
  2900. S.isInitListConstructor(Info.Constructor) &&
  2901. (AllowExplicit || !Info.Constructor->isExplicit());
  2902. if (Usable) {
  2903. // If the first argument is (a reference to) the target type,
  2904. // suppress conversions.
  2905. bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2906. S.Context, Info.Constructor, ToType);
  2907. if (Info.ConstructorTmpl)
  2908. S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
  2909. /*ExplicitArgs*/ nullptr, From,
  2910. CandidateSet, SuppressUserConversions,
  2911. /*PartialOverloading*/ false,
  2912. AllowExplicit);
  2913. else
  2914. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
  2915. CandidateSet, SuppressUserConversions,
  2916. /*PartialOverloading*/ false, AllowExplicit);
  2917. }
  2918. }
  2919. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2920. OverloadCandidateSet::iterator Best;
  2921. switch (auto Result =
  2922. CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
  2923. case OR_Deleted:
  2924. case OR_Success: {
  2925. // Record the standard conversion we used and the conversion function.
  2926. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2927. QualType ThisType = Constructor->getThisType();
  2928. // Initializer lists don't have conversions as such.
  2929. User.Before.setAsIdentityConversion();
  2930. User.HadMultipleCandidates = HadMultipleCandidates;
  2931. User.ConversionFunction = Constructor;
  2932. User.FoundConversionFunction = Best->FoundDecl;
  2933. User.After.setAsIdentityConversion();
  2934. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2935. User.After.setAllToTypes(ToType);
  2936. return Result;
  2937. }
  2938. case OR_No_Viable_Function:
  2939. return OR_No_Viable_Function;
  2940. case OR_Ambiguous:
  2941. return OR_Ambiguous;
  2942. }
  2943. llvm_unreachable("Invalid OverloadResult!");
  2944. }
  2945. /// Determines whether there is a user-defined conversion sequence
  2946. /// (C++ [over.ics.user]) that converts expression From to the type
  2947. /// ToType. If such a conversion exists, User will contain the
  2948. /// user-defined conversion sequence that performs such a conversion
  2949. /// and this routine will return true. Otherwise, this routine returns
  2950. /// false and User is unspecified.
  2951. ///
  2952. /// \param AllowExplicit true if the conversion should consider C++0x
  2953. /// "explicit" conversion functions as well as non-explicit conversion
  2954. /// functions (C++0x [class.conv.fct]p2).
  2955. ///
  2956. /// \param AllowObjCConversionOnExplicit true if the conversion should
  2957. /// allow an extra Objective-C pointer conversion on uses of explicit
  2958. /// constructors. Requires \c AllowExplicit to also be set.
  2959. static OverloadingResult
  2960. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2961. UserDefinedConversionSequence &User,
  2962. OverloadCandidateSet &CandidateSet,
  2963. bool AllowExplicit,
  2964. bool AllowObjCConversionOnExplicit) {
  2965. assert(AllowExplicit || !AllowObjCConversionOnExplicit);
  2966. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  2967. // Whether we will only visit constructors.
  2968. bool ConstructorsOnly = false;
  2969. // If the type we are conversion to is a class type, enumerate its
  2970. // constructors.
  2971. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2972. // C++ [over.match.ctor]p1:
  2973. // When objects of class type are direct-initialized (8.5), or
  2974. // copy-initialized from an expression of the same or a
  2975. // derived class type (8.5), overload resolution selects the
  2976. // constructor. [...] For copy-initialization, the candidate
  2977. // functions are all the converting constructors (12.3.1) of
  2978. // that class. The argument list is the expression-list within
  2979. // the parentheses of the initializer.
  2980. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  2981. (From->getType()->getAs<RecordType>() &&
  2982. S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
  2983. ConstructorsOnly = true;
  2984. if (!S.isCompleteType(From->getExprLoc(), ToType)) {
  2985. // We're not going to find any constructors.
  2986. } else if (CXXRecordDecl *ToRecordDecl
  2987. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  2988. Expr **Args = &From;
  2989. unsigned NumArgs = 1;
  2990. bool ListInitializing = false;
  2991. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  2992. // But first, see if there is an init-list-constructor that will work.
  2993. OverloadingResult Result = IsInitializerListConstructorConversion(
  2994. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  2995. if (Result != OR_No_Viable_Function)
  2996. return Result;
  2997. // Never mind.
  2998. CandidateSet.clear(
  2999. OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3000. // If we're list-initializing, we pass the individual elements as
  3001. // arguments, not the entire list.
  3002. Args = InitList->getInits();
  3003. NumArgs = InitList->getNumInits();
  3004. ListInitializing = true;
  3005. }
  3006. for (auto *D : S.LookupConstructors(ToRecordDecl)) {
  3007. auto Info = getConstructorInfo(D);
  3008. if (!Info)
  3009. continue;
  3010. bool Usable = !Info.Constructor->isInvalidDecl();
  3011. if (ListInitializing)
  3012. Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
  3013. else
  3014. Usable = Usable &&
  3015. Info.Constructor->isConvertingConstructor(AllowExplicit);
  3016. if (Usable) {
  3017. bool SuppressUserConversions = !ConstructorsOnly;
  3018. if (SuppressUserConversions && ListInitializing) {
  3019. SuppressUserConversions = false;
  3020. if (NumArgs == 1) {
  3021. // If the first argument is (a reference to) the target type,
  3022. // suppress conversions.
  3023. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  3024. S.Context, Info.Constructor, ToType);
  3025. }
  3026. }
  3027. if (Info.ConstructorTmpl)
  3028. S.AddTemplateOverloadCandidate(
  3029. Info.ConstructorTmpl, Info.FoundDecl,
  3030. /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
  3031. CandidateSet, SuppressUserConversions,
  3032. /*PartialOverloading*/ false, AllowExplicit);
  3033. else
  3034. // Allow one user-defined conversion when user specifies a
  3035. // From->ToType conversion via an static cast (c-style, etc).
  3036. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
  3037. llvm::makeArrayRef(Args, NumArgs),
  3038. CandidateSet, SuppressUserConversions,
  3039. /*PartialOverloading*/ false, AllowExplicit);
  3040. }
  3041. }
  3042. }
  3043. }
  3044. // Enumerate conversion functions, if we're allowed to.
  3045. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  3046. } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
  3047. // No conversion functions from incomplete types.
  3048. } else if (const RecordType *FromRecordType =
  3049. From->getType()->getAs<RecordType>()) {
  3050. if (CXXRecordDecl *FromRecordDecl
  3051. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  3052. // Add all of the conversion functions as candidates.
  3053. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  3054. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3055. DeclAccessPair FoundDecl = I.getPair();
  3056. NamedDecl *D = FoundDecl.getDecl();
  3057. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  3058. if (isa<UsingShadowDecl>(D))
  3059. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3060. CXXConversionDecl *Conv;
  3061. FunctionTemplateDecl *ConvTemplate;
  3062. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  3063. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3064. else
  3065. Conv = cast<CXXConversionDecl>(D);
  3066. if (AllowExplicit || !Conv->isExplicit()) {
  3067. if (ConvTemplate)
  3068. S.AddTemplateConversionCandidate(
  3069. ConvTemplate, FoundDecl, ActingContext, From, ToType,
  3070. CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
  3071. else
  3072. S.AddConversionCandidate(
  3073. Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
  3074. AllowObjCConversionOnExplicit, AllowExplicit);
  3075. }
  3076. }
  3077. }
  3078. }
  3079. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3080. OverloadCandidateSet::iterator Best;
  3081. switch (auto Result =
  3082. CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
  3083. case OR_Success:
  3084. case OR_Deleted:
  3085. // Record the standard conversion we used and the conversion function.
  3086. if (CXXConstructorDecl *Constructor
  3087. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  3088. // C++ [over.ics.user]p1:
  3089. // If the user-defined conversion is specified by a
  3090. // constructor (12.3.1), the initial standard conversion
  3091. // sequence converts the source type to the type required by
  3092. // the argument of the constructor.
  3093. //
  3094. QualType ThisType = Constructor->getThisType();
  3095. if (isa<InitListExpr>(From)) {
  3096. // Initializer lists don't have conversions as such.
  3097. User.Before.setAsIdentityConversion();
  3098. } else {
  3099. if (Best->Conversions[0].isEllipsis())
  3100. User.EllipsisConversion = true;
  3101. else {
  3102. User.Before = Best->Conversions[0].Standard;
  3103. User.EllipsisConversion = false;
  3104. }
  3105. }
  3106. User.HadMultipleCandidates = HadMultipleCandidates;
  3107. User.ConversionFunction = Constructor;
  3108. User.FoundConversionFunction = Best->FoundDecl;
  3109. User.After.setAsIdentityConversion();
  3110. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  3111. User.After.setAllToTypes(ToType);
  3112. return Result;
  3113. }
  3114. if (CXXConversionDecl *Conversion
  3115. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  3116. // C++ [over.ics.user]p1:
  3117. //
  3118. // [...] If the user-defined conversion is specified by a
  3119. // conversion function (12.3.2), the initial standard
  3120. // conversion sequence converts the source type to the
  3121. // implicit object parameter of the conversion function.
  3122. User.Before = Best->Conversions[0].Standard;
  3123. User.HadMultipleCandidates = HadMultipleCandidates;
  3124. User.ConversionFunction = Conversion;
  3125. User.FoundConversionFunction = Best->FoundDecl;
  3126. User.EllipsisConversion = false;
  3127. // C++ [over.ics.user]p2:
  3128. // The second standard conversion sequence converts the
  3129. // result of the user-defined conversion to the target type
  3130. // for the sequence. Since an implicit conversion sequence
  3131. // is an initialization, the special rules for
  3132. // initialization by user-defined conversion apply when
  3133. // selecting the best user-defined conversion for a
  3134. // user-defined conversion sequence (see 13.3.3 and
  3135. // 13.3.3.1).
  3136. User.After = Best->FinalConversion;
  3137. return Result;
  3138. }
  3139. llvm_unreachable("Not a constructor or conversion function?");
  3140. case OR_No_Viable_Function:
  3141. return OR_No_Viable_Function;
  3142. case OR_Ambiguous:
  3143. return OR_Ambiguous;
  3144. }
  3145. llvm_unreachable("Invalid OverloadResult!");
  3146. }
  3147. bool
  3148. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  3149. ImplicitConversionSequence ICS;
  3150. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  3151. OverloadCandidateSet::CSK_Normal);
  3152. OverloadingResult OvResult =
  3153. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  3154. CandidateSet, false, false);
  3155. if (!(OvResult == OR_Ambiguous ||
  3156. (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
  3157. return false;
  3158. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
  3159. if (OvResult == OR_Ambiguous)
  3160. Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
  3161. << From->getType() << ToType << From->getSourceRange();
  3162. else { // OR_No_Viable_Function && !CandidateSet.empty()
  3163. if (!RequireCompleteType(From->getBeginLoc(), ToType,
  3164. diag::err_typecheck_nonviable_condition_incomplete,
  3165. From->getType(), From->getSourceRange()))
  3166. Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
  3167. << false << From->getType() << From->getSourceRange() << ToType;
  3168. }
  3169. CandidateSet.NoteCandidates(
  3170. *this, From, Cands);
  3171. return true;
  3172. }
  3173. /// Compare the user-defined conversion functions or constructors
  3174. /// of two user-defined conversion sequences to determine whether any ordering
  3175. /// is possible.
  3176. static ImplicitConversionSequence::CompareKind
  3177. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  3178. FunctionDecl *Function2) {
  3179. if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
  3180. return ImplicitConversionSequence::Indistinguishable;
  3181. // Objective-C++:
  3182. // If both conversion functions are implicitly-declared conversions from
  3183. // a lambda closure type to a function pointer and a block pointer,
  3184. // respectively, always prefer the conversion to a function pointer,
  3185. // because the function pointer is more lightweight and is more likely
  3186. // to keep code working.
  3187. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  3188. if (!Conv1)
  3189. return ImplicitConversionSequence::Indistinguishable;
  3190. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  3191. if (!Conv2)
  3192. return ImplicitConversionSequence::Indistinguishable;
  3193. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  3194. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  3195. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  3196. if (Block1 != Block2)
  3197. return Block1 ? ImplicitConversionSequence::Worse
  3198. : ImplicitConversionSequence::Better;
  3199. }
  3200. return ImplicitConversionSequence::Indistinguishable;
  3201. }
  3202. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  3203. const ImplicitConversionSequence &ICS) {
  3204. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  3205. (ICS.isUserDefined() &&
  3206. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  3207. }
  3208. /// CompareImplicitConversionSequences - Compare two implicit
  3209. /// conversion sequences to determine whether one is better than the
  3210. /// other or if they are indistinguishable (C++ 13.3.3.2).
  3211. static ImplicitConversionSequence::CompareKind
  3212. CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
  3213. const ImplicitConversionSequence& ICS1,
  3214. const ImplicitConversionSequence& ICS2)
  3215. {
  3216. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  3217. // conversion sequences (as defined in 13.3.3.1)
  3218. // -- a standard conversion sequence (13.3.3.1.1) is a better
  3219. // conversion sequence than a user-defined conversion sequence or
  3220. // an ellipsis conversion sequence, and
  3221. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3222. // conversion sequence than an ellipsis conversion sequence
  3223. // (13.3.3.1.3).
  3224. //
  3225. // C++0x [over.best.ics]p10:
  3226. // For the purpose of ranking implicit conversion sequences as
  3227. // described in 13.3.3.2, the ambiguous conversion sequence is
  3228. // treated as a user-defined sequence that is indistinguishable
  3229. // from any other user-defined conversion sequence.
  3230. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3231. // been removed from C++11. We still accept this conversion, if it happens at
  3232. // the best viable function. Otherwise, this conversion is considered worse
  3233. // than ellipsis conversion. Consider this as an extension; this is not in the
  3234. // standard. For example:
  3235. //
  3236. // int &f(...); // #1
  3237. // void f(char*); // #2
  3238. // void g() { int &r = f("foo"); }
  3239. //
  3240. // In C++03, we pick #2 as the best viable function.
  3241. // In C++11, we pick #1 as the best viable function, because ellipsis
  3242. // conversion is better than string-literal to char* conversion (since there
  3243. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3244. // convert arguments, #2 would be the best viable function in C++11.
  3245. // If the best viable function has this conversion, a warning will be issued
  3246. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3247. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3248. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3249. hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
  3250. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3251. ? ImplicitConversionSequence::Worse
  3252. : ImplicitConversionSequence::Better;
  3253. if (ICS1.getKindRank() < ICS2.getKindRank())
  3254. return ImplicitConversionSequence::Better;
  3255. if (ICS2.getKindRank() < ICS1.getKindRank())
  3256. return ImplicitConversionSequence::Worse;
  3257. // The following checks require both conversion sequences to be of
  3258. // the same kind.
  3259. if (ICS1.getKind() != ICS2.getKind())
  3260. return ImplicitConversionSequence::Indistinguishable;
  3261. ImplicitConversionSequence::CompareKind Result =
  3262. ImplicitConversionSequence::Indistinguishable;
  3263. // Two implicit conversion sequences of the same form are
  3264. // indistinguishable conversion sequences unless one of the
  3265. // following rules apply: (C++ 13.3.3.2p3):
  3266. // List-initialization sequence L1 is a better conversion sequence than
  3267. // list-initialization sequence L2 if:
  3268. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3269. // if not that,
  3270. // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
  3271. // and N1 is smaller than N2.,
  3272. // even if one of the other rules in this paragraph would otherwise apply.
  3273. if (!ICS1.isBad()) {
  3274. if (ICS1.isStdInitializerListElement() &&
  3275. !ICS2.isStdInitializerListElement())
  3276. return ImplicitConversionSequence::Better;
  3277. if (!ICS1.isStdInitializerListElement() &&
  3278. ICS2.isStdInitializerListElement())
  3279. return ImplicitConversionSequence::Worse;
  3280. }
  3281. if (ICS1.isStandard())
  3282. // Standard conversion sequence S1 is a better conversion sequence than
  3283. // standard conversion sequence S2 if [...]
  3284. Result = CompareStandardConversionSequences(S, Loc,
  3285. ICS1.Standard, ICS2.Standard);
  3286. else if (ICS1.isUserDefined()) {
  3287. // User-defined conversion sequence U1 is a better conversion
  3288. // sequence than another user-defined conversion sequence U2 if
  3289. // they contain the same user-defined conversion function or
  3290. // constructor and if the second standard conversion sequence of
  3291. // U1 is better than the second standard conversion sequence of
  3292. // U2 (C++ 13.3.3.2p3).
  3293. if (ICS1.UserDefined.ConversionFunction ==
  3294. ICS2.UserDefined.ConversionFunction)
  3295. Result = CompareStandardConversionSequences(S, Loc,
  3296. ICS1.UserDefined.After,
  3297. ICS2.UserDefined.After);
  3298. else
  3299. Result = compareConversionFunctions(S,
  3300. ICS1.UserDefined.ConversionFunction,
  3301. ICS2.UserDefined.ConversionFunction);
  3302. }
  3303. return Result;
  3304. }
  3305. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3306. // determine if one is a proper subset of the other.
  3307. static ImplicitConversionSequence::CompareKind
  3308. compareStandardConversionSubsets(ASTContext &Context,
  3309. const StandardConversionSequence& SCS1,
  3310. const StandardConversionSequence& SCS2) {
  3311. ImplicitConversionSequence::CompareKind Result
  3312. = ImplicitConversionSequence::Indistinguishable;
  3313. // the identity conversion sequence is considered to be a subsequence of
  3314. // any non-identity conversion sequence
  3315. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3316. return ImplicitConversionSequence::Better;
  3317. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3318. return ImplicitConversionSequence::Worse;
  3319. if (SCS1.Second != SCS2.Second) {
  3320. if (SCS1.Second == ICK_Identity)
  3321. Result = ImplicitConversionSequence::Better;
  3322. else if (SCS2.Second == ICK_Identity)
  3323. Result = ImplicitConversionSequence::Worse;
  3324. else
  3325. return ImplicitConversionSequence::Indistinguishable;
  3326. } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
  3327. return ImplicitConversionSequence::Indistinguishable;
  3328. if (SCS1.Third == SCS2.Third) {
  3329. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3330. : ImplicitConversionSequence::Indistinguishable;
  3331. }
  3332. if (SCS1.Third == ICK_Identity)
  3333. return Result == ImplicitConversionSequence::Worse
  3334. ? ImplicitConversionSequence::Indistinguishable
  3335. : ImplicitConversionSequence::Better;
  3336. if (SCS2.Third == ICK_Identity)
  3337. return Result == ImplicitConversionSequence::Better
  3338. ? ImplicitConversionSequence::Indistinguishable
  3339. : ImplicitConversionSequence::Worse;
  3340. return ImplicitConversionSequence::Indistinguishable;
  3341. }
  3342. /// Determine whether one of the given reference bindings is better
  3343. /// than the other based on what kind of bindings they are.
  3344. static bool
  3345. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3346. const StandardConversionSequence &SCS2) {
  3347. // C++0x [over.ics.rank]p3b4:
  3348. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3349. // implicit object parameter of a non-static member function declared
  3350. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3351. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3352. // lvalue reference to a function lvalue and S2 binds an rvalue
  3353. // reference*.
  3354. //
  3355. // FIXME: Rvalue references. We're going rogue with the above edits,
  3356. // because the semantics in the current C++0x working paper (N3225 at the
  3357. // time of this writing) break the standard definition of std::forward
  3358. // and std::reference_wrapper when dealing with references to functions.
  3359. // Proposed wording changes submitted to CWG for consideration.
  3360. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3361. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3362. return false;
  3363. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3364. SCS2.IsLvalueReference) ||
  3365. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3366. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3367. }
  3368. /// CompareStandardConversionSequences - Compare two standard
  3369. /// conversion sequences to determine whether one is better than the
  3370. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3371. static ImplicitConversionSequence::CompareKind
  3372. CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
  3373. const StandardConversionSequence& SCS1,
  3374. const StandardConversionSequence& SCS2)
  3375. {
  3376. // Standard conversion sequence S1 is a better conversion sequence
  3377. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3378. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3379. // sequences in the canonical form defined by 13.3.3.1.1,
  3380. // excluding any Lvalue Transformation; the identity conversion
  3381. // sequence is considered to be a subsequence of any
  3382. // non-identity conversion sequence) or, if not that,
  3383. if (ImplicitConversionSequence::CompareKind CK
  3384. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3385. return CK;
  3386. // -- the rank of S1 is better than the rank of S2 (by the rules
  3387. // defined below), or, if not that,
  3388. ImplicitConversionRank Rank1 = SCS1.getRank();
  3389. ImplicitConversionRank Rank2 = SCS2.getRank();
  3390. if (Rank1 < Rank2)
  3391. return ImplicitConversionSequence::Better;
  3392. else if (Rank2 < Rank1)
  3393. return ImplicitConversionSequence::Worse;
  3394. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3395. // are indistinguishable unless one of the following rules
  3396. // applies:
  3397. // A conversion that is not a conversion of a pointer, or
  3398. // pointer to member, to bool is better than another conversion
  3399. // that is such a conversion.
  3400. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3401. return SCS2.isPointerConversionToBool()
  3402. ? ImplicitConversionSequence::Better
  3403. : ImplicitConversionSequence::Worse;
  3404. // C++ [over.ics.rank]p4b2:
  3405. //
  3406. // If class B is derived directly or indirectly from class A,
  3407. // conversion of B* to A* is better than conversion of B* to
  3408. // void*, and conversion of A* to void* is better than conversion
  3409. // of B* to void*.
  3410. bool SCS1ConvertsToVoid
  3411. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3412. bool SCS2ConvertsToVoid
  3413. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3414. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3415. // Exactly one of the conversion sequences is a conversion to
  3416. // a void pointer; it's the worse conversion.
  3417. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3418. : ImplicitConversionSequence::Worse;
  3419. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3420. // Neither conversion sequence converts to a void pointer; compare
  3421. // their derived-to-base conversions.
  3422. if (ImplicitConversionSequence::CompareKind DerivedCK
  3423. = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
  3424. return DerivedCK;
  3425. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3426. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3427. // Both conversion sequences are conversions to void
  3428. // pointers. Compare the source types to determine if there's an
  3429. // inheritance relationship in their sources.
  3430. QualType FromType1 = SCS1.getFromType();
  3431. QualType FromType2 = SCS2.getFromType();
  3432. // Adjust the types we're converting from via the array-to-pointer
  3433. // conversion, if we need to.
  3434. if (SCS1.First == ICK_Array_To_Pointer)
  3435. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3436. if (SCS2.First == ICK_Array_To_Pointer)
  3437. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3438. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3439. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3440. if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3441. return ImplicitConversionSequence::Better;
  3442. else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3443. return ImplicitConversionSequence::Worse;
  3444. // Objective-C++: If one interface is more specific than the
  3445. // other, it is the better one.
  3446. const ObjCObjectPointerType* FromObjCPtr1
  3447. = FromType1->getAs<ObjCObjectPointerType>();
  3448. const ObjCObjectPointerType* FromObjCPtr2
  3449. = FromType2->getAs<ObjCObjectPointerType>();
  3450. if (FromObjCPtr1 && FromObjCPtr2) {
  3451. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3452. FromObjCPtr2);
  3453. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3454. FromObjCPtr1);
  3455. if (AssignLeft != AssignRight) {
  3456. return AssignLeft? ImplicitConversionSequence::Better
  3457. : ImplicitConversionSequence::Worse;
  3458. }
  3459. }
  3460. }
  3461. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3462. // bullet 3).
  3463. if (ImplicitConversionSequence::CompareKind QualCK
  3464. = CompareQualificationConversions(S, SCS1, SCS2))
  3465. return QualCK;
  3466. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3467. // Check for a better reference binding based on the kind of bindings.
  3468. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3469. return ImplicitConversionSequence::Better;
  3470. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3471. return ImplicitConversionSequence::Worse;
  3472. // C++ [over.ics.rank]p3b4:
  3473. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3474. // which the references refer are the same type except for
  3475. // top-level cv-qualifiers, and the type to which the reference
  3476. // initialized by S2 refers is more cv-qualified than the type
  3477. // to which the reference initialized by S1 refers.
  3478. QualType T1 = SCS1.getToType(2);
  3479. QualType T2 = SCS2.getToType(2);
  3480. T1 = S.Context.getCanonicalType(T1);
  3481. T2 = S.Context.getCanonicalType(T2);
  3482. Qualifiers T1Quals, T2Quals;
  3483. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3484. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3485. if (UnqualT1 == UnqualT2) {
  3486. // Objective-C++ ARC: If the references refer to objects with different
  3487. // lifetimes, prefer bindings that don't change lifetime.
  3488. if (SCS1.ObjCLifetimeConversionBinding !=
  3489. SCS2.ObjCLifetimeConversionBinding) {
  3490. return SCS1.ObjCLifetimeConversionBinding
  3491. ? ImplicitConversionSequence::Worse
  3492. : ImplicitConversionSequence::Better;
  3493. }
  3494. // If the type is an array type, promote the element qualifiers to the
  3495. // type for comparison.
  3496. if (isa<ArrayType>(T1) && T1Quals)
  3497. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3498. if (isa<ArrayType>(T2) && T2Quals)
  3499. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3500. if (T2.isMoreQualifiedThan(T1))
  3501. return ImplicitConversionSequence::Better;
  3502. else if (T1.isMoreQualifiedThan(T2))
  3503. return ImplicitConversionSequence::Worse;
  3504. }
  3505. }
  3506. // In Microsoft mode, prefer an integral conversion to a
  3507. // floating-to-integral conversion if the integral conversion
  3508. // is between types of the same size.
  3509. // For example:
  3510. // void f(float);
  3511. // void f(int);
  3512. // int main {
  3513. // long a;
  3514. // f(a);
  3515. // }
  3516. // Here, MSVC will call f(int) instead of generating a compile error
  3517. // as clang will do in standard mode.
  3518. if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
  3519. SCS2.Second == ICK_Floating_Integral &&
  3520. S.Context.getTypeSize(SCS1.getFromType()) ==
  3521. S.Context.getTypeSize(SCS1.getToType(2)))
  3522. return ImplicitConversionSequence::Better;
  3523. // Prefer a compatible vector conversion over a lax vector conversion
  3524. // For example:
  3525. //
  3526. // typedef float __v4sf __attribute__((__vector_size__(16)));
  3527. // void f(vector float);
  3528. // void f(vector signed int);
  3529. // int main() {
  3530. // __v4sf a;
  3531. // f(a);
  3532. // }
  3533. // Here, we'd like to choose f(vector float) and not
  3534. // report an ambiguous call error
  3535. if (SCS1.Second == ICK_Vector_Conversion &&
  3536. SCS2.Second == ICK_Vector_Conversion) {
  3537. bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
  3538. SCS1.getFromType(), SCS1.getToType(2));
  3539. bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
  3540. SCS2.getFromType(), SCS2.getToType(2));
  3541. if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
  3542. return SCS1IsCompatibleVectorConversion
  3543. ? ImplicitConversionSequence::Better
  3544. : ImplicitConversionSequence::Worse;
  3545. }
  3546. return ImplicitConversionSequence::Indistinguishable;
  3547. }
  3548. /// CompareQualificationConversions - Compares two standard conversion
  3549. /// sequences to determine whether they can be ranked based on their
  3550. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3551. static ImplicitConversionSequence::CompareKind
  3552. CompareQualificationConversions(Sema &S,
  3553. const StandardConversionSequence& SCS1,
  3554. const StandardConversionSequence& SCS2) {
  3555. // C++ 13.3.3.2p3:
  3556. // -- S1 and S2 differ only in their qualification conversion and
  3557. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3558. // cv-qualification signature of type T1 is a proper subset of
  3559. // the cv-qualification signature of type T2, and S1 is not the
  3560. // deprecated string literal array-to-pointer conversion (4.2).
  3561. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3562. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3563. return ImplicitConversionSequence::Indistinguishable;
  3564. // FIXME: the example in the standard doesn't use a qualification
  3565. // conversion (!)
  3566. QualType T1 = SCS1.getToType(2);
  3567. QualType T2 = SCS2.getToType(2);
  3568. T1 = S.Context.getCanonicalType(T1);
  3569. T2 = S.Context.getCanonicalType(T2);
  3570. Qualifiers T1Quals, T2Quals;
  3571. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3572. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3573. // If the types are the same, we won't learn anything by unwrapped
  3574. // them.
  3575. if (UnqualT1 == UnqualT2)
  3576. return ImplicitConversionSequence::Indistinguishable;
  3577. // If the type is an array type, promote the element qualifiers to the type
  3578. // for comparison.
  3579. if (isa<ArrayType>(T1) && T1Quals)
  3580. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3581. if (isa<ArrayType>(T2) && T2Quals)
  3582. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3583. ImplicitConversionSequence::CompareKind Result
  3584. = ImplicitConversionSequence::Indistinguishable;
  3585. // Objective-C++ ARC:
  3586. // Prefer qualification conversions not involving a change in lifetime
  3587. // to qualification conversions that do not change lifetime.
  3588. if (SCS1.QualificationIncludesObjCLifetime !=
  3589. SCS2.QualificationIncludesObjCLifetime) {
  3590. Result = SCS1.QualificationIncludesObjCLifetime
  3591. ? ImplicitConversionSequence::Worse
  3592. : ImplicitConversionSequence::Better;
  3593. }
  3594. while (S.Context.UnwrapSimilarTypes(T1, T2)) {
  3595. // Within each iteration of the loop, we check the qualifiers to
  3596. // determine if this still looks like a qualification
  3597. // conversion. Then, if all is well, we unwrap one more level of
  3598. // pointers or pointers-to-members and do it all again
  3599. // until there are no more pointers or pointers-to-members left
  3600. // to unwrap. This essentially mimics what
  3601. // IsQualificationConversion does, but here we're checking for a
  3602. // strict subset of qualifiers.
  3603. if (T1.getQualifiers().withoutObjCLifetime() ==
  3604. T2.getQualifiers().withoutObjCLifetime())
  3605. // The qualifiers are the same, so this doesn't tell us anything
  3606. // about how the sequences rank.
  3607. // ObjC ownership quals are omitted above as they interfere with
  3608. // the ARC overload rule.
  3609. ;
  3610. else if (T2.isMoreQualifiedThan(T1)) {
  3611. // T1 has fewer qualifiers, so it could be the better sequence.
  3612. if (Result == ImplicitConversionSequence::Worse)
  3613. // Neither has qualifiers that are a subset of the other's
  3614. // qualifiers.
  3615. return ImplicitConversionSequence::Indistinguishable;
  3616. Result = ImplicitConversionSequence::Better;
  3617. } else if (T1.isMoreQualifiedThan(T2)) {
  3618. // T2 has fewer qualifiers, so it could be the better sequence.
  3619. if (Result == ImplicitConversionSequence::Better)
  3620. // Neither has qualifiers that are a subset of the other's
  3621. // qualifiers.
  3622. return ImplicitConversionSequence::Indistinguishable;
  3623. Result = ImplicitConversionSequence::Worse;
  3624. } else {
  3625. // Qualifiers are disjoint.
  3626. return ImplicitConversionSequence::Indistinguishable;
  3627. }
  3628. // If the types after this point are equivalent, we're done.
  3629. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3630. break;
  3631. }
  3632. // Check that the winning standard conversion sequence isn't using
  3633. // the deprecated string literal array to pointer conversion.
  3634. switch (Result) {
  3635. case ImplicitConversionSequence::Better:
  3636. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3637. Result = ImplicitConversionSequence::Indistinguishable;
  3638. break;
  3639. case ImplicitConversionSequence::Indistinguishable:
  3640. break;
  3641. case ImplicitConversionSequence::Worse:
  3642. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3643. Result = ImplicitConversionSequence::Indistinguishable;
  3644. break;
  3645. }
  3646. return Result;
  3647. }
  3648. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3649. /// sequences to determine whether they can be ranked based on their
  3650. /// various kinds of derived-to-base conversions (C++
  3651. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3652. /// conversions between Objective-C interface types.
  3653. static ImplicitConversionSequence::CompareKind
  3654. CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
  3655. const StandardConversionSequence& SCS1,
  3656. const StandardConversionSequence& SCS2) {
  3657. QualType FromType1 = SCS1.getFromType();
  3658. QualType ToType1 = SCS1.getToType(1);
  3659. QualType FromType2 = SCS2.getFromType();
  3660. QualType ToType2 = SCS2.getToType(1);
  3661. // Adjust the types we're converting from via the array-to-pointer
  3662. // conversion, if we need to.
  3663. if (SCS1.First == ICK_Array_To_Pointer)
  3664. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3665. if (SCS2.First == ICK_Array_To_Pointer)
  3666. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3667. // Canonicalize all of the types.
  3668. FromType1 = S.Context.getCanonicalType(FromType1);
  3669. ToType1 = S.Context.getCanonicalType(ToType1);
  3670. FromType2 = S.Context.getCanonicalType(FromType2);
  3671. ToType2 = S.Context.getCanonicalType(ToType2);
  3672. // C++ [over.ics.rank]p4b3:
  3673. //
  3674. // If class B is derived directly or indirectly from class A and
  3675. // class C is derived directly or indirectly from B,
  3676. //
  3677. // Compare based on pointer conversions.
  3678. if (SCS1.Second == ICK_Pointer_Conversion &&
  3679. SCS2.Second == ICK_Pointer_Conversion &&
  3680. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3681. FromType1->isPointerType() && FromType2->isPointerType() &&
  3682. ToType1->isPointerType() && ToType2->isPointerType()) {
  3683. QualType FromPointee1
  3684. = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3685. QualType ToPointee1
  3686. = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3687. QualType FromPointee2
  3688. = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3689. QualType ToPointee2
  3690. = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3691. // -- conversion of C* to B* is better than conversion of C* to A*,
  3692. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3693. if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
  3694. return ImplicitConversionSequence::Better;
  3695. else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
  3696. return ImplicitConversionSequence::Worse;
  3697. }
  3698. // -- conversion of B* to A* is better than conversion of C* to A*,
  3699. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3700. if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3701. return ImplicitConversionSequence::Better;
  3702. else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3703. return ImplicitConversionSequence::Worse;
  3704. }
  3705. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3706. SCS2.Second == ICK_Pointer_Conversion) {
  3707. const ObjCObjectPointerType *FromPtr1
  3708. = FromType1->getAs<ObjCObjectPointerType>();
  3709. const ObjCObjectPointerType *FromPtr2
  3710. = FromType2->getAs<ObjCObjectPointerType>();
  3711. const ObjCObjectPointerType *ToPtr1
  3712. = ToType1->getAs<ObjCObjectPointerType>();
  3713. const ObjCObjectPointerType *ToPtr2
  3714. = ToType2->getAs<ObjCObjectPointerType>();
  3715. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3716. // Apply the same conversion ranking rules for Objective-C pointer types
  3717. // that we do for C++ pointers to class types. However, we employ the
  3718. // Objective-C pseudo-subtyping relationship used for assignment of
  3719. // Objective-C pointer types.
  3720. bool FromAssignLeft
  3721. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3722. bool FromAssignRight
  3723. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3724. bool ToAssignLeft
  3725. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3726. bool ToAssignRight
  3727. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3728. // A conversion to an a non-id object pointer type or qualified 'id'
  3729. // type is better than a conversion to 'id'.
  3730. if (ToPtr1->isObjCIdType() &&
  3731. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3732. return ImplicitConversionSequence::Worse;
  3733. if (ToPtr2->isObjCIdType() &&
  3734. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3735. return ImplicitConversionSequence::Better;
  3736. // A conversion to a non-id object pointer type is better than a
  3737. // conversion to a qualified 'id' type
  3738. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3739. return ImplicitConversionSequence::Worse;
  3740. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3741. return ImplicitConversionSequence::Better;
  3742. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3743. // type is better than a conversion to 'Class'.
  3744. if (ToPtr1->isObjCClassType() &&
  3745. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3746. return ImplicitConversionSequence::Worse;
  3747. if (ToPtr2->isObjCClassType() &&
  3748. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3749. return ImplicitConversionSequence::Better;
  3750. // A conversion to a non-Class object pointer type is better than a
  3751. // conversion to a qualified 'Class' type.
  3752. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3753. return ImplicitConversionSequence::Worse;
  3754. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3755. return ImplicitConversionSequence::Better;
  3756. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3757. if (S.Context.hasSameType(FromType1, FromType2) &&
  3758. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3759. (ToAssignLeft != ToAssignRight)) {
  3760. if (FromPtr1->isSpecialized()) {
  3761. // "conversion of B<A> * to B * is better than conversion of B * to
  3762. // C *.
  3763. bool IsFirstSame =
  3764. FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
  3765. bool IsSecondSame =
  3766. FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
  3767. if (IsFirstSame) {
  3768. if (!IsSecondSame)
  3769. return ImplicitConversionSequence::Better;
  3770. } else if (IsSecondSame)
  3771. return ImplicitConversionSequence::Worse;
  3772. }
  3773. return ToAssignLeft? ImplicitConversionSequence::Worse
  3774. : ImplicitConversionSequence::Better;
  3775. }
  3776. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3777. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3778. (FromAssignLeft != FromAssignRight))
  3779. return FromAssignLeft? ImplicitConversionSequence::Better
  3780. : ImplicitConversionSequence::Worse;
  3781. }
  3782. }
  3783. // Ranking of member-pointer types.
  3784. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3785. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3786. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3787. const MemberPointerType * FromMemPointer1 =
  3788. FromType1->getAs<MemberPointerType>();
  3789. const MemberPointerType * ToMemPointer1 =
  3790. ToType1->getAs<MemberPointerType>();
  3791. const MemberPointerType * FromMemPointer2 =
  3792. FromType2->getAs<MemberPointerType>();
  3793. const MemberPointerType * ToMemPointer2 =
  3794. ToType2->getAs<MemberPointerType>();
  3795. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3796. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3797. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3798. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3799. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3800. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3801. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3802. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3803. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3804. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3805. if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
  3806. return ImplicitConversionSequence::Worse;
  3807. else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
  3808. return ImplicitConversionSequence::Better;
  3809. }
  3810. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3811. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3812. if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3813. return ImplicitConversionSequence::Better;
  3814. else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3815. return ImplicitConversionSequence::Worse;
  3816. }
  3817. }
  3818. if (SCS1.Second == ICK_Derived_To_Base) {
  3819. // -- conversion of C to B is better than conversion of C to A,
  3820. // -- binding of an expression of type C to a reference of type
  3821. // B& is better than binding an expression of type C to a
  3822. // reference of type A&,
  3823. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3824. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3825. if (S.IsDerivedFrom(Loc, ToType1, ToType2))
  3826. return ImplicitConversionSequence::Better;
  3827. else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
  3828. return ImplicitConversionSequence::Worse;
  3829. }
  3830. // -- conversion of B to A is better than conversion of C to A.
  3831. // -- binding of an expression of type B to a reference of type
  3832. // A& is better than binding an expression of type C to a
  3833. // reference of type A&,
  3834. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3835. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3836. if (S.IsDerivedFrom(Loc, FromType2, FromType1))
  3837. return ImplicitConversionSequence::Better;
  3838. else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
  3839. return ImplicitConversionSequence::Worse;
  3840. }
  3841. }
  3842. return ImplicitConversionSequence::Indistinguishable;
  3843. }
  3844. /// Determine whether the given type is valid, e.g., it is not an invalid
  3845. /// C++ class.
  3846. static bool isTypeValid(QualType T) {
  3847. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3848. return !Record->isInvalidDecl();
  3849. return true;
  3850. }
  3851. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3852. /// determine whether they are reference-related,
  3853. /// reference-compatible, reference-compatible with added
  3854. /// qualification, or incompatible, for use in C++ initialization by
  3855. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3856. /// type, and the first type (T1) is the pointee type of the reference
  3857. /// type being initialized.
  3858. Sema::ReferenceCompareResult
  3859. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3860. QualType OrigT1, QualType OrigT2,
  3861. bool &DerivedToBase,
  3862. bool &ObjCConversion,
  3863. bool &ObjCLifetimeConversion) {
  3864. assert(!OrigT1->isReferenceType() &&
  3865. "T1 must be the pointee type of the reference type");
  3866. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3867. QualType T1 = Context.getCanonicalType(OrigT1);
  3868. QualType T2 = Context.getCanonicalType(OrigT2);
  3869. Qualifiers T1Quals, T2Quals;
  3870. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3871. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3872. // C++ [dcl.init.ref]p4:
  3873. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3874. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3875. // T1 is a base class of T2.
  3876. DerivedToBase = false;
  3877. ObjCConversion = false;
  3878. ObjCLifetimeConversion = false;
  3879. QualType ConvertedT2;
  3880. if (UnqualT1 == UnqualT2) {
  3881. // Nothing to do.
  3882. } else if (isCompleteType(Loc, OrigT2) &&
  3883. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3884. IsDerivedFrom(Loc, UnqualT2, UnqualT1))
  3885. DerivedToBase = true;
  3886. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3887. UnqualT2->isObjCObjectOrInterfaceType() &&
  3888. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3889. ObjCConversion = true;
  3890. else if (UnqualT2->isFunctionType() &&
  3891. IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
  3892. // C++1z [dcl.init.ref]p4:
  3893. // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
  3894. // function" and T1 is "function"
  3895. //
  3896. // We extend this to also apply to 'noreturn', so allow any function
  3897. // conversion between function types.
  3898. return Ref_Compatible;
  3899. else
  3900. return Ref_Incompatible;
  3901. // At this point, we know that T1 and T2 are reference-related (at
  3902. // least).
  3903. // If the type is an array type, promote the element qualifiers to the type
  3904. // for comparison.
  3905. if (isa<ArrayType>(T1) && T1Quals)
  3906. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3907. if (isa<ArrayType>(T2) && T2Quals)
  3908. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3909. // C++ [dcl.init.ref]p4:
  3910. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3911. // reference-related to T2 and cv1 is the same cv-qualification
  3912. // as, or greater cv-qualification than, cv2. For purposes of
  3913. // overload resolution, cases for which cv1 is greater
  3914. // cv-qualification than cv2 are identified as
  3915. // reference-compatible with added qualification (see 13.3.3.2).
  3916. //
  3917. // Note that we also require equivalence of Objective-C GC and address-space
  3918. // qualifiers when performing these computations, so that e.g., an int in
  3919. // address space 1 is not reference-compatible with an int in address
  3920. // space 2.
  3921. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3922. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3923. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3924. ObjCLifetimeConversion = true;
  3925. T1Quals.removeObjCLifetime();
  3926. T2Quals.removeObjCLifetime();
  3927. }
  3928. // MS compiler ignores __unaligned qualifier for references; do the same.
  3929. T1Quals.removeUnaligned();
  3930. T2Quals.removeUnaligned();
  3931. if (T1Quals.compatiblyIncludes(T2Quals))
  3932. return Ref_Compatible;
  3933. else
  3934. return Ref_Related;
  3935. }
  3936. /// Look for a user-defined conversion to a value reference-compatible
  3937. /// with DeclType. Return true if something definite is found.
  3938. static bool
  3939. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  3940. QualType DeclType, SourceLocation DeclLoc,
  3941. Expr *Init, QualType T2, bool AllowRvalues,
  3942. bool AllowExplicit) {
  3943. assert(T2->isRecordType() && "Can only find conversions of record types.");
  3944. CXXRecordDecl *T2RecordDecl
  3945. = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
  3946. OverloadCandidateSet CandidateSet(
  3947. DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3948. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3949. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3950. NamedDecl *D = *I;
  3951. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3952. if (isa<UsingShadowDecl>(D))
  3953. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3954. FunctionTemplateDecl *ConvTemplate
  3955. = dyn_cast<FunctionTemplateDecl>(D);
  3956. CXXConversionDecl *Conv;
  3957. if (ConvTemplate)
  3958. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3959. else
  3960. Conv = cast<CXXConversionDecl>(D);
  3961. // If this is an explicit conversion, and we're not allowed to consider
  3962. // explicit conversions, skip it.
  3963. if (!AllowExplicit && Conv->isExplicit())
  3964. continue;
  3965. if (AllowRvalues) {
  3966. bool DerivedToBase = false;
  3967. bool ObjCConversion = false;
  3968. bool ObjCLifetimeConversion = false;
  3969. // If we are initializing an rvalue reference, don't permit conversion
  3970. // functions that return lvalues.
  3971. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  3972. const ReferenceType *RefType
  3973. = Conv->getConversionType()->getAs<LValueReferenceType>();
  3974. if (RefType && !RefType->getPointeeType()->isFunctionType())
  3975. continue;
  3976. }
  3977. if (!ConvTemplate &&
  3978. S.CompareReferenceRelationship(
  3979. DeclLoc,
  3980. Conv->getConversionType().getNonReferenceType()
  3981. .getUnqualifiedType(),
  3982. DeclType.getNonReferenceType().getUnqualifiedType(),
  3983. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  3984. Sema::Ref_Incompatible)
  3985. continue;
  3986. } else {
  3987. // If the conversion function doesn't return a reference type,
  3988. // it can't be considered for this conversion. An rvalue reference
  3989. // is only acceptable if its referencee is a function type.
  3990. const ReferenceType *RefType =
  3991. Conv->getConversionType()->getAs<ReferenceType>();
  3992. if (!RefType ||
  3993. (!RefType->isLValueReferenceType() &&
  3994. !RefType->getPointeeType()->isFunctionType()))
  3995. continue;
  3996. }
  3997. if (ConvTemplate)
  3998. S.AddTemplateConversionCandidate(
  3999. ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4000. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4001. else
  4002. S.AddConversionCandidate(
  4003. Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4004. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4005. }
  4006. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4007. OverloadCandidateSet::iterator Best;
  4008. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  4009. case OR_Success:
  4010. // C++ [over.ics.ref]p1:
  4011. //
  4012. // [...] If the parameter binds directly to the result of
  4013. // applying a conversion function to the argument
  4014. // expression, the implicit conversion sequence is a
  4015. // user-defined conversion sequence (13.3.3.1.2), with the
  4016. // second standard conversion sequence either an identity
  4017. // conversion or, if the conversion function returns an
  4018. // entity of a type that is a derived class of the parameter
  4019. // type, a derived-to-base Conversion.
  4020. if (!Best->FinalConversion.DirectBinding)
  4021. return false;
  4022. ICS.setUserDefined();
  4023. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  4024. ICS.UserDefined.After = Best->FinalConversion;
  4025. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  4026. ICS.UserDefined.ConversionFunction = Best->Function;
  4027. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  4028. ICS.UserDefined.EllipsisConversion = false;
  4029. assert(ICS.UserDefined.After.ReferenceBinding &&
  4030. ICS.UserDefined.After.DirectBinding &&
  4031. "Expected a direct reference binding!");
  4032. return true;
  4033. case OR_Ambiguous:
  4034. ICS.setAmbiguous();
  4035. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  4036. Cand != CandidateSet.end(); ++Cand)
  4037. if (Cand->Viable)
  4038. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  4039. return true;
  4040. case OR_No_Viable_Function:
  4041. case OR_Deleted:
  4042. // There was no suitable conversion, or we found a deleted
  4043. // conversion; continue with other checks.
  4044. return false;
  4045. }
  4046. llvm_unreachable("Invalid OverloadResult!");
  4047. }
  4048. /// Compute an implicit conversion sequence for reference
  4049. /// initialization.
  4050. static ImplicitConversionSequence
  4051. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  4052. SourceLocation DeclLoc,
  4053. bool SuppressUserConversions,
  4054. bool AllowExplicit) {
  4055. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  4056. // Most paths end in a failed conversion.
  4057. ImplicitConversionSequence ICS;
  4058. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4059. QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
  4060. QualType T2 = Init->getType();
  4061. // If the initializer is the address of an overloaded function, try
  4062. // to resolve the overloaded function. If all goes well, T2 is the
  4063. // type of the resulting function.
  4064. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4065. DeclAccessPair Found;
  4066. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  4067. false, Found))
  4068. T2 = Fn->getType();
  4069. }
  4070. // Compute some basic properties of the types and the initializer.
  4071. bool isRValRef = DeclType->isRValueReferenceType();
  4072. bool DerivedToBase = false;
  4073. bool ObjCConversion = false;
  4074. bool ObjCLifetimeConversion = false;
  4075. Expr::Classification InitCategory = Init->Classify(S.Context);
  4076. Sema::ReferenceCompareResult RefRelationship
  4077. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  4078. ObjCConversion, ObjCLifetimeConversion);
  4079. // C++0x [dcl.init.ref]p5:
  4080. // A reference to type "cv1 T1" is initialized by an expression
  4081. // of type "cv2 T2" as follows:
  4082. // -- If reference is an lvalue reference and the initializer expression
  4083. if (!isRValRef) {
  4084. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  4085. // reference-compatible with "cv2 T2," or
  4086. //
  4087. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  4088. if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
  4089. // C++ [over.ics.ref]p1:
  4090. // When a parameter of reference type binds directly (8.5.3)
  4091. // to an argument expression, the implicit conversion sequence
  4092. // is the identity conversion, unless the argument expression
  4093. // has a type that is a derived class of the parameter type,
  4094. // in which case the implicit conversion sequence is a
  4095. // derived-to-base Conversion (13.3.3.1).
  4096. ICS.setStandard();
  4097. ICS.Standard.First = ICK_Identity;
  4098. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  4099. : ObjCConversion? ICK_Compatible_Conversion
  4100. : ICK_Identity;
  4101. ICS.Standard.Third = ICK_Identity;
  4102. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  4103. ICS.Standard.setToType(0, T2);
  4104. ICS.Standard.setToType(1, T1);
  4105. ICS.Standard.setToType(2, T1);
  4106. ICS.Standard.ReferenceBinding = true;
  4107. ICS.Standard.DirectBinding = true;
  4108. ICS.Standard.IsLvalueReference = !isRValRef;
  4109. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4110. ICS.Standard.BindsToRvalue = false;
  4111. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4112. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  4113. ICS.Standard.CopyConstructor = nullptr;
  4114. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4115. // Nothing more to do: the inaccessibility/ambiguity check for
  4116. // derived-to-base conversions is suppressed when we're
  4117. // computing the implicit conversion sequence (C++
  4118. // [over.best.ics]p2).
  4119. return ICS;
  4120. }
  4121. // -- has a class type (i.e., T2 is a class type), where T1 is
  4122. // not reference-related to T2, and can be implicitly
  4123. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  4124. // is reference-compatible with "cv3 T3" 92) (this
  4125. // conversion is selected by enumerating the applicable
  4126. // conversion functions (13.3.1.6) and choosing the best
  4127. // one through overload resolution (13.3)),
  4128. if (!SuppressUserConversions && T2->isRecordType() &&
  4129. S.isCompleteType(DeclLoc, T2) &&
  4130. RefRelationship == Sema::Ref_Incompatible) {
  4131. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4132. Init, T2, /*AllowRvalues=*/false,
  4133. AllowExplicit))
  4134. return ICS;
  4135. }
  4136. }
  4137. // -- Otherwise, the reference shall be an lvalue reference to a
  4138. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4139. // shall be an rvalue reference.
  4140. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  4141. return ICS;
  4142. // -- If the initializer expression
  4143. //
  4144. // -- is an xvalue, class prvalue, array prvalue or function
  4145. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  4146. if (RefRelationship == Sema::Ref_Compatible &&
  4147. (InitCategory.isXValue() ||
  4148. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  4149. (InitCategory.isLValue() && T2->isFunctionType()))) {
  4150. ICS.setStandard();
  4151. ICS.Standard.First = ICK_Identity;
  4152. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  4153. : ObjCConversion? ICK_Compatible_Conversion
  4154. : ICK_Identity;
  4155. ICS.Standard.Third = ICK_Identity;
  4156. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  4157. ICS.Standard.setToType(0, T2);
  4158. ICS.Standard.setToType(1, T1);
  4159. ICS.Standard.setToType(2, T1);
  4160. ICS.Standard.ReferenceBinding = true;
  4161. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  4162. // binding unless we're binding to a class prvalue.
  4163. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  4164. // allow the use of rvalue references in C++98/03 for the benefit of
  4165. // standard library implementors; therefore, we need the xvalue check here.
  4166. ICS.Standard.DirectBinding =
  4167. S.getLangOpts().CPlusPlus11 ||
  4168. !(InitCategory.isPRValue() || T2->isRecordType());
  4169. ICS.Standard.IsLvalueReference = !isRValRef;
  4170. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4171. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  4172. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4173. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  4174. ICS.Standard.CopyConstructor = nullptr;
  4175. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4176. return ICS;
  4177. }
  4178. // -- has a class type (i.e., T2 is a class type), where T1 is not
  4179. // reference-related to T2, and can be implicitly converted to
  4180. // an xvalue, class prvalue, or function lvalue of type
  4181. // "cv3 T3", where "cv1 T1" is reference-compatible with
  4182. // "cv3 T3",
  4183. //
  4184. // then the reference is bound to the value of the initializer
  4185. // expression in the first case and to the result of the conversion
  4186. // in the second case (or, in either case, to an appropriate base
  4187. // class subobject).
  4188. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4189. T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
  4190. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4191. Init, T2, /*AllowRvalues=*/true,
  4192. AllowExplicit)) {
  4193. // In the second case, if the reference is an rvalue reference
  4194. // and the second standard conversion sequence of the
  4195. // user-defined conversion sequence includes an lvalue-to-rvalue
  4196. // conversion, the program is ill-formed.
  4197. if (ICS.isUserDefined() && isRValRef &&
  4198. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  4199. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4200. return ICS;
  4201. }
  4202. // A temporary of function type cannot be created; don't even try.
  4203. if (T1->isFunctionType())
  4204. return ICS;
  4205. // -- Otherwise, a temporary of type "cv1 T1" is created and
  4206. // initialized from the initializer expression using the
  4207. // rules for a non-reference copy initialization (8.5). The
  4208. // reference is then bound to the temporary. If T1 is
  4209. // reference-related to T2, cv1 must be the same
  4210. // cv-qualification as, or greater cv-qualification than,
  4211. // cv2; otherwise, the program is ill-formed.
  4212. if (RefRelationship == Sema::Ref_Related) {
  4213. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  4214. // we would be reference-compatible or reference-compatible with
  4215. // added qualification. But that wasn't the case, so the reference
  4216. // initialization fails.
  4217. //
  4218. // Note that we only want to check address spaces and cvr-qualifiers here.
  4219. // ObjC GC, lifetime and unaligned qualifiers aren't important.
  4220. Qualifiers T1Quals = T1.getQualifiers();
  4221. Qualifiers T2Quals = T2.getQualifiers();
  4222. T1Quals.removeObjCGCAttr();
  4223. T1Quals.removeObjCLifetime();
  4224. T2Quals.removeObjCGCAttr();
  4225. T2Quals.removeObjCLifetime();
  4226. // MS compiler ignores __unaligned qualifier for references; do the same.
  4227. T1Quals.removeUnaligned();
  4228. T2Quals.removeUnaligned();
  4229. if (!T1Quals.compatiblyIncludes(T2Quals))
  4230. return ICS;
  4231. }
  4232. // If at least one of the types is a class type, the types are not
  4233. // related, and we aren't allowed any user conversions, the
  4234. // reference binding fails. This case is important for breaking
  4235. // recursion, since TryImplicitConversion below will attempt to
  4236. // create a temporary through the use of a copy constructor.
  4237. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4238. (T1->isRecordType() || T2->isRecordType()))
  4239. return ICS;
  4240. // If T1 is reference-related to T2 and the reference is an rvalue
  4241. // reference, the initializer expression shall not be an lvalue.
  4242. if (RefRelationship >= Sema::Ref_Related &&
  4243. isRValRef && Init->Classify(S.Context).isLValue())
  4244. return ICS;
  4245. // C++ [over.ics.ref]p2:
  4246. // When a parameter of reference type is not bound directly to
  4247. // an argument expression, the conversion sequence is the one
  4248. // required to convert the argument expression to the
  4249. // underlying type of the reference according to
  4250. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  4251. // to copy-initializing a temporary of the underlying type with
  4252. // the argument expression. Any difference in top-level
  4253. // cv-qualification is subsumed by the initialization itself
  4254. // and does not constitute a conversion.
  4255. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4256. /*AllowExplicit=*/false,
  4257. /*InOverloadResolution=*/false,
  4258. /*CStyle=*/false,
  4259. /*AllowObjCWritebackConversion=*/false,
  4260. /*AllowObjCConversionOnExplicit=*/false);
  4261. // Of course, that's still a reference binding.
  4262. if (ICS.isStandard()) {
  4263. ICS.Standard.ReferenceBinding = true;
  4264. ICS.Standard.IsLvalueReference = !isRValRef;
  4265. ICS.Standard.BindsToFunctionLvalue = false;
  4266. ICS.Standard.BindsToRvalue = true;
  4267. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4268. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4269. } else if (ICS.isUserDefined()) {
  4270. const ReferenceType *LValRefType =
  4271. ICS.UserDefined.ConversionFunction->getReturnType()
  4272. ->getAs<LValueReferenceType>();
  4273. // C++ [over.ics.ref]p3:
  4274. // Except for an implicit object parameter, for which see 13.3.1, a
  4275. // standard conversion sequence cannot be formed if it requires [...]
  4276. // binding an rvalue reference to an lvalue other than a function
  4277. // lvalue.
  4278. // Note that the function case is not possible here.
  4279. if (DeclType->isRValueReferenceType() && LValRefType) {
  4280. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4281. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4282. // reference to an rvalue!
  4283. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4284. return ICS;
  4285. }
  4286. ICS.UserDefined.After.ReferenceBinding = true;
  4287. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4288. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4289. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4290. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4291. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4292. }
  4293. return ICS;
  4294. }
  4295. static ImplicitConversionSequence
  4296. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4297. bool SuppressUserConversions,
  4298. bool InOverloadResolution,
  4299. bool AllowObjCWritebackConversion,
  4300. bool AllowExplicit = false);
  4301. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4302. /// initializer list From.
  4303. static ImplicitConversionSequence
  4304. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4305. bool SuppressUserConversions,
  4306. bool InOverloadResolution,
  4307. bool AllowObjCWritebackConversion) {
  4308. // C++11 [over.ics.list]p1:
  4309. // When an argument is an initializer list, it is not an expression and
  4310. // special rules apply for converting it to a parameter type.
  4311. ImplicitConversionSequence Result;
  4312. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4313. // We need a complete type for what follows. Incomplete types can never be
  4314. // initialized from init lists.
  4315. if (!S.isCompleteType(From->getBeginLoc(), ToType))
  4316. return Result;
  4317. // Per DR1467:
  4318. // If the parameter type is a class X and the initializer list has a single
  4319. // element of type cv U, where U is X or a class derived from X, the
  4320. // implicit conversion sequence is the one required to convert the element
  4321. // to the parameter type.
  4322. //
  4323. // Otherwise, if the parameter type is a character array [... ]
  4324. // and the initializer list has a single element that is an
  4325. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4326. // implicit conversion sequence is the identity conversion.
  4327. if (From->getNumInits() == 1) {
  4328. if (ToType->isRecordType()) {
  4329. QualType InitType = From->getInit(0)->getType();
  4330. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4331. S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
  4332. return TryCopyInitialization(S, From->getInit(0), ToType,
  4333. SuppressUserConversions,
  4334. InOverloadResolution,
  4335. AllowObjCWritebackConversion);
  4336. }
  4337. // FIXME: Check the other conditions here: array of character type,
  4338. // initializer is a string literal.
  4339. if (ToType->isArrayType()) {
  4340. InitializedEntity Entity =
  4341. InitializedEntity::InitializeParameter(S.Context, ToType,
  4342. /*Consumed=*/false);
  4343. if (S.CanPerformCopyInitialization(Entity, From)) {
  4344. Result.setStandard();
  4345. Result.Standard.setAsIdentityConversion();
  4346. Result.Standard.setFromType(ToType);
  4347. Result.Standard.setAllToTypes(ToType);
  4348. return Result;
  4349. }
  4350. }
  4351. }
  4352. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4353. // C++11 [over.ics.list]p2:
  4354. // If the parameter type is std::initializer_list<X> or "array of X" and
  4355. // all the elements can be implicitly converted to X, the implicit
  4356. // conversion sequence is the worst conversion necessary to convert an
  4357. // element of the list to X.
  4358. //
  4359. // C++14 [over.ics.list]p3:
  4360. // Otherwise, if the parameter type is "array of N X", if the initializer
  4361. // list has exactly N elements or if it has fewer than N elements and X is
  4362. // default-constructible, and if all the elements of the initializer list
  4363. // can be implicitly converted to X, the implicit conversion sequence is
  4364. // the worst conversion necessary to convert an element of the list to X.
  4365. //
  4366. // FIXME: We're missing a lot of these checks.
  4367. bool toStdInitializerList = false;
  4368. QualType X;
  4369. if (ToType->isArrayType())
  4370. X = S.Context.getAsArrayType(ToType)->getElementType();
  4371. else
  4372. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4373. if (!X.isNull()) {
  4374. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4375. Expr *Init = From->getInit(i);
  4376. ImplicitConversionSequence ICS =
  4377. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4378. InOverloadResolution,
  4379. AllowObjCWritebackConversion);
  4380. // If a single element isn't convertible, fail.
  4381. if (ICS.isBad()) {
  4382. Result = ICS;
  4383. break;
  4384. }
  4385. // Otherwise, look for the worst conversion.
  4386. if (Result.isBad() || CompareImplicitConversionSequences(
  4387. S, From->getBeginLoc(), ICS, Result) ==
  4388. ImplicitConversionSequence::Worse)
  4389. Result = ICS;
  4390. }
  4391. // For an empty list, we won't have computed any conversion sequence.
  4392. // Introduce the identity conversion sequence.
  4393. if (From->getNumInits() == 0) {
  4394. Result.setStandard();
  4395. Result.Standard.setAsIdentityConversion();
  4396. Result.Standard.setFromType(ToType);
  4397. Result.Standard.setAllToTypes(ToType);
  4398. }
  4399. Result.setStdInitializerListElement(toStdInitializerList);
  4400. return Result;
  4401. }
  4402. // C++14 [over.ics.list]p4:
  4403. // C++11 [over.ics.list]p3:
  4404. // Otherwise, if the parameter is a non-aggregate class X and overload
  4405. // resolution chooses a single best constructor [...] the implicit
  4406. // conversion sequence is a user-defined conversion sequence. If multiple
  4407. // constructors are viable but none is better than the others, the
  4408. // implicit conversion sequence is a user-defined conversion sequence.
  4409. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4410. // This function can deal with initializer lists.
  4411. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4412. /*AllowExplicit=*/false,
  4413. InOverloadResolution, /*CStyle=*/false,
  4414. AllowObjCWritebackConversion,
  4415. /*AllowObjCConversionOnExplicit=*/false);
  4416. }
  4417. // C++14 [over.ics.list]p5:
  4418. // C++11 [over.ics.list]p4:
  4419. // Otherwise, if the parameter has an aggregate type which can be
  4420. // initialized from the initializer list [...] the implicit conversion
  4421. // sequence is a user-defined conversion sequence.
  4422. if (ToType->isAggregateType()) {
  4423. // Type is an aggregate, argument is an init list. At this point it comes
  4424. // down to checking whether the initialization works.
  4425. // FIXME: Find out whether this parameter is consumed or not.
  4426. // FIXME: Expose SemaInit's aggregate initialization code so that we don't
  4427. // need to call into the initialization code here; overload resolution
  4428. // should not be doing that.
  4429. InitializedEntity Entity =
  4430. InitializedEntity::InitializeParameter(S.Context, ToType,
  4431. /*Consumed=*/false);
  4432. if (S.CanPerformCopyInitialization(Entity, From)) {
  4433. Result.setUserDefined();
  4434. Result.UserDefined.Before.setAsIdentityConversion();
  4435. // Initializer lists don't have a type.
  4436. Result.UserDefined.Before.setFromType(QualType());
  4437. Result.UserDefined.Before.setAllToTypes(QualType());
  4438. Result.UserDefined.After.setAsIdentityConversion();
  4439. Result.UserDefined.After.setFromType(ToType);
  4440. Result.UserDefined.After.setAllToTypes(ToType);
  4441. Result.UserDefined.ConversionFunction = nullptr;
  4442. }
  4443. return Result;
  4444. }
  4445. // C++14 [over.ics.list]p6:
  4446. // C++11 [over.ics.list]p5:
  4447. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4448. if (ToType->isReferenceType()) {
  4449. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4450. // mention initializer lists in any way. So we go by what list-
  4451. // initialization would do and try to extrapolate from that.
  4452. QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
  4453. // If the initializer list has a single element that is reference-related
  4454. // to the parameter type, we initialize the reference from that.
  4455. if (From->getNumInits() == 1) {
  4456. Expr *Init = From->getInit(0);
  4457. QualType T2 = Init->getType();
  4458. // If the initializer is the address of an overloaded function, try
  4459. // to resolve the overloaded function. If all goes well, T2 is the
  4460. // type of the resulting function.
  4461. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4462. DeclAccessPair Found;
  4463. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4464. Init, ToType, false, Found))
  4465. T2 = Fn->getType();
  4466. }
  4467. // Compute some basic properties of the types and the initializer.
  4468. bool dummy1 = false;
  4469. bool dummy2 = false;
  4470. bool dummy3 = false;
  4471. Sema::ReferenceCompareResult RefRelationship =
  4472. S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
  4473. dummy2, dummy3);
  4474. if (RefRelationship >= Sema::Ref_Related) {
  4475. return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
  4476. SuppressUserConversions,
  4477. /*AllowExplicit=*/false);
  4478. }
  4479. }
  4480. // Otherwise, we bind the reference to a temporary created from the
  4481. // initializer list.
  4482. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4483. InOverloadResolution,
  4484. AllowObjCWritebackConversion);
  4485. if (Result.isFailure())
  4486. return Result;
  4487. assert(!Result.isEllipsis() &&
  4488. "Sub-initialization cannot result in ellipsis conversion.");
  4489. // Can we even bind to a temporary?
  4490. if (ToType->isRValueReferenceType() ||
  4491. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4492. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4493. Result.UserDefined.After;
  4494. SCS.ReferenceBinding = true;
  4495. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4496. SCS.BindsToRvalue = true;
  4497. SCS.BindsToFunctionLvalue = false;
  4498. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4499. SCS.ObjCLifetimeConversionBinding = false;
  4500. } else
  4501. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4502. From, ToType);
  4503. return Result;
  4504. }
  4505. // C++14 [over.ics.list]p7:
  4506. // C++11 [over.ics.list]p6:
  4507. // Otherwise, if the parameter type is not a class:
  4508. if (!ToType->isRecordType()) {
  4509. // - if the initializer list has one element that is not itself an
  4510. // initializer list, the implicit conversion sequence is the one
  4511. // required to convert the element to the parameter type.
  4512. unsigned NumInits = From->getNumInits();
  4513. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4514. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4515. SuppressUserConversions,
  4516. InOverloadResolution,
  4517. AllowObjCWritebackConversion);
  4518. // - if the initializer list has no elements, the implicit conversion
  4519. // sequence is the identity conversion.
  4520. else if (NumInits == 0) {
  4521. Result.setStandard();
  4522. Result.Standard.setAsIdentityConversion();
  4523. Result.Standard.setFromType(ToType);
  4524. Result.Standard.setAllToTypes(ToType);
  4525. }
  4526. return Result;
  4527. }
  4528. // C++14 [over.ics.list]p8:
  4529. // C++11 [over.ics.list]p7:
  4530. // In all cases other than those enumerated above, no conversion is possible
  4531. return Result;
  4532. }
  4533. /// TryCopyInitialization - Try to copy-initialize a value of type
  4534. /// ToType from the expression From. Return the implicit conversion
  4535. /// sequence required to pass this argument, which may be a bad
  4536. /// conversion sequence (meaning that the argument cannot be passed to
  4537. /// a parameter of this type). If @p SuppressUserConversions, then we
  4538. /// do not permit any user-defined conversion sequences.
  4539. static ImplicitConversionSequence
  4540. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4541. bool SuppressUserConversions,
  4542. bool InOverloadResolution,
  4543. bool AllowObjCWritebackConversion,
  4544. bool AllowExplicit) {
  4545. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4546. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4547. InOverloadResolution,AllowObjCWritebackConversion);
  4548. if (ToType->isReferenceType())
  4549. return TryReferenceInit(S, From, ToType,
  4550. /*FIXME:*/ From->getBeginLoc(),
  4551. SuppressUserConversions, AllowExplicit);
  4552. return TryImplicitConversion(S, From, ToType,
  4553. SuppressUserConversions,
  4554. /*AllowExplicit=*/false,
  4555. InOverloadResolution,
  4556. /*CStyle=*/false,
  4557. AllowObjCWritebackConversion,
  4558. /*AllowObjCConversionOnExplicit=*/false);
  4559. }
  4560. static bool TryCopyInitialization(const CanQualType FromQTy,
  4561. const CanQualType ToQTy,
  4562. Sema &S,
  4563. SourceLocation Loc,
  4564. ExprValueKind FromVK) {
  4565. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4566. ImplicitConversionSequence ICS =
  4567. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4568. return !ICS.isBad();
  4569. }
  4570. /// TryObjectArgumentInitialization - Try to initialize the object
  4571. /// parameter of the given member function (@c Method) from the
  4572. /// expression @p From.
  4573. static ImplicitConversionSequence
  4574. TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
  4575. Expr::Classification FromClassification,
  4576. CXXMethodDecl *Method,
  4577. CXXRecordDecl *ActingContext) {
  4578. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4579. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4580. // const volatile object.
  4581. Qualifiers Quals;
  4582. if (isa<CXXDestructorDecl>(Method)) {
  4583. Quals.addConst();
  4584. Quals.addVolatile();
  4585. } else {
  4586. Quals = Method->getMethodQualifiers();
  4587. }
  4588. QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
  4589. // Set up the conversion sequence as a "bad" conversion, to allow us
  4590. // to exit early.
  4591. ImplicitConversionSequence ICS;
  4592. // We need to have an object of class type.
  4593. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4594. FromType = PT->getPointeeType();
  4595. // When we had a pointer, it's implicitly dereferenced, so we
  4596. // better have an lvalue.
  4597. assert(FromClassification.isLValue());
  4598. }
  4599. assert(FromType->isRecordType());
  4600. // C++0x [over.match.funcs]p4:
  4601. // For non-static member functions, the type of the implicit object
  4602. // parameter is
  4603. //
  4604. // - "lvalue reference to cv X" for functions declared without a
  4605. // ref-qualifier or with the & ref-qualifier
  4606. // - "rvalue reference to cv X" for functions declared with the &&
  4607. // ref-qualifier
  4608. //
  4609. // where X is the class of which the function is a member and cv is the
  4610. // cv-qualification on the member function declaration.
  4611. //
  4612. // However, when finding an implicit conversion sequence for the argument, we
  4613. // are not allowed to perform user-defined conversions
  4614. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4615. // reference binding here, that allows class rvalues to bind to
  4616. // non-constant references.
  4617. // First check the qualifiers.
  4618. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4619. if (ImplicitParamType.getCVRQualifiers()
  4620. != FromTypeCanon.getLocalCVRQualifiers() &&
  4621. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4622. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4623. FromType, ImplicitParamType);
  4624. return ICS;
  4625. }
  4626. if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
  4627. Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
  4628. Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
  4629. if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
  4630. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4631. FromType, ImplicitParamType);
  4632. return ICS;
  4633. }
  4634. }
  4635. // Check that we have either the same type or a derived type. It
  4636. // affects the conversion rank.
  4637. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4638. ImplicitConversionKind SecondKind;
  4639. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4640. SecondKind = ICK_Identity;
  4641. } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
  4642. SecondKind = ICK_Derived_To_Base;
  4643. else {
  4644. ICS.setBad(BadConversionSequence::unrelated_class,
  4645. FromType, ImplicitParamType);
  4646. return ICS;
  4647. }
  4648. // Check the ref-qualifier.
  4649. switch (Method->getRefQualifier()) {
  4650. case RQ_None:
  4651. // Do nothing; we don't care about lvalueness or rvalueness.
  4652. break;
  4653. case RQ_LValue:
  4654. if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
  4655. // non-const lvalue reference cannot bind to an rvalue
  4656. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4657. ImplicitParamType);
  4658. return ICS;
  4659. }
  4660. break;
  4661. case RQ_RValue:
  4662. if (!FromClassification.isRValue()) {
  4663. // rvalue reference cannot bind to an lvalue
  4664. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4665. ImplicitParamType);
  4666. return ICS;
  4667. }
  4668. break;
  4669. }
  4670. // Success. Mark this as a reference binding.
  4671. ICS.setStandard();
  4672. ICS.Standard.setAsIdentityConversion();
  4673. ICS.Standard.Second = SecondKind;
  4674. ICS.Standard.setFromType(FromType);
  4675. ICS.Standard.setAllToTypes(ImplicitParamType);
  4676. ICS.Standard.ReferenceBinding = true;
  4677. ICS.Standard.DirectBinding = true;
  4678. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4679. ICS.Standard.BindsToFunctionLvalue = false;
  4680. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4681. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4682. = (Method->getRefQualifier() == RQ_None);
  4683. return ICS;
  4684. }
  4685. /// PerformObjectArgumentInitialization - Perform initialization of
  4686. /// the implicit object parameter for the given Method with the given
  4687. /// expression.
  4688. ExprResult
  4689. Sema::PerformObjectArgumentInitialization(Expr *From,
  4690. NestedNameSpecifier *Qualifier,
  4691. NamedDecl *FoundDecl,
  4692. CXXMethodDecl *Method) {
  4693. QualType FromRecordType, DestType;
  4694. QualType ImplicitParamRecordType =
  4695. Method->getThisType()->getAs<PointerType>()->getPointeeType();
  4696. Expr::Classification FromClassification;
  4697. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4698. FromRecordType = PT->getPointeeType();
  4699. DestType = Method->getThisType();
  4700. FromClassification = Expr::Classification::makeSimpleLValue();
  4701. } else {
  4702. FromRecordType = From->getType();
  4703. DestType = ImplicitParamRecordType;
  4704. FromClassification = From->Classify(Context);
  4705. // When performing member access on an rvalue, materialize a temporary.
  4706. if (From->isRValue()) {
  4707. From = CreateMaterializeTemporaryExpr(FromRecordType, From,
  4708. Method->getRefQualifier() !=
  4709. RefQualifierKind::RQ_RValue);
  4710. }
  4711. }
  4712. // Note that we always use the true parent context when performing
  4713. // the actual argument initialization.
  4714. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4715. *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
  4716. Method->getParent());
  4717. if (ICS.isBad()) {
  4718. switch (ICS.Bad.Kind) {
  4719. case BadConversionSequence::bad_qualifiers: {
  4720. Qualifiers FromQs = FromRecordType.getQualifiers();
  4721. Qualifiers ToQs = DestType.getQualifiers();
  4722. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4723. if (CVR) {
  4724. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
  4725. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4726. << From->getSourceRange();
  4727. Diag(Method->getLocation(), diag::note_previous_decl)
  4728. << Method->getDeclName();
  4729. return ExprError();
  4730. }
  4731. break;
  4732. }
  4733. case BadConversionSequence::lvalue_ref_to_rvalue:
  4734. case BadConversionSequence::rvalue_ref_to_lvalue: {
  4735. bool IsRValueQualified =
  4736. Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
  4737. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
  4738. << Method->getDeclName() << FromClassification.isRValue()
  4739. << IsRValueQualified;
  4740. Diag(Method->getLocation(), diag::note_previous_decl)
  4741. << Method->getDeclName();
  4742. return ExprError();
  4743. }
  4744. case BadConversionSequence::no_conversion:
  4745. case BadConversionSequence::unrelated_class:
  4746. break;
  4747. }
  4748. return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
  4749. << ImplicitParamRecordType << FromRecordType
  4750. << From->getSourceRange();
  4751. }
  4752. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4753. ExprResult FromRes =
  4754. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4755. if (FromRes.isInvalid())
  4756. return ExprError();
  4757. From = FromRes.get();
  4758. }
  4759. if (!Context.hasSameType(From->getType(), DestType)) {
  4760. CastKind CK;
  4761. if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
  4762. CK = CK_AddressSpaceConversion;
  4763. else
  4764. CK = CK_NoOp;
  4765. From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
  4766. }
  4767. return From;
  4768. }
  4769. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4770. /// expression From to bool (C++0x [conv]p3).
  4771. static ImplicitConversionSequence
  4772. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4773. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4774. /*SuppressUserConversions=*/false,
  4775. /*AllowExplicit=*/true,
  4776. /*InOverloadResolution=*/false,
  4777. /*CStyle=*/false,
  4778. /*AllowObjCWritebackConversion=*/false,
  4779. /*AllowObjCConversionOnExplicit=*/false);
  4780. }
  4781. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4782. /// of the expression From to bool (C++0x [conv]p3).
  4783. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4784. if (checkPlaceholderForOverload(*this, From))
  4785. return ExprError();
  4786. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4787. if (!ICS.isBad())
  4788. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4789. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4790. return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
  4791. << From->getType() << From->getSourceRange();
  4792. return ExprError();
  4793. }
  4794. /// Check that the specified conversion is permitted in a converted constant
  4795. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4796. /// is acceptable.
  4797. static bool CheckConvertedConstantConversions(Sema &S,
  4798. StandardConversionSequence &SCS) {
  4799. // Since we know that the target type is an integral or unscoped enumeration
  4800. // type, most conversion kinds are impossible. All possible First and Third
  4801. // conversions are fine.
  4802. switch (SCS.Second) {
  4803. case ICK_Identity:
  4804. case ICK_Function_Conversion:
  4805. case ICK_Integral_Promotion:
  4806. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4807. case ICK_Zero_Queue_Conversion:
  4808. return true;
  4809. case ICK_Boolean_Conversion:
  4810. // Conversion from an integral or unscoped enumeration type to bool is
  4811. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4812. // conversion, so we allow it in a converted constant expression.
  4813. //
  4814. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4815. // a lot of popular code. We should at least add a warning for this
  4816. // (non-conforming) extension.
  4817. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4818. SCS.getToType(2)->isBooleanType();
  4819. case ICK_Pointer_Conversion:
  4820. case ICK_Pointer_Member:
  4821. // C++1z: null pointer conversions and null member pointer conversions are
  4822. // only permitted if the source type is std::nullptr_t.
  4823. return SCS.getFromType()->isNullPtrType();
  4824. case ICK_Floating_Promotion:
  4825. case ICK_Complex_Promotion:
  4826. case ICK_Floating_Conversion:
  4827. case ICK_Complex_Conversion:
  4828. case ICK_Floating_Integral:
  4829. case ICK_Compatible_Conversion:
  4830. case ICK_Derived_To_Base:
  4831. case ICK_Vector_Conversion:
  4832. case ICK_Vector_Splat:
  4833. case ICK_Complex_Real:
  4834. case ICK_Block_Pointer_Conversion:
  4835. case ICK_TransparentUnionConversion:
  4836. case ICK_Writeback_Conversion:
  4837. case ICK_Zero_Event_Conversion:
  4838. case ICK_C_Only_Conversion:
  4839. case ICK_Incompatible_Pointer_Conversion:
  4840. return false;
  4841. case ICK_Lvalue_To_Rvalue:
  4842. case ICK_Array_To_Pointer:
  4843. case ICK_Function_To_Pointer:
  4844. llvm_unreachable("found a first conversion kind in Second");
  4845. case ICK_Qualification:
  4846. llvm_unreachable("found a third conversion kind in Second");
  4847. case ICK_Num_Conversion_Kinds:
  4848. break;
  4849. }
  4850. llvm_unreachable("unknown conversion kind");
  4851. }
  4852. /// CheckConvertedConstantExpression - Check that the expression From is a
  4853. /// converted constant expression of type T, perform the conversion and produce
  4854. /// the converted expression, per C++11 [expr.const]p3.
  4855. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4856. QualType T, APValue &Value,
  4857. Sema::CCEKind CCE,
  4858. bool RequireInt) {
  4859. assert(S.getLangOpts().CPlusPlus11 &&
  4860. "converted constant expression outside C++11");
  4861. if (checkPlaceholderForOverload(S, From))
  4862. return ExprError();
  4863. // C++1z [expr.const]p3:
  4864. // A converted constant expression of type T is an expression,
  4865. // implicitly converted to type T, where the converted
  4866. // expression is a constant expression and the implicit conversion
  4867. // sequence contains only [... list of conversions ...].
  4868. // C++1z [stmt.if]p2:
  4869. // If the if statement is of the form if constexpr, the value of the
  4870. // condition shall be a contextually converted constant expression of type
  4871. // bool.
  4872. ImplicitConversionSequence ICS =
  4873. CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
  4874. ? TryContextuallyConvertToBool(S, From)
  4875. : TryCopyInitialization(S, From, T,
  4876. /*SuppressUserConversions=*/false,
  4877. /*InOverloadResolution=*/false,
  4878. /*AllowObjCWritebackConversion=*/false,
  4879. /*AllowExplicit=*/false);
  4880. StandardConversionSequence *SCS = nullptr;
  4881. switch (ICS.getKind()) {
  4882. case ImplicitConversionSequence::StandardConversion:
  4883. SCS = &ICS.Standard;
  4884. break;
  4885. case ImplicitConversionSequence::UserDefinedConversion:
  4886. // We are converting to a non-class type, so the Before sequence
  4887. // must be trivial.
  4888. SCS = &ICS.UserDefined.After;
  4889. break;
  4890. case ImplicitConversionSequence::AmbiguousConversion:
  4891. case ImplicitConversionSequence::BadConversion:
  4892. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4893. return S.Diag(From->getBeginLoc(),
  4894. diag::err_typecheck_converted_constant_expression)
  4895. << From->getType() << From->getSourceRange() << T;
  4896. return ExprError();
  4897. case ImplicitConversionSequence::EllipsisConversion:
  4898. llvm_unreachable("ellipsis conversion in converted constant expression");
  4899. }
  4900. // Check that we would only use permitted conversions.
  4901. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4902. return S.Diag(From->getBeginLoc(),
  4903. diag::err_typecheck_converted_constant_expression_disallowed)
  4904. << From->getType() << From->getSourceRange() << T;
  4905. }
  4906. // [...] and where the reference binding (if any) binds directly.
  4907. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4908. return S.Diag(From->getBeginLoc(),
  4909. diag::err_typecheck_converted_constant_expression_indirect)
  4910. << From->getType() << From->getSourceRange() << T;
  4911. }
  4912. ExprResult Result =
  4913. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4914. if (Result.isInvalid())
  4915. return Result;
  4916. // Check for a narrowing implicit conversion.
  4917. APValue PreNarrowingValue;
  4918. QualType PreNarrowingType;
  4919. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4920. PreNarrowingType)) {
  4921. case NK_Dependent_Narrowing:
  4922. // Implicit conversion to a narrower type, but the expression is
  4923. // value-dependent so we can't tell whether it's actually narrowing.
  4924. case NK_Variable_Narrowing:
  4925. // Implicit conversion to a narrower type, and the value is not a constant
  4926. // expression. We'll diagnose this in a moment.
  4927. case NK_Not_Narrowing:
  4928. break;
  4929. case NK_Constant_Narrowing:
  4930. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  4931. << CCE << /*Constant*/ 1
  4932. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  4933. break;
  4934. case NK_Type_Narrowing:
  4935. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  4936. << CCE << /*Constant*/ 0 << From->getType() << T;
  4937. break;
  4938. }
  4939. if (Result.get()->isValueDependent()) {
  4940. Value = APValue();
  4941. return Result;
  4942. }
  4943. // Check the expression is a constant expression.
  4944. SmallVector<PartialDiagnosticAt, 8> Notes;
  4945. Expr::EvalResult Eval;
  4946. Eval.Diag = &Notes;
  4947. Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
  4948. ? Expr::EvaluateForMangling
  4949. : Expr::EvaluateForCodeGen;
  4950. if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
  4951. (RequireInt && !Eval.Val.isInt())) {
  4952. // The expression can't be folded, so we can't keep it at this position in
  4953. // the AST.
  4954. Result = ExprError();
  4955. } else {
  4956. Value = Eval.Val;
  4957. if (Notes.empty()) {
  4958. // It's a constant expression.
  4959. return ConstantExpr::Create(S.Context, Result.get(), Value);
  4960. }
  4961. }
  4962. // It's not a constant expression. Produce an appropriate diagnostic.
  4963. if (Notes.size() == 1 &&
  4964. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  4965. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  4966. else {
  4967. S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
  4968. << CCE << From->getSourceRange();
  4969. for (unsigned I = 0; I < Notes.size(); ++I)
  4970. S.Diag(Notes[I].first, Notes[I].second);
  4971. }
  4972. return ExprError();
  4973. }
  4974. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4975. APValue &Value, CCEKind CCE) {
  4976. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  4977. }
  4978. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4979. llvm::APSInt &Value,
  4980. CCEKind CCE) {
  4981. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  4982. APValue V;
  4983. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  4984. if (!R.isInvalid() && !R.get()->isValueDependent())
  4985. Value = V.getInt();
  4986. return R;
  4987. }
  4988. /// dropPointerConversions - If the given standard conversion sequence
  4989. /// involves any pointer conversions, remove them. This may change
  4990. /// the result type of the conversion sequence.
  4991. static void dropPointerConversion(StandardConversionSequence &SCS) {
  4992. if (SCS.Second == ICK_Pointer_Conversion) {
  4993. SCS.Second = ICK_Identity;
  4994. SCS.Third = ICK_Identity;
  4995. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  4996. }
  4997. }
  4998. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  4999. /// convert the expression From to an Objective-C pointer type.
  5000. static ImplicitConversionSequence
  5001. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  5002. // Do an implicit conversion to 'id'.
  5003. QualType Ty = S.Context.getObjCIdType();
  5004. ImplicitConversionSequence ICS
  5005. = TryImplicitConversion(S, From, Ty,
  5006. // FIXME: Are these flags correct?
  5007. /*SuppressUserConversions=*/false,
  5008. /*AllowExplicit=*/true,
  5009. /*InOverloadResolution=*/false,
  5010. /*CStyle=*/false,
  5011. /*AllowObjCWritebackConversion=*/false,
  5012. /*AllowObjCConversionOnExplicit=*/true);
  5013. // Strip off any final conversions to 'id'.
  5014. switch (ICS.getKind()) {
  5015. case ImplicitConversionSequence::BadConversion:
  5016. case ImplicitConversionSequence::AmbiguousConversion:
  5017. case ImplicitConversionSequence::EllipsisConversion:
  5018. break;
  5019. case ImplicitConversionSequence::UserDefinedConversion:
  5020. dropPointerConversion(ICS.UserDefined.After);
  5021. break;
  5022. case ImplicitConversionSequence::StandardConversion:
  5023. dropPointerConversion(ICS.Standard);
  5024. break;
  5025. }
  5026. return ICS;
  5027. }
  5028. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  5029. /// conversion of the expression From to an Objective-C pointer type.
  5030. /// Returns a valid but null ExprResult if no conversion sequence exists.
  5031. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  5032. if (checkPlaceholderForOverload(*this, From))
  5033. return ExprError();
  5034. QualType Ty = Context.getObjCIdType();
  5035. ImplicitConversionSequence ICS =
  5036. TryContextuallyConvertToObjCPointer(*this, From);
  5037. if (!ICS.isBad())
  5038. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  5039. return ExprResult();
  5040. }
  5041. /// Determine whether the provided type is an integral type, or an enumeration
  5042. /// type of a permitted flavor.
  5043. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  5044. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  5045. : T->isIntegralOrUnscopedEnumerationType();
  5046. }
  5047. static ExprResult
  5048. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  5049. Sema::ContextualImplicitConverter &Converter,
  5050. QualType T, UnresolvedSetImpl &ViableConversions) {
  5051. if (Converter.Suppress)
  5052. return ExprError();
  5053. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  5054. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5055. CXXConversionDecl *Conv =
  5056. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  5057. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  5058. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  5059. }
  5060. return From;
  5061. }
  5062. static bool
  5063. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5064. Sema::ContextualImplicitConverter &Converter,
  5065. QualType T, bool HadMultipleCandidates,
  5066. UnresolvedSetImpl &ExplicitConversions) {
  5067. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  5068. DeclAccessPair Found = ExplicitConversions[0];
  5069. CXXConversionDecl *Conversion =
  5070. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5071. // The user probably meant to invoke the given explicit
  5072. // conversion; use it.
  5073. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  5074. std::string TypeStr;
  5075. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  5076. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  5077. << FixItHint::CreateInsertion(From->getBeginLoc(),
  5078. "static_cast<" + TypeStr + ">(")
  5079. << FixItHint::CreateInsertion(
  5080. SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
  5081. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  5082. // If we aren't in a SFINAE context, build a call to the
  5083. // explicit conversion function.
  5084. if (SemaRef.isSFINAEContext())
  5085. return true;
  5086. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5087. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5088. HadMultipleCandidates);
  5089. if (Result.isInvalid())
  5090. return true;
  5091. // Record usage of conversion in an implicit cast.
  5092. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5093. CK_UserDefinedConversion, Result.get(),
  5094. nullptr, Result.get()->getValueKind());
  5095. }
  5096. return false;
  5097. }
  5098. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5099. Sema::ContextualImplicitConverter &Converter,
  5100. QualType T, bool HadMultipleCandidates,
  5101. DeclAccessPair &Found) {
  5102. CXXConversionDecl *Conversion =
  5103. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5104. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5105. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  5106. if (!Converter.SuppressConversion) {
  5107. if (SemaRef.isSFINAEContext())
  5108. return true;
  5109. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  5110. << From->getSourceRange();
  5111. }
  5112. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5113. HadMultipleCandidates);
  5114. if (Result.isInvalid())
  5115. return true;
  5116. // Record usage of conversion in an implicit cast.
  5117. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5118. CK_UserDefinedConversion, Result.get(),
  5119. nullptr, Result.get()->getValueKind());
  5120. return false;
  5121. }
  5122. static ExprResult finishContextualImplicitConversion(
  5123. Sema &SemaRef, SourceLocation Loc, Expr *From,
  5124. Sema::ContextualImplicitConverter &Converter) {
  5125. if (!Converter.match(From->getType()) && !Converter.Suppress)
  5126. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  5127. << From->getSourceRange();
  5128. return SemaRef.DefaultLvalueConversion(From);
  5129. }
  5130. static void
  5131. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  5132. UnresolvedSetImpl &ViableConversions,
  5133. OverloadCandidateSet &CandidateSet) {
  5134. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5135. DeclAccessPair FoundDecl = ViableConversions[I];
  5136. NamedDecl *D = FoundDecl.getDecl();
  5137. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  5138. if (isa<UsingShadowDecl>(D))
  5139. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  5140. CXXConversionDecl *Conv;
  5141. FunctionTemplateDecl *ConvTemplate;
  5142. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  5143. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5144. else
  5145. Conv = cast<CXXConversionDecl>(D);
  5146. if (ConvTemplate)
  5147. SemaRef.AddTemplateConversionCandidate(
  5148. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  5149. /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
  5150. else
  5151. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  5152. ToType, CandidateSet,
  5153. /*AllowObjCConversionOnExplicit=*/false,
  5154. /*AllowExplicit*/ true);
  5155. }
  5156. }
  5157. /// Attempt to convert the given expression to a type which is accepted
  5158. /// by the given converter.
  5159. ///
  5160. /// This routine will attempt to convert an expression of class type to a
  5161. /// type accepted by the specified converter. In C++11 and before, the class
  5162. /// must have a single non-explicit conversion function converting to a matching
  5163. /// type. In C++1y, there can be multiple such conversion functions, but only
  5164. /// one target type.
  5165. ///
  5166. /// \param Loc The source location of the construct that requires the
  5167. /// conversion.
  5168. ///
  5169. /// \param From The expression we're converting from.
  5170. ///
  5171. /// \param Converter Used to control and diagnose the conversion process.
  5172. ///
  5173. /// \returns The expression, converted to an integral or enumeration type if
  5174. /// successful.
  5175. ExprResult Sema::PerformContextualImplicitConversion(
  5176. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  5177. // We can't perform any more checking for type-dependent expressions.
  5178. if (From->isTypeDependent())
  5179. return From;
  5180. // Process placeholders immediately.
  5181. if (From->hasPlaceholderType()) {
  5182. ExprResult result = CheckPlaceholderExpr(From);
  5183. if (result.isInvalid())
  5184. return result;
  5185. From = result.get();
  5186. }
  5187. // If the expression already has a matching type, we're golden.
  5188. QualType T = From->getType();
  5189. if (Converter.match(T))
  5190. return DefaultLvalueConversion(From);
  5191. // FIXME: Check for missing '()' if T is a function type?
  5192. // We can only perform contextual implicit conversions on objects of class
  5193. // type.
  5194. const RecordType *RecordTy = T->getAs<RecordType>();
  5195. if (!RecordTy || !getLangOpts().CPlusPlus) {
  5196. if (!Converter.Suppress)
  5197. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  5198. return From;
  5199. }
  5200. // We must have a complete class type.
  5201. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  5202. ContextualImplicitConverter &Converter;
  5203. Expr *From;
  5204. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  5205. : Converter(Converter), From(From) {}
  5206. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  5207. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  5208. }
  5209. } IncompleteDiagnoser(Converter, From);
  5210. if (Converter.Suppress ? !isCompleteType(Loc, T)
  5211. : RequireCompleteType(Loc, T, IncompleteDiagnoser))
  5212. return From;
  5213. // Look for a conversion to an integral or enumeration type.
  5214. UnresolvedSet<4>
  5215. ViableConversions; // These are *potentially* viable in C++1y.
  5216. UnresolvedSet<4> ExplicitConversions;
  5217. const auto &Conversions =
  5218. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  5219. bool HadMultipleCandidates =
  5220. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  5221. // To check that there is only one target type, in C++1y:
  5222. QualType ToType;
  5223. bool HasUniqueTargetType = true;
  5224. // Collect explicit or viable (potentially in C++1y) conversions.
  5225. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  5226. NamedDecl *D = (*I)->getUnderlyingDecl();
  5227. CXXConversionDecl *Conversion;
  5228. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  5229. if (ConvTemplate) {
  5230. if (getLangOpts().CPlusPlus14)
  5231. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5232. else
  5233. continue; // C++11 does not consider conversion operator templates(?).
  5234. } else
  5235. Conversion = cast<CXXConversionDecl>(D);
  5236. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  5237. "Conversion operator templates are considered potentially "
  5238. "viable in C++1y");
  5239. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  5240. if (Converter.match(CurToType) || ConvTemplate) {
  5241. if (Conversion->isExplicit()) {
  5242. // FIXME: For C++1y, do we need this restriction?
  5243. // cf. diagnoseNoViableConversion()
  5244. if (!ConvTemplate)
  5245. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  5246. } else {
  5247. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  5248. if (ToType.isNull())
  5249. ToType = CurToType.getUnqualifiedType();
  5250. else if (HasUniqueTargetType &&
  5251. (CurToType.getUnqualifiedType() != ToType))
  5252. HasUniqueTargetType = false;
  5253. }
  5254. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5255. }
  5256. }
  5257. }
  5258. if (getLangOpts().CPlusPlus14) {
  5259. // C++1y [conv]p6:
  5260. // ... An expression e of class type E appearing in such a context
  5261. // is said to be contextually implicitly converted to a specified
  5262. // type T and is well-formed if and only if e can be implicitly
  5263. // converted to a type T that is determined as follows: E is searched
  5264. // for conversion functions whose return type is cv T or reference to
  5265. // cv T such that T is allowed by the context. There shall be
  5266. // exactly one such T.
  5267. // If no unique T is found:
  5268. if (ToType.isNull()) {
  5269. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5270. HadMultipleCandidates,
  5271. ExplicitConversions))
  5272. return ExprError();
  5273. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5274. }
  5275. // If more than one unique Ts are found:
  5276. if (!HasUniqueTargetType)
  5277. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5278. ViableConversions);
  5279. // If one unique T is found:
  5280. // First, build a candidate set from the previously recorded
  5281. // potentially viable conversions.
  5282. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5283. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5284. CandidateSet);
  5285. // Then, perform overload resolution over the candidate set.
  5286. OverloadCandidateSet::iterator Best;
  5287. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5288. case OR_Success: {
  5289. // Apply this conversion.
  5290. DeclAccessPair Found =
  5291. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5292. if (recordConversion(*this, Loc, From, Converter, T,
  5293. HadMultipleCandidates, Found))
  5294. return ExprError();
  5295. break;
  5296. }
  5297. case OR_Ambiguous:
  5298. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5299. ViableConversions);
  5300. case OR_No_Viable_Function:
  5301. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5302. HadMultipleCandidates,
  5303. ExplicitConversions))
  5304. return ExprError();
  5305. LLVM_FALLTHROUGH;
  5306. case OR_Deleted:
  5307. // We'll complain below about a non-integral condition type.
  5308. break;
  5309. }
  5310. } else {
  5311. switch (ViableConversions.size()) {
  5312. case 0: {
  5313. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5314. HadMultipleCandidates,
  5315. ExplicitConversions))
  5316. return ExprError();
  5317. // We'll complain below about a non-integral condition type.
  5318. break;
  5319. }
  5320. case 1: {
  5321. // Apply this conversion.
  5322. DeclAccessPair Found = ViableConversions[0];
  5323. if (recordConversion(*this, Loc, From, Converter, T,
  5324. HadMultipleCandidates, Found))
  5325. return ExprError();
  5326. break;
  5327. }
  5328. default:
  5329. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5330. ViableConversions);
  5331. }
  5332. }
  5333. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5334. }
  5335. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5336. /// an acceptable non-member overloaded operator for a call whose
  5337. /// arguments have types T1 (and, if non-empty, T2). This routine
  5338. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5339. /// enumeration types.
  5340. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5341. FunctionDecl *Fn,
  5342. ArrayRef<Expr *> Args) {
  5343. QualType T1 = Args[0]->getType();
  5344. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5345. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5346. return true;
  5347. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5348. return true;
  5349. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5350. if (Proto->getNumParams() < 1)
  5351. return false;
  5352. if (T1->isEnumeralType()) {
  5353. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5354. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5355. return true;
  5356. }
  5357. if (Proto->getNumParams() < 2)
  5358. return false;
  5359. if (!T2.isNull() && T2->isEnumeralType()) {
  5360. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5361. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5362. return true;
  5363. }
  5364. return false;
  5365. }
  5366. /// AddOverloadCandidate - Adds the given function to the set of
  5367. /// candidate functions, using the given function call arguments. If
  5368. /// @p SuppressUserConversions, then don't allow user-defined
  5369. /// conversions via constructors or conversion operators.
  5370. ///
  5371. /// \param PartialOverloading true if we are performing "partial" overloading
  5372. /// based on an incomplete set of function arguments. This feature is used by
  5373. /// code completion.
  5374. void Sema::AddOverloadCandidate(
  5375. FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
  5376. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  5377. bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
  5378. ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) {
  5379. const FunctionProtoType *Proto
  5380. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5381. assert(Proto && "Functions without a prototype cannot be overloaded");
  5382. assert(!Function->getDescribedFunctionTemplate() &&
  5383. "Use AddTemplateOverloadCandidate for function templates");
  5384. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5385. if (!isa<CXXConstructorDecl>(Method)) {
  5386. // If we get here, it's because we're calling a member function
  5387. // that is named without a member access expression (e.g.,
  5388. // "this->f") that was either written explicitly or created
  5389. // implicitly. This can happen with a qualified call to a member
  5390. // function, e.g., X::f(). We use an empty type for the implied
  5391. // object argument (C++ [over.call.func]p3), and the acting context
  5392. // is irrelevant.
  5393. AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
  5394. Expr::Classification::makeSimpleLValue(), Args,
  5395. CandidateSet, SuppressUserConversions,
  5396. PartialOverloading, EarlyConversions);
  5397. return;
  5398. }
  5399. // We treat a constructor like a non-member function, since its object
  5400. // argument doesn't participate in overload resolution.
  5401. }
  5402. if (!CandidateSet.isNewCandidate(Function))
  5403. return;
  5404. // C++ [over.match.oper]p3:
  5405. // if no operand has a class type, only those non-member functions in the
  5406. // lookup set that have a first parameter of type T1 or "reference to
  5407. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5408. // is a right operand) a second parameter of type T2 or "reference to
  5409. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5410. // candidate functions.
  5411. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5412. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5413. return;
  5414. // C++11 [class.copy]p11: [DR1402]
  5415. // A defaulted move constructor that is defined as deleted is ignored by
  5416. // overload resolution.
  5417. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5418. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5419. Constructor->isMoveConstructor())
  5420. return;
  5421. // Overload resolution is always an unevaluated context.
  5422. EnterExpressionEvaluationContext Unevaluated(
  5423. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5424. // Add this candidate
  5425. OverloadCandidate &Candidate =
  5426. CandidateSet.addCandidate(Args.size(), EarlyConversions);
  5427. Candidate.FoundDecl = FoundDecl;
  5428. Candidate.Function = Function;
  5429. Candidate.Viable = true;
  5430. Candidate.IsSurrogate = false;
  5431. Candidate.IsADLCandidate = IsADLCandidate;
  5432. Candidate.IgnoreObjectArgument = false;
  5433. Candidate.ExplicitCallArguments = Args.size();
  5434. if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
  5435. !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
  5436. Candidate.Viable = false;
  5437. Candidate.FailureKind = ovl_non_default_multiversion_function;
  5438. return;
  5439. }
  5440. if (Constructor) {
  5441. // C++ [class.copy]p3:
  5442. // A member function template is never instantiated to perform the copy
  5443. // of a class object to an object of its class type.
  5444. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5445. if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
  5446. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5447. IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
  5448. ClassType))) {
  5449. Candidate.Viable = false;
  5450. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5451. return;
  5452. }
  5453. // C++ [over.match.funcs]p8: (proposed DR resolution)
  5454. // A constructor inherited from class type C that has a first parameter
  5455. // of type "reference to P" (including such a constructor instantiated
  5456. // from a template) is excluded from the set of candidate functions when
  5457. // constructing an object of type cv D if the argument list has exactly
  5458. // one argument and D is reference-related to P and P is reference-related
  5459. // to C.
  5460. auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
  5461. if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
  5462. Constructor->getParamDecl(0)->getType()->isReferenceType()) {
  5463. QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
  5464. QualType C = Context.getRecordType(Constructor->getParent());
  5465. QualType D = Context.getRecordType(Shadow->getParent());
  5466. SourceLocation Loc = Args.front()->getExprLoc();
  5467. if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
  5468. (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
  5469. Candidate.Viable = false;
  5470. Candidate.FailureKind = ovl_fail_inhctor_slice;
  5471. return;
  5472. }
  5473. }
  5474. // Check that the constructor is capable of constructing an object in the
  5475. // destination address space.
  5476. if (!Qualifiers::isAddressSpaceSupersetOf(
  5477. Constructor->getMethodQualifiers().getAddressSpace(),
  5478. CandidateSet.getDestAS())) {
  5479. Candidate.Viable = false;
  5480. Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
  5481. }
  5482. }
  5483. unsigned NumParams = Proto->getNumParams();
  5484. // (C++ 13.3.2p2): A candidate function having fewer than m
  5485. // parameters is viable only if it has an ellipsis in its parameter
  5486. // list (8.3.5).
  5487. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5488. !Proto->isVariadic()) {
  5489. Candidate.Viable = false;
  5490. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5491. return;
  5492. }
  5493. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5494. // is viable only if the (m+1)st parameter has a default argument
  5495. // (8.3.6). For the purposes of overload resolution, the
  5496. // parameter list is truncated on the right, so that there are
  5497. // exactly m parameters.
  5498. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5499. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5500. // Not enough arguments.
  5501. Candidate.Viable = false;
  5502. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5503. return;
  5504. }
  5505. // (CUDA B.1): Check for invalid calls between targets.
  5506. if (getLangOpts().CUDA)
  5507. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5508. // Skip the check for callers that are implicit members, because in this
  5509. // case we may not yet know what the member's target is; the target is
  5510. // inferred for the member automatically, based on the bases and fields of
  5511. // the class.
  5512. if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
  5513. Candidate.Viable = false;
  5514. Candidate.FailureKind = ovl_fail_bad_target;
  5515. return;
  5516. }
  5517. // Determine the implicit conversion sequences for each of the
  5518. // arguments.
  5519. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5520. if (Candidate.Conversions[ArgIdx].isInitialized()) {
  5521. // We already formed a conversion sequence for this parameter during
  5522. // template argument deduction.
  5523. } else if (ArgIdx < NumParams) {
  5524. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5525. // exist for each argument an implicit conversion sequence
  5526. // (13.3.3.1) that converts that argument to the corresponding
  5527. // parameter of F.
  5528. QualType ParamType = Proto->getParamType(ArgIdx);
  5529. Candidate.Conversions[ArgIdx] = TryCopyInitialization(
  5530. *this, Args[ArgIdx], ParamType, SuppressUserConversions,
  5531. /*InOverloadResolution=*/true,
  5532. /*AllowObjCWritebackConversion=*/
  5533. getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
  5534. if (Candidate.Conversions[ArgIdx].isBad()) {
  5535. Candidate.Viable = false;
  5536. Candidate.FailureKind = ovl_fail_bad_conversion;
  5537. return;
  5538. }
  5539. } else {
  5540. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5541. // argument for which there is no corresponding parameter is
  5542. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5543. Candidate.Conversions[ArgIdx].setEllipsis();
  5544. }
  5545. }
  5546. if (!AllowExplicit) {
  5547. ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
  5548. if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
  5549. Candidate.Viable = false;
  5550. Candidate.FailureKind = ovl_fail_explicit_resolved;
  5551. return;
  5552. }
  5553. }
  5554. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5555. Candidate.Viable = false;
  5556. Candidate.FailureKind = ovl_fail_enable_if;
  5557. Candidate.DeductionFailure.Data = FailedAttr;
  5558. return;
  5559. }
  5560. if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
  5561. Candidate.Viable = false;
  5562. Candidate.FailureKind = ovl_fail_ext_disabled;
  5563. return;
  5564. }
  5565. }
  5566. ObjCMethodDecl *
  5567. Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
  5568. SmallVectorImpl<ObjCMethodDecl *> &Methods) {
  5569. if (Methods.size() <= 1)
  5570. return nullptr;
  5571. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5572. bool Match = true;
  5573. ObjCMethodDecl *Method = Methods[b];
  5574. unsigned NumNamedArgs = Sel.getNumArgs();
  5575. // Method might have more arguments than selector indicates. This is due
  5576. // to addition of c-style arguments in method.
  5577. if (Method->param_size() > NumNamedArgs)
  5578. NumNamedArgs = Method->param_size();
  5579. if (Args.size() < NumNamedArgs)
  5580. continue;
  5581. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5582. // We can't do any type-checking on a type-dependent argument.
  5583. if (Args[i]->isTypeDependent()) {
  5584. Match = false;
  5585. break;
  5586. }
  5587. ParmVarDecl *param = Method->parameters()[i];
  5588. Expr *argExpr = Args[i];
  5589. assert(argExpr && "SelectBestMethod(): missing expression");
  5590. // Strip the unbridged-cast placeholder expression off unless it's
  5591. // a consumed argument.
  5592. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5593. !param->hasAttr<CFConsumedAttr>())
  5594. argExpr = stripARCUnbridgedCast(argExpr);
  5595. // If the parameter is __unknown_anytype, move on to the next method.
  5596. if (param->getType() == Context.UnknownAnyTy) {
  5597. Match = false;
  5598. break;
  5599. }
  5600. ImplicitConversionSequence ConversionState
  5601. = TryCopyInitialization(*this, argExpr, param->getType(),
  5602. /*SuppressUserConversions*/false,
  5603. /*InOverloadResolution=*/true,
  5604. /*AllowObjCWritebackConversion=*/
  5605. getLangOpts().ObjCAutoRefCount,
  5606. /*AllowExplicit*/false);
  5607. // This function looks for a reasonably-exact match, so we consider
  5608. // incompatible pointer conversions to be a failure here.
  5609. if (ConversionState.isBad() ||
  5610. (ConversionState.isStandard() &&
  5611. ConversionState.Standard.Second ==
  5612. ICK_Incompatible_Pointer_Conversion)) {
  5613. Match = false;
  5614. break;
  5615. }
  5616. }
  5617. // Promote additional arguments to variadic methods.
  5618. if (Match && Method->isVariadic()) {
  5619. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5620. if (Args[i]->isTypeDependent()) {
  5621. Match = false;
  5622. break;
  5623. }
  5624. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5625. nullptr);
  5626. if (Arg.isInvalid()) {
  5627. Match = false;
  5628. break;
  5629. }
  5630. }
  5631. } else {
  5632. // Check for extra arguments to non-variadic methods.
  5633. if (Args.size() != NumNamedArgs)
  5634. Match = false;
  5635. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5636. // Special case when selectors have no argument. In this case, select
  5637. // one with the most general result type of 'id'.
  5638. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5639. QualType ReturnT = Methods[b]->getReturnType();
  5640. if (ReturnT->isObjCIdType())
  5641. return Methods[b];
  5642. }
  5643. }
  5644. }
  5645. if (Match)
  5646. return Method;
  5647. }
  5648. return nullptr;
  5649. }
  5650. static bool
  5651. convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
  5652. ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
  5653. bool MissingImplicitThis, Expr *&ConvertedThis,
  5654. SmallVectorImpl<Expr *> &ConvertedArgs) {
  5655. if (ThisArg) {
  5656. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5657. assert(!isa<CXXConstructorDecl>(Method) &&
  5658. "Shouldn't have `this` for ctors!");
  5659. assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
  5660. ExprResult R = S.PerformObjectArgumentInitialization(
  5661. ThisArg, /*Qualifier=*/nullptr, Method, Method);
  5662. if (R.isInvalid())
  5663. return false;
  5664. ConvertedThis = R.get();
  5665. } else {
  5666. if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
  5667. (void)MD;
  5668. assert((MissingImplicitThis || MD->isStatic() ||
  5669. isa<CXXConstructorDecl>(MD)) &&
  5670. "Expected `this` for non-ctor instance methods");
  5671. }
  5672. ConvertedThis = nullptr;
  5673. }
  5674. // Ignore any variadic arguments. Converting them is pointless, since the
  5675. // user can't refer to them in the function condition.
  5676. unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
  5677. // Convert the arguments.
  5678. for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
  5679. ExprResult R;
  5680. R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5681. S.Context, Function->getParamDecl(I)),
  5682. SourceLocation(), Args[I]);
  5683. if (R.isInvalid())
  5684. return false;
  5685. ConvertedArgs.push_back(R.get());
  5686. }
  5687. if (Trap.hasErrorOccurred())
  5688. return false;
  5689. // Push default arguments if needed.
  5690. if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
  5691. for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
  5692. ParmVarDecl *P = Function->getParamDecl(i);
  5693. Expr *DefArg = P->hasUninstantiatedDefaultArg()
  5694. ? P->getUninstantiatedDefaultArg()
  5695. : P->getDefaultArg();
  5696. // This can only happen in code completion, i.e. when PartialOverloading
  5697. // is true.
  5698. if (!DefArg)
  5699. return false;
  5700. ExprResult R =
  5701. S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5702. S.Context, Function->getParamDecl(i)),
  5703. SourceLocation(), DefArg);
  5704. if (R.isInvalid())
  5705. return false;
  5706. ConvertedArgs.push_back(R.get());
  5707. }
  5708. if (Trap.hasErrorOccurred())
  5709. return false;
  5710. }
  5711. return true;
  5712. }
  5713. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5714. bool MissingImplicitThis) {
  5715. auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
  5716. if (EnableIfAttrs.begin() == EnableIfAttrs.end())
  5717. return nullptr;
  5718. SFINAETrap Trap(*this);
  5719. SmallVector<Expr *, 16> ConvertedArgs;
  5720. // FIXME: We should look into making enable_if late-parsed.
  5721. Expr *DiscardedThis;
  5722. if (!convertArgsForAvailabilityChecks(
  5723. *this, Function, /*ThisArg=*/nullptr, Args, Trap,
  5724. /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
  5725. return *EnableIfAttrs.begin();
  5726. for (auto *EIA : EnableIfAttrs) {
  5727. APValue Result;
  5728. // FIXME: This doesn't consider value-dependent cases, because doing so is
  5729. // very difficult. Ideally, we should handle them more gracefully.
  5730. if (EIA->getCond()->isValueDependent() ||
  5731. !EIA->getCond()->EvaluateWithSubstitution(
  5732. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
  5733. return EIA;
  5734. if (!Result.isInt() || !Result.getInt().getBoolValue())
  5735. return EIA;
  5736. }
  5737. return nullptr;
  5738. }
  5739. template <typename CheckFn>
  5740. static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
  5741. bool ArgDependent, SourceLocation Loc,
  5742. CheckFn &&IsSuccessful) {
  5743. SmallVector<const DiagnoseIfAttr *, 8> Attrs;
  5744. for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
  5745. if (ArgDependent == DIA->getArgDependent())
  5746. Attrs.push_back(DIA);
  5747. }
  5748. // Common case: No diagnose_if attributes, so we can quit early.
  5749. if (Attrs.empty())
  5750. return false;
  5751. auto WarningBegin = std::stable_partition(
  5752. Attrs.begin(), Attrs.end(),
  5753. [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
  5754. // Note that diagnose_if attributes are late-parsed, so they appear in the
  5755. // correct order (unlike enable_if attributes).
  5756. auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
  5757. IsSuccessful);
  5758. if (ErrAttr != WarningBegin) {
  5759. const DiagnoseIfAttr *DIA = *ErrAttr;
  5760. S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
  5761. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  5762. << DIA->getParent() << DIA->getCond()->getSourceRange();
  5763. return true;
  5764. }
  5765. for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
  5766. if (IsSuccessful(DIA)) {
  5767. S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
  5768. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  5769. << DIA->getParent() << DIA->getCond()->getSourceRange();
  5770. }
  5771. return false;
  5772. }
  5773. bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
  5774. const Expr *ThisArg,
  5775. ArrayRef<const Expr *> Args,
  5776. SourceLocation Loc) {
  5777. return diagnoseDiagnoseIfAttrsWith(
  5778. *this, Function, /*ArgDependent=*/true, Loc,
  5779. [&](const DiagnoseIfAttr *DIA) {
  5780. APValue Result;
  5781. // It's sane to use the same Args for any redecl of this function, since
  5782. // EvaluateWithSubstitution only cares about the position of each
  5783. // argument in the arg list, not the ParmVarDecl* it maps to.
  5784. if (!DIA->getCond()->EvaluateWithSubstitution(
  5785. Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
  5786. return false;
  5787. return Result.isInt() && Result.getInt().getBoolValue();
  5788. });
  5789. }
  5790. bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
  5791. SourceLocation Loc) {
  5792. return diagnoseDiagnoseIfAttrsWith(
  5793. *this, ND, /*ArgDependent=*/false, Loc,
  5794. [&](const DiagnoseIfAttr *DIA) {
  5795. bool Result;
  5796. return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
  5797. Result;
  5798. });
  5799. }
  5800. /// Add all of the function declarations in the given function set to
  5801. /// the overload candidate set.
  5802. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5803. ArrayRef<Expr *> Args,
  5804. OverloadCandidateSet &CandidateSet,
  5805. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5806. bool SuppressUserConversions,
  5807. bool PartialOverloading,
  5808. bool FirstArgumentIsBase) {
  5809. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5810. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5811. ArrayRef<Expr *> FunctionArgs = Args;
  5812. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  5813. FunctionDecl *FD =
  5814. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  5815. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
  5816. QualType ObjectType;
  5817. Expr::Classification ObjectClassification;
  5818. if (Args.size() > 0) {
  5819. if (Expr *E = Args[0]) {
  5820. // Use the explicit base to restrict the lookup:
  5821. ObjectType = E->getType();
  5822. // Pointers in the object arguments are implicitly dereferenced, so we
  5823. // always classify them as l-values.
  5824. if (!ObjectType.isNull() && ObjectType->isPointerType())
  5825. ObjectClassification = Expr::Classification::makeSimpleLValue();
  5826. else
  5827. ObjectClassification = E->Classify(Context);
  5828. } // .. else there is an implicit base.
  5829. FunctionArgs = Args.slice(1);
  5830. }
  5831. if (FunTmpl) {
  5832. AddMethodTemplateCandidate(
  5833. FunTmpl, F.getPair(),
  5834. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5835. ExplicitTemplateArgs, ObjectType, ObjectClassification,
  5836. FunctionArgs, CandidateSet, SuppressUserConversions,
  5837. PartialOverloading);
  5838. } else {
  5839. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5840. cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
  5841. ObjectClassification, FunctionArgs, CandidateSet,
  5842. SuppressUserConversions, PartialOverloading);
  5843. }
  5844. } else {
  5845. // This branch handles both standalone functions and static methods.
  5846. // Slice the first argument (which is the base) when we access
  5847. // static method as non-static.
  5848. if (Args.size() > 0 &&
  5849. (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
  5850. !isa<CXXConstructorDecl>(FD)))) {
  5851. assert(cast<CXXMethodDecl>(FD)->isStatic());
  5852. FunctionArgs = Args.slice(1);
  5853. }
  5854. if (FunTmpl) {
  5855. AddTemplateOverloadCandidate(
  5856. FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
  5857. CandidateSet, SuppressUserConversions, PartialOverloading);
  5858. } else {
  5859. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
  5860. SuppressUserConversions, PartialOverloading);
  5861. }
  5862. }
  5863. }
  5864. }
  5865. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5866. /// method) as a method candidate to the given overload set.
  5867. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
  5868. QualType ObjectType,
  5869. Expr::Classification ObjectClassification,
  5870. ArrayRef<Expr *> Args,
  5871. OverloadCandidateSet& CandidateSet,
  5872. bool SuppressUserConversions) {
  5873. NamedDecl *Decl = FoundDecl.getDecl();
  5874. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5875. if (isa<UsingShadowDecl>(Decl))
  5876. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5877. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5878. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5879. "Expected a member function template");
  5880. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5881. /*ExplicitArgs*/ nullptr, ObjectType,
  5882. ObjectClassification, Args, CandidateSet,
  5883. SuppressUserConversions);
  5884. } else {
  5885. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5886. ObjectType, ObjectClassification, Args, CandidateSet,
  5887. SuppressUserConversions);
  5888. }
  5889. }
  5890. /// AddMethodCandidate - Adds the given C++ member function to the set
  5891. /// of candidate functions, using the given function call arguments
  5892. /// and the object argument (@c Object). For example, in a call
  5893. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5894. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5895. /// allow user-defined conversions via constructors or conversion
  5896. /// operators.
  5897. void
  5898. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5899. CXXRecordDecl *ActingContext, QualType ObjectType,
  5900. Expr::Classification ObjectClassification,
  5901. ArrayRef<Expr *> Args,
  5902. OverloadCandidateSet &CandidateSet,
  5903. bool SuppressUserConversions,
  5904. bool PartialOverloading,
  5905. ConversionSequenceList EarlyConversions) {
  5906. const FunctionProtoType *Proto
  5907. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5908. assert(Proto && "Methods without a prototype cannot be overloaded");
  5909. assert(!isa<CXXConstructorDecl>(Method) &&
  5910. "Use AddOverloadCandidate for constructors");
  5911. if (!CandidateSet.isNewCandidate(Method))
  5912. return;
  5913. // C++11 [class.copy]p23: [DR1402]
  5914. // A defaulted move assignment operator that is defined as deleted is
  5915. // ignored by overload resolution.
  5916. if (Method->isDefaulted() && Method->isDeleted() &&
  5917. Method->isMoveAssignmentOperator())
  5918. return;
  5919. // Overload resolution is always an unevaluated context.
  5920. EnterExpressionEvaluationContext Unevaluated(
  5921. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5922. // Add this candidate
  5923. OverloadCandidate &Candidate =
  5924. CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
  5925. Candidate.FoundDecl = FoundDecl;
  5926. Candidate.Function = Method;
  5927. Candidate.IsSurrogate = false;
  5928. Candidate.IgnoreObjectArgument = false;
  5929. Candidate.ExplicitCallArguments = Args.size();
  5930. unsigned NumParams = Proto->getNumParams();
  5931. // (C++ 13.3.2p2): A candidate function having fewer than m
  5932. // parameters is viable only if it has an ellipsis in its parameter
  5933. // list (8.3.5).
  5934. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5935. !Proto->isVariadic()) {
  5936. Candidate.Viable = false;
  5937. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5938. return;
  5939. }
  5940. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5941. // is viable only if the (m+1)st parameter has a default argument
  5942. // (8.3.6). For the purposes of overload resolution, the
  5943. // parameter list is truncated on the right, so that there are
  5944. // exactly m parameters.
  5945. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  5946. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5947. // Not enough arguments.
  5948. Candidate.Viable = false;
  5949. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5950. return;
  5951. }
  5952. Candidate.Viable = true;
  5953. if (Method->isStatic() || ObjectType.isNull())
  5954. // The implicit object argument is ignored.
  5955. Candidate.IgnoreObjectArgument = true;
  5956. else {
  5957. // Determine the implicit conversion sequence for the object
  5958. // parameter.
  5959. Candidate.Conversions[0] = TryObjectArgumentInitialization(
  5960. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  5961. Method, ActingContext);
  5962. if (Candidate.Conversions[0].isBad()) {
  5963. Candidate.Viable = false;
  5964. Candidate.FailureKind = ovl_fail_bad_conversion;
  5965. return;
  5966. }
  5967. }
  5968. // (CUDA B.1): Check for invalid calls between targets.
  5969. if (getLangOpts().CUDA)
  5970. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5971. if (!IsAllowedCUDACall(Caller, Method)) {
  5972. Candidate.Viable = false;
  5973. Candidate.FailureKind = ovl_fail_bad_target;
  5974. return;
  5975. }
  5976. // Determine the implicit conversion sequences for each of the
  5977. // arguments.
  5978. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5979. if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
  5980. // We already formed a conversion sequence for this parameter during
  5981. // template argument deduction.
  5982. } else if (ArgIdx < NumParams) {
  5983. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5984. // exist for each argument an implicit conversion sequence
  5985. // (13.3.3.1) that converts that argument to the corresponding
  5986. // parameter of F.
  5987. QualType ParamType = Proto->getParamType(ArgIdx);
  5988. Candidate.Conversions[ArgIdx + 1]
  5989. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5990. SuppressUserConversions,
  5991. /*InOverloadResolution=*/true,
  5992. /*AllowObjCWritebackConversion=*/
  5993. getLangOpts().ObjCAutoRefCount);
  5994. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  5995. Candidate.Viable = false;
  5996. Candidate.FailureKind = ovl_fail_bad_conversion;
  5997. return;
  5998. }
  5999. } else {
  6000. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6001. // argument for which there is no corresponding parameter is
  6002. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  6003. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6004. }
  6005. }
  6006. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  6007. Candidate.Viable = false;
  6008. Candidate.FailureKind = ovl_fail_enable_if;
  6009. Candidate.DeductionFailure.Data = FailedAttr;
  6010. return;
  6011. }
  6012. if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
  6013. !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
  6014. Candidate.Viable = false;
  6015. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6016. }
  6017. }
  6018. /// Add a C++ member function template as a candidate to the candidate
  6019. /// set, using template argument deduction to produce an appropriate member
  6020. /// function template specialization.
  6021. void
  6022. Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
  6023. DeclAccessPair FoundDecl,
  6024. CXXRecordDecl *ActingContext,
  6025. TemplateArgumentListInfo *ExplicitTemplateArgs,
  6026. QualType ObjectType,
  6027. Expr::Classification ObjectClassification,
  6028. ArrayRef<Expr *> Args,
  6029. OverloadCandidateSet& CandidateSet,
  6030. bool SuppressUserConversions,
  6031. bool PartialOverloading) {
  6032. if (!CandidateSet.isNewCandidate(MethodTmpl))
  6033. return;
  6034. // C++ [over.match.funcs]p7:
  6035. // In each case where a candidate is a function template, candidate
  6036. // function template specializations are generated using template argument
  6037. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6038. // candidate functions in the usual way.113) A given name can refer to one
  6039. // or more function templates and also to a set of overloaded non-template
  6040. // functions. In such a case, the candidate functions generated from each
  6041. // function template are combined with the set of non-template candidate
  6042. // functions.
  6043. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6044. FunctionDecl *Specialization = nullptr;
  6045. ConversionSequenceList Conversions;
  6046. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6047. MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
  6048. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6049. return CheckNonDependentConversions(
  6050. MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
  6051. SuppressUserConversions, ActingContext, ObjectType,
  6052. ObjectClassification);
  6053. })) {
  6054. OverloadCandidate &Candidate =
  6055. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6056. Candidate.FoundDecl = FoundDecl;
  6057. Candidate.Function = MethodTmpl->getTemplatedDecl();
  6058. Candidate.Viable = false;
  6059. Candidate.IsSurrogate = false;
  6060. Candidate.IgnoreObjectArgument =
  6061. cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
  6062. ObjectType.isNull();
  6063. Candidate.ExplicitCallArguments = Args.size();
  6064. if (Result == TDK_NonDependentConversionFailure)
  6065. Candidate.FailureKind = ovl_fail_bad_conversion;
  6066. else {
  6067. Candidate.FailureKind = ovl_fail_bad_deduction;
  6068. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6069. Info);
  6070. }
  6071. return;
  6072. }
  6073. // Add the function template specialization produced by template argument
  6074. // deduction as a candidate.
  6075. assert(Specialization && "Missing member function template specialization?");
  6076. assert(isa<CXXMethodDecl>(Specialization) &&
  6077. "Specialization is not a member function?");
  6078. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  6079. ActingContext, ObjectType, ObjectClassification, Args,
  6080. CandidateSet, SuppressUserConversions, PartialOverloading,
  6081. Conversions);
  6082. }
  6083. /// Add a C++ function template specialization as a candidate
  6084. /// in the candidate set, using template argument deduction to produce
  6085. /// an appropriate function template specialization.
  6086. void Sema::AddTemplateOverloadCandidate(
  6087. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6088. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  6089. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6090. bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) {
  6091. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  6092. return;
  6093. // C++ [over.match.funcs]p7:
  6094. // In each case where a candidate is a function template, candidate
  6095. // function template specializations are generated using template argument
  6096. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6097. // candidate functions in the usual way.113) A given name can refer to one
  6098. // or more function templates and also to a set of overloaded non-template
  6099. // functions. In such a case, the candidate functions generated from each
  6100. // function template are combined with the set of non-template candidate
  6101. // functions.
  6102. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6103. FunctionDecl *Specialization = nullptr;
  6104. ConversionSequenceList Conversions;
  6105. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6106. FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
  6107. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6108. return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
  6109. Args, CandidateSet, Conversions,
  6110. SuppressUserConversions);
  6111. })) {
  6112. OverloadCandidate &Candidate =
  6113. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6114. Candidate.FoundDecl = FoundDecl;
  6115. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6116. Candidate.Viable = false;
  6117. Candidate.IsSurrogate = false;
  6118. Candidate.IsADLCandidate = IsADLCandidate;
  6119. // Ignore the object argument if there is one, since we don't have an object
  6120. // type.
  6121. Candidate.IgnoreObjectArgument =
  6122. isa<CXXMethodDecl>(Candidate.Function) &&
  6123. !isa<CXXConstructorDecl>(Candidate.Function);
  6124. Candidate.ExplicitCallArguments = Args.size();
  6125. if (Result == TDK_NonDependentConversionFailure)
  6126. Candidate.FailureKind = ovl_fail_bad_conversion;
  6127. else {
  6128. Candidate.FailureKind = ovl_fail_bad_deduction;
  6129. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6130. Info);
  6131. }
  6132. return;
  6133. }
  6134. // Add the function template specialization produced by template argument
  6135. // deduction as a candidate.
  6136. assert(Specialization && "Missing function template specialization?");
  6137. AddOverloadCandidate(
  6138. Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
  6139. PartialOverloading, AllowExplicit,
  6140. /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions);
  6141. }
  6142. /// Check that implicit conversion sequences can be formed for each argument
  6143. /// whose corresponding parameter has a non-dependent type, per DR1391's
  6144. /// [temp.deduct.call]p10.
  6145. bool Sema::CheckNonDependentConversions(
  6146. FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
  6147. ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
  6148. ConversionSequenceList &Conversions, bool SuppressUserConversions,
  6149. CXXRecordDecl *ActingContext, QualType ObjectType,
  6150. Expr::Classification ObjectClassification) {
  6151. // FIXME: The cases in which we allow explicit conversions for constructor
  6152. // arguments never consider calling a constructor template. It's not clear
  6153. // that is correct.
  6154. const bool AllowExplicit = false;
  6155. auto *FD = FunctionTemplate->getTemplatedDecl();
  6156. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  6157. bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
  6158. unsigned ThisConversions = HasThisConversion ? 1 : 0;
  6159. Conversions =
  6160. CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
  6161. // Overload resolution is always an unevaluated context.
  6162. EnterExpressionEvaluationContext Unevaluated(
  6163. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6164. // For a method call, check the 'this' conversion here too. DR1391 doesn't
  6165. // require that, but this check should never result in a hard error, and
  6166. // overload resolution is permitted to sidestep instantiations.
  6167. if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
  6168. !ObjectType.isNull()) {
  6169. Conversions[0] = TryObjectArgumentInitialization(
  6170. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6171. Method, ActingContext);
  6172. if (Conversions[0].isBad())
  6173. return true;
  6174. }
  6175. for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
  6176. ++I) {
  6177. QualType ParamType = ParamTypes[I];
  6178. if (!ParamType->isDependentType()) {
  6179. Conversions[ThisConversions + I]
  6180. = TryCopyInitialization(*this, Args[I], ParamType,
  6181. SuppressUserConversions,
  6182. /*InOverloadResolution=*/true,
  6183. /*AllowObjCWritebackConversion=*/
  6184. getLangOpts().ObjCAutoRefCount,
  6185. AllowExplicit);
  6186. if (Conversions[ThisConversions + I].isBad())
  6187. return true;
  6188. }
  6189. }
  6190. return false;
  6191. }
  6192. /// Determine whether this is an allowable conversion from the result
  6193. /// of an explicit conversion operator to the expected type, per C++
  6194. /// [over.match.conv]p1 and [over.match.ref]p1.
  6195. ///
  6196. /// \param ConvType The return type of the conversion function.
  6197. ///
  6198. /// \param ToType The type we are converting to.
  6199. ///
  6200. /// \param AllowObjCPointerConversion Allow a conversion from one
  6201. /// Objective-C pointer to another.
  6202. ///
  6203. /// \returns true if the conversion is allowable, false otherwise.
  6204. static bool isAllowableExplicitConversion(Sema &S,
  6205. QualType ConvType, QualType ToType,
  6206. bool AllowObjCPointerConversion) {
  6207. QualType ToNonRefType = ToType.getNonReferenceType();
  6208. // Easy case: the types are the same.
  6209. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  6210. return true;
  6211. // Allow qualification conversions.
  6212. bool ObjCLifetimeConversion;
  6213. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  6214. ObjCLifetimeConversion))
  6215. return true;
  6216. // If we're not allowed to consider Objective-C pointer conversions,
  6217. // we're done.
  6218. if (!AllowObjCPointerConversion)
  6219. return false;
  6220. // Is this an Objective-C pointer conversion?
  6221. bool IncompatibleObjC = false;
  6222. QualType ConvertedType;
  6223. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  6224. IncompatibleObjC);
  6225. }
  6226. /// AddConversionCandidate - Add a C++ conversion function as a
  6227. /// candidate in the candidate set (C++ [over.match.conv],
  6228. /// C++ [over.match.copy]). From is the expression we're converting from,
  6229. /// and ToType is the type that we're eventually trying to convert to
  6230. /// (which may or may not be the same type as the type that the
  6231. /// conversion function produces).
  6232. void Sema::AddConversionCandidate(
  6233. CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
  6234. CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
  6235. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6236. bool AllowExplicit, bool AllowResultConversion) {
  6237. assert(!Conversion->getDescribedFunctionTemplate() &&
  6238. "Conversion function templates use AddTemplateConversionCandidate");
  6239. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  6240. if (!CandidateSet.isNewCandidate(Conversion))
  6241. return;
  6242. // If the conversion function has an undeduced return type, trigger its
  6243. // deduction now.
  6244. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  6245. if (DeduceReturnType(Conversion, From->getExprLoc()))
  6246. return;
  6247. ConvType = Conversion->getConversionType().getNonReferenceType();
  6248. }
  6249. // If we don't allow any conversion of the result type, ignore conversion
  6250. // functions that don't convert to exactly (possibly cv-qualified) T.
  6251. if (!AllowResultConversion &&
  6252. !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
  6253. return;
  6254. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  6255. // operator is only a candidate if its return type is the target type or
  6256. // can be converted to the target type with a qualification conversion.
  6257. if (Conversion->isExplicit() &&
  6258. !isAllowableExplicitConversion(*this, ConvType, ToType,
  6259. AllowObjCConversionOnExplicit))
  6260. return;
  6261. // Overload resolution is always an unevaluated context.
  6262. EnterExpressionEvaluationContext Unevaluated(
  6263. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6264. // Add this candidate
  6265. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  6266. Candidate.FoundDecl = FoundDecl;
  6267. Candidate.Function = Conversion;
  6268. Candidate.IsSurrogate = false;
  6269. Candidate.IgnoreObjectArgument = false;
  6270. Candidate.FinalConversion.setAsIdentityConversion();
  6271. Candidate.FinalConversion.setFromType(ConvType);
  6272. Candidate.FinalConversion.setAllToTypes(ToType);
  6273. Candidate.Viable = true;
  6274. Candidate.ExplicitCallArguments = 1;
  6275. // C++ [over.match.funcs]p4:
  6276. // For conversion functions, the function is considered to be a member of
  6277. // the class of the implicit implied object argument for the purpose of
  6278. // defining the type of the implicit object parameter.
  6279. //
  6280. // Determine the implicit conversion sequence for the implicit
  6281. // object parameter.
  6282. QualType ImplicitParamType = From->getType();
  6283. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  6284. ImplicitParamType = FromPtrType->getPointeeType();
  6285. CXXRecordDecl *ConversionContext
  6286. = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
  6287. Candidate.Conversions[0] = TryObjectArgumentInitialization(
  6288. *this, CandidateSet.getLocation(), From->getType(),
  6289. From->Classify(Context), Conversion, ConversionContext);
  6290. if (Candidate.Conversions[0].isBad()) {
  6291. Candidate.Viable = false;
  6292. Candidate.FailureKind = ovl_fail_bad_conversion;
  6293. return;
  6294. }
  6295. // We won't go through a user-defined type conversion function to convert a
  6296. // derived to base as such conversions are given Conversion Rank. They only
  6297. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  6298. QualType FromCanon
  6299. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  6300. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  6301. if (FromCanon == ToCanon ||
  6302. IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
  6303. Candidate.Viable = false;
  6304. Candidate.FailureKind = ovl_fail_trivial_conversion;
  6305. return;
  6306. }
  6307. // To determine what the conversion from the result of calling the
  6308. // conversion function to the type we're eventually trying to
  6309. // convert to (ToType), we need to synthesize a call to the
  6310. // conversion function and attempt copy initialization from it. This
  6311. // makes sure that we get the right semantics with respect to
  6312. // lvalues/rvalues and the type. Fortunately, we can allocate this
  6313. // call on the stack and we don't need its arguments to be
  6314. // well-formed.
  6315. DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
  6316. VK_LValue, From->getBeginLoc());
  6317. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  6318. Context.getPointerType(Conversion->getType()),
  6319. CK_FunctionToPointerDecay,
  6320. &ConversionRef, VK_RValue);
  6321. QualType ConversionType = Conversion->getConversionType();
  6322. if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
  6323. Candidate.Viable = false;
  6324. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6325. return;
  6326. }
  6327. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  6328. // Note that it is safe to allocate CallExpr on the stack here because
  6329. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  6330. // allocator).
  6331. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  6332. llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
  6333. Buffer;
  6334. CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
  6335. Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
  6336. ImplicitConversionSequence ICS =
  6337. TryCopyInitialization(*this, TheTemporaryCall, ToType,
  6338. /*SuppressUserConversions=*/true,
  6339. /*InOverloadResolution=*/false,
  6340. /*AllowObjCWritebackConversion=*/false);
  6341. switch (ICS.getKind()) {
  6342. case ImplicitConversionSequence::StandardConversion:
  6343. Candidate.FinalConversion = ICS.Standard;
  6344. // C++ [over.ics.user]p3:
  6345. // If the user-defined conversion is specified by a specialization of a
  6346. // conversion function template, the second standard conversion sequence
  6347. // shall have exact match rank.
  6348. if (Conversion->getPrimaryTemplate() &&
  6349. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  6350. Candidate.Viable = false;
  6351. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  6352. return;
  6353. }
  6354. // C++0x [dcl.init.ref]p5:
  6355. // In the second case, if the reference is an rvalue reference and
  6356. // the second standard conversion sequence of the user-defined
  6357. // conversion sequence includes an lvalue-to-rvalue conversion, the
  6358. // program is ill-formed.
  6359. if (ToType->isRValueReferenceType() &&
  6360. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  6361. Candidate.Viable = false;
  6362. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6363. return;
  6364. }
  6365. break;
  6366. case ImplicitConversionSequence::BadConversion:
  6367. Candidate.Viable = false;
  6368. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6369. return;
  6370. default:
  6371. llvm_unreachable(
  6372. "Can only end up with a standard conversion sequence or failure");
  6373. }
  6374. if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
  6375. ExplicitSpecKind::ResolvedFalse) {
  6376. Candidate.Viable = false;
  6377. Candidate.FailureKind = ovl_fail_explicit_resolved;
  6378. return;
  6379. }
  6380. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6381. Candidate.Viable = false;
  6382. Candidate.FailureKind = ovl_fail_enable_if;
  6383. Candidate.DeductionFailure.Data = FailedAttr;
  6384. return;
  6385. }
  6386. if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
  6387. !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
  6388. Candidate.Viable = false;
  6389. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6390. }
  6391. }
  6392. /// Adds a conversion function template specialization
  6393. /// candidate to the overload set, using template argument deduction
  6394. /// to deduce the template arguments of the conversion function
  6395. /// template from the type that we are converting to (C++
  6396. /// [temp.deduct.conv]).
  6397. void Sema::AddTemplateConversionCandidate(
  6398. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6399. CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
  6400. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6401. bool AllowExplicit, bool AllowResultConversion) {
  6402. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  6403. "Only conversion function templates permitted here");
  6404. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  6405. return;
  6406. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6407. CXXConversionDecl *Specialization = nullptr;
  6408. if (TemplateDeductionResult Result
  6409. = DeduceTemplateArguments(FunctionTemplate, ToType,
  6410. Specialization, Info)) {
  6411. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  6412. Candidate.FoundDecl = FoundDecl;
  6413. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6414. Candidate.Viable = false;
  6415. Candidate.FailureKind = ovl_fail_bad_deduction;
  6416. Candidate.IsSurrogate = false;
  6417. Candidate.IgnoreObjectArgument = false;
  6418. Candidate.ExplicitCallArguments = 1;
  6419. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6420. Info);
  6421. return;
  6422. }
  6423. // Add the conversion function template specialization produced by
  6424. // template argument deduction as a candidate.
  6425. assert(Specialization && "Missing function template specialization?");
  6426. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  6427. CandidateSet, AllowObjCConversionOnExplicit,
  6428. AllowExplicit, AllowResultConversion);
  6429. }
  6430. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  6431. /// converts the given @c Object to a function pointer via the
  6432. /// conversion function @c Conversion, and then attempts to call it
  6433. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  6434. /// the type of function that we'll eventually be calling.
  6435. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  6436. DeclAccessPair FoundDecl,
  6437. CXXRecordDecl *ActingContext,
  6438. const FunctionProtoType *Proto,
  6439. Expr *Object,
  6440. ArrayRef<Expr *> Args,
  6441. OverloadCandidateSet& CandidateSet) {
  6442. if (!CandidateSet.isNewCandidate(Conversion))
  6443. return;
  6444. // Overload resolution is always an unevaluated context.
  6445. EnterExpressionEvaluationContext Unevaluated(
  6446. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6447. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  6448. Candidate.FoundDecl = FoundDecl;
  6449. Candidate.Function = nullptr;
  6450. Candidate.Surrogate = Conversion;
  6451. Candidate.Viable = true;
  6452. Candidate.IsSurrogate = true;
  6453. Candidate.IgnoreObjectArgument = false;
  6454. Candidate.ExplicitCallArguments = Args.size();
  6455. // Determine the implicit conversion sequence for the implicit
  6456. // object parameter.
  6457. ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
  6458. *this, CandidateSet.getLocation(), Object->getType(),
  6459. Object->Classify(Context), Conversion, ActingContext);
  6460. if (ObjectInit.isBad()) {
  6461. Candidate.Viable = false;
  6462. Candidate.FailureKind = ovl_fail_bad_conversion;
  6463. Candidate.Conversions[0] = ObjectInit;
  6464. return;
  6465. }
  6466. // The first conversion is actually a user-defined conversion whose
  6467. // first conversion is ObjectInit's standard conversion (which is
  6468. // effectively a reference binding). Record it as such.
  6469. Candidate.Conversions[0].setUserDefined();
  6470. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  6471. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  6472. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  6473. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  6474. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  6475. Candidate.Conversions[0].UserDefined.After
  6476. = Candidate.Conversions[0].UserDefined.Before;
  6477. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  6478. // Find the
  6479. unsigned NumParams = Proto->getNumParams();
  6480. // (C++ 13.3.2p2): A candidate function having fewer than m
  6481. // parameters is viable only if it has an ellipsis in its parameter
  6482. // list (8.3.5).
  6483. if (Args.size() > NumParams && !Proto->isVariadic()) {
  6484. Candidate.Viable = false;
  6485. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6486. return;
  6487. }
  6488. // Function types don't have any default arguments, so just check if
  6489. // we have enough arguments.
  6490. if (Args.size() < NumParams) {
  6491. // Not enough arguments.
  6492. Candidate.Viable = false;
  6493. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6494. return;
  6495. }
  6496. // Determine the implicit conversion sequences for each of the
  6497. // arguments.
  6498. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6499. if (ArgIdx < NumParams) {
  6500. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6501. // exist for each argument an implicit conversion sequence
  6502. // (13.3.3.1) that converts that argument to the corresponding
  6503. // parameter of F.
  6504. QualType ParamType = Proto->getParamType(ArgIdx);
  6505. Candidate.Conversions[ArgIdx + 1]
  6506. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6507. /*SuppressUserConversions=*/false,
  6508. /*InOverloadResolution=*/false,
  6509. /*AllowObjCWritebackConversion=*/
  6510. getLangOpts().ObjCAutoRefCount);
  6511. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6512. Candidate.Viable = false;
  6513. Candidate.FailureKind = ovl_fail_bad_conversion;
  6514. return;
  6515. }
  6516. } else {
  6517. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6518. // argument for which there is no corresponding parameter is
  6519. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6520. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6521. }
  6522. }
  6523. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6524. Candidate.Viable = false;
  6525. Candidate.FailureKind = ovl_fail_enable_if;
  6526. Candidate.DeductionFailure.Data = FailedAttr;
  6527. return;
  6528. }
  6529. }
  6530. /// Add overload candidates for overloaded operators that are
  6531. /// member functions.
  6532. ///
  6533. /// Add the overloaded operator candidates that are member functions
  6534. /// for the operator Op that was used in an operator expression such
  6535. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6536. /// CandidateSet will store the added overload candidates. (C++
  6537. /// [over.match.oper]).
  6538. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6539. SourceLocation OpLoc,
  6540. ArrayRef<Expr *> Args,
  6541. OverloadCandidateSet& CandidateSet,
  6542. SourceRange OpRange) {
  6543. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6544. // C++ [over.match.oper]p3:
  6545. // For a unary operator @ with an operand of a type whose
  6546. // cv-unqualified version is T1, and for a binary operator @ with
  6547. // a left operand of a type whose cv-unqualified version is T1 and
  6548. // a right operand of a type whose cv-unqualified version is T2,
  6549. // three sets of candidate functions, designated member
  6550. // candidates, non-member candidates and built-in candidates, are
  6551. // constructed as follows:
  6552. QualType T1 = Args[0]->getType();
  6553. // -- If T1 is a complete class type or a class currently being
  6554. // defined, the set of member candidates is the result of the
  6555. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6556. // the set of member candidates is empty.
  6557. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6558. // Complete the type if it can be completed.
  6559. if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
  6560. return;
  6561. // If the type is neither complete nor being defined, bail out now.
  6562. if (!T1Rec->getDecl()->getDefinition())
  6563. return;
  6564. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6565. LookupQualifiedName(Operators, T1Rec->getDecl());
  6566. Operators.suppressDiagnostics();
  6567. for (LookupResult::iterator Oper = Operators.begin(),
  6568. OperEnd = Operators.end();
  6569. Oper != OperEnd;
  6570. ++Oper)
  6571. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6572. Args[0]->Classify(Context), Args.slice(1),
  6573. CandidateSet, /*SuppressUserConversion=*/false);
  6574. }
  6575. }
  6576. /// AddBuiltinCandidate - Add a candidate for a built-in
  6577. /// operator. ResultTy and ParamTys are the result and parameter types
  6578. /// of the built-in candidate, respectively. Args and NumArgs are the
  6579. /// arguments being passed to the candidate. IsAssignmentOperator
  6580. /// should be true when this built-in candidate is an assignment
  6581. /// operator. NumContextualBoolArguments is the number of arguments
  6582. /// (at the beginning of the argument list) that will be contextually
  6583. /// converted to bool.
  6584. void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
  6585. OverloadCandidateSet& CandidateSet,
  6586. bool IsAssignmentOperator,
  6587. unsigned NumContextualBoolArguments) {
  6588. // Overload resolution is always an unevaluated context.
  6589. EnterExpressionEvaluationContext Unevaluated(
  6590. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6591. // Add this candidate
  6592. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6593. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6594. Candidate.Function = nullptr;
  6595. Candidate.IsSurrogate = false;
  6596. Candidate.IgnoreObjectArgument = false;
  6597. std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
  6598. // Determine the implicit conversion sequences for each of the
  6599. // arguments.
  6600. Candidate.Viable = true;
  6601. Candidate.ExplicitCallArguments = Args.size();
  6602. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6603. // C++ [over.match.oper]p4:
  6604. // For the built-in assignment operators, conversions of the
  6605. // left operand are restricted as follows:
  6606. // -- no temporaries are introduced to hold the left operand, and
  6607. // -- no user-defined conversions are applied to the left
  6608. // operand to achieve a type match with the left-most
  6609. // parameter of a built-in candidate.
  6610. //
  6611. // We block these conversions by turning off user-defined
  6612. // conversions, since that is the only way that initialization of
  6613. // a reference to a non-class type can occur from something that
  6614. // is not of the same type.
  6615. if (ArgIdx < NumContextualBoolArguments) {
  6616. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6617. "Contextual conversion to bool requires bool type");
  6618. Candidate.Conversions[ArgIdx]
  6619. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6620. } else {
  6621. Candidate.Conversions[ArgIdx]
  6622. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6623. ArgIdx == 0 && IsAssignmentOperator,
  6624. /*InOverloadResolution=*/false,
  6625. /*AllowObjCWritebackConversion=*/
  6626. getLangOpts().ObjCAutoRefCount);
  6627. }
  6628. if (Candidate.Conversions[ArgIdx].isBad()) {
  6629. Candidate.Viable = false;
  6630. Candidate.FailureKind = ovl_fail_bad_conversion;
  6631. break;
  6632. }
  6633. }
  6634. }
  6635. namespace {
  6636. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6637. /// candidate operator functions for built-in operators (C++
  6638. /// [over.built]). The types are separated into pointer types and
  6639. /// enumeration types.
  6640. class BuiltinCandidateTypeSet {
  6641. /// TypeSet - A set of types.
  6642. typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
  6643. llvm::SmallPtrSet<QualType, 8>> TypeSet;
  6644. /// PointerTypes - The set of pointer types that will be used in the
  6645. /// built-in candidates.
  6646. TypeSet PointerTypes;
  6647. /// MemberPointerTypes - The set of member pointer types that will be
  6648. /// used in the built-in candidates.
  6649. TypeSet MemberPointerTypes;
  6650. /// EnumerationTypes - The set of enumeration types that will be
  6651. /// used in the built-in candidates.
  6652. TypeSet EnumerationTypes;
  6653. /// The set of vector types that will be used in the built-in
  6654. /// candidates.
  6655. TypeSet VectorTypes;
  6656. /// A flag indicating non-record types are viable candidates
  6657. bool HasNonRecordTypes;
  6658. /// A flag indicating whether either arithmetic or enumeration types
  6659. /// were present in the candidate set.
  6660. bool HasArithmeticOrEnumeralTypes;
  6661. /// A flag indicating whether the nullptr type was present in the
  6662. /// candidate set.
  6663. bool HasNullPtrType;
  6664. /// Sema - The semantic analysis instance where we are building the
  6665. /// candidate type set.
  6666. Sema &SemaRef;
  6667. /// Context - The AST context in which we will build the type sets.
  6668. ASTContext &Context;
  6669. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6670. const Qualifiers &VisibleQuals);
  6671. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6672. public:
  6673. /// iterator - Iterates through the types that are part of the set.
  6674. typedef TypeSet::iterator iterator;
  6675. BuiltinCandidateTypeSet(Sema &SemaRef)
  6676. : HasNonRecordTypes(false),
  6677. HasArithmeticOrEnumeralTypes(false),
  6678. HasNullPtrType(false),
  6679. SemaRef(SemaRef),
  6680. Context(SemaRef.Context) { }
  6681. void AddTypesConvertedFrom(QualType Ty,
  6682. SourceLocation Loc,
  6683. bool AllowUserConversions,
  6684. bool AllowExplicitConversions,
  6685. const Qualifiers &VisibleTypeConversionsQuals);
  6686. /// pointer_begin - First pointer type found;
  6687. iterator pointer_begin() { return PointerTypes.begin(); }
  6688. /// pointer_end - Past the last pointer type found;
  6689. iterator pointer_end() { return PointerTypes.end(); }
  6690. /// member_pointer_begin - First member pointer type found;
  6691. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6692. /// member_pointer_end - Past the last member pointer type found;
  6693. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6694. /// enumeration_begin - First enumeration type found;
  6695. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6696. /// enumeration_end - Past the last enumeration type found;
  6697. iterator enumeration_end() { return EnumerationTypes.end(); }
  6698. iterator vector_begin() { return VectorTypes.begin(); }
  6699. iterator vector_end() { return VectorTypes.end(); }
  6700. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6701. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6702. bool hasNullPtrType() const { return HasNullPtrType; }
  6703. };
  6704. } // end anonymous namespace
  6705. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6706. /// the set of pointer types along with any more-qualified variants of
  6707. /// that type. For example, if @p Ty is "int const *", this routine
  6708. /// will add "int const *", "int const volatile *", "int const
  6709. /// restrict *", and "int const volatile restrict *" to the set of
  6710. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6711. /// false otherwise.
  6712. ///
  6713. /// FIXME: what to do about extended qualifiers?
  6714. bool
  6715. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6716. const Qualifiers &VisibleQuals) {
  6717. // Insert this type.
  6718. if (!PointerTypes.insert(Ty))
  6719. return false;
  6720. QualType PointeeTy;
  6721. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6722. bool buildObjCPtr = false;
  6723. if (!PointerTy) {
  6724. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6725. PointeeTy = PTy->getPointeeType();
  6726. buildObjCPtr = true;
  6727. } else {
  6728. PointeeTy = PointerTy->getPointeeType();
  6729. }
  6730. // Don't add qualified variants of arrays. For one, they're not allowed
  6731. // (the qualifier would sink to the element type), and for another, the
  6732. // only overload situation where it matters is subscript or pointer +- int,
  6733. // and those shouldn't have qualifier variants anyway.
  6734. if (PointeeTy->isArrayType())
  6735. return true;
  6736. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6737. bool hasVolatile = VisibleQuals.hasVolatile();
  6738. bool hasRestrict = VisibleQuals.hasRestrict();
  6739. // Iterate through all strict supersets of BaseCVR.
  6740. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6741. if ((CVR | BaseCVR) != CVR) continue;
  6742. // Skip over volatile if no volatile found anywhere in the types.
  6743. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6744. // Skip over restrict if no restrict found anywhere in the types, or if
  6745. // the type cannot be restrict-qualified.
  6746. if ((CVR & Qualifiers::Restrict) &&
  6747. (!hasRestrict ||
  6748. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6749. continue;
  6750. // Build qualified pointee type.
  6751. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6752. // Build qualified pointer type.
  6753. QualType QPointerTy;
  6754. if (!buildObjCPtr)
  6755. QPointerTy = Context.getPointerType(QPointeeTy);
  6756. else
  6757. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6758. // Insert qualified pointer type.
  6759. PointerTypes.insert(QPointerTy);
  6760. }
  6761. return true;
  6762. }
  6763. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6764. /// to the set of pointer types along with any more-qualified variants of
  6765. /// that type. For example, if @p Ty is "int const *", this routine
  6766. /// will add "int const *", "int const volatile *", "int const
  6767. /// restrict *", and "int const volatile restrict *" to the set of
  6768. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6769. /// false otherwise.
  6770. ///
  6771. /// FIXME: what to do about extended qualifiers?
  6772. bool
  6773. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6774. QualType Ty) {
  6775. // Insert this type.
  6776. if (!MemberPointerTypes.insert(Ty))
  6777. return false;
  6778. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6779. assert(PointerTy && "type was not a member pointer type!");
  6780. QualType PointeeTy = PointerTy->getPointeeType();
  6781. // Don't add qualified variants of arrays. For one, they're not allowed
  6782. // (the qualifier would sink to the element type), and for another, the
  6783. // only overload situation where it matters is subscript or pointer +- int,
  6784. // and those shouldn't have qualifier variants anyway.
  6785. if (PointeeTy->isArrayType())
  6786. return true;
  6787. const Type *ClassTy = PointerTy->getClass();
  6788. // Iterate through all strict supersets of the pointee type's CVR
  6789. // qualifiers.
  6790. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6791. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6792. if ((CVR | BaseCVR) != CVR) continue;
  6793. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6794. MemberPointerTypes.insert(
  6795. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6796. }
  6797. return true;
  6798. }
  6799. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6800. /// Ty can be implicit converted to the given set of @p Types. We're
  6801. /// primarily interested in pointer types and enumeration types. We also
  6802. /// take member pointer types, for the conditional operator.
  6803. /// AllowUserConversions is true if we should look at the conversion
  6804. /// functions of a class type, and AllowExplicitConversions if we
  6805. /// should also include the explicit conversion functions of a class
  6806. /// type.
  6807. void
  6808. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6809. SourceLocation Loc,
  6810. bool AllowUserConversions,
  6811. bool AllowExplicitConversions,
  6812. const Qualifiers &VisibleQuals) {
  6813. // Only deal with canonical types.
  6814. Ty = Context.getCanonicalType(Ty);
  6815. // Look through reference types; they aren't part of the type of an
  6816. // expression for the purposes of conversions.
  6817. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6818. Ty = RefTy->getPointeeType();
  6819. // If we're dealing with an array type, decay to the pointer.
  6820. if (Ty->isArrayType())
  6821. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6822. // Otherwise, we don't care about qualifiers on the type.
  6823. Ty = Ty.getLocalUnqualifiedType();
  6824. // Flag if we ever add a non-record type.
  6825. const RecordType *TyRec = Ty->getAs<RecordType>();
  6826. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6827. // Flag if we encounter an arithmetic type.
  6828. HasArithmeticOrEnumeralTypes =
  6829. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6830. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6831. PointerTypes.insert(Ty);
  6832. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6833. // Insert our type, and its more-qualified variants, into the set
  6834. // of types.
  6835. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6836. return;
  6837. } else if (Ty->isMemberPointerType()) {
  6838. // Member pointers are far easier, since the pointee can't be converted.
  6839. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6840. return;
  6841. } else if (Ty->isEnumeralType()) {
  6842. HasArithmeticOrEnumeralTypes = true;
  6843. EnumerationTypes.insert(Ty);
  6844. } else if (Ty->isVectorType()) {
  6845. // We treat vector types as arithmetic types in many contexts as an
  6846. // extension.
  6847. HasArithmeticOrEnumeralTypes = true;
  6848. VectorTypes.insert(Ty);
  6849. } else if (Ty->isNullPtrType()) {
  6850. HasNullPtrType = true;
  6851. } else if (AllowUserConversions && TyRec) {
  6852. // No conversion functions in incomplete types.
  6853. if (!SemaRef.isCompleteType(Loc, Ty))
  6854. return;
  6855. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6856. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6857. if (isa<UsingShadowDecl>(D))
  6858. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6859. // Skip conversion function templates; they don't tell us anything
  6860. // about which builtin types we can convert to.
  6861. if (isa<FunctionTemplateDecl>(D))
  6862. continue;
  6863. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6864. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6865. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6866. VisibleQuals);
  6867. }
  6868. }
  6869. }
  6870. }
  6871. /// Helper function for adjusting address spaces for the pointer or reference
  6872. /// operands of builtin operators depending on the argument.
  6873. static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
  6874. Expr *Arg) {
  6875. return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
  6876. }
  6877. /// Helper function for AddBuiltinOperatorCandidates() that adds
  6878. /// the volatile- and non-volatile-qualified assignment operators for the
  6879. /// given type to the candidate set.
  6880. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  6881. QualType T,
  6882. ArrayRef<Expr *> Args,
  6883. OverloadCandidateSet &CandidateSet) {
  6884. QualType ParamTypes[2];
  6885. // T& operator=(T&, T)
  6886. ParamTypes[0] = S.Context.getLValueReferenceType(
  6887. AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
  6888. ParamTypes[1] = T;
  6889. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  6890. /*IsAssignmentOperator=*/true);
  6891. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  6892. // volatile T& operator=(volatile T&, T)
  6893. ParamTypes[0] = S.Context.getLValueReferenceType(
  6894. AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
  6895. Args[0]));
  6896. ParamTypes[1] = T;
  6897. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  6898. /*IsAssignmentOperator=*/true);
  6899. }
  6900. }
  6901. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  6902. /// if any, found in visible type conversion functions found in ArgExpr's type.
  6903. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  6904. Qualifiers VRQuals;
  6905. const RecordType *TyRec;
  6906. if (const MemberPointerType *RHSMPType =
  6907. ArgExpr->getType()->getAs<MemberPointerType>())
  6908. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  6909. else
  6910. TyRec = ArgExpr->getType()->getAs<RecordType>();
  6911. if (!TyRec) {
  6912. // Just to be safe, assume the worst case.
  6913. VRQuals.addVolatile();
  6914. VRQuals.addRestrict();
  6915. return VRQuals;
  6916. }
  6917. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6918. if (!ClassDecl->hasDefinition())
  6919. return VRQuals;
  6920. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6921. if (isa<UsingShadowDecl>(D))
  6922. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6923. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  6924. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  6925. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  6926. CanTy = ResTypeRef->getPointeeType();
  6927. // Need to go down the pointer/mempointer chain and add qualifiers
  6928. // as see them.
  6929. bool done = false;
  6930. while (!done) {
  6931. if (CanTy.isRestrictQualified())
  6932. VRQuals.addRestrict();
  6933. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  6934. CanTy = ResTypePtr->getPointeeType();
  6935. else if (const MemberPointerType *ResTypeMPtr =
  6936. CanTy->getAs<MemberPointerType>())
  6937. CanTy = ResTypeMPtr->getPointeeType();
  6938. else
  6939. done = true;
  6940. if (CanTy.isVolatileQualified())
  6941. VRQuals.addVolatile();
  6942. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  6943. return VRQuals;
  6944. }
  6945. }
  6946. }
  6947. return VRQuals;
  6948. }
  6949. namespace {
  6950. /// Helper class to manage the addition of builtin operator overload
  6951. /// candidates. It provides shared state and utility methods used throughout
  6952. /// the process, as well as a helper method to add each group of builtin
  6953. /// operator overloads from the standard to a candidate set.
  6954. class BuiltinOperatorOverloadBuilder {
  6955. // Common instance state available to all overload candidate addition methods.
  6956. Sema &S;
  6957. ArrayRef<Expr *> Args;
  6958. Qualifiers VisibleTypeConversionsQuals;
  6959. bool HasArithmeticOrEnumeralCandidateType;
  6960. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  6961. OverloadCandidateSet &CandidateSet;
  6962. static constexpr int ArithmeticTypesCap = 24;
  6963. SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
  6964. // Define some indices used to iterate over the arithemetic types in
  6965. // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
  6966. // types are that preserved by promotion (C++ [over.built]p2).
  6967. unsigned FirstIntegralType,
  6968. LastIntegralType;
  6969. unsigned FirstPromotedIntegralType,
  6970. LastPromotedIntegralType;
  6971. unsigned FirstPromotedArithmeticType,
  6972. LastPromotedArithmeticType;
  6973. unsigned NumArithmeticTypes;
  6974. void InitArithmeticTypes() {
  6975. // Start of promoted types.
  6976. FirstPromotedArithmeticType = 0;
  6977. ArithmeticTypes.push_back(S.Context.FloatTy);
  6978. ArithmeticTypes.push_back(S.Context.DoubleTy);
  6979. ArithmeticTypes.push_back(S.Context.LongDoubleTy);
  6980. if (S.Context.getTargetInfo().hasFloat128Type())
  6981. ArithmeticTypes.push_back(S.Context.Float128Ty);
  6982. // Start of integral types.
  6983. FirstIntegralType = ArithmeticTypes.size();
  6984. FirstPromotedIntegralType = ArithmeticTypes.size();
  6985. ArithmeticTypes.push_back(S.Context.IntTy);
  6986. ArithmeticTypes.push_back(S.Context.LongTy);
  6987. ArithmeticTypes.push_back(S.Context.LongLongTy);
  6988. if (S.Context.getTargetInfo().hasInt128Type())
  6989. ArithmeticTypes.push_back(S.Context.Int128Ty);
  6990. ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
  6991. ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
  6992. ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
  6993. if (S.Context.getTargetInfo().hasInt128Type())
  6994. ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
  6995. LastPromotedIntegralType = ArithmeticTypes.size();
  6996. LastPromotedArithmeticType = ArithmeticTypes.size();
  6997. // End of promoted types.
  6998. ArithmeticTypes.push_back(S.Context.BoolTy);
  6999. ArithmeticTypes.push_back(S.Context.CharTy);
  7000. ArithmeticTypes.push_back(S.Context.WCharTy);
  7001. if (S.Context.getLangOpts().Char8)
  7002. ArithmeticTypes.push_back(S.Context.Char8Ty);
  7003. ArithmeticTypes.push_back(S.Context.Char16Ty);
  7004. ArithmeticTypes.push_back(S.Context.Char32Ty);
  7005. ArithmeticTypes.push_back(S.Context.SignedCharTy);
  7006. ArithmeticTypes.push_back(S.Context.ShortTy);
  7007. ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
  7008. ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
  7009. LastIntegralType = ArithmeticTypes.size();
  7010. NumArithmeticTypes = ArithmeticTypes.size();
  7011. // End of integral types.
  7012. // FIXME: What about complex? What about half?
  7013. assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
  7014. "Enough inline storage for all arithmetic types.");
  7015. }
  7016. /// Helper method to factor out the common pattern of adding overloads
  7017. /// for '++' and '--' builtin operators.
  7018. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  7019. bool HasVolatile,
  7020. bool HasRestrict) {
  7021. QualType ParamTypes[2] = {
  7022. S.Context.getLValueReferenceType(CandidateTy),
  7023. S.Context.IntTy
  7024. };
  7025. // Non-volatile version.
  7026. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7027. // Use a heuristic to reduce number of builtin candidates in the set:
  7028. // add volatile version only if there are conversions to a volatile type.
  7029. if (HasVolatile) {
  7030. ParamTypes[0] =
  7031. S.Context.getLValueReferenceType(
  7032. S.Context.getVolatileType(CandidateTy));
  7033. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7034. }
  7035. // Add restrict version only if there are conversions to a restrict type
  7036. // and our candidate type is a non-restrict-qualified pointer.
  7037. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  7038. !CandidateTy.isRestrictQualified()) {
  7039. ParamTypes[0]
  7040. = S.Context.getLValueReferenceType(
  7041. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  7042. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7043. if (HasVolatile) {
  7044. ParamTypes[0]
  7045. = S.Context.getLValueReferenceType(
  7046. S.Context.getCVRQualifiedType(CandidateTy,
  7047. (Qualifiers::Volatile |
  7048. Qualifiers::Restrict)));
  7049. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7050. }
  7051. }
  7052. }
  7053. public:
  7054. BuiltinOperatorOverloadBuilder(
  7055. Sema &S, ArrayRef<Expr *> Args,
  7056. Qualifiers VisibleTypeConversionsQuals,
  7057. bool HasArithmeticOrEnumeralCandidateType,
  7058. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  7059. OverloadCandidateSet &CandidateSet)
  7060. : S(S), Args(Args),
  7061. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  7062. HasArithmeticOrEnumeralCandidateType(
  7063. HasArithmeticOrEnumeralCandidateType),
  7064. CandidateTypes(CandidateTypes),
  7065. CandidateSet(CandidateSet) {
  7066. InitArithmeticTypes();
  7067. }
  7068. // Increment is deprecated for bool since C++17.
  7069. //
  7070. // C++ [over.built]p3:
  7071. //
  7072. // For every pair (T, VQ), where T is an arithmetic type other
  7073. // than bool, and VQ is either volatile or empty, there exist
  7074. // candidate operator functions of the form
  7075. //
  7076. // VQ T& operator++(VQ T&);
  7077. // T operator++(VQ T&, int);
  7078. //
  7079. // C++ [over.built]p4:
  7080. //
  7081. // For every pair (T, VQ), where T is an arithmetic type other
  7082. // than bool, and VQ is either volatile or empty, there exist
  7083. // candidate operator functions of the form
  7084. //
  7085. // VQ T& operator--(VQ T&);
  7086. // T operator--(VQ T&, int);
  7087. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  7088. if (!HasArithmeticOrEnumeralCandidateType)
  7089. return;
  7090. for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
  7091. const auto TypeOfT = ArithmeticTypes[Arith];
  7092. if (TypeOfT == S.Context.BoolTy) {
  7093. if (Op == OO_MinusMinus)
  7094. continue;
  7095. if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
  7096. continue;
  7097. }
  7098. addPlusPlusMinusMinusStyleOverloads(
  7099. TypeOfT,
  7100. VisibleTypeConversionsQuals.hasVolatile(),
  7101. VisibleTypeConversionsQuals.hasRestrict());
  7102. }
  7103. }
  7104. // C++ [over.built]p5:
  7105. //
  7106. // For every pair (T, VQ), where T is a cv-qualified or
  7107. // cv-unqualified object type, and VQ is either volatile or
  7108. // empty, there exist candidate operator functions of the form
  7109. //
  7110. // T*VQ& operator++(T*VQ&);
  7111. // T*VQ& operator--(T*VQ&);
  7112. // T* operator++(T*VQ&, int);
  7113. // T* operator--(T*VQ&, int);
  7114. void addPlusPlusMinusMinusPointerOverloads() {
  7115. for (BuiltinCandidateTypeSet::iterator
  7116. Ptr = CandidateTypes[0].pointer_begin(),
  7117. PtrEnd = CandidateTypes[0].pointer_end();
  7118. Ptr != PtrEnd; ++Ptr) {
  7119. // Skip pointer types that aren't pointers to object types.
  7120. if (!(*Ptr)->getPointeeType()->isObjectType())
  7121. continue;
  7122. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  7123. (!(*Ptr).isVolatileQualified() &&
  7124. VisibleTypeConversionsQuals.hasVolatile()),
  7125. (!(*Ptr).isRestrictQualified() &&
  7126. VisibleTypeConversionsQuals.hasRestrict()));
  7127. }
  7128. }
  7129. // C++ [over.built]p6:
  7130. // For every cv-qualified or cv-unqualified object type T, there
  7131. // exist candidate operator functions of the form
  7132. //
  7133. // T& operator*(T*);
  7134. //
  7135. // C++ [over.built]p7:
  7136. // For every function type T that does not have cv-qualifiers or a
  7137. // ref-qualifier, there exist candidate operator functions of the form
  7138. // T& operator*(T*);
  7139. void addUnaryStarPointerOverloads() {
  7140. for (BuiltinCandidateTypeSet::iterator
  7141. Ptr = CandidateTypes[0].pointer_begin(),
  7142. PtrEnd = CandidateTypes[0].pointer_end();
  7143. Ptr != PtrEnd; ++Ptr) {
  7144. QualType ParamTy = *Ptr;
  7145. QualType PointeeTy = ParamTy->getPointeeType();
  7146. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  7147. continue;
  7148. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  7149. if (Proto->getMethodQuals() || Proto->getRefQualifier())
  7150. continue;
  7151. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7152. }
  7153. }
  7154. // C++ [over.built]p9:
  7155. // For every promoted arithmetic type T, there exist candidate
  7156. // operator functions of the form
  7157. //
  7158. // T operator+(T);
  7159. // T operator-(T);
  7160. void addUnaryPlusOrMinusArithmeticOverloads() {
  7161. if (!HasArithmeticOrEnumeralCandidateType)
  7162. return;
  7163. for (unsigned Arith = FirstPromotedArithmeticType;
  7164. Arith < LastPromotedArithmeticType; ++Arith) {
  7165. QualType ArithTy = ArithmeticTypes[Arith];
  7166. S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
  7167. }
  7168. // Extension: We also add these operators for vector types.
  7169. for (BuiltinCandidateTypeSet::iterator
  7170. Vec = CandidateTypes[0].vector_begin(),
  7171. VecEnd = CandidateTypes[0].vector_end();
  7172. Vec != VecEnd; ++Vec) {
  7173. QualType VecTy = *Vec;
  7174. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7175. }
  7176. }
  7177. // C++ [over.built]p8:
  7178. // For every type T, there exist candidate operator functions of
  7179. // the form
  7180. //
  7181. // T* operator+(T*);
  7182. void addUnaryPlusPointerOverloads() {
  7183. for (BuiltinCandidateTypeSet::iterator
  7184. Ptr = CandidateTypes[0].pointer_begin(),
  7185. PtrEnd = CandidateTypes[0].pointer_end();
  7186. Ptr != PtrEnd; ++Ptr) {
  7187. QualType ParamTy = *Ptr;
  7188. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7189. }
  7190. }
  7191. // C++ [over.built]p10:
  7192. // For every promoted integral type T, there exist candidate
  7193. // operator functions of the form
  7194. //
  7195. // T operator~(T);
  7196. void addUnaryTildePromotedIntegralOverloads() {
  7197. if (!HasArithmeticOrEnumeralCandidateType)
  7198. return;
  7199. for (unsigned Int = FirstPromotedIntegralType;
  7200. Int < LastPromotedIntegralType; ++Int) {
  7201. QualType IntTy = ArithmeticTypes[Int];
  7202. S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
  7203. }
  7204. // Extension: We also add this operator for vector types.
  7205. for (BuiltinCandidateTypeSet::iterator
  7206. Vec = CandidateTypes[0].vector_begin(),
  7207. VecEnd = CandidateTypes[0].vector_end();
  7208. Vec != VecEnd; ++Vec) {
  7209. QualType VecTy = *Vec;
  7210. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7211. }
  7212. }
  7213. // C++ [over.match.oper]p16:
  7214. // For every pointer to member type T or type std::nullptr_t, there
  7215. // exist candidate operator functions of the form
  7216. //
  7217. // bool operator==(T,T);
  7218. // bool operator!=(T,T);
  7219. void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
  7220. /// Set of (canonical) types that we've already handled.
  7221. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7222. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7223. for (BuiltinCandidateTypeSet::iterator
  7224. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7225. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7226. MemPtr != MemPtrEnd;
  7227. ++MemPtr) {
  7228. // Don't add the same builtin candidate twice.
  7229. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7230. continue;
  7231. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7232. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7233. }
  7234. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  7235. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  7236. if (AddedTypes.insert(NullPtrTy).second) {
  7237. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  7238. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7239. }
  7240. }
  7241. }
  7242. }
  7243. // C++ [over.built]p15:
  7244. //
  7245. // For every T, where T is an enumeration type or a pointer type,
  7246. // there exist candidate operator functions of the form
  7247. //
  7248. // bool operator<(T, T);
  7249. // bool operator>(T, T);
  7250. // bool operator<=(T, T);
  7251. // bool operator>=(T, T);
  7252. // bool operator==(T, T);
  7253. // bool operator!=(T, T);
  7254. // R operator<=>(T, T)
  7255. void addGenericBinaryPointerOrEnumeralOverloads() {
  7256. // C++ [over.match.oper]p3:
  7257. // [...]the built-in candidates include all of the candidate operator
  7258. // functions defined in 13.6 that, compared to the given operator, [...]
  7259. // do not have the same parameter-type-list as any non-template non-member
  7260. // candidate.
  7261. //
  7262. // Note that in practice, this only affects enumeration types because there
  7263. // aren't any built-in candidates of record type, and a user-defined operator
  7264. // must have an operand of record or enumeration type. Also, the only other
  7265. // overloaded operator with enumeration arguments, operator=,
  7266. // cannot be overloaded for enumeration types, so this is the only place
  7267. // where we must suppress candidates like this.
  7268. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  7269. UserDefinedBinaryOperators;
  7270. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7271. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  7272. CandidateTypes[ArgIdx].enumeration_end()) {
  7273. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  7274. CEnd = CandidateSet.end();
  7275. C != CEnd; ++C) {
  7276. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  7277. continue;
  7278. if (C->Function->isFunctionTemplateSpecialization())
  7279. continue;
  7280. QualType FirstParamType =
  7281. C->Function->getParamDecl(0)->getType().getUnqualifiedType();
  7282. QualType SecondParamType =
  7283. C->Function->getParamDecl(1)->getType().getUnqualifiedType();
  7284. // Skip if either parameter isn't of enumeral type.
  7285. if (!FirstParamType->isEnumeralType() ||
  7286. !SecondParamType->isEnumeralType())
  7287. continue;
  7288. // Add this operator to the set of known user-defined operators.
  7289. UserDefinedBinaryOperators.insert(
  7290. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  7291. S.Context.getCanonicalType(SecondParamType)));
  7292. }
  7293. }
  7294. }
  7295. /// Set of (canonical) types that we've already handled.
  7296. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7297. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7298. for (BuiltinCandidateTypeSet::iterator
  7299. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7300. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7301. Ptr != PtrEnd; ++Ptr) {
  7302. // Don't add the same builtin candidate twice.
  7303. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7304. continue;
  7305. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7306. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7307. }
  7308. for (BuiltinCandidateTypeSet::iterator
  7309. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7310. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7311. Enum != EnumEnd; ++Enum) {
  7312. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  7313. // Don't add the same builtin candidate twice, or if a user defined
  7314. // candidate exists.
  7315. if (!AddedTypes.insert(CanonType).second ||
  7316. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  7317. CanonType)))
  7318. continue;
  7319. QualType ParamTypes[2] = { *Enum, *Enum };
  7320. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7321. }
  7322. }
  7323. }
  7324. // C++ [over.built]p13:
  7325. //
  7326. // For every cv-qualified or cv-unqualified object type T
  7327. // there exist candidate operator functions of the form
  7328. //
  7329. // T* operator+(T*, ptrdiff_t);
  7330. // T& operator[](T*, ptrdiff_t); [BELOW]
  7331. // T* operator-(T*, ptrdiff_t);
  7332. // T* operator+(ptrdiff_t, T*);
  7333. // T& operator[](ptrdiff_t, T*); [BELOW]
  7334. //
  7335. // C++ [over.built]p14:
  7336. //
  7337. // For every T, where T is a pointer to object type, there
  7338. // exist candidate operator functions of the form
  7339. //
  7340. // ptrdiff_t operator-(T, T);
  7341. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  7342. /// Set of (canonical) types that we've already handled.
  7343. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7344. for (int Arg = 0; Arg < 2; ++Arg) {
  7345. QualType AsymmetricParamTypes[2] = {
  7346. S.Context.getPointerDiffType(),
  7347. S.Context.getPointerDiffType(),
  7348. };
  7349. for (BuiltinCandidateTypeSet::iterator
  7350. Ptr = CandidateTypes[Arg].pointer_begin(),
  7351. PtrEnd = CandidateTypes[Arg].pointer_end();
  7352. Ptr != PtrEnd; ++Ptr) {
  7353. QualType PointeeTy = (*Ptr)->getPointeeType();
  7354. if (!PointeeTy->isObjectType())
  7355. continue;
  7356. AsymmetricParamTypes[Arg] = *Ptr;
  7357. if (Arg == 0 || Op == OO_Plus) {
  7358. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  7359. // T* operator+(ptrdiff_t, T*);
  7360. S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
  7361. }
  7362. if (Op == OO_Minus) {
  7363. // ptrdiff_t operator-(T, T);
  7364. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7365. continue;
  7366. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7367. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7368. }
  7369. }
  7370. }
  7371. }
  7372. // C++ [over.built]p12:
  7373. //
  7374. // For every pair of promoted arithmetic types L and R, there
  7375. // exist candidate operator functions of the form
  7376. //
  7377. // LR operator*(L, R);
  7378. // LR operator/(L, R);
  7379. // LR operator+(L, R);
  7380. // LR operator-(L, R);
  7381. // bool operator<(L, R);
  7382. // bool operator>(L, R);
  7383. // bool operator<=(L, R);
  7384. // bool operator>=(L, R);
  7385. // bool operator==(L, R);
  7386. // bool operator!=(L, R);
  7387. //
  7388. // where LR is the result of the usual arithmetic conversions
  7389. // between types L and R.
  7390. //
  7391. // C++ [over.built]p24:
  7392. //
  7393. // For every pair of promoted arithmetic types L and R, there exist
  7394. // candidate operator functions of the form
  7395. //
  7396. // LR operator?(bool, L, R);
  7397. //
  7398. // where LR is the result of the usual arithmetic conversions
  7399. // between types L and R.
  7400. // Our candidates ignore the first parameter.
  7401. void addGenericBinaryArithmeticOverloads() {
  7402. if (!HasArithmeticOrEnumeralCandidateType)
  7403. return;
  7404. for (unsigned Left = FirstPromotedArithmeticType;
  7405. Left < LastPromotedArithmeticType; ++Left) {
  7406. for (unsigned Right = FirstPromotedArithmeticType;
  7407. Right < LastPromotedArithmeticType; ++Right) {
  7408. QualType LandR[2] = { ArithmeticTypes[Left],
  7409. ArithmeticTypes[Right] };
  7410. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7411. }
  7412. }
  7413. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  7414. // conditional operator for vector types.
  7415. for (BuiltinCandidateTypeSet::iterator
  7416. Vec1 = CandidateTypes[0].vector_begin(),
  7417. Vec1End = CandidateTypes[0].vector_end();
  7418. Vec1 != Vec1End; ++Vec1) {
  7419. for (BuiltinCandidateTypeSet::iterator
  7420. Vec2 = CandidateTypes[1].vector_begin(),
  7421. Vec2End = CandidateTypes[1].vector_end();
  7422. Vec2 != Vec2End; ++Vec2) {
  7423. QualType LandR[2] = { *Vec1, *Vec2 };
  7424. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7425. }
  7426. }
  7427. }
  7428. // C++2a [over.built]p14:
  7429. //
  7430. // For every integral type T there exists a candidate operator function
  7431. // of the form
  7432. //
  7433. // std::strong_ordering operator<=>(T, T)
  7434. //
  7435. // C++2a [over.built]p15:
  7436. //
  7437. // For every pair of floating-point types L and R, there exists a candidate
  7438. // operator function of the form
  7439. //
  7440. // std::partial_ordering operator<=>(L, R);
  7441. //
  7442. // FIXME: The current specification for integral types doesn't play nice with
  7443. // the direction of p0946r0, which allows mixed integral and unscoped-enum
  7444. // comparisons. Under the current spec this can lead to ambiguity during
  7445. // overload resolution. For example:
  7446. //
  7447. // enum A : int {a};
  7448. // auto x = (a <=> (long)42);
  7449. //
  7450. // error: call is ambiguous for arguments 'A' and 'long'.
  7451. // note: candidate operator<=>(int, int)
  7452. // note: candidate operator<=>(long, long)
  7453. //
  7454. // To avoid this error, this function deviates from the specification and adds
  7455. // the mixed overloads `operator<=>(L, R)` where L and R are promoted
  7456. // arithmetic types (the same as the generic relational overloads).
  7457. //
  7458. // For now this function acts as a placeholder.
  7459. void addThreeWayArithmeticOverloads() {
  7460. addGenericBinaryArithmeticOverloads();
  7461. }
  7462. // C++ [over.built]p17:
  7463. //
  7464. // For every pair of promoted integral types L and R, there
  7465. // exist candidate operator functions of the form
  7466. //
  7467. // LR operator%(L, R);
  7468. // LR operator&(L, R);
  7469. // LR operator^(L, R);
  7470. // LR operator|(L, R);
  7471. // L operator<<(L, R);
  7472. // L operator>>(L, R);
  7473. //
  7474. // where LR is the result of the usual arithmetic conversions
  7475. // between types L and R.
  7476. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7477. if (!HasArithmeticOrEnumeralCandidateType)
  7478. return;
  7479. for (unsigned Left = FirstPromotedIntegralType;
  7480. Left < LastPromotedIntegralType; ++Left) {
  7481. for (unsigned Right = FirstPromotedIntegralType;
  7482. Right < LastPromotedIntegralType; ++Right) {
  7483. QualType LandR[2] = { ArithmeticTypes[Left],
  7484. ArithmeticTypes[Right] };
  7485. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7486. }
  7487. }
  7488. }
  7489. // C++ [over.built]p20:
  7490. //
  7491. // For every pair (T, VQ), where T is an enumeration or
  7492. // pointer to member type and VQ is either volatile or
  7493. // empty, there exist candidate operator functions of the form
  7494. //
  7495. // VQ T& operator=(VQ T&, T);
  7496. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7497. /// Set of (canonical) types that we've already handled.
  7498. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7499. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7500. for (BuiltinCandidateTypeSet::iterator
  7501. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7502. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7503. Enum != EnumEnd; ++Enum) {
  7504. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7505. continue;
  7506. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7507. }
  7508. for (BuiltinCandidateTypeSet::iterator
  7509. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7510. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7511. MemPtr != MemPtrEnd; ++MemPtr) {
  7512. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7513. continue;
  7514. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7515. }
  7516. }
  7517. }
  7518. // C++ [over.built]p19:
  7519. //
  7520. // For every pair (T, VQ), where T is any type and VQ is either
  7521. // volatile or empty, there exist candidate operator functions
  7522. // of the form
  7523. //
  7524. // T*VQ& operator=(T*VQ&, T*);
  7525. //
  7526. // C++ [over.built]p21:
  7527. //
  7528. // For every pair (T, VQ), where T is a cv-qualified or
  7529. // cv-unqualified object type and VQ is either volatile or
  7530. // empty, there exist candidate operator functions of the form
  7531. //
  7532. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7533. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7534. void addAssignmentPointerOverloads(bool isEqualOp) {
  7535. /// Set of (canonical) types that we've already handled.
  7536. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7537. for (BuiltinCandidateTypeSet::iterator
  7538. Ptr = CandidateTypes[0].pointer_begin(),
  7539. PtrEnd = CandidateTypes[0].pointer_end();
  7540. Ptr != PtrEnd; ++Ptr) {
  7541. // If this is operator=, keep track of the builtin candidates we added.
  7542. if (isEqualOp)
  7543. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7544. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7545. continue;
  7546. // non-volatile version
  7547. QualType ParamTypes[2] = {
  7548. S.Context.getLValueReferenceType(*Ptr),
  7549. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7550. };
  7551. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7552. /*IsAssignmentOperator=*/ isEqualOp);
  7553. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7554. VisibleTypeConversionsQuals.hasVolatile();
  7555. if (NeedVolatile) {
  7556. // volatile version
  7557. ParamTypes[0] =
  7558. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7559. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7560. /*IsAssignmentOperator=*/isEqualOp);
  7561. }
  7562. if (!(*Ptr).isRestrictQualified() &&
  7563. VisibleTypeConversionsQuals.hasRestrict()) {
  7564. // restrict version
  7565. ParamTypes[0]
  7566. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7567. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7568. /*IsAssignmentOperator=*/isEqualOp);
  7569. if (NeedVolatile) {
  7570. // volatile restrict version
  7571. ParamTypes[0]
  7572. = S.Context.getLValueReferenceType(
  7573. S.Context.getCVRQualifiedType(*Ptr,
  7574. (Qualifiers::Volatile |
  7575. Qualifiers::Restrict)));
  7576. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7577. /*IsAssignmentOperator=*/isEqualOp);
  7578. }
  7579. }
  7580. }
  7581. if (isEqualOp) {
  7582. for (BuiltinCandidateTypeSet::iterator
  7583. Ptr = CandidateTypes[1].pointer_begin(),
  7584. PtrEnd = CandidateTypes[1].pointer_end();
  7585. Ptr != PtrEnd; ++Ptr) {
  7586. // Make sure we don't add the same candidate twice.
  7587. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7588. continue;
  7589. QualType ParamTypes[2] = {
  7590. S.Context.getLValueReferenceType(*Ptr),
  7591. *Ptr,
  7592. };
  7593. // non-volatile version
  7594. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7595. /*IsAssignmentOperator=*/true);
  7596. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7597. VisibleTypeConversionsQuals.hasVolatile();
  7598. if (NeedVolatile) {
  7599. // volatile version
  7600. ParamTypes[0] =
  7601. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7602. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7603. /*IsAssignmentOperator=*/true);
  7604. }
  7605. if (!(*Ptr).isRestrictQualified() &&
  7606. VisibleTypeConversionsQuals.hasRestrict()) {
  7607. // restrict version
  7608. ParamTypes[0]
  7609. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7610. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7611. /*IsAssignmentOperator=*/true);
  7612. if (NeedVolatile) {
  7613. // volatile restrict version
  7614. ParamTypes[0]
  7615. = S.Context.getLValueReferenceType(
  7616. S.Context.getCVRQualifiedType(*Ptr,
  7617. (Qualifiers::Volatile |
  7618. Qualifiers::Restrict)));
  7619. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7620. /*IsAssignmentOperator=*/true);
  7621. }
  7622. }
  7623. }
  7624. }
  7625. }
  7626. // C++ [over.built]p18:
  7627. //
  7628. // For every triple (L, VQ, R), where L is an arithmetic type,
  7629. // VQ is either volatile or empty, and R is a promoted
  7630. // arithmetic type, there exist candidate operator functions of
  7631. // the form
  7632. //
  7633. // VQ L& operator=(VQ L&, R);
  7634. // VQ L& operator*=(VQ L&, R);
  7635. // VQ L& operator/=(VQ L&, R);
  7636. // VQ L& operator+=(VQ L&, R);
  7637. // VQ L& operator-=(VQ L&, R);
  7638. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7639. if (!HasArithmeticOrEnumeralCandidateType)
  7640. return;
  7641. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7642. for (unsigned Right = FirstPromotedArithmeticType;
  7643. Right < LastPromotedArithmeticType; ++Right) {
  7644. QualType ParamTypes[2];
  7645. ParamTypes[1] = ArithmeticTypes[Right];
  7646. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  7647. S, ArithmeticTypes[Left], Args[0]);
  7648. // Add this built-in operator as a candidate (VQ is empty).
  7649. ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
  7650. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7651. /*IsAssignmentOperator=*/isEqualOp);
  7652. // Add this built-in operator as a candidate (VQ is 'volatile').
  7653. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7654. ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
  7655. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7656. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7657. /*IsAssignmentOperator=*/isEqualOp);
  7658. }
  7659. }
  7660. }
  7661. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7662. for (BuiltinCandidateTypeSet::iterator
  7663. Vec1 = CandidateTypes[0].vector_begin(),
  7664. Vec1End = CandidateTypes[0].vector_end();
  7665. Vec1 != Vec1End; ++Vec1) {
  7666. for (BuiltinCandidateTypeSet::iterator
  7667. Vec2 = CandidateTypes[1].vector_begin(),
  7668. Vec2End = CandidateTypes[1].vector_end();
  7669. Vec2 != Vec2End; ++Vec2) {
  7670. QualType ParamTypes[2];
  7671. ParamTypes[1] = *Vec2;
  7672. // Add this built-in operator as a candidate (VQ is empty).
  7673. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7674. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7675. /*IsAssignmentOperator=*/isEqualOp);
  7676. // Add this built-in operator as a candidate (VQ is 'volatile').
  7677. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7678. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7679. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7680. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7681. /*IsAssignmentOperator=*/isEqualOp);
  7682. }
  7683. }
  7684. }
  7685. }
  7686. // C++ [over.built]p22:
  7687. //
  7688. // For every triple (L, VQ, R), where L is an integral type, VQ
  7689. // is either volatile or empty, and R is a promoted integral
  7690. // type, there exist candidate operator functions of the form
  7691. //
  7692. // VQ L& operator%=(VQ L&, R);
  7693. // VQ L& operator<<=(VQ L&, R);
  7694. // VQ L& operator>>=(VQ L&, R);
  7695. // VQ L& operator&=(VQ L&, R);
  7696. // VQ L& operator^=(VQ L&, R);
  7697. // VQ L& operator|=(VQ L&, R);
  7698. void addAssignmentIntegralOverloads() {
  7699. if (!HasArithmeticOrEnumeralCandidateType)
  7700. return;
  7701. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7702. for (unsigned Right = FirstPromotedIntegralType;
  7703. Right < LastPromotedIntegralType; ++Right) {
  7704. QualType ParamTypes[2];
  7705. ParamTypes[1] = ArithmeticTypes[Right];
  7706. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  7707. S, ArithmeticTypes[Left], Args[0]);
  7708. // Add this built-in operator as a candidate (VQ is empty).
  7709. ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
  7710. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7711. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7712. // Add this built-in operator as a candidate (VQ is 'volatile').
  7713. ParamTypes[0] = LeftBaseTy;
  7714. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7715. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7716. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7717. }
  7718. }
  7719. }
  7720. }
  7721. // C++ [over.operator]p23:
  7722. //
  7723. // There also exist candidate operator functions of the form
  7724. //
  7725. // bool operator!(bool);
  7726. // bool operator&&(bool, bool);
  7727. // bool operator||(bool, bool);
  7728. void addExclaimOverload() {
  7729. QualType ParamTy = S.Context.BoolTy;
  7730. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
  7731. /*IsAssignmentOperator=*/false,
  7732. /*NumContextualBoolArguments=*/1);
  7733. }
  7734. void addAmpAmpOrPipePipeOverload() {
  7735. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7736. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7737. /*IsAssignmentOperator=*/false,
  7738. /*NumContextualBoolArguments=*/2);
  7739. }
  7740. // C++ [over.built]p13:
  7741. //
  7742. // For every cv-qualified or cv-unqualified object type T there
  7743. // exist candidate operator functions of the form
  7744. //
  7745. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7746. // T& operator[](T*, ptrdiff_t);
  7747. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7748. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7749. // T& operator[](ptrdiff_t, T*);
  7750. void addSubscriptOverloads() {
  7751. for (BuiltinCandidateTypeSet::iterator
  7752. Ptr = CandidateTypes[0].pointer_begin(),
  7753. PtrEnd = CandidateTypes[0].pointer_end();
  7754. Ptr != PtrEnd; ++Ptr) {
  7755. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7756. QualType PointeeType = (*Ptr)->getPointeeType();
  7757. if (!PointeeType->isObjectType())
  7758. continue;
  7759. // T& operator[](T*, ptrdiff_t)
  7760. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7761. }
  7762. for (BuiltinCandidateTypeSet::iterator
  7763. Ptr = CandidateTypes[1].pointer_begin(),
  7764. PtrEnd = CandidateTypes[1].pointer_end();
  7765. Ptr != PtrEnd; ++Ptr) {
  7766. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7767. QualType PointeeType = (*Ptr)->getPointeeType();
  7768. if (!PointeeType->isObjectType())
  7769. continue;
  7770. // T& operator[](ptrdiff_t, T*)
  7771. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7772. }
  7773. }
  7774. // C++ [over.built]p11:
  7775. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7776. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7777. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7778. // there exist candidate operator functions of the form
  7779. //
  7780. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7781. //
  7782. // where CV12 is the union of CV1 and CV2.
  7783. void addArrowStarOverloads() {
  7784. for (BuiltinCandidateTypeSet::iterator
  7785. Ptr = CandidateTypes[0].pointer_begin(),
  7786. PtrEnd = CandidateTypes[0].pointer_end();
  7787. Ptr != PtrEnd; ++Ptr) {
  7788. QualType C1Ty = (*Ptr);
  7789. QualType C1;
  7790. QualifierCollector Q1;
  7791. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7792. if (!isa<RecordType>(C1))
  7793. continue;
  7794. // heuristic to reduce number of builtin candidates in the set.
  7795. // Add volatile/restrict version only if there are conversions to a
  7796. // volatile/restrict type.
  7797. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7798. continue;
  7799. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7800. continue;
  7801. for (BuiltinCandidateTypeSet::iterator
  7802. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7803. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7804. MemPtr != MemPtrEnd; ++MemPtr) {
  7805. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7806. QualType C2 = QualType(mptr->getClass(), 0);
  7807. C2 = C2.getUnqualifiedType();
  7808. if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
  7809. break;
  7810. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7811. // build CV12 T&
  7812. QualType T = mptr->getPointeeType();
  7813. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7814. T.isVolatileQualified())
  7815. continue;
  7816. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7817. T.isRestrictQualified())
  7818. continue;
  7819. T = Q1.apply(S.Context, T);
  7820. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7821. }
  7822. }
  7823. }
  7824. // Note that we don't consider the first argument, since it has been
  7825. // contextually converted to bool long ago. The candidates below are
  7826. // therefore added as binary.
  7827. //
  7828. // C++ [over.built]p25:
  7829. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7830. // enumeration type, there exist candidate operator functions of the form
  7831. //
  7832. // T operator?(bool, T, T);
  7833. //
  7834. void addConditionalOperatorOverloads() {
  7835. /// Set of (canonical) types that we've already handled.
  7836. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7837. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7838. for (BuiltinCandidateTypeSet::iterator
  7839. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7840. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7841. Ptr != PtrEnd; ++Ptr) {
  7842. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7843. continue;
  7844. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7845. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7846. }
  7847. for (BuiltinCandidateTypeSet::iterator
  7848. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7849. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7850. MemPtr != MemPtrEnd; ++MemPtr) {
  7851. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7852. continue;
  7853. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7854. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7855. }
  7856. if (S.getLangOpts().CPlusPlus11) {
  7857. for (BuiltinCandidateTypeSet::iterator
  7858. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7859. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7860. Enum != EnumEnd; ++Enum) {
  7861. if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
  7862. continue;
  7863. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7864. continue;
  7865. QualType ParamTypes[2] = { *Enum, *Enum };
  7866. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7867. }
  7868. }
  7869. }
  7870. }
  7871. };
  7872. } // end anonymous namespace
  7873. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  7874. /// operator overloads to the candidate set (C++ [over.built]), based
  7875. /// on the operator @p Op and the arguments given. For example, if the
  7876. /// operator is a binary '+', this routine might add "int
  7877. /// operator+(int, int)" to cover integer addition.
  7878. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  7879. SourceLocation OpLoc,
  7880. ArrayRef<Expr *> Args,
  7881. OverloadCandidateSet &CandidateSet) {
  7882. // Find all of the types that the arguments can convert to, but only
  7883. // if the operator we're looking at has built-in operator candidates
  7884. // that make use of these types. Also record whether we encounter non-record
  7885. // candidate types or either arithmetic or enumeral candidate types.
  7886. Qualifiers VisibleTypeConversionsQuals;
  7887. VisibleTypeConversionsQuals.addConst();
  7888. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  7889. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  7890. bool HasNonRecordCandidateType = false;
  7891. bool HasArithmeticOrEnumeralCandidateType = false;
  7892. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  7893. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7894. CandidateTypes.emplace_back(*this);
  7895. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  7896. OpLoc,
  7897. true,
  7898. (Op == OO_Exclaim ||
  7899. Op == OO_AmpAmp ||
  7900. Op == OO_PipePipe),
  7901. VisibleTypeConversionsQuals);
  7902. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  7903. CandidateTypes[ArgIdx].hasNonRecordTypes();
  7904. HasArithmeticOrEnumeralCandidateType =
  7905. HasArithmeticOrEnumeralCandidateType ||
  7906. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  7907. }
  7908. // Exit early when no non-record types have been added to the candidate set
  7909. // for any of the arguments to the operator.
  7910. //
  7911. // We can't exit early for !, ||, or &&, since there we have always have
  7912. // 'bool' overloads.
  7913. if (!HasNonRecordCandidateType &&
  7914. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  7915. return;
  7916. // Setup an object to manage the common state for building overloads.
  7917. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  7918. VisibleTypeConversionsQuals,
  7919. HasArithmeticOrEnumeralCandidateType,
  7920. CandidateTypes, CandidateSet);
  7921. // Dispatch over the operation to add in only those overloads which apply.
  7922. switch (Op) {
  7923. case OO_None:
  7924. case NUM_OVERLOADED_OPERATORS:
  7925. llvm_unreachable("Expected an overloaded operator");
  7926. case OO_New:
  7927. case OO_Delete:
  7928. case OO_Array_New:
  7929. case OO_Array_Delete:
  7930. case OO_Call:
  7931. llvm_unreachable(
  7932. "Special operators don't use AddBuiltinOperatorCandidates");
  7933. case OO_Comma:
  7934. case OO_Arrow:
  7935. case OO_Coawait:
  7936. // C++ [over.match.oper]p3:
  7937. // -- For the operator ',', the unary operator '&', the
  7938. // operator '->', or the operator 'co_await', the
  7939. // built-in candidates set is empty.
  7940. break;
  7941. case OO_Plus: // '+' is either unary or binary
  7942. if (Args.size() == 1)
  7943. OpBuilder.addUnaryPlusPointerOverloads();
  7944. LLVM_FALLTHROUGH;
  7945. case OO_Minus: // '-' is either unary or binary
  7946. if (Args.size() == 1) {
  7947. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  7948. } else {
  7949. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  7950. OpBuilder.addGenericBinaryArithmeticOverloads();
  7951. }
  7952. break;
  7953. case OO_Star: // '*' is either unary or binary
  7954. if (Args.size() == 1)
  7955. OpBuilder.addUnaryStarPointerOverloads();
  7956. else
  7957. OpBuilder.addGenericBinaryArithmeticOverloads();
  7958. break;
  7959. case OO_Slash:
  7960. OpBuilder.addGenericBinaryArithmeticOverloads();
  7961. break;
  7962. case OO_PlusPlus:
  7963. case OO_MinusMinus:
  7964. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  7965. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  7966. break;
  7967. case OO_EqualEqual:
  7968. case OO_ExclaimEqual:
  7969. OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
  7970. LLVM_FALLTHROUGH;
  7971. case OO_Less:
  7972. case OO_Greater:
  7973. case OO_LessEqual:
  7974. case OO_GreaterEqual:
  7975. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
  7976. OpBuilder.addGenericBinaryArithmeticOverloads();
  7977. break;
  7978. case OO_Spaceship:
  7979. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
  7980. OpBuilder.addThreeWayArithmeticOverloads();
  7981. break;
  7982. case OO_Percent:
  7983. case OO_Caret:
  7984. case OO_Pipe:
  7985. case OO_LessLess:
  7986. case OO_GreaterGreater:
  7987. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7988. break;
  7989. case OO_Amp: // '&' is either unary or binary
  7990. if (Args.size() == 1)
  7991. // C++ [over.match.oper]p3:
  7992. // -- For the operator ',', the unary operator '&', or the
  7993. // operator '->', the built-in candidates set is empty.
  7994. break;
  7995. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7996. break;
  7997. case OO_Tilde:
  7998. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  7999. break;
  8000. case OO_Equal:
  8001. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  8002. LLVM_FALLTHROUGH;
  8003. case OO_PlusEqual:
  8004. case OO_MinusEqual:
  8005. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  8006. LLVM_FALLTHROUGH;
  8007. case OO_StarEqual:
  8008. case OO_SlashEqual:
  8009. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  8010. break;
  8011. case OO_PercentEqual:
  8012. case OO_LessLessEqual:
  8013. case OO_GreaterGreaterEqual:
  8014. case OO_AmpEqual:
  8015. case OO_CaretEqual:
  8016. case OO_PipeEqual:
  8017. OpBuilder.addAssignmentIntegralOverloads();
  8018. break;
  8019. case OO_Exclaim:
  8020. OpBuilder.addExclaimOverload();
  8021. break;
  8022. case OO_AmpAmp:
  8023. case OO_PipePipe:
  8024. OpBuilder.addAmpAmpOrPipePipeOverload();
  8025. break;
  8026. case OO_Subscript:
  8027. OpBuilder.addSubscriptOverloads();
  8028. break;
  8029. case OO_ArrowStar:
  8030. OpBuilder.addArrowStarOverloads();
  8031. break;
  8032. case OO_Conditional:
  8033. OpBuilder.addConditionalOperatorOverloads();
  8034. OpBuilder.addGenericBinaryArithmeticOverloads();
  8035. break;
  8036. }
  8037. }
  8038. /// Add function candidates found via argument-dependent lookup
  8039. /// to the set of overloading candidates.
  8040. ///
  8041. /// This routine performs argument-dependent name lookup based on the
  8042. /// given function name (which may also be an operator name) and adds
  8043. /// all of the overload candidates found by ADL to the overload
  8044. /// candidate set (C++ [basic.lookup.argdep]).
  8045. void
  8046. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  8047. SourceLocation Loc,
  8048. ArrayRef<Expr *> Args,
  8049. TemplateArgumentListInfo *ExplicitTemplateArgs,
  8050. OverloadCandidateSet& CandidateSet,
  8051. bool PartialOverloading) {
  8052. ADLResult Fns;
  8053. // FIXME: This approach for uniquing ADL results (and removing
  8054. // redundant candidates from the set) relies on pointer-equality,
  8055. // which means we need to key off the canonical decl. However,
  8056. // always going back to the canonical decl might not get us the
  8057. // right set of default arguments. What default arguments are
  8058. // we supposed to consider on ADL candidates, anyway?
  8059. // FIXME: Pass in the explicit template arguments?
  8060. ArgumentDependentLookup(Name, Loc, Args, Fns);
  8061. // Erase all of the candidates we already knew about.
  8062. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  8063. CandEnd = CandidateSet.end();
  8064. Cand != CandEnd; ++Cand)
  8065. if (Cand->Function) {
  8066. Fns.erase(Cand->Function);
  8067. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  8068. Fns.erase(FunTmpl);
  8069. }
  8070. // For each of the ADL candidates we found, add it to the overload
  8071. // set.
  8072. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  8073. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  8074. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  8075. if (ExplicitTemplateArgs)
  8076. continue;
  8077. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
  8078. /*SuppressUserConversions=*/false, PartialOverloading,
  8079. /*AllowExplicit*/ true,
  8080. /*AllowExplicitConversions*/ false,
  8081. ADLCallKind::UsesADL);
  8082. } else {
  8083. AddTemplateOverloadCandidate(
  8084. cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
  8085. CandidateSet,
  8086. /*SuppressUserConversions=*/false, PartialOverloading,
  8087. /*AllowExplicit*/true, ADLCallKind::UsesADL);
  8088. }
  8089. }
  8090. }
  8091. namespace {
  8092. enum class Comparison { Equal, Better, Worse };
  8093. }
  8094. /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
  8095. /// overload resolution.
  8096. ///
  8097. /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
  8098. /// Cand1's first N enable_if attributes have precisely the same conditions as
  8099. /// Cand2's first N enable_if attributes (where N = the number of enable_if
  8100. /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
  8101. ///
  8102. /// Note that you can have a pair of candidates such that Cand1's enable_if
  8103. /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
  8104. /// worse than Cand1's.
  8105. static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
  8106. const FunctionDecl *Cand2) {
  8107. // Common case: One (or both) decls don't have enable_if attrs.
  8108. bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
  8109. bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
  8110. if (!Cand1Attr || !Cand2Attr) {
  8111. if (Cand1Attr == Cand2Attr)
  8112. return Comparison::Equal;
  8113. return Cand1Attr ? Comparison::Better : Comparison::Worse;
  8114. }
  8115. auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
  8116. auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
  8117. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  8118. for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
  8119. Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  8120. Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  8121. // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
  8122. // has fewer enable_if attributes than Cand2, and vice versa.
  8123. if (!Cand1A)
  8124. return Comparison::Worse;
  8125. if (!Cand2A)
  8126. return Comparison::Better;
  8127. Cand1ID.clear();
  8128. Cand2ID.clear();
  8129. (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
  8130. (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
  8131. if (Cand1ID != Cand2ID)
  8132. return Comparison::Worse;
  8133. }
  8134. return Comparison::Equal;
  8135. }
  8136. static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
  8137. const OverloadCandidate &Cand2) {
  8138. if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
  8139. !Cand2.Function->isMultiVersion())
  8140. return false;
  8141. // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
  8142. // is obviously better.
  8143. if (Cand1.Function->isInvalidDecl()) return false;
  8144. if (Cand2.Function->isInvalidDecl()) return true;
  8145. // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
  8146. // cpu_dispatch, else arbitrarily based on the identifiers.
  8147. bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
  8148. bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
  8149. const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
  8150. const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
  8151. if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
  8152. return false;
  8153. if (Cand1CPUDisp && !Cand2CPUDisp)
  8154. return true;
  8155. if (Cand2CPUDisp && !Cand1CPUDisp)
  8156. return false;
  8157. if (Cand1CPUSpec && Cand2CPUSpec) {
  8158. if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
  8159. return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
  8160. std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
  8161. FirstDiff = std::mismatch(
  8162. Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
  8163. Cand2CPUSpec->cpus_begin(),
  8164. [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
  8165. return LHS->getName() == RHS->getName();
  8166. });
  8167. assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
  8168. "Two different cpu-specific versions should not have the same "
  8169. "identifier list, otherwise they'd be the same decl!");
  8170. return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
  8171. }
  8172. llvm_unreachable("No way to get here unless both had cpu_dispatch");
  8173. }
  8174. /// isBetterOverloadCandidate - Determines whether the first overload
  8175. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  8176. bool clang::isBetterOverloadCandidate(
  8177. Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
  8178. SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
  8179. // Define viable functions to be better candidates than non-viable
  8180. // functions.
  8181. if (!Cand2.Viable)
  8182. return Cand1.Viable;
  8183. else if (!Cand1.Viable)
  8184. return false;
  8185. // C++ [over.match.best]p1:
  8186. //
  8187. // -- if F is a static member function, ICS1(F) is defined such
  8188. // that ICS1(F) is neither better nor worse than ICS1(G) for
  8189. // any function G, and, symmetrically, ICS1(G) is neither
  8190. // better nor worse than ICS1(F).
  8191. unsigned StartArg = 0;
  8192. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  8193. StartArg = 1;
  8194. auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
  8195. // We don't allow incompatible pointer conversions in C++.
  8196. if (!S.getLangOpts().CPlusPlus)
  8197. return ICS.isStandard() &&
  8198. ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
  8199. // The only ill-formed conversion we allow in C++ is the string literal to
  8200. // char* conversion, which is only considered ill-formed after C++11.
  8201. return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  8202. hasDeprecatedStringLiteralToCharPtrConversion(ICS);
  8203. };
  8204. // Define functions that don't require ill-formed conversions for a given
  8205. // argument to be better candidates than functions that do.
  8206. unsigned NumArgs = Cand1.Conversions.size();
  8207. assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
  8208. bool HasBetterConversion = false;
  8209. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8210. bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
  8211. bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
  8212. if (Cand1Bad != Cand2Bad) {
  8213. if (Cand1Bad)
  8214. return false;
  8215. HasBetterConversion = true;
  8216. }
  8217. }
  8218. if (HasBetterConversion)
  8219. return true;
  8220. // C++ [over.match.best]p1:
  8221. // A viable function F1 is defined to be a better function than another
  8222. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  8223. // conversion sequence than ICSi(F2), and then...
  8224. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8225. switch (CompareImplicitConversionSequences(S, Loc,
  8226. Cand1.Conversions[ArgIdx],
  8227. Cand2.Conversions[ArgIdx])) {
  8228. case ImplicitConversionSequence::Better:
  8229. // Cand1 has a better conversion sequence.
  8230. HasBetterConversion = true;
  8231. break;
  8232. case ImplicitConversionSequence::Worse:
  8233. // Cand1 can't be better than Cand2.
  8234. return false;
  8235. case ImplicitConversionSequence::Indistinguishable:
  8236. // Do nothing.
  8237. break;
  8238. }
  8239. }
  8240. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  8241. // ICSj(F2), or, if not that,
  8242. if (HasBetterConversion)
  8243. return true;
  8244. // -- the context is an initialization by user-defined conversion
  8245. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  8246. // from the return type of F1 to the destination type (i.e.,
  8247. // the type of the entity being initialized) is a better
  8248. // conversion sequence than the standard conversion sequence
  8249. // from the return type of F2 to the destination type.
  8250. if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
  8251. Cand1.Function && Cand2.Function &&
  8252. isa<CXXConversionDecl>(Cand1.Function) &&
  8253. isa<CXXConversionDecl>(Cand2.Function)) {
  8254. // First check whether we prefer one of the conversion functions over the
  8255. // other. This only distinguishes the results in non-standard, extension
  8256. // cases such as the conversion from a lambda closure type to a function
  8257. // pointer or block.
  8258. ImplicitConversionSequence::CompareKind Result =
  8259. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  8260. if (Result == ImplicitConversionSequence::Indistinguishable)
  8261. Result = CompareStandardConversionSequences(S, Loc,
  8262. Cand1.FinalConversion,
  8263. Cand2.FinalConversion);
  8264. if (Result != ImplicitConversionSequence::Indistinguishable)
  8265. return Result == ImplicitConversionSequence::Better;
  8266. // FIXME: Compare kind of reference binding if conversion functions
  8267. // convert to a reference type used in direct reference binding, per
  8268. // C++14 [over.match.best]p1 section 2 bullet 3.
  8269. }
  8270. // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
  8271. // as combined with the resolution to CWG issue 243.
  8272. //
  8273. // When the context is initialization by constructor ([over.match.ctor] or
  8274. // either phase of [over.match.list]), a constructor is preferred over
  8275. // a conversion function.
  8276. if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
  8277. Cand1.Function && Cand2.Function &&
  8278. isa<CXXConstructorDecl>(Cand1.Function) !=
  8279. isa<CXXConstructorDecl>(Cand2.Function))
  8280. return isa<CXXConstructorDecl>(Cand1.Function);
  8281. // -- F1 is a non-template function and F2 is a function template
  8282. // specialization, or, if not that,
  8283. bool Cand1IsSpecialization = Cand1.Function &&
  8284. Cand1.Function->getPrimaryTemplate();
  8285. bool Cand2IsSpecialization = Cand2.Function &&
  8286. Cand2.Function->getPrimaryTemplate();
  8287. if (Cand1IsSpecialization != Cand2IsSpecialization)
  8288. return Cand2IsSpecialization;
  8289. // -- F1 and F2 are function template specializations, and the function
  8290. // template for F1 is more specialized than the template for F2
  8291. // according to the partial ordering rules described in 14.5.5.2, or,
  8292. // if not that,
  8293. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  8294. if (FunctionTemplateDecl *BetterTemplate
  8295. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  8296. Cand2.Function->getPrimaryTemplate(),
  8297. Loc,
  8298. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  8299. : TPOC_Call,
  8300. Cand1.ExplicitCallArguments,
  8301. Cand2.ExplicitCallArguments))
  8302. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  8303. }
  8304. // FIXME: Work around a defect in the C++17 inheriting constructor wording.
  8305. // A derived-class constructor beats an (inherited) base class constructor.
  8306. bool Cand1IsInherited =
  8307. dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
  8308. bool Cand2IsInherited =
  8309. dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
  8310. if (Cand1IsInherited != Cand2IsInherited)
  8311. return Cand2IsInherited;
  8312. else if (Cand1IsInherited) {
  8313. assert(Cand2IsInherited);
  8314. auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
  8315. auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
  8316. if (Cand1Class->isDerivedFrom(Cand2Class))
  8317. return true;
  8318. if (Cand2Class->isDerivedFrom(Cand1Class))
  8319. return false;
  8320. // Inherited from sibling base classes: still ambiguous.
  8321. }
  8322. // Check C++17 tie-breakers for deduction guides.
  8323. {
  8324. auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
  8325. auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
  8326. if (Guide1 && Guide2) {
  8327. // -- F1 is generated from a deduction-guide and F2 is not
  8328. if (Guide1->isImplicit() != Guide2->isImplicit())
  8329. return Guide2->isImplicit();
  8330. // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
  8331. if (Guide1->isCopyDeductionCandidate())
  8332. return true;
  8333. }
  8334. }
  8335. // Check for enable_if value-based overload resolution.
  8336. if (Cand1.Function && Cand2.Function) {
  8337. Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
  8338. if (Cmp != Comparison::Equal)
  8339. return Cmp == Comparison::Better;
  8340. }
  8341. if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
  8342. FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
  8343. return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
  8344. S.IdentifyCUDAPreference(Caller, Cand2.Function);
  8345. }
  8346. bool HasPS1 = Cand1.Function != nullptr &&
  8347. functionHasPassObjectSizeParams(Cand1.Function);
  8348. bool HasPS2 = Cand2.Function != nullptr &&
  8349. functionHasPassObjectSizeParams(Cand2.Function);
  8350. if (HasPS1 != HasPS2 && HasPS1)
  8351. return true;
  8352. return isBetterMultiversionCandidate(Cand1, Cand2);
  8353. }
  8354. /// Determine whether two declarations are "equivalent" for the purposes of
  8355. /// name lookup and overload resolution. This applies when the same internal/no
  8356. /// linkage entity is defined by two modules (probably by textually including
  8357. /// the same header). In such a case, we don't consider the declarations to
  8358. /// declare the same entity, but we also don't want lookups with both
  8359. /// declarations visible to be ambiguous in some cases (this happens when using
  8360. /// a modularized libstdc++).
  8361. bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
  8362. const NamedDecl *B) {
  8363. auto *VA = dyn_cast_or_null<ValueDecl>(A);
  8364. auto *VB = dyn_cast_or_null<ValueDecl>(B);
  8365. if (!VA || !VB)
  8366. return false;
  8367. // The declarations must be declaring the same name as an internal linkage
  8368. // entity in different modules.
  8369. if (!VA->getDeclContext()->getRedeclContext()->Equals(
  8370. VB->getDeclContext()->getRedeclContext()) ||
  8371. getOwningModule(const_cast<ValueDecl *>(VA)) ==
  8372. getOwningModule(const_cast<ValueDecl *>(VB)) ||
  8373. VA->isExternallyVisible() || VB->isExternallyVisible())
  8374. return false;
  8375. // Check that the declarations appear to be equivalent.
  8376. //
  8377. // FIXME: Checking the type isn't really enough to resolve the ambiguity.
  8378. // For constants and functions, we should check the initializer or body is
  8379. // the same. For non-constant variables, we shouldn't allow it at all.
  8380. if (Context.hasSameType(VA->getType(), VB->getType()))
  8381. return true;
  8382. // Enum constants within unnamed enumerations will have different types, but
  8383. // may still be similar enough to be interchangeable for our purposes.
  8384. if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
  8385. if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
  8386. // Only handle anonymous enums. If the enumerations were named and
  8387. // equivalent, they would have been merged to the same type.
  8388. auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
  8389. auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
  8390. if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
  8391. !Context.hasSameType(EnumA->getIntegerType(),
  8392. EnumB->getIntegerType()))
  8393. return false;
  8394. // Allow this only if the value is the same for both enumerators.
  8395. return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
  8396. }
  8397. }
  8398. // Nothing else is sufficiently similar.
  8399. return false;
  8400. }
  8401. void Sema::diagnoseEquivalentInternalLinkageDeclarations(
  8402. SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
  8403. Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
  8404. Module *M = getOwningModule(const_cast<NamedDecl*>(D));
  8405. Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
  8406. << !M << (M ? M->getFullModuleName() : "");
  8407. for (auto *E : Equiv) {
  8408. Module *M = getOwningModule(const_cast<NamedDecl*>(E));
  8409. Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
  8410. << !M << (M ? M->getFullModuleName() : "");
  8411. }
  8412. }
  8413. /// Computes the best viable function (C++ 13.3.3)
  8414. /// within an overload candidate set.
  8415. ///
  8416. /// \param Loc The location of the function name (or operator symbol) for
  8417. /// which overload resolution occurs.
  8418. ///
  8419. /// \param Best If overload resolution was successful or found a deleted
  8420. /// function, \p Best points to the candidate function found.
  8421. ///
  8422. /// \returns The result of overload resolution.
  8423. OverloadingResult
  8424. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  8425. iterator &Best) {
  8426. llvm::SmallVector<OverloadCandidate *, 16> Candidates;
  8427. std::transform(begin(), end(), std::back_inserter(Candidates),
  8428. [](OverloadCandidate &Cand) { return &Cand; });
  8429. // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
  8430. // are accepted by both clang and NVCC. However, during a particular
  8431. // compilation mode only one call variant is viable. We need to
  8432. // exclude non-viable overload candidates from consideration based
  8433. // only on their host/device attributes. Specifically, if one
  8434. // candidate call is WrongSide and the other is SameSide, we ignore
  8435. // the WrongSide candidate.
  8436. if (S.getLangOpts().CUDA) {
  8437. const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
  8438. bool ContainsSameSideCandidate =
  8439. llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
  8440. return Cand->Function &&
  8441. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  8442. Sema::CFP_SameSide;
  8443. });
  8444. if (ContainsSameSideCandidate) {
  8445. auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
  8446. return Cand->Function &&
  8447. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  8448. Sema::CFP_WrongSide;
  8449. };
  8450. llvm::erase_if(Candidates, IsWrongSideCandidate);
  8451. }
  8452. }
  8453. // Find the best viable function.
  8454. Best = end();
  8455. for (auto *Cand : Candidates)
  8456. if (Cand->Viable)
  8457. if (Best == end() ||
  8458. isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
  8459. Best = Cand;
  8460. // If we didn't find any viable functions, abort.
  8461. if (Best == end())
  8462. return OR_No_Viable_Function;
  8463. llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
  8464. // Make sure that this function is better than every other viable
  8465. // function. If not, we have an ambiguity.
  8466. for (auto *Cand : Candidates) {
  8467. if (Cand->Viable && Cand != Best &&
  8468. !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
  8469. if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
  8470. Cand->Function)) {
  8471. EquivalentCands.push_back(Cand->Function);
  8472. continue;
  8473. }
  8474. Best = end();
  8475. return OR_Ambiguous;
  8476. }
  8477. }
  8478. // Best is the best viable function.
  8479. if (Best->Function && Best->Function->isDeleted())
  8480. return OR_Deleted;
  8481. if (!EquivalentCands.empty())
  8482. S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
  8483. EquivalentCands);
  8484. return OR_Success;
  8485. }
  8486. namespace {
  8487. enum OverloadCandidateKind {
  8488. oc_function,
  8489. oc_method,
  8490. oc_constructor,
  8491. oc_implicit_default_constructor,
  8492. oc_implicit_copy_constructor,
  8493. oc_implicit_move_constructor,
  8494. oc_implicit_copy_assignment,
  8495. oc_implicit_move_assignment,
  8496. oc_inherited_constructor
  8497. };
  8498. enum OverloadCandidateSelect {
  8499. ocs_non_template,
  8500. ocs_template,
  8501. ocs_described_template,
  8502. };
  8503. static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
  8504. ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
  8505. std::string &Description) {
  8506. bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
  8507. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  8508. isTemplate = true;
  8509. Description = S.getTemplateArgumentBindingsText(
  8510. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  8511. }
  8512. OverloadCandidateSelect Select = [&]() {
  8513. if (!Description.empty())
  8514. return ocs_described_template;
  8515. return isTemplate ? ocs_template : ocs_non_template;
  8516. }();
  8517. OverloadCandidateKind Kind = [&]() {
  8518. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  8519. if (!Ctor->isImplicit()) {
  8520. if (isa<ConstructorUsingShadowDecl>(Found))
  8521. return oc_inherited_constructor;
  8522. else
  8523. return oc_constructor;
  8524. }
  8525. if (Ctor->isDefaultConstructor())
  8526. return oc_implicit_default_constructor;
  8527. if (Ctor->isMoveConstructor())
  8528. return oc_implicit_move_constructor;
  8529. assert(Ctor->isCopyConstructor() &&
  8530. "unexpected sort of implicit constructor");
  8531. return oc_implicit_copy_constructor;
  8532. }
  8533. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  8534. // This actually gets spelled 'candidate function' for now, but
  8535. // it doesn't hurt to split it out.
  8536. if (!Meth->isImplicit())
  8537. return oc_method;
  8538. if (Meth->isMoveAssignmentOperator())
  8539. return oc_implicit_move_assignment;
  8540. if (Meth->isCopyAssignmentOperator())
  8541. return oc_implicit_copy_assignment;
  8542. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  8543. return oc_method;
  8544. }
  8545. return oc_function;
  8546. }();
  8547. return std::make_pair(Kind, Select);
  8548. }
  8549. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
  8550. // FIXME: It'd be nice to only emit a note once per using-decl per overload
  8551. // set.
  8552. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
  8553. S.Diag(FoundDecl->getLocation(),
  8554. diag::note_ovl_candidate_inherited_constructor)
  8555. << Shadow->getNominatedBaseClass();
  8556. }
  8557. } // end anonymous namespace
  8558. static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
  8559. const FunctionDecl *FD) {
  8560. for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
  8561. bool AlwaysTrue;
  8562. if (EnableIf->getCond()->isValueDependent() ||
  8563. !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
  8564. return false;
  8565. if (!AlwaysTrue)
  8566. return false;
  8567. }
  8568. return true;
  8569. }
  8570. /// Returns true if we can take the address of the function.
  8571. ///
  8572. /// \param Complain - If true, we'll emit a diagnostic
  8573. /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
  8574. /// we in overload resolution?
  8575. /// \param Loc - The location of the statement we're complaining about. Ignored
  8576. /// if we're not complaining, or if we're in overload resolution.
  8577. static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
  8578. bool Complain,
  8579. bool InOverloadResolution,
  8580. SourceLocation Loc) {
  8581. if (!isFunctionAlwaysEnabled(S.Context, FD)) {
  8582. if (Complain) {
  8583. if (InOverloadResolution)
  8584. S.Diag(FD->getBeginLoc(),
  8585. diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
  8586. else
  8587. S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
  8588. }
  8589. return false;
  8590. }
  8591. auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
  8592. return P->hasAttr<PassObjectSizeAttr>();
  8593. });
  8594. if (I == FD->param_end())
  8595. return true;
  8596. if (Complain) {
  8597. // Add one to ParamNo because it's user-facing
  8598. unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
  8599. if (InOverloadResolution)
  8600. S.Diag(FD->getLocation(),
  8601. diag::note_ovl_candidate_has_pass_object_size_params)
  8602. << ParamNo;
  8603. else
  8604. S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
  8605. << FD << ParamNo;
  8606. }
  8607. return false;
  8608. }
  8609. static bool checkAddressOfCandidateIsAvailable(Sema &S,
  8610. const FunctionDecl *FD) {
  8611. return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
  8612. /*InOverloadResolution=*/true,
  8613. /*Loc=*/SourceLocation());
  8614. }
  8615. bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
  8616. bool Complain,
  8617. SourceLocation Loc) {
  8618. return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
  8619. /*InOverloadResolution=*/false,
  8620. Loc);
  8621. }
  8622. // Notes the location of an overload candidate.
  8623. void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
  8624. QualType DestType, bool TakingAddress) {
  8625. if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
  8626. return;
  8627. if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
  8628. !Fn->getAttr<TargetAttr>()->isDefaultVersion())
  8629. return;
  8630. std::string FnDesc;
  8631. std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
  8632. ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
  8633. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  8634. << (unsigned)KSPair.first << (unsigned)KSPair.second
  8635. << Fn << FnDesc;
  8636. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  8637. Diag(Fn->getLocation(), PD);
  8638. MaybeEmitInheritedConstructorNote(*this, Found);
  8639. }
  8640. // Notes the location of all overload candidates designated through
  8641. // OverloadedExpr
  8642. void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
  8643. bool TakingAddress) {
  8644. assert(OverloadedExpr->getType() == Context.OverloadTy);
  8645. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  8646. OverloadExpr *OvlExpr = Ovl.Expression;
  8647. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  8648. IEnd = OvlExpr->decls_end();
  8649. I != IEnd; ++I) {
  8650. if (FunctionTemplateDecl *FunTmpl =
  8651. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  8652. NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
  8653. TakingAddress);
  8654. } else if (FunctionDecl *Fun
  8655. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  8656. NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
  8657. }
  8658. }
  8659. }
  8660. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  8661. /// "lead" diagnostic; it will be given two arguments, the source and
  8662. /// target types of the conversion.
  8663. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  8664. Sema &S,
  8665. SourceLocation CaretLoc,
  8666. const PartialDiagnostic &PDiag) const {
  8667. S.Diag(CaretLoc, PDiag)
  8668. << Ambiguous.getFromType() << Ambiguous.getToType();
  8669. // FIXME: The note limiting machinery is borrowed from
  8670. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  8671. // refactoring here.
  8672. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8673. unsigned CandsShown = 0;
  8674. AmbiguousConversionSequence::const_iterator I, E;
  8675. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  8676. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8677. break;
  8678. ++CandsShown;
  8679. S.NoteOverloadCandidate(I->first, I->second);
  8680. }
  8681. if (I != E)
  8682. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  8683. }
  8684. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  8685. unsigned I, bool TakingCandidateAddress) {
  8686. const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  8687. assert(Conv.isBad());
  8688. assert(Cand->Function && "for now, candidate must be a function");
  8689. FunctionDecl *Fn = Cand->Function;
  8690. // There's a conversion slot for the object argument if this is a
  8691. // non-constructor method. Note that 'I' corresponds the
  8692. // conversion-slot index.
  8693. bool isObjectArgument = false;
  8694. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  8695. if (I == 0)
  8696. isObjectArgument = true;
  8697. else
  8698. I--;
  8699. }
  8700. std::string FnDesc;
  8701. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  8702. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
  8703. Expr *FromExpr = Conv.Bad.FromExpr;
  8704. QualType FromTy = Conv.Bad.getFromType();
  8705. QualType ToTy = Conv.Bad.getToType();
  8706. if (FromTy == S.Context.OverloadTy) {
  8707. assert(FromExpr && "overload set argument came from implicit argument?");
  8708. Expr *E = FromExpr->IgnoreParens();
  8709. if (isa<UnaryOperator>(E))
  8710. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  8711. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  8712. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
  8713. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8714. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
  8715. << Name << I + 1;
  8716. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8717. return;
  8718. }
  8719. // Do some hand-waving analysis to see if the non-viability is due
  8720. // to a qualifier mismatch.
  8721. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  8722. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  8723. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  8724. CToTy = RT->getPointeeType();
  8725. else {
  8726. // TODO: detect and diagnose the full richness of const mismatches.
  8727. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  8728. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
  8729. CFromTy = FromPT->getPointeeType();
  8730. CToTy = ToPT->getPointeeType();
  8731. }
  8732. }
  8733. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  8734. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  8735. Qualifiers FromQs = CFromTy.getQualifiers();
  8736. Qualifiers ToQs = CToTy.getQualifiers();
  8737. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  8738. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
  8739. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8740. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8741. << ToTy << (unsigned)isObjectArgument << I + 1;
  8742. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8743. return;
  8744. }
  8745. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8746. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
  8747. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8748. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8749. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  8750. << (unsigned)isObjectArgument << I + 1;
  8751. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8752. return;
  8753. }
  8754. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  8755. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
  8756. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8757. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8758. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  8759. << (unsigned)isObjectArgument << I + 1;
  8760. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8761. return;
  8762. }
  8763. if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
  8764. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
  8765. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8766. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8767. << FromQs.hasUnaligned() << I + 1;
  8768. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8769. return;
  8770. }
  8771. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  8772. assert(CVR && "unexpected qualifiers mismatch");
  8773. if (isObjectArgument) {
  8774. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
  8775. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8776. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8777. << (CVR - 1);
  8778. } else {
  8779. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
  8780. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8781. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8782. << (CVR - 1) << I + 1;
  8783. }
  8784. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8785. return;
  8786. }
  8787. // Special diagnostic for failure to convert an initializer list, since
  8788. // telling the user that it has type void is not useful.
  8789. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8790. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
  8791. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8792. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8793. << ToTy << (unsigned)isObjectArgument << I + 1;
  8794. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8795. return;
  8796. }
  8797. // Diagnose references or pointers to incomplete types differently,
  8798. // since it's far from impossible that the incompleteness triggered
  8799. // the failure.
  8800. QualType TempFromTy = FromTy.getNonReferenceType();
  8801. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8802. TempFromTy = PTy->getPointeeType();
  8803. if (TempFromTy->isIncompleteType()) {
  8804. // Emit the generic diagnostic and, optionally, add the hints to it.
  8805. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
  8806. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8807. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8808. << ToTy << (unsigned)isObjectArgument << I + 1
  8809. << (unsigned)(Cand->Fix.Kind);
  8810. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8811. return;
  8812. }
  8813. // Diagnose base -> derived pointer conversions.
  8814. unsigned BaseToDerivedConversion = 0;
  8815. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8816. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8817. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8818. FromPtrTy->getPointeeType()) &&
  8819. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8820. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8821. S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
  8822. FromPtrTy->getPointeeType()))
  8823. BaseToDerivedConversion = 1;
  8824. }
  8825. } else if (const ObjCObjectPointerType *FromPtrTy
  8826. = FromTy->getAs<ObjCObjectPointerType>()) {
  8827. if (const ObjCObjectPointerType *ToPtrTy
  8828. = ToTy->getAs<ObjCObjectPointerType>())
  8829. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8830. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8831. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8832. FromPtrTy->getPointeeType()) &&
  8833. FromIface->isSuperClassOf(ToIface))
  8834. BaseToDerivedConversion = 2;
  8835. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  8836. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  8837. !FromTy->isIncompleteType() &&
  8838. !ToRefTy->getPointeeType()->isIncompleteType() &&
  8839. S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
  8840. BaseToDerivedConversion = 3;
  8841. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  8842. ToTy.getNonReferenceType().getCanonicalType() ==
  8843. FromTy.getNonReferenceType().getCanonicalType()) {
  8844. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
  8845. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8846. << (unsigned)isObjectArgument << I + 1
  8847. << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
  8848. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8849. return;
  8850. }
  8851. }
  8852. if (BaseToDerivedConversion) {
  8853. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
  8854. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8855. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8856. << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
  8857. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8858. return;
  8859. }
  8860. if (isa<ObjCObjectPointerType>(CFromTy) &&
  8861. isa<PointerType>(CToTy)) {
  8862. Qualifiers FromQs = CFromTy.getQualifiers();
  8863. Qualifiers ToQs = CToTy.getQualifiers();
  8864. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8865. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
  8866. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  8867. << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8868. << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
  8869. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8870. return;
  8871. }
  8872. }
  8873. if (TakingCandidateAddress &&
  8874. !checkAddressOfCandidateIsAvailable(S, Cand->Function))
  8875. return;
  8876. // Emit the generic diagnostic and, optionally, add the hints to it.
  8877. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  8878. FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8879. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8880. << ToTy << (unsigned)isObjectArgument << I + 1
  8881. << (unsigned)(Cand->Fix.Kind);
  8882. // If we can fix the conversion, suggest the FixIts.
  8883. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  8884. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  8885. FDiag << *HI;
  8886. S.Diag(Fn->getLocation(), FDiag);
  8887. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8888. }
  8889. /// Additional arity mismatch diagnosis specific to a function overload
  8890. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  8891. /// over a candidate in any candidate set.
  8892. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  8893. unsigned NumArgs) {
  8894. FunctionDecl *Fn = Cand->Function;
  8895. unsigned MinParams = Fn->getMinRequiredArguments();
  8896. // With invalid overloaded operators, it's possible that we think we
  8897. // have an arity mismatch when in fact it looks like we have the
  8898. // right number of arguments, because only overloaded operators have
  8899. // the weird behavior of overloading member and non-member functions.
  8900. // Just don't report anything.
  8901. if (Fn->isInvalidDecl() &&
  8902. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  8903. return true;
  8904. if (NumArgs < MinParams) {
  8905. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  8906. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8907. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  8908. } else {
  8909. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  8910. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8911. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  8912. }
  8913. return false;
  8914. }
  8915. /// General arity mismatch diagnosis over a candidate in a candidate set.
  8916. static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
  8917. unsigned NumFormalArgs) {
  8918. assert(isa<FunctionDecl>(D) &&
  8919. "The templated declaration should at least be a function"
  8920. " when diagnosing bad template argument deduction due to too many"
  8921. " or too few arguments");
  8922. FunctionDecl *Fn = cast<FunctionDecl>(D);
  8923. // TODO: treat calls to a missing default constructor as a special case
  8924. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  8925. unsigned MinParams = Fn->getMinRequiredArguments();
  8926. // at least / at most / exactly
  8927. unsigned mode, modeCount;
  8928. if (NumFormalArgs < MinParams) {
  8929. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  8930. FnTy->isTemplateVariadic())
  8931. mode = 0; // "at least"
  8932. else
  8933. mode = 2; // "exactly"
  8934. modeCount = MinParams;
  8935. } else {
  8936. if (MinParams != FnTy->getNumParams())
  8937. mode = 1; // "at most"
  8938. else
  8939. mode = 2; // "exactly"
  8940. modeCount = FnTy->getNumParams();
  8941. }
  8942. std::string Description;
  8943. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  8944. ClassifyOverloadCandidate(S, Found, Fn, Description);
  8945. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  8946. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
  8947. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  8948. << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
  8949. else
  8950. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
  8951. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  8952. << Description << mode << modeCount << NumFormalArgs;
  8953. MaybeEmitInheritedConstructorNote(S, Found);
  8954. }
  8955. /// Arity mismatch diagnosis specific to a function overload candidate.
  8956. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  8957. unsigned NumFormalArgs) {
  8958. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  8959. DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
  8960. }
  8961. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  8962. if (TemplateDecl *TD = Templated->getDescribedTemplate())
  8963. return TD;
  8964. llvm_unreachable("Unsupported: Getting the described template declaration"
  8965. " for bad deduction diagnosis");
  8966. }
  8967. /// Diagnose a failed template-argument deduction.
  8968. static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
  8969. DeductionFailureInfo &DeductionFailure,
  8970. unsigned NumArgs,
  8971. bool TakingCandidateAddress) {
  8972. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  8973. NamedDecl *ParamD;
  8974. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  8975. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  8976. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  8977. switch (DeductionFailure.Result) {
  8978. case Sema::TDK_Success:
  8979. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8980. case Sema::TDK_Incomplete: {
  8981. assert(ParamD && "no parameter found for incomplete deduction result");
  8982. S.Diag(Templated->getLocation(),
  8983. diag::note_ovl_candidate_incomplete_deduction)
  8984. << ParamD->getDeclName();
  8985. MaybeEmitInheritedConstructorNote(S, Found);
  8986. return;
  8987. }
  8988. case Sema::TDK_IncompletePack: {
  8989. assert(ParamD && "no parameter found for incomplete deduction result");
  8990. S.Diag(Templated->getLocation(),
  8991. diag::note_ovl_candidate_incomplete_deduction_pack)
  8992. << ParamD->getDeclName()
  8993. << (DeductionFailure.getFirstArg()->pack_size() + 1)
  8994. << *DeductionFailure.getFirstArg();
  8995. MaybeEmitInheritedConstructorNote(S, Found);
  8996. return;
  8997. }
  8998. case Sema::TDK_Underqualified: {
  8999. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  9000. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  9001. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  9002. // Param will have been canonicalized, but it should just be a
  9003. // qualified version of ParamD, so move the qualifiers to that.
  9004. QualifierCollector Qs;
  9005. Qs.strip(Param);
  9006. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  9007. assert(S.Context.hasSameType(Param, NonCanonParam));
  9008. // Arg has also been canonicalized, but there's nothing we can do
  9009. // about that. It also doesn't matter as much, because it won't
  9010. // have any template parameters in it (because deduction isn't
  9011. // done on dependent types).
  9012. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  9013. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  9014. << ParamD->getDeclName() << Arg << NonCanonParam;
  9015. MaybeEmitInheritedConstructorNote(S, Found);
  9016. return;
  9017. }
  9018. case Sema::TDK_Inconsistent: {
  9019. assert(ParamD && "no parameter found for inconsistent deduction result");
  9020. int which = 0;
  9021. if (isa<TemplateTypeParmDecl>(ParamD))
  9022. which = 0;
  9023. else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
  9024. // Deduction might have failed because we deduced arguments of two
  9025. // different types for a non-type template parameter.
  9026. // FIXME: Use a different TDK value for this.
  9027. QualType T1 =
  9028. DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
  9029. QualType T2 =
  9030. DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
  9031. if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
  9032. S.Diag(Templated->getLocation(),
  9033. diag::note_ovl_candidate_inconsistent_deduction_types)
  9034. << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
  9035. << *DeductionFailure.getSecondArg() << T2;
  9036. MaybeEmitInheritedConstructorNote(S, Found);
  9037. return;
  9038. }
  9039. which = 1;
  9040. } else {
  9041. which = 2;
  9042. }
  9043. S.Diag(Templated->getLocation(),
  9044. diag::note_ovl_candidate_inconsistent_deduction)
  9045. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  9046. << *DeductionFailure.getSecondArg();
  9047. MaybeEmitInheritedConstructorNote(S, Found);
  9048. return;
  9049. }
  9050. case Sema::TDK_InvalidExplicitArguments:
  9051. assert(ParamD && "no parameter found for invalid explicit arguments");
  9052. if (ParamD->getDeclName())
  9053. S.Diag(Templated->getLocation(),
  9054. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  9055. << ParamD->getDeclName();
  9056. else {
  9057. int index = 0;
  9058. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  9059. index = TTP->getIndex();
  9060. else if (NonTypeTemplateParmDecl *NTTP
  9061. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  9062. index = NTTP->getIndex();
  9063. else
  9064. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  9065. S.Diag(Templated->getLocation(),
  9066. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  9067. << (index + 1);
  9068. }
  9069. MaybeEmitInheritedConstructorNote(S, Found);
  9070. return;
  9071. case Sema::TDK_TooManyArguments:
  9072. case Sema::TDK_TooFewArguments:
  9073. DiagnoseArityMismatch(S, Found, Templated, NumArgs);
  9074. return;
  9075. case Sema::TDK_InstantiationDepth:
  9076. S.Diag(Templated->getLocation(),
  9077. diag::note_ovl_candidate_instantiation_depth);
  9078. MaybeEmitInheritedConstructorNote(S, Found);
  9079. return;
  9080. case Sema::TDK_SubstitutionFailure: {
  9081. // Format the template argument list into the argument string.
  9082. SmallString<128> TemplateArgString;
  9083. if (TemplateArgumentList *Args =
  9084. DeductionFailure.getTemplateArgumentList()) {
  9085. TemplateArgString = " ";
  9086. TemplateArgString += S.getTemplateArgumentBindingsText(
  9087. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9088. }
  9089. // If this candidate was disabled by enable_if, say so.
  9090. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  9091. if (PDiag && PDiag->second.getDiagID() ==
  9092. diag::err_typename_nested_not_found_enable_if) {
  9093. // FIXME: Use the source range of the condition, and the fully-qualified
  9094. // name of the enable_if template. These are both present in PDiag.
  9095. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  9096. << "'enable_if'" << TemplateArgString;
  9097. return;
  9098. }
  9099. // We found a specific requirement that disabled the enable_if.
  9100. if (PDiag && PDiag->second.getDiagID() ==
  9101. diag::err_typename_nested_not_found_requirement) {
  9102. S.Diag(Templated->getLocation(),
  9103. diag::note_ovl_candidate_disabled_by_requirement)
  9104. << PDiag->second.getStringArg(0) << TemplateArgString;
  9105. return;
  9106. }
  9107. // Format the SFINAE diagnostic into the argument string.
  9108. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  9109. // formatted message in another diagnostic.
  9110. SmallString<128> SFINAEArgString;
  9111. SourceRange R;
  9112. if (PDiag) {
  9113. SFINAEArgString = ": ";
  9114. R = SourceRange(PDiag->first, PDiag->first);
  9115. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  9116. }
  9117. S.Diag(Templated->getLocation(),
  9118. diag::note_ovl_candidate_substitution_failure)
  9119. << TemplateArgString << SFINAEArgString << R;
  9120. MaybeEmitInheritedConstructorNote(S, Found);
  9121. return;
  9122. }
  9123. case Sema::TDK_DeducedMismatch:
  9124. case Sema::TDK_DeducedMismatchNested: {
  9125. // Format the template argument list into the argument string.
  9126. SmallString<128> TemplateArgString;
  9127. if (TemplateArgumentList *Args =
  9128. DeductionFailure.getTemplateArgumentList()) {
  9129. TemplateArgString = " ";
  9130. TemplateArgString += S.getTemplateArgumentBindingsText(
  9131. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9132. }
  9133. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
  9134. << (*DeductionFailure.getCallArgIndex() + 1)
  9135. << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
  9136. << TemplateArgString
  9137. << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
  9138. break;
  9139. }
  9140. case Sema::TDK_NonDeducedMismatch: {
  9141. // FIXME: Provide a source location to indicate what we couldn't match.
  9142. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  9143. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  9144. if (FirstTA.getKind() == TemplateArgument::Template &&
  9145. SecondTA.getKind() == TemplateArgument::Template) {
  9146. TemplateName FirstTN = FirstTA.getAsTemplate();
  9147. TemplateName SecondTN = SecondTA.getAsTemplate();
  9148. if (FirstTN.getKind() == TemplateName::Template &&
  9149. SecondTN.getKind() == TemplateName::Template) {
  9150. if (FirstTN.getAsTemplateDecl()->getName() ==
  9151. SecondTN.getAsTemplateDecl()->getName()) {
  9152. // FIXME: This fixes a bad diagnostic where both templates are named
  9153. // the same. This particular case is a bit difficult since:
  9154. // 1) It is passed as a string to the diagnostic printer.
  9155. // 2) The diagnostic printer only attempts to find a better
  9156. // name for types, not decls.
  9157. // Ideally, this should folded into the diagnostic printer.
  9158. S.Diag(Templated->getLocation(),
  9159. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  9160. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  9161. return;
  9162. }
  9163. }
  9164. }
  9165. if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
  9166. !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
  9167. return;
  9168. // FIXME: For generic lambda parameters, check if the function is a lambda
  9169. // call operator, and if so, emit a prettier and more informative
  9170. // diagnostic that mentions 'auto' and lambda in addition to
  9171. // (or instead of?) the canonical template type parameters.
  9172. S.Diag(Templated->getLocation(),
  9173. diag::note_ovl_candidate_non_deduced_mismatch)
  9174. << FirstTA << SecondTA;
  9175. return;
  9176. }
  9177. // TODO: diagnose these individually, then kill off
  9178. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  9179. case Sema::TDK_MiscellaneousDeductionFailure:
  9180. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  9181. MaybeEmitInheritedConstructorNote(S, Found);
  9182. return;
  9183. case Sema::TDK_CUDATargetMismatch:
  9184. S.Diag(Templated->getLocation(),
  9185. diag::note_cuda_ovl_candidate_target_mismatch);
  9186. return;
  9187. }
  9188. }
  9189. /// Diagnose a failed template-argument deduction, for function calls.
  9190. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  9191. unsigned NumArgs,
  9192. bool TakingCandidateAddress) {
  9193. unsigned TDK = Cand->DeductionFailure.Result;
  9194. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  9195. if (CheckArityMismatch(S, Cand, NumArgs))
  9196. return;
  9197. }
  9198. DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
  9199. Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
  9200. }
  9201. /// CUDA: diagnose an invalid call across targets.
  9202. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  9203. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  9204. FunctionDecl *Callee = Cand->Function;
  9205. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  9206. CalleeTarget = S.IdentifyCUDATarget(Callee);
  9207. std::string FnDesc;
  9208. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9209. ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
  9210. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  9211. << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
  9212. << FnDesc /* Ignored */
  9213. << CalleeTarget << CallerTarget;
  9214. // This could be an implicit constructor for which we could not infer the
  9215. // target due to a collsion. Diagnose that case.
  9216. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  9217. if (Meth != nullptr && Meth->isImplicit()) {
  9218. CXXRecordDecl *ParentClass = Meth->getParent();
  9219. Sema::CXXSpecialMember CSM;
  9220. switch (FnKindPair.first) {
  9221. default:
  9222. return;
  9223. case oc_implicit_default_constructor:
  9224. CSM = Sema::CXXDefaultConstructor;
  9225. break;
  9226. case oc_implicit_copy_constructor:
  9227. CSM = Sema::CXXCopyConstructor;
  9228. break;
  9229. case oc_implicit_move_constructor:
  9230. CSM = Sema::CXXMoveConstructor;
  9231. break;
  9232. case oc_implicit_copy_assignment:
  9233. CSM = Sema::CXXCopyAssignment;
  9234. break;
  9235. case oc_implicit_move_assignment:
  9236. CSM = Sema::CXXMoveAssignment;
  9237. break;
  9238. };
  9239. bool ConstRHS = false;
  9240. if (Meth->getNumParams()) {
  9241. if (const ReferenceType *RT =
  9242. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  9243. ConstRHS = RT->getPointeeType().isConstQualified();
  9244. }
  9245. }
  9246. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  9247. /* ConstRHS */ ConstRHS,
  9248. /* Diagnose */ true);
  9249. }
  9250. }
  9251. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  9252. FunctionDecl *Callee = Cand->Function;
  9253. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  9254. S.Diag(Callee->getLocation(),
  9255. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  9256. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  9257. }
  9258. static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
  9259. ExplicitSpecifier ES;
  9260. const char *DeclName;
  9261. switch (Cand->Function->getDeclKind()) {
  9262. case Decl::Kind::CXXConstructor:
  9263. ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
  9264. DeclName = "constructor";
  9265. break;
  9266. case Decl::Kind::CXXConversion:
  9267. ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
  9268. DeclName = "conversion operator";
  9269. break;
  9270. case Decl::Kind::CXXDeductionGuide:
  9271. ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
  9272. DeclName = "deductiong guide";
  9273. break;
  9274. default:
  9275. llvm_unreachable("invalid Decl");
  9276. }
  9277. assert(ES.getExpr() && "null expression should be handled before");
  9278. S.Diag(Cand->Function->getLocation(),
  9279. diag::note_ovl_candidate_explicit_forbidden)
  9280. << DeclName;
  9281. S.Diag(ES.getExpr()->getBeginLoc(),
  9282. diag::note_explicit_bool_resolved_to_true);
  9283. }
  9284. static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
  9285. FunctionDecl *Callee = Cand->Function;
  9286. S.Diag(Callee->getLocation(),
  9287. diag::note_ovl_candidate_disabled_by_extension)
  9288. << S.getOpenCLExtensionsFromDeclExtMap(Callee);
  9289. }
  9290. /// Generates a 'note' diagnostic for an overload candidate. We've
  9291. /// already generated a primary error at the call site.
  9292. ///
  9293. /// It really does need to be a single diagnostic with its caret
  9294. /// pointed at the candidate declaration. Yes, this creates some
  9295. /// major challenges of technical writing. Yes, this makes pointing
  9296. /// out problems with specific arguments quite awkward. It's still
  9297. /// better than generating twenty screens of text for every failed
  9298. /// overload.
  9299. ///
  9300. /// It would be great to be able to express per-candidate problems
  9301. /// more richly for those diagnostic clients that cared, but we'd
  9302. /// still have to be just as careful with the default diagnostics.
  9303. /// \param CtorDestAS Addr space of object being constructed (for ctor
  9304. /// candidates only).
  9305. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  9306. unsigned NumArgs,
  9307. bool TakingCandidateAddress,
  9308. LangAS CtorDestAS = LangAS::Default) {
  9309. FunctionDecl *Fn = Cand->Function;
  9310. // Note deleted candidates, but only if they're viable.
  9311. if (Cand->Viable) {
  9312. if (Fn->isDeleted()) {
  9313. std::string FnDesc;
  9314. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9315. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
  9316. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  9317. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9318. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  9319. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9320. return;
  9321. }
  9322. // We don't really have anything else to say about viable candidates.
  9323. S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
  9324. return;
  9325. }
  9326. switch (Cand->FailureKind) {
  9327. case ovl_fail_too_many_arguments:
  9328. case ovl_fail_too_few_arguments:
  9329. return DiagnoseArityMismatch(S, Cand, NumArgs);
  9330. case ovl_fail_bad_deduction:
  9331. return DiagnoseBadDeduction(S, Cand, NumArgs,
  9332. TakingCandidateAddress);
  9333. case ovl_fail_illegal_constructor: {
  9334. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  9335. << (Fn->getPrimaryTemplate() ? 1 : 0);
  9336. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9337. return;
  9338. }
  9339. case ovl_fail_object_addrspace_mismatch: {
  9340. Qualifiers QualsForPrinting;
  9341. QualsForPrinting.setAddressSpace(CtorDestAS);
  9342. S.Diag(Fn->getLocation(),
  9343. diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
  9344. << QualsForPrinting;
  9345. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9346. return;
  9347. }
  9348. case ovl_fail_trivial_conversion:
  9349. case ovl_fail_bad_final_conversion:
  9350. case ovl_fail_final_conversion_not_exact:
  9351. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
  9352. case ovl_fail_bad_conversion: {
  9353. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  9354. for (unsigned N = Cand->Conversions.size(); I != N; ++I)
  9355. if (Cand->Conversions[I].isBad())
  9356. return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
  9357. // FIXME: this currently happens when we're called from SemaInit
  9358. // when user-conversion overload fails. Figure out how to handle
  9359. // those conditions and diagnose them well.
  9360. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
  9361. }
  9362. case ovl_fail_bad_target:
  9363. return DiagnoseBadTarget(S, Cand);
  9364. case ovl_fail_enable_if:
  9365. return DiagnoseFailedEnableIfAttr(S, Cand);
  9366. case ovl_fail_explicit_resolved:
  9367. return DiagnoseFailedExplicitSpec(S, Cand);
  9368. case ovl_fail_ext_disabled:
  9369. return DiagnoseOpenCLExtensionDisabled(S, Cand);
  9370. case ovl_fail_inhctor_slice:
  9371. // It's generally not interesting to note copy/move constructors here.
  9372. if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
  9373. return;
  9374. S.Diag(Fn->getLocation(),
  9375. diag::note_ovl_candidate_inherited_constructor_slice)
  9376. << (Fn->getPrimaryTemplate() ? 1 : 0)
  9377. << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
  9378. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9379. return;
  9380. case ovl_fail_addr_not_available: {
  9381. bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
  9382. (void)Available;
  9383. assert(!Available);
  9384. break;
  9385. }
  9386. case ovl_non_default_multiversion_function:
  9387. // Do nothing, these should simply be ignored.
  9388. break;
  9389. }
  9390. }
  9391. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  9392. // Desugar the type of the surrogate down to a function type,
  9393. // retaining as many typedefs as possible while still showing
  9394. // the function type (and, therefore, its parameter types).
  9395. QualType FnType = Cand->Surrogate->getConversionType();
  9396. bool isLValueReference = false;
  9397. bool isRValueReference = false;
  9398. bool isPointer = false;
  9399. if (const LValueReferenceType *FnTypeRef =
  9400. FnType->getAs<LValueReferenceType>()) {
  9401. FnType = FnTypeRef->getPointeeType();
  9402. isLValueReference = true;
  9403. } else if (const RValueReferenceType *FnTypeRef =
  9404. FnType->getAs<RValueReferenceType>()) {
  9405. FnType = FnTypeRef->getPointeeType();
  9406. isRValueReference = true;
  9407. }
  9408. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  9409. FnType = FnTypePtr->getPointeeType();
  9410. isPointer = true;
  9411. }
  9412. // Desugar down to a function type.
  9413. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  9414. // Reconstruct the pointer/reference as appropriate.
  9415. if (isPointer) FnType = S.Context.getPointerType(FnType);
  9416. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  9417. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  9418. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  9419. << FnType;
  9420. }
  9421. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  9422. SourceLocation OpLoc,
  9423. OverloadCandidate *Cand) {
  9424. assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
  9425. std::string TypeStr("operator");
  9426. TypeStr += Opc;
  9427. TypeStr += "(";
  9428. TypeStr += Cand->BuiltinParamTypes[0].getAsString();
  9429. if (Cand->Conversions.size() == 1) {
  9430. TypeStr += ")";
  9431. S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
  9432. } else {
  9433. TypeStr += ", ";
  9434. TypeStr += Cand->BuiltinParamTypes[1].getAsString();
  9435. TypeStr += ")";
  9436. S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
  9437. }
  9438. }
  9439. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  9440. OverloadCandidate *Cand) {
  9441. for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
  9442. if (ICS.isBad()) break; // all meaningless after first invalid
  9443. if (!ICS.isAmbiguous()) continue;
  9444. ICS.DiagnoseAmbiguousConversion(
  9445. S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
  9446. }
  9447. }
  9448. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  9449. if (Cand->Function)
  9450. return Cand->Function->getLocation();
  9451. if (Cand->IsSurrogate)
  9452. return Cand->Surrogate->getLocation();
  9453. return SourceLocation();
  9454. }
  9455. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  9456. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  9457. case Sema::TDK_Success:
  9458. case Sema::TDK_NonDependentConversionFailure:
  9459. llvm_unreachable("non-deduction failure while diagnosing bad deduction");
  9460. case Sema::TDK_Invalid:
  9461. case Sema::TDK_Incomplete:
  9462. case Sema::TDK_IncompletePack:
  9463. return 1;
  9464. case Sema::TDK_Underqualified:
  9465. case Sema::TDK_Inconsistent:
  9466. return 2;
  9467. case Sema::TDK_SubstitutionFailure:
  9468. case Sema::TDK_DeducedMismatch:
  9469. case Sema::TDK_DeducedMismatchNested:
  9470. case Sema::TDK_NonDeducedMismatch:
  9471. case Sema::TDK_MiscellaneousDeductionFailure:
  9472. case Sema::TDK_CUDATargetMismatch:
  9473. return 3;
  9474. case Sema::TDK_InstantiationDepth:
  9475. return 4;
  9476. case Sema::TDK_InvalidExplicitArguments:
  9477. return 5;
  9478. case Sema::TDK_TooManyArguments:
  9479. case Sema::TDK_TooFewArguments:
  9480. return 6;
  9481. }
  9482. llvm_unreachable("Unhandled deduction result");
  9483. }
  9484. namespace {
  9485. struct CompareOverloadCandidatesForDisplay {
  9486. Sema &S;
  9487. SourceLocation Loc;
  9488. size_t NumArgs;
  9489. OverloadCandidateSet::CandidateSetKind CSK;
  9490. CompareOverloadCandidatesForDisplay(
  9491. Sema &S, SourceLocation Loc, size_t NArgs,
  9492. OverloadCandidateSet::CandidateSetKind CSK)
  9493. : S(S), NumArgs(NArgs), CSK(CSK) {}
  9494. bool operator()(const OverloadCandidate *L,
  9495. const OverloadCandidate *R) {
  9496. // Fast-path this check.
  9497. if (L == R) return false;
  9498. // Order first by viability.
  9499. if (L->Viable) {
  9500. if (!R->Viable) return true;
  9501. // TODO: introduce a tri-valued comparison for overload
  9502. // candidates. Would be more worthwhile if we had a sort
  9503. // that could exploit it.
  9504. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
  9505. return true;
  9506. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
  9507. return false;
  9508. } else if (R->Viable)
  9509. return false;
  9510. assert(L->Viable == R->Viable);
  9511. // Criteria by which we can sort non-viable candidates:
  9512. if (!L->Viable) {
  9513. // 1. Arity mismatches come after other candidates.
  9514. if (L->FailureKind == ovl_fail_too_many_arguments ||
  9515. L->FailureKind == ovl_fail_too_few_arguments) {
  9516. if (R->FailureKind == ovl_fail_too_many_arguments ||
  9517. R->FailureKind == ovl_fail_too_few_arguments) {
  9518. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  9519. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  9520. if (LDist == RDist) {
  9521. if (L->FailureKind == R->FailureKind)
  9522. // Sort non-surrogates before surrogates.
  9523. return !L->IsSurrogate && R->IsSurrogate;
  9524. // Sort candidates requiring fewer parameters than there were
  9525. // arguments given after candidates requiring more parameters
  9526. // than there were arguments given.
  9527. return L->FailureKind == ovl_fail_too_many_arguments;
  9528. }
  9529. return LDist < RDist;
  9530. }
  9531. return false;
  9532. }
  9533. if (R->FailureKind == ovl_fail_too_many_arguments ||
  9534. R->FailureKind == ovl_fail_too_few_arguments)
  9535. return true;
  9536. // 2. Bad conversions come first and are ordered by the number
  9537. // of bad conversions and quality of good conversions.
  9538. if (L->FailureKind == ovl_fail_bad_conversion) {
  9539. if (R->FailureKind != ovl_fail_bad_conversion)
  9540. return true;
  9541. // The conversion that can be fixed with a smaller number of changes,
  9542. // comes first.
  9543. unsigned numLFixes = L->Fix.NumConversionsFixed;
  9544. unsigned numRFixes = R->Fix.NumConversionsFixed;
  9545. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  9546. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  9547. if (numLFixes != numRFixes) {
  9548. return numLFixes < numRFixes;
  9549. }
  9550. // If there's any ordering between the defined conversions...
  9551. // FIXME: this might not be transitive.
  9552. assert(L->Conversions.size() == R->Conversions.size());
  9553. int leftBetter = 0;
  9554. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  9555. for (unsigned E = L->Conversions.size(); I != E; ++I) {
  9556. switch (CompareImplicitConversionSequences(S, Loc,
  9557. L->Conversions[I],
  9558. R->Conversions[I])) {
  9559. case ImplicitConversionSequence::Better:
  9560. leftBetter++;
  9561. break;
  9562. case ImplicitConversionSequence::Worse:
  9563. leftBetter--;
  9564. break;
  9565. case ImplicitConversionSequence::Indistinguishable:
  9566. break;
  9567. }
  9568. }
  9569. if (leftBetter > 0) return true;
  9570. if (leftBetter < 0) return false;
  9571. } else if (R->FailureKind == ovl_fail_bad_conversion)
  9572. return false;
  9573. if (L->FailureKind == ovl_fail_bad_deduction) {
  9574. if (R->FailureKind != ovl_fail_bad_deduction)
  9575. return true;
  9576. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  9577. return RankDeductionFailure(L->DeductionFailure)
  9578. < RankDeductionFailure(R->DeductionFailure);
  9579. } else if (R->FailureKind == ovl_fail_bad_deduction)
  9580. return false;
  9581. // TODO: others?
  9582. }
  9583. // Sort everything else by location.
  9584. SourceLocation LLoc = GetLocationForCandidate(L);
  9585. SourceLocation RLoc = GetLocationForCandidate(R);
  9586. // Put candidates without locations (e.g. builtins) at the end.
  9587. if (LLoc.isInvalid()) return false;
  9588. if (RLoc.isInvalid()) return true;
  9589. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  9590. }
  9591. };
  9592. }
  9593. /// CompleteNonViableCandidate - Normally, overload resolution only
  9594. /// computes up to the first bad conversion. Produces the FixIt set if
  9595. /// possible.
  9596. static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  9597. ArrayRef<Expr *> Args) {
  9598. assert(!Cand->Viable);
  9599. // Don't do anything on failures other than bad conversion.
  9600. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  9601. // We only want the FixIts if all the arguments can be corrected.
  9602. bool Unfixable = false;
  9603. // Use a implicit copy initialization to check conversion fixes.
  9604. Cand->Fix.setConversionChecker(TryCopyInitialization);
  9605. // Attempt to fix the bad conversion.
  9606. unsigned ConvCount = Cand->Conversions.size();
  9607. for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
  9608. ++ConvIdx) {
  9609. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  9610. if (Cand->Conversions[ConvIdx].isInitialized() &&
  9611. Cand->Conversions[ConvIdx].isBad()) {
  9612. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  9613. break;
  9614. }
  9615. }
  9616. // FIXME: this should probably be preserved from the overload
  9617. // operation somehow.
  9618. bool SuppressUserConversions = false;
  9619. unsigned ConvIdx = 0;
  9620. ArrayRef<QualType> ParamTypes;
  9621. if (Cand->IsSurrogate) {
  9622. QualType ConvType
  9623. = Cand->Surrogate->getConversionType().getNonReferenceType();
  9624. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  9625. ConvType = ConvPtrType->getPointeeType();
  9626. ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
  9627. // Conversion 0 is 'this', which doesn't have a corresponding argument.
  9628. ConvIdx = 1;
  9629. } else if (Cand->Function) {
  9630. ParamTypes =
  9631. Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
  9632. if (isa<CXXMethodDecl>(Cand->Function) &&
  9633. !isa<CXXConstructorDecl>(Cand->Function)) {
  9634. // Conversion 0 is 'this', which doesn't have a corresponding argument.
  9635. ConvIdx = 1;
  9636. }
  9637. } else {
  9638. // Builtin operator.
  9639. assert(ConvCount <= 3);
  9640. ParamTypes = Cand->BuiltinParamTypes;
  9641. }
  9642. // Fill in the rest of the conversions.
  9643. for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
  9644. if (Cand->Conversions[ConvIdx].isInitialized()) {
  9645. // We've already checked this conversion.
  9646. } else if (ArgIdx < ParamTypes.size()) {
  9647. if (ParamTypes[ArgIdx]->isDependentType())
  9648. Cand->Conversions[ConvIdx].setAsIdentityConversion(
  9649. Args[ArgIdx]->getType());
  9650. else {
  9651. Cand->Conversions[ConvIdx] =
  9652. TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
  9653. SuppressUserConversions,
  9654. /*InOverloadResolution=*/true,
  9655. /*AllowObjCWritebackConversion=*/
  9656. S.getLangOpts().ObjCAutoRefCount);
  9657. // Store the FixIt in the candidate if it exists.
  9658. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  9659. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  9660. }
  9661. } else
  9662. Cand->Conversions[ConvIdx].setEllipsis();
  9663. }
  9664. }
  9665. SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
  9666. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  9667. SourceLocation OpLoc,
  9668. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  9669. // Sort the candidates by viability and position. Sorting directly would
  9670. // be prohibitive, so we make a set of pointers and sort those.
  9671. SmallVector<OverloadCandidate*, 32> Cands;
  9672. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  9673. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  9674. if (!Filter(*Cand))
  9675. continue;
  9676. if (Cand->Viable)
  9677. Cands.push_back(Cand);
  9678. else if (OCD == OCD_AllCandidates) {
  9679. CompleteNonViableCandidate(S, Cand, Args);
  9680. if (Cand->Function || Cand->IsSurrogate)
  9681. Cands.push_back(Cand);
  9682. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  9683. // want to list every possible builtin candidate.
  9684. }
  9685. }
  9686. llvm::stable_sort(
  9687. Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
  9688. return Cands;
  9689. }
  9690. /// When overload resolution fails, prints diagnostic messages containing the
  9691. /// candidates in the candidate set.
  9692. void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
  9693. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  9694. StringRef Opc, SourceLocation OpLoc,
  9695. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  9696. auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
  9697. S.Diag(PD.first, PD.second);
  9698. NoteCandidates(S, Args, Cands, Opc, OpLoc);
  9699. }
  9700. void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
  9701. ArrayRef<OverloadCandidate *> Cands,
  9702. StringRef Opc, SourceLocation OpLoc) {
  9703. bool ReportedAmbiguousConversions = false;
  9704. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  9705. unsigned CandsShown = 0;
  9706. auto I = Cands.begin(), E = Cands.end();
  9707. for (; I != E; ++I) {
  9708. OverloadCandidate *Cand = *I;
  9709. // Set an arbitrary limit on the number of candidate functions we'll spam
  9710. // the user with. FIXME: This limit should depend on details of the
  9711. // candidate list.
  9712. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  9713. break;
  9714. }
  9715. ++CandsShown;
  9716. if (Cand->Function)
  9717. NoteFunctionCandidate(S, Cand, Args.size(),
  9718. /*TakingCandidateAddress=*/false, DestAS);
  9719. else if (Cand->IsSurrogate)
  9720. NoteSurrogateCandidate(S, Cand);
  9721. else {
  9722. assert(Cand->Viable &&
  9723. "Non-viable built-in candidates are not added to Cands.");
  9724. // Generally we only see ambiguities including viable builtin
  9725. // operators if overload resolution got screwed up by an
  9726. // ambiguous user-defined conversion.
  9727. //
  9728. // FIXME: It's quite possible for different conversions to see
  9729. // different ambiguities, though.
  9730. if (!ReportedAmbiguousConversions) {
  9731. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  9732. ReportedAmbiguousConversions = true;
  9733. }
  9734. // If this is a viable builtin, print it.
  9735. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  9736. }
  9737. }
  9738. if (I != E)
  9739. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  9740. }
  9741. static SourceLocation
  9742. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  9743. return Cand->Specialization ? Cand->Specialization->getLocation()
  9744. : SourceLocation();
  9745. }
  9746. namespace {
  9747. struct CompareTemplateSpecCandidatesForDisplay {
  9748. Sema &S;
  9749. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  9750. bool operator()(const TemplateSpecCandidate *L,
  9751. const TemplateSpecCandidate *R) {
  9752. // Fast-path this check.
  9753. if (L == R)
  9754. return false;
  9755. // Assuming that both candidates are not matches...
  9756. // Sort by the ranking of deduction failures.
  9757. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  9758. return RankDeductionFailure(L->DeductionFailure) <
  9759. RankDeductionFailure(R->DeductionFailure);
  9760. // Sort everything else by location.
  9761. SourceLocation LLoc = GetLocationForCandidate(L);
  9762. SourceLocation RLoc = GetLocationForCandidate(R);
  9763. // Put candidates without locations (e.g. builtins) at the end.
  9764. if (LLoc.isInvalid())
  9765. return false;
  9766. if (RLoc.isInvalid())
  9767. return true;
  9768. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  9769. }
  9770. };
  9771. }
  9772. /// Diagnose a template argument deduction failure.
  9773. /// We are treating these failures as overload failures due to bad
  9774. /// deductions.
  9775. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
  9776. bool ForTakingAddress) {
  9777. DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
  9778. DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
  9779. }
  9780. void TemplateSpecCandidateSet::destroyCandidates() {
  9781. for (iterator i = begin(), e = end(); i != e; ++i) {
  9782. i->DeductionFailure.Destroy();
  9783. }
  9784. }
  9785. void TemplateSpecCandidateSet::clear() {
  9786. destroyCandidates();
  9787. Candidates.clear();
  9788. }
  9789. /// NoteCandidates - When no template specialization match is found, prints
  9790. /// diagnostic messages containing the non-matching specializations that form
  9791. /// the candidate set.
  9792. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  9793. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  9794. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  9795. // Sort the candidates by position (assuming no candidate is a match).
  9796. // Sorting directly would be prohibitive, so we make a set of pointers
  9797. // and sort those.
  9798. SmallVector<TemplateSpecCandidate *, 32> Cands;
  9799. Cands.reserve(size());
  9800. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  9801. if (Cand->Specialization)
  9802. Cands.push_back(Cand);
  9803. // Otherwise, this is a non-matching builtin candidate. We do not,
  9804. // in general, want to list every possible builtin candidate.
  9805. }
  9806. llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
  9807. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  9808. // for generalization purposes (?).
  9809. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  9810. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  9811. unsigned CandsShown = 0;
  9812. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  9813. TemplateSpecCandidate *Cand = *I;
  9814. // Set an arbitrary limit on the number of candidates we'll spam
  9815. // the user with. FIXME: This limit should depend on details of the
  9816. // candidate list.
  9817. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  9818. break;
  9819. ++CandsShown;
  9820. assert(Cand->Specialization &&
  9821. "Non-matching built-in candidates are not added to Cands.");
  9822. Cand->NoteDeductionFailure(S, ForTakingAddress);
  9823. }
  9824. if (I != E)
  9825. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  9826. }
  9827. // [PossiblyAFunctionType] --> [Return]
  9828. // NonFunctionType --> NonFunctionType
  9829. // R (A) --> R(A)
  9830. // R (*)(A) --> R (A)
  9831. // R (&)(A) --> R (A)
  9832. // R (S::*)(A) --> R (A)
  9833. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  9834. QualType Ret = PossiblyAFunctionType;
  9835. if (const PointerType *ToTypePtr =
  9836. PossiblyAFunctionType->getAs<PointerType>())
  9837. Ret = ToTypePtr->getPointeeType();
  9838. else if (const ReferenceType *ToTypeRef =
  9839. PossiblyAFunctionType->getAs<ReferenceType>())
  9840. Ret = ToTypeRef->getPointeeType();
  9841. else if (const MemberPointerType *MemTypePtr =
  9842. PossiblyAFunctionType->getAs<MemberPointerType>())
  9843. Ret = MemTypePtr->getPointeeType();
  9844. Ret =
  9845. Context.getCanonicalType(Ret).getUnqualifiedType();
  9846. return Ret;
  9847. }
  9848. static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
  9849. bool Complain = true) {
  9850. if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  9851. S.DeduceReturnType(FD, Loc, Complain))
  9852. return true;
  9853. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  9854. if (S.getLangOpts().CPlusPlus17 &&
  9855. isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  9856. !S.ResolveExceptionSpec(Loc, FPT))
  9857. return true;
  9858. return false;
  9859. }
  9860. namespace {
  9861. // A helper class to help with address of function resolution
  9862. // - allows us to avoid passing around all those ugly parameters
  9863. class AddressOfFunctionResolver {
  9864. Sema& S;
  9865. Expr* SourceExpr;
  9866. const QualType& TargetType;
  9867. QualType TargetFunctionType; // Extracted function type from target type
  9868. bool Complain;
  9869. //DeclAccessPair& ResultFunctionAccessPair;
  9870. ASTContext& Context;
  9871. bool TargetTypeIsNonStaticMemberFunction;
  9872. bool FoundNonTemplateFunction;
  9873. bool StaticMemberFunctionFromBoundPointer;
  9874. bool HasComplained;
  9875. OverloadExpr::FindResult OvlExprInfo;
  9876. OverloadExpr *OvlExpr;
  9877. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  9878. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  9879. TemplateSpecCandidateSet FailedCandidates;
  9880. public:
  9881. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  9882. const QualType &TargetType, bool Complain)
  9883. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  9884. Complain(Complain), Context(S.getASTContext()),
  9885. TargetTypeIsNonStaticMemberFunction(
  9886. !!TargetType->getAs<MemberPointerType>()),
  9887. FoundNonTemplateFunction(false),
  9888. StaticMemberFunctionFromBoundPointer(false),
  9889. HasComplained(false),
  9890. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  9891. OvlExpr(OvlExprInfo.Expression),
  9892. FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
  9893. ExtractUnqualifiedFunctionTypeFromTargetType();
  9894. if (TargetFunctionType->isFunctionType()) {
  9895. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  9896. if (!UME->isImplicitAccess() &&
  9897. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  9898. StaticMemberFunctionFromBoundPointer = true;
  9899. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  9900. DeclAccessPair dap;
  9901. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  9902. OvlExpr, false, &dap)) {
  9903. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  9904. if (!Method->isStatic()) {
  9905. // If the target type is a non-function type and the function found
  9906. // is a non-static member function, pretend as if that was the
  9907. // target, it's the only possible type to end up with.
  9908. TargetTypeIsNonStaticMemberFunction = true;
  9909. // And skip adding the function if its not in the proper form.
  9910. // We'll diagnose this due to an empty set of functions.
  9911. if (!OvlExprInfo.HasFormOfMemberPointer)
  9912. return;
  9913. }
  9914. Matches.push_back(std::make_pair(dap, Fn));
  9915. }
  9916. return;
  9917. }
  9918. if (OvlExpr->hasExplicitTemplateArgs())
  9919. OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
  9920. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  9921. // C++ [over.over]p4:
  9922. // If more than one function is selected, [...]
  9923. if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
  9924. if (FoundNonTemplateFunction)
  9925. EliminateAllTemplateMatches();
  9926. else
  9927. EliminateAllExceptMostSpecializedTemplate();
  9928. }
  9929. }
  9930. if (S.getLangOpts().CUDA && Matches.size() > 1)
  9931. EliminateSuboptimalCudaMatches();
  9932. }
  9933. bool hasComplained() const { return HasComplained; }
  9934. private:
  9935. bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
  9936. QualType Discard;
  9937. return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
  9938. S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
  9939. }
  9940. /// \return true if A is considered a better overload candidate for the
  9941. /// desired type than B.
  9942. bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
  9943. // If A doesn't have exactly the correct type, we don't want to classify it
  9944. // as "better" than anything else. This way, the user is required to
  9945. // disambiguate for us if there are multiple candidates and no exact match.
  9946. return candidateHasExactlyCorrectType(A) &&
  9947. (!candidateHasExactlyCorrectType(B) ||
  9948. compareEnableIfAttrs(S, A, B) == Comparison::Better);
  9949. }
  9950. /// \return true if we were able to eliminate all but one overload candidate,
  9951. /// false otherwise.
  9952. bool eliminiateSuboptimalOverloadCandidates() {
  9953. // Same algorithm as overload resolution -- one pass to pick the "best",
  9954. // another pass to be sure that nothing is better than the best.
  9955. auto Best = Matches.begin();
  9956. for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
  9957. if (isBetterCandidate(I->second, Best->second))
  9958. Best = I;
  9959. const FunctionDecl *BestFn = Best->second;
  9960. auto IsBestOrInferiorToBest = [this, BestFn](
  9961. const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
  9962. return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
  9963. };
  9964. // Note: We explicitly leave Matches unmodified if there isn't a clear best
  9965. // option, so we can potentially give the user a better error
  9966. if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
  9967. return false;
  9968. Matches[0] = *Best;
  9969. Matches.resize(1);
  9970. return true;
  9971. }
  9972. bool isTargetTypeAFunction() const {
  9973. return TargetFunctionType->isFunctionType();
  9974. }
  9975. // [ToType] [Return]
  9976. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  9977. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  9978. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  9979. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  9980. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  9981. }
  9982. // return true if any matching specializations were found
  9983. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  9984. const DeclAccessPair& CurAccessFunPair) {
  9985. if (CXXMethodDecl *Method
  9986. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  9987. // Skip non-static function templates when converting to pointer, and
  9988. // static when converting to member pointer.
  9989. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9990. return false;
  9991. }
  9992. else if (TargetTypeIsNonStaticMemberFunction)
  9993. return false;
  9994. // C++ [over.over]p2:
  9995. // If the name is a function template, template argument deduction is
  9996. // done (14.8.2.2), and if the argument deduction succeeds, the
  9997. // resulting template argument list is used to generate a single
  9998. // function template specialization, which is added to the set of
  9999. // overloaded functions considered.
  10000. FunctionDecl *Specialization = nullptr;
  10001. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  10002. if (Sema::TemplateDeductionResult Result
  10003. = S.DeduceTemplateArguments(FunctionTemplate,
  10004. &OvlExplicitTemplateArgs,
  10005. TargetFunctionType, Specialization,
  10006. Info, /*IsAddressOfFunction*/true)) {
  10007. // Make a note of the failed deduction for diagnostics.
  10008. FailedCandidates.addCandidate()
  10009. .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
  10010. MakeDeductionFailureInfo(Context, Result, Info));
  10011. return false;
  10012. }
  10013. // Template argument deduction ensures that we have an exact match or
  10014. // compatible pointer-to-function arguments that would be adjusted by ICS.
  10015. // This function template specicalization works.
  10016. assert(S.isSameOrCompatibleFunctionType(
  10017. Context.getCanonicalType(Specialization->getType()),
  10018. Context.getCanonicalType(TargetFunctionType)));
  10019. if (!S.checkAddressOfFunctionIsAvailable(Specialization))
  10020. return false;
  10021. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  10022. return true;
  10023. }
  10024. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  10025. const DeclAccessPair& CurAccessFunPair) {
  10026. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  10027. // Skip non-static functions when converting to pointer, and static
  10028. // when converting to member pointer.
  10029. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  10030. return false;
  10031. }
  10032. else if (TargetTypeIsNonStaticMemberFunction)
  10033. return false;
  10034. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  10035. if (S.getLangOpts().CUDA)
  10036. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  10037. if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
  10038. return false;
  10039. if (FunDecl->isMultiVersion()) {
  10040. const auto *TA = FunDecl->getAttr<TargetAttr>();
  10041. if (TA && !TA->isDefaultVersion())
  10042. return false;
  10043. }
  10044. // If any candidate has a placeholder return type, trigger its deduction
  10045. // now.
  10046. if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
  10047. Complain)) {
  10048. HasComplained |= Complain;
  10049. return false;
  10050. }
  10051. if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
  10052. return false;
  10053. // If we're in C, we need to support types that aren't exactly identical.
  10054. if (!S.getLangOpts().CPlusPlus ||
  10055. candidateHasExactlyCorrectType(FunDecl)) {
  10056. Matches.push_back(std::make_pair(
  10057. CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  10058. FoundNonTemplateFunction = true;
  10059. return true;
  10060. }
  10061. }
  10062. return false;
  10063. }
  10064. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  10065. bool Ret = false;
  10066. // If the overload expression doesn't have the form of a pointer to
  10067. // member, don't try to convert it to a pointer-to-member type.
  10068. if (IsInvalidFormOfPointerToMemberFunction())
  10069. return false;
  10070. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  10071. E = OvlExpr->decls_end();
  10072. I != E; ++I) {
  10073. // Look through any using declarations to find the underlying function.
  10074. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  10075. // C++ [over.over]p3:
  10076. // Non-member functions and static member functions match
  10077. // targets of type "pointer-to-function" or "reference-to-function."
  10078. // Nonstatic member functions match targets of
  10079. // type "pointer-to-member-function."
  10080. // Note that according to DR 247, the containing class does not matter.
  10081. if (FunctionTemplateDecl *FunctionTemplate
  10082. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  10083. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  10084. Ret = true;
  10085. }
  10086. // If we have explicit template arguments supplied, skip non-templates.
  10087. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  10088. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  10089. Ret = true;
  10090. }
  10091. assert(Ret || Matches.empty());
  10092. return Ret;
  10093. }
  10094. void EliminateAllExceptMostSpecializedTemplate() {
  10095. // [...] and any given function template specialization F1 is
  10096. // eliminated if the set contains a second function template
  10097. // specialization whose function template is more specialized
  10098. // than the function template of F1 according to the partial
  10099. // ordering rules of 14.5.5.2.
  10100. // The algorithm specified above is quadratic. We instead use a
  10101. // two-pass algorithm (similar to the one used to identify the
  10102. // best viable function in an overload set) that identifies the
  10103. // best function template (if it exists).
  10104. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  10105. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  10106. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  10107. // TODO: It looks like FailedCandidates does not serve much purpose
  10108. // here, since the no_viable diagnostic has index 0.
  10109. UnresolvedSetIterator Result = S.getMostSpecialized(
  10110. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  10111. SourceExpr->getBeginLoc(), S.PDiag(),
  10112. S.PDiag(diag::err_addr_ovl_ambiguous)
  10113. << Matches[0].second->getDeclName(),
  10114. S.PDiag(diag::note_ovl_candidate)
  10115. << (unsigned)oc_function << (unsigned)ocs_described_template,
  10116. Complain, TargetFunctionType);
  10117. if (Result != MatchesCopy.end()) {
  10118. // Make it the first and only element
  10119. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  10120. Matches[0].second = cast<FunctionDecl>(*Result);
  10121. Matches.resize(1);
  10122. } else
  10123. HasComplained |= Complain;
  10124. }
  10125. void EliminateAllTemplateMatches() {
  10126. // [...] any function template specializations in the set are
  10127. // eliminated if the set also contains a non-template function, [...]
  10128. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  10129. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  10130. ++I;
  10131. else {
  10132. Matches[I] = Matches[--N];
  10133. Matches.resize(N);
  10134. }
  10135. }
  10136. }
  10137. void EliminateSuboptimalCudaMatches() {
  10138. S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
  10139. }
  10140. public:
  10141. void ComplainNoMatchesFound() const {
  10142. assert(Matches.empty());
  10143. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
  10144. << OvlExpr->getName() << TargetFunctionType
  10145. << OvlExpr->getSourceRange();
  10146. if (FailedCandidates.empty())
  10147. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  10148. /*TakingAddress=*/true);
  10149. else {
  10150. // We have some deduction failure messages. Use them to diagnose
  10151. // the function templates, and diagnose the non-template candidates
  10152. // normally.
  10153. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  10154. IEnd = OvlExpr->decls_end();
  10155. I != IEnd; ++I)
  10156. if (FunctionDecl *Fun =
  10157. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  10158. if (!functionHasPassObjectSizeParams(Fun))
  10159. S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
  10160. /*TakingAddress=*/true);
  10161. FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
  10162. }
  10163. }
  10164. bool IsInvalidFormOfPointerToMemberFunction() const {
  10165. return TargetTypeIsNonStaticMemberFunction &&
  10166. !OvlExprInfo.HasFormOfMemberPointer;
  10167. }
  10168. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  10169. // TODO: Should we condition this on whether any functions might
  10170. // have matched, or is it more appropriate to do that in callers?
  10171. // TODO: a fixit wouldn't hurt.
  10172. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  10173. << TargetType << OvlExpr->getSourceRange();
  10174. }
  10175. bool IsStaticMemberFunctionFromBoundPointer() const {
  10176. return StaticMemberFunctionFromBoundPointer;
  10177. }
  10178. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  10179. S.Diag(OvlExpr->getBeginLoc(),
  10180. diag::err_invalid_form_pointer_member_function)
  10181. << OvlExpr->getSourceRange();
  10182. }
  10183. void ComplainOfInvalidConversion() const {
  10184. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
  10185. << OvlExpr->getName() << TargetType;
  10186. }
  10187. void ComplainMultipleMatchesFound() const {
  10188. assert(Matches.size() > 1);
  10189. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
  10190. << OvlExpr->getName() << OvlExpr->getSourceRange();
  10191. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  10192. /*TakingAddress=*/true);
  10193. }
  10194. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  10195. int getNumMatches() const { return Matches.size(); }
  10196. FunctionDecl* getMatchingFunctionDecl() const {
  10197. if (Matches.size() != 1) return nullptr;
  10198. return Matches[0].second;
  10199. }
  10200. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  10201. if (Matches.size() != 1) return nullptr;
  10202. return &Matches[0].first;
  10203. }
  10204. };
  10205. }
  10206. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  10207. /// an overloaded function (C++ [over.over]), where @p From is an
  10208. /// expression with overloaded function type and @p ToType is the type
  10209. /// we're trying to resolve to. For example:
  10210. ///
  10211. /// @code
  10212. /// int f(double);
  10213. /// int f(int);
  10214. ///
  10215. /// int (*pfd)(double) = f; // selects f(double)
  10216. /// @endcode
  10217. ///
  10218. /// This routine returns the resulting FunctionDecl if it could be
  10219. /// resolved, and NULL otherwise. When @p Complain is true, this
  10220. /// routine will emit diagnostics if there is an error.
  10221. FunctionDecl *
  10222. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  10223. QualType TargetType,
  10224. bool Complain,
  10225. DeclAccessPair &FoundResult,
  10226. bool *pHadMultipleCandidates) {
  10227. assert(AddressOfExpr->getType() == Context.OverloadTy);
  10228. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  10229. Complain);
  10230. int NumMatches = Resolver.getNumMatches();
  10231. FunctionDecl *Fn = nullptr;
  10232. bool ShouldComplain = Complain && !Resolver.hasComplained();
  10233. if (NumMatches == 0 && ShouldComplain) {
  10234. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  10235. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  10236. else
  10237. Resolver.ComplainNoMatchesFound();
  10238. }
  10239. else if (NumMatches > 1 && ShouldComplain)
  10240. Resolver.ComplainMultipleMatchesFound();
  10241. else if (NumMatches == 1) {
  10242. Fn = Resolver.getMatchingFunctionDecl();
  10243. assert(Fn);
  10244. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  10245. ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
  10246. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  10247. if (Complain) {
  10248. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  10249. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  10250. else
  10251. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  10252. }
  10253. }
  10254. if (pHadMultipleCandidates)
  10255. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  10256. return Fn;
  10257. }
  10258. /// Given an expression that refers to an overloaded function, try to
  10259. /// resolve that function to a single function that can have its address taken.
  10260. /// This will modify `Pair` iff it returns non-null.
  10261. ///
  10262. /// This routine can only realistically succeed if all but one candidates in the
  10263. /// overload set for SrcExpr cannot have their addresses taken.
  10264. FunctionDecl *
  10265. Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
  10266. DeclAccessPair &Pair) {
  10267. OverloadExpr::FindResult R = OverloadExpr::find(E);
  10268. OverloadExpr *Ovl = R.Expression;
  10269. FunctionDecl *Result = nullptr;
  10270. DeclAccessPair DAP;
  10271. // Don't use the AddressOfResolver because we're specifically looking for
  10272. // cases where we have one overload candidate that lacks
  10273. // enable_if/pass_object_size/...
  10274. for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
  10275. auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
  10276. if (!FD)
  10277. return nullptr;
  10278. if (!checkAddressOfFunctionIsAvailable(FD))
  10279. continue;
  10280. // We have more than one result; quit.
  10281. if (Result)
  10282. return nullptr;
  10283. DAP = I.getPair();
  10284. Result = FD;
  10285. }
  10286. if (Result)
  10287. Pair = DAP;
  10288. return Result;
  10289. }
  10290. /// Given an overloaded function, tries to turn it into a non-overloaded
  10291. /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
  10292. /// will perform access checks, diagnose the use of the resultant decl, and, if
  10293. /// requested, potentially perform a function-to-pointer decay.
  10294. ///
  10295. /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
  10296. /// Otherwise, returns true. This may emit diagnostics and return true.
  10297. bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
  10298. ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
  10299. Expr *E = SrcExpr.get();
  10300. assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
  10301. DeclAccessPair DAP;
  10302. FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
  10303. if (!Found || Found->isCPUDispatchMultiVersion() ||
  10304. Found->isCPUSpecificMultiVersion())
  10305. return false;
  10306. // Emitting multiple diagnostics for a function that is both inaccessible and
  10307. // unavailable is consistent with our behavior elsewhere. So, always check
  10308. // for both.
  10309. DiagnoseUseOfDecl(Found, E->getExprLoc());
  10310. CheckAddressOfMemberAccess(E, DAP);
  10311. Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
  10312. if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
  10313. SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
  10314. else
  10315. SrcExpr = Fixed;
  10316. return true;
  10317. }
  10318. /// Given an expression that refers to an overloaded function, try to
  10319. /// resolve that overloaded function expression down to a single function.
  10320. ///
  10321. /// This routine can only resolve template-ids that refer to a single function
  10322. /// template, where that template-id refers to a single template whose template
  10323. /// arguments are either provided by the template-id or have defaults,
  10324. /// as described in C++0x [temp.arg.explicit]p3.
  10325. ///
  10326. /// If no template-ids are found, no diagnostics are emitted and NULL is
  10327. /// returned.
  10328. FunctionDecl *
  10329. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  10330. bool Complain,
  10331. DeclAccessPair *FoundResult) {
  10332. // C++ [over.over]p1:
  10333. // [...] [Note: any redundant set of parentheses surrounding the
  10334. // overloaded function name is ignored (5.1). ]
  10335. // C++ [over.over]p1:
  10336. // [...] The overloaded function name can be preceded by the &
  10337. // operator.
  10338. // If we didn't actually find any template-ids, we're done.
  10339. if (!ovl->hasExplicitTemplateArgs())
  10340. return nullptr;
  10341. TemplateArgumentListInfo ExplicitTemplateArgs;
  10342. ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
  10343. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  10344. // Look through all of the overloaded functions, searching for one
  10345. // whose type matches exactly.
  10346. FunctionDecl *Matched = nullptr;
  10347. for (UnresolvedSetIterator I = ovl->decls_begin(),
  10348. E = ovl->decls_end(); I != E; ++I) {
  10349. // C++0x [temp.arg.explicit]p3:
  10350. // [...] In contexts where deduction is done and fails, or in contexts
  10351. // where deduction is not done, if a template argument list is
  10352. // specified and it, along with any default template arguments,
  10353. // identifies a single function template specialization, then the
  10354. // template-id is an lvalue for the function template specialization.
  10355. FunctionTemplateDecl *FunctionTemplate
  10356. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  10357. // C++ [over.over]p2:
  10358. // If the name is a function template, template argument deduction is
  10359. // done (14.8.2.2), and if the argument deduction succeeds, the
  10360. // resulting template argument list is used to generate a single
  10361. // function template specialization, which is added to the set of
  10362. // overloaded functions considered.
  10363. FunctionDecl *Specialization = nullptr;
  10364. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  10365. if (TemplateDeductionResult Result
  10366. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  10367. Specialization, Info,
  10368. /*IsAddressOfFunction*/true)) {
  10369. // Make a note of the failed deduction for diagnostics.
  10370. // TODO: Actually use the failed-deduction info?
  10371. FailedCandidates.addCandidate()
  10372. .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
  10373. MakeDeductionFailureInfo(Context, Result, Info));
  10374. continue;
  10375. }
  10376. assert(Specialization && "no specialization and no error?");
  10377. // Multiple matches; we can't resolve to a single declaration.
  10378. if (Matched) {
  10379. if (Complain) {
  10380. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  10381. << ovl->getName();
  10382. NoteAllOverloadCandidates(ovl);
  10383. }
  10384. return nullptr;
  10385. }
  10386. Matched = Specialization;
  10387. if (FoundResult) *FoundResult = I.getPair();
  10388. }
  10389. if (Matched &&
  10390. completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
  10391. return nullptr;
  10392. return Matched;
  10393. }
  10394. // Resolve and fix an overloaded expression that can be resolved
  10395. // because it identifies a single function template specialization.
  10396. //
  10397. // Last three arguments should only be supplied if Complain = true
  10398. //
  10399. // Return true if it was logically possible to so resolve the
  10400. // expression, regardless of whether or not it succeeded. Always
  10401. // returns true if 'complain' is set.
  10402. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  10403. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  10404. bool complain, SourceRange OpRangeForComplaining,
  10405. QualType DestTypeForComplaining,
  10406. unsigned DiagIDForComplaining) {
  10407. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  10408. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  10409. DeclAccessPair found;
  10410. ExprResult SingleFunctionExpression;
  10411. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  10412. ovl.Expression, /*complain*/ false, &found)) {
  10413. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
  10414. SrcExpr = ExprError();
  10415. return true;
  10416. }
  10417. // It is only correct to resolve to an instance method if we're
  10418. // resolving a form that's permitted to be a pointer to member.
  10419. // Otherwise we'll end up making a bound member expression, which
  10420. // is illegal in all the contexts we resolve like this.
  10421. if (!ovl.HasFormOfMemberPointer &&
  10422. isa<CXXMethodDecl>(fn) &&
  10423. cast<CXXMethodDecl>(fn)->isInstance()) {
  10424. if (!complain) return false;
  10425. Diag(ovl.Expression->getExprLoc(),
  10426. diag::err_bound_member_function)
  10427. << 0 << ovl.Expression->getSourceRange();
  10428. // TODO: I believe we only end up here if there's a mix of
  10429. // static and non-static candidates (otherwise the expression
  10430. // would have 'bound member' type, not 'overload' type).
  10431. // Ideally we would note which candidate was chosen and why
  10432. // the static candidates were rejected.
  10433. SrcExpr = ExprError();
  10434. return true;
  10435. }
  10436. // Fix the expression to refer to 'fn'.
  10437. SingleFunctionExpression =
  10438. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  10439. // If desired, do function-to-pointer decay.
  10440. if (doFunctionPointerConverion) {
  10441. SingleFunctionExpression =
  10442. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  10443. if (SingleFunctionExpression.isInvalid()) {
  10444. SrcExpr = ExprError();
  10445. return true;
  10446. }
  10447. }
  10448. }
  10449. if (!SingleFunctionExpression.isUsable()) {
  10450. if (complain) {
  10451. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  10452. << ovl.Expression->getName()
  10453. << DestTypeForComplaining
  10454. << OpRangeForComplaining
  10455. << ovl.Expression->getQualifierLoc().getSourceRange();
  10456. NoteAllOverloadCandidates(SrcExpr.get());
  10457. SrcExpr = ExprError();
  10458. return true;
  10459. }
  10460. return false;
  10461. }
  10462. SrcExpr = SingleFunctionExpression;
  10463. return true;
  10464. }
  10465. /// Add a single candidate to the overload set.
  10466. static void AddOverloadedCallCandidate(Sema &S,
  10467. DeclAccessPair FoundDecl,
  10468. TemplateArgumentListInfo *ExplicitTemplateArgs,
  10469. ArrayRef<Expr *> Args,
  10470. OverloadCandidateSet &CandidateSet,
  10471. bool PartialOverloading,
  10472. bool KnownValid) {
  10473. NamedDecl *Callee = FoundDecl.getDecl();
  10474. if (isa<UsingShadowDecl>(Callee))
  10475. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  10476. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  10477. if (ExplicitTemplateArgs) {
  10478. assert(!KnownValid && "Explicit template arguments?");
  10479. return;
  10480. }
  10481. // Prevent ill-formed function decls to be added as overload candidates.
  10482. if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
  10483. return;
  10484. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  10485. /*SuppressUserConversions=*/false,
  10486. PartialOverloading);
  10487. return;
  10488. }
  10489. if (FunctionTemplateDecl *FuncTemplate
  10490. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  10491. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  10492. ExplicitTemplateArgs, Args, CandidateSet,
  10493. /*SuppressUserConversions=*/false,
  10494. PartialOverloading);
  10495. return;
  10496. }
  10497. assert(!KnownValid && "unhandled case in overloaded call candidate");
  10498. }
  10499. /// Add the overload candidates named by callee and/or found by argument
  10500. /// dependent lookup to the given overload set.
  10501. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  10502. ArrayRef<Expr *> Args,
  10503. OverloadCandidateSet &CandidateSet,
  10504. bool PartialOverloading) {
  10505. #ifndef NDEBUG
  10506. // Verify that ArgumentDependentLookup is consistent with the rules
  10507. // in C++0x [basic.lookup.argdep]p3:
  10508. //
  10509. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  10510. // and let Y be the lookup set produced by argument dependent
  10511. // lookup (defined as follows). If X contains
  10512. //
  10513. // -- a declaration of a class member, or
  10514. //
  10515. // -- a block-scope function declaration that is not a
  10516. // using-declaration, or
  10517. //
  10518. // -- a declaration that is neither a function or a function
  10519. // template
  10520. //
  10521. // then Y is empty.
  10522. if (ULE->requiresADL()) {
  10523. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  10524. E = ULE->decls_end(); I != E; ++I) {
  10525. assert(!(*I)->getDeclContext()->isRecord());
  10526. assert(isa<UsingShadowDecl>(*I) ||
  10527. !(*I)->getDeclContext()->isFunctionOrMethod());
  10528. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  10529. }
  10530. }
  10531. #endif
  10532. // It would be nice to avoid this copy.
  10533. TemplateArgumentListInfo TABuffer;
  10534. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  10535. if (ULE->hasExplicitTemplateArgs()) {
  10536. ULE->copyTemplateArgumentsInto(TABuffer);
  10537. ExplicitTemplateArgs = &TABuffer;
  10538. }
  10539. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  10540. E = ULE->decls_end(); I != E; ++I)
  10541. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  10542. CandidateSet, PartialOverloading,
  10543. /*KnownValid*/ true);
  10544. if (ULE->requiresADL())
  10545. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  10546. Args, ExplicitTemplateArgs,
  10547. CandidateSet, PartialOverloading);
  10548. }
  10549. /// Determine whether a declaration with the specified name could be moved into
  10550. /// a different namespace.
  10551. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  10552. switch (Name.getCXXOverloadedOperator()) {
  10553. case OO_New: case OO_Array_New:
  10554. case OO_Delete: case OO_Array_Delete:
  10555. return false;
  10556. default:
  10557. return true;
  10558. }
  10559. }
  10560. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  10561. /// template, where the non-dependent name was declared after the template
  10562. /// was defined. This is common in code written for a compilers which do not
  10563. /// correctly implement two-stage name lookup.
  10564. ///
  10565. /// Returns true if a viable candidate was found and a diagnostic was issued.
  10566. static bool
  10567. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  10568. const CXXScopeSpec &SS, LookupResult &R,
  10569. OverloadCandidateSet::CandidateSetKind CSK,
  10570. TemplateArgumentListInfo *ExplicitTemplateArgs,
  10571. ArrayRef<Expr *> Args,
  10572. bool *DoDiagnoseEmptyLookup = nullptr) {
  10573. if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
  10574. return false;
  10575. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  10576. if (DC->isTransparentContext())
  10577. continue;
  10578. SemaRef.LookupQualifiedName(R, DC);
  10579. if (!R.empty()) {
  10580. R.suppressDiagnostics();
  10581. if (isa<CXXRecordDecl>(DC)) {
  10582. // Don't diagnose names we find in classes; we get much better
  10583. // diagnostics for these from DiagnoseEmptyLookup.
  10584. R.clear();
  10585. if (DoDiagnoseEmptyLookup)
  10586. *DoDiagnoseEmptyLookup = true;
  10587. return false;
  10588. }
  10589. OverloadCandidateSet Candidates(FnLoc, CSK);
  10590. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  10591. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  10592. ExplicitTemplateArgs, Args,
  10593. Candidates, false, /*KnownValid*/ false);
  10594. OverloadCandidateSet::iterator Best;
  10595. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  10596. // No viable functions. Don't bother the user with notes for functions
  10597. // which don't work and shouldn't be found anyway.
  10598. R.clear();
  10599. return false;
  10600. }
  10601. // Find the namespaces where ADL would have looked, and suggest
  10602. // declaring the function there instead.
  10603. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  10604. Sema::AssociatedClassSet AssociatedClasses;
  10605. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  10606. AssociatedNamespaces,
  10607. AssociatedClasses);
  10608. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  10609. if (canBeDeclaredInNamespace(R.getLookupName())) {
  10610. DeclContext *Std = SemaRef.getStdNamespace();
  10611. for (Sema::AssociatedNamespaceSet::iterator
  10612. it = AssociatedNamespaces.begin(),
  10613. end = AssociatedNamespaces.end(); it != end; ++it) {
  10614. // Never suggest declaring a function within namespace 'std'.
  10615. if (Std && Std->Encloses(*it))
  10616. continue;
  10617. // Never suggest declaring a function within a namespace with a
  10618. // reserved name, like __gnu_cxx.
  10619. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  10620. if (NS &&
  10621. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  10622. continue;
  10623. SuggestedNamespaces.insert(*it);
  10624. }
  10625. }
  10626. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  10627. << R.getLookupName();
  10628. if (SuggestedNamespaces.empty()) {
  10629. SemaRef.Diag(Best->Function->getLocation(),
  10630. diag::note_not_found_by_two_phase_lookup)
  10631. << R.getLookupName() << 0;
  10632. } else if (SuggestedNamespaces.size() == 1) {
  10633. SemaRef.Diag(Best->Function->getLocation(),
  10634. diag::note_not_found_by_two_phase_lookup)
  10635. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  10636. } else {
  10637. // FIXME: It would be useful to list the associated namespaces here,
  10638. // but the diagnostics infrastructure doesn't provide a way to produce
  10639. // a localized representation of a list of items.
  10640. SemaRef.Diag(Best->Function->getLocation(),
  10641. diag::note_not_found_by_two_phase_lookup)
  10642. << R.getLookupName() << 2;
  10643. }
  10644. // Try to recover by calling this function.
  10645. return true;
  10646. }
  10647. R.clear();
  10648. }
  10649. return false;
  10650. }
  10651. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  10652. /// template, where the non-dependent operator was declared after the template
  10653. /// was defined.
  10654. ///
  10655. /// Returns true if a viable candidate was found and a diagnostic was issued.
  10656. static bool
  10657. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  10658. SourceLocation OpLoc,
  10659. ArrayRef<Expr *> Args) {
  10660. DeclarationName OpName =
  10661. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  10662. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  10663. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  10664. OverloadCandidateSet::CSK_Operator,
  10665. /*ExplicitTemplateArgs=*/nullptr, Args);
  10666. }
  10667. namespace {
  10668. class BuildRecoveryCallExprRAII {
  10669. Sema &SemaRef;
  10670. public:
  10671. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  10672. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  10673. SemaRef.IsBuildingRecoveryCallExpr = true;
  10674. }
  10675. ~BuildRecoveryCallExprRAII() {
  10676. SemaRef.IsBuildingRecoveryCallExpr = false;
  10677. }
  10678. };
  10679. }
  10680. /// Attempts to recover from a call where no functions were found.
  10681. ///
  10682. /// Returns true if new candidates were found.
  10683. static ExprResult
  10684. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  10685. UnresolvedLookupExpr *ULE,
  10686. SourceLocation LParenLoc,
  10687. MutableArrayRef<Expr *> Args,
  10688. SourceLocation RParenLoc,
  10689. bool EmptyLookup, bool AllowTypoCorrection) {
  10690. // Do not try to recover if it is already building a recovery call.
  10691. // This stops infinite loops for template instantiations like
  10692. //
  10693. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  10694. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  10695. //
  10696. if (SemaRef.IsBuildingRecoveryCallExpr)
  10697. return ExprError();
  10698. BuildRecoveryCallExprRAII RCE(SemaRef);
  10699. CXXScopeSpec SS;
  10700. SS.Adopt(ULE->getQualifierLoc());
  10701. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  10702. TemplateArgumentListInfo TABuffer;
  10703. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  10704. if (ULE->hasExplicitTemplateArgs()) {
  10705. ULE->copyTemplateArgumentsInto(TABuffer);
  10706. ExplicitTemplateArgs = &TABuffer;
  10707. }
  10708. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  10709. Sema::LookupOrdinaryName);
  10710. bool DoDiagnoseEmptyLookup = EmptyLookup;
  10711. if (!DiagnoseTwoPhaseLookup(
  10712. SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
  10713. ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
  10714. NoTypoCorrectionCCC NoTypoValidator{};
  10715. FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
  10716. ExplicitTemplateArgs != nullptr,
  10717. dyn_cast<MemberExpr>(Fn));
  10718. CorrectionCandidateCallback &Validator =
  10719. AllowTypoCorrection
  10720. ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
  10721. : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
  10722. if (!DoDiagnoseEmptyLookup ||
  10723. SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
  10724. Args))
  10725. return ExprError();
  10726. }
  10727. assert(!R.empty() && "lookup results empty despite recovery");
  10728. // If recovery created an ambiguity, just bail out.
  10729. if (R.isAmbiguous()) {
  10730. R.suppressDiagnostics();
  10731. return ExprError();
  10732. }
  10733. // Build an implicit member call if appropriate. Just drop the
  10734. // casts and such from the call, we don't really care.
  10735. ExprResult NewFn = ExprError();
  10736. if ((*R.begin())->isCXXClassMember())
  10737. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
  10738. ExplicitTemplateArgs, S);
  10739. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  10740. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  10741. ExplicitTemplateArgs);
  10742. else
  10743. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  10744. if (NewFn.isInvalid())
  10745. return ExprError();
  10746. // This shouldn't cause an infinite loop because we're giving it
  10747. // an expression with viable lookup results, which should never
  10748. // end up here.
  10749. return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  10750. MultiExprArg(Args.data(), Args.size()),
  10751. RParenLoc);
  10752. }
  10753. /// Constructs and populates an OverloadedCandidateSet from
  10754. /// the given function.
  10755. /// \returns true when an the ExprResult output parameter has been set.
  10756. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  10757. UnresolvedLookupExpr *ULE,
  10758. MultiExprArg Args,
  10759. SourceLocation RParenLoc,
  10760. OverloadCandidateSet *CandidateSet,
  10761. ExprResult *Result) {
  10762. #ifndef NDEBUG
  10763. if (ULE->requiresADL()) {
  10764. // To do ADL, we must have found an unqualified name.
  10765. assert(!ULE->getQualifier() && "qualified name with ADL");
  10766. // We don't perform ADL for implicit declarations of builtins.
  10767. // Verify that this was correctly set up.
  10768. FunctionDecl *F;
  10769. if (ULE->decls_begin() != ULE->decls_end() &&
  10770. ULE->decls_begin() + 1 == ULE->decls_end() &&
  10771. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  10772. F->getBuiltinID() && F->isImplicit())
  10773. llvm_unreachable("performing ADL for builtin");
  10774. // We don't perform ADL in C.
  10775. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  10776. }
  10777. #endif
  10778. UnbridgedCastsSet UnbridgedCasts;
  10779. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  10780. *Result = ExprError();
  10781. return true;
  10782. }
  10783. // Add the functions denoted by the callee to the set of candidate
  10784. // functions, including those from argument-dependent lookup.
  10785. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  10786. if (getLangOpts().MSVCCompat &&
  10787. CurContext->isDependentContext() && !isSFINAEContext() &&
  10788. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  10789. OverloadCandidateSet::iterator Best;
  10790. if (CandidateSet->empty() ||
  10791. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
  10792. OR_No_Viable_Function) {
  10793. // In Microsoft mode, if we are inside a template class member function
  10794. // then create a type dependent CallExpr. The goal is to postpone name
  10795. // lookup to instantiation time to be able to search into type dependent
  10796. // base classes.
  10797. CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
  10798. VK_RValue, RParenLoc);
  10799. CE->setTypeDependent(true);
  10800. CE->setValueDependent(true);
  10801. CE->setInstantiationDependent(true);
  10802. *Result = CE;
  10803. return true;
  10804. }
  10805. }
  10806. if (CandidateSet->empty())
  10807. return false;
  10808. UnbridgedCasts.restore();
  10809. return false;
  10810. }
  10811. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  10812. /// the completed call expression. If overload resolution fails, emits
  10813. /// diagnostics and returns ExprError()
  10814. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  10815. UnresolvedLookupExpr *ULE,
  10816. SourceLocation LParenLoc,
  10817. MultiExprArg Args,
  10818. SourceLocation RParenLoc,
  10819. Expr *ExecConfig,
  10820. OverloadCandidateSet *CandidateSet,
  10821. OverloadCandidateSet::iterator *Best,
  10822. OverloadingResult OverloadResult,
  10823. bool AllowTypoCorrection) {
  10824. if (CandidateSet->empty())
  10825. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  10826. RParenLoc, /*EmptyLookup=*/true,
  10827. AllowTypoCorrection);
  10828. switch (OverloadResult) {
  10829. case OR_Success: {
  10830. FunctionDecl *FDecl = (*Best)->Function;
  10831. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  10832. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  10833. return ExprError();
  10834. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  10835. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  10836. ExecConfig, /*IsExecConfig=*/false,
  10837. (*Best)->IsADLCandidate);
  10838. }
  10839. case OR_No_Viable_Function: {
  10840. // Try to recover by looking for viable functions which the user might
  10841. // have meant to call.
  10842. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  10843. Args, RParenLoc,
  10844. /*EmptyLookup=*/false,
  10845. AllowTypoCorrection);
  10846. if (!Recovery.isInvalid())
  10847. return Recovery;
  10848. // If the user passes in a function that we can't take the address of, we
  10849. // generally end up emitting really bad error messages. Here, we attempt to
  10850. // emit better ones.
  10851. for (const Expr *Arg : Args) {
  10852. if (!Arg->getType()->isFunctionType())
  10853. continue;
  10854. if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
  10855. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  10856. if (FD &&
  10857. !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10858. Arg->getExprLoc()))
  10859. return ExprError();
  10860. }
  10861. }
  10862. CandidateSet->NoteCandidates(
  10863. PartialDiagnosticAt(
  10864. Fn->getBeginLoc(),
  10865. SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
  10866. << ULE->getName() << Fn->getSourceRange()),
  10867. SemaRef, OCD_AllCandidates, Args);
  10868. break;
  10869. }
  10870. case OR_Ambiguous:
  10871. CandidateSet->NoteCandidates(
  10872. PartialDiagnosticAt(Fn->getBeginLoc(),
  10873. SemaRef.PDiag(diag::err_ovl_ambiguous_call)
  10874. << ULE->getName() << Fn->getSourceRange()),
  10875. SemaRef, OCD_ViableCandidates, Args);
  10876. break;
  10877. case OR_Deleted: {
  10878. CandidateSet->NoteCandidates(
  10879. PartialDiagnosticAt(Fn->getBeginLoc(),
  10880. SemaRef.PDiag(diag::err_ovl_deleted_call)
  10881. << ULE->getName() << Fn->getSourceRange()),
  10882. SemaRef, OCD_AllCandidates, Args);
  10883. // We emitted an error for the unavailable/deleted function call but keep
  10884. // the call in the AST.
  10885. FunctionDecl *FDecl = (*Best)->Function;
  10886. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  10887. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  10888. ExecConfig, /*IsExecConfig=*/false,
  10889. (*Best)->IsADLCandidate);
  10890. }
  10891. }
  10892. // Overload resolution failed.
  10893. return ExprError();
  10894. }
  10895. static void markUnaddressableCandidatesUnviable(Sema &S,
  10896. OverloadCandidateSet &CS) {
  10897. for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
  10898. if (I->Viable &&
  10899. !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
  10900. I->Viable = false;
  10901. I->FailureKind = ovl_fail_addr_not_available;
  10902. }
  10903. }
  10904. }
  10905. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  10906. /// (which eventually refers to the declaration Func) and the call
  10907. /// arguments Args/NumArgs, attempt to resolve the function call down
  10908. /// to a specific function. If overload resolution succeeds, returns
  10909. /// the call expression produced by overload resolution.
  10910. /// Otherwise, emits diagnostics and returns ExprError.
  10911. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  10912. UnresolvedLookupExpr *ULE,
  10913. SourceLocation LParenLoc,
  10914. MultiExprArg Args,
  10915. SourceLocation RParenLoc,
  10916. Expr *ExecConfig,
  10917. bool AllowTypoCorrection,
  10918. bool CalleesAddressIsTaken) {
  10919. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  10920. OverloadCandidateSet::CSK_Normal);
  10921. ExprResult result;
  10922. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  10923. &result))
  10924. return result;
  10925. // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
  10926. // functions that aren't addressible are considered unviable.
  10927. if (CalleesAddressIsTaken)
  10928. markUnaddressableCandidatesUnviable(*this, CandidateSet);
  10929. OverloadCandidateSet::iterator Best;
  10930. OverloadingResult OverloadResult =
  10931. CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
  10932. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
  10933. ExecConfig, &CandidateSet, &Best,
  10934. OverloadResult, AllowTypoCorrection);
  10935. }
  10936. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  10937. return Functions.size() > 1 ||
  10938. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  10939. }
  10940. /// Create a unary operation that may resolve to an overloaded
  10941. /// operator.
  10942. ///
  10943. /// \param OpLoc The location of the operator itself (e.g., '*').
  10944. ///
  10945. /// \param Opc The UnaryOperatorKind that describes this operator.
  10946. ///
  10947. /// \param Fns The set of non-member functions that will be
  10948. /// considered by overload resolution. The caller needs to build this
  10949. /// set based on the context using, e.g.,
  10950. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  10951. /// set should not contain any member functions; those will be added
  10952. /// by CreateOverloadedUnaryOp().
  10953. ///
  10954. /// \param Input The input argument.
  10955. ExprResult
  10956. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
  10957. const UnresolvedSetImpl &Fns,
  10958. Expr *Input, bool PerformADL) {
  10959. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  10960. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  10961. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  10962. // TODO: provide better source location info.
  10963. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  10964. if (checkPlaceholderForOverload(*this, Input))
  10965. return ExprError();
  10966. Expr *Args[2] = { Input, nullptr };
  10967. unsigned NumArgs = 1;
  10968. // For post-increment and post-decrement, add the implicit '0' as
  10969. // the second argument, so that we know this is a post-increment or
  10970. // post-decrement.
  10971. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  10972. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  10973. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  10974. SourceLocation());
  10975. NumArgs = 2;
  10976. }
  10977. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  10978. if (Input->isTypeDependent()) {
  10979. if (Fns.empty())
  10980. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  10981. VK_RValue, OK_Ordinary, OpLoc, false);
  10982. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10983. UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
  10984. Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
  10985. /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
  10986. return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
  10987. Context.DependentTy, VK_RValue, OpLoc,
  10988. FPOptions());
  10989. }
  10990. // Build an empty overload set.
  10991. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  10992. // Add the candidates from the given function set.
  10993. AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
  10994. // Add operator candidates that are member functions.
  10995. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  10996. // Add candidates from ADL.
  10997. if (PerformADL) {
  10998. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  10999. /*ExplicitTemplateArgs*/nullptr,
  11000. CandidateSet);
  11001. }
  11002. // Add builtin operator candidates.
  11003. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  11004. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11005. // Perform overload resolution.
  11006. OverloadCandidateSet::iterator Best;
  11007. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  11008. case OR_Success: {
  11009. // We found a built-in operator or an overloaded operator.
  11010. FunctionDecl *FnDecl = Best->Function;
  11011. if (FnDecl) {
  11012. Expr *Base = nullptr;
  11013. // We matched an overloaded operator. Build a call to that
  11014. // operator.
  11015. // Convert the arguments.
  11016. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11017. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  11018. ExprResult InputRes =
  11019. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  11020. Best->FoundDecl, Method);
  11021. if (InputRes.isInvalid())
  11022. return ExprError();
  11023. Base = Input = InputRes.get();
  11024. } else {
  11025. // Convert the arguments.
  11026. ExprResult InputInit
  11027. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11028. Context,
  11029. FnDecl->getParamDecl(0)),
  11030. SourceLocation(),
  11031. Input);
  11032. if (InputInit.isInvalid())
  11033. return ExprError();
  11034. Input = InputInit.get();
  11035. }
  11036. // Build the actual expression node.
  11037. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  11038. Base, HadMultipleCandidates,
  11039. OpLoc);
  11040. if (FnExpr.isInvalid())
  11041. return ExprError();
  11042. // Determine the result type.
  11043. QualType ResultTy = FnDecl->getReturnType();
  11044. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11045. ResultTy = ResultTy.getNonLValueExprType(Context);
  11046. Args[0] = Input;
  11047. CallExpr *TheCall = CXXOperatorCallExpr::Create(
  11048. Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
  11049. FPOptions(), Best->IsADLCandidate);
  11050. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  11051. return ExprError();
  11052. if (CheckFunctionCall(FnDecl, TheCall,
  11053. FnDecl->getType()->castAs<FunctionProtoType>()))
  11054. return ExprError();
  11055. return MaybeBindToTemporary(TheCall);
  11056. } else {
  11057. // We matched a built-in operator. Convert the arguments, then
  11058. // break out so that we will build the appropriate built-in
  11059. // operator node.
  11060. ExprResult InputRes = PerformImplicitConversion(
  11061. Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
  11062. CCK_ForBuiltinOverloadedOp);
  11063. if (InputRes.isInvalid())
  11064. return ExprError();
  11065. Input = InputRes.get();
  11066. break;
  11067. }
  11068. }
  11069. case OR_No_Viable_Function:
  11070. // This is an erroneous use of an operator which can be overloaded by
  11071. // a non-member function. Check for non-member operators which were
  11072. // defined too late to be candidates.
  11073. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  11074. // FIXME: Recover by calling the found function.
  11075. return ExprError();
  11076. // No viable function; fall through to handling this as a
  11077. // built-in operator, which will produce an error message for us.
  11078. break;
  11079. case OR_Ambiguous:
  11080. CandidateSet.NoteCandidates(
  11081. PartialDiagnosticAt(OpLoc,
  11082. PDiag(diag::err_ovl_ambiguous_oper_unary)
  11083. << UnaryOperator::getOpcodeStr(Opc)
  11084. << Input->getType() << Input->getSourceRange()),
  11085. *this, OCD_ViableCandidates, ArgsArray,
  11086. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  11087. return ExprError();
  11088. case OR_Deleted:
  11089. CandidateSet.NoteCandidates(
  11090. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  11091. << UnaryOperator::getOpcodeStr(Opc)
  11092. << Input->getSourceRange()),
  11093. *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
  11094. OpLoc);
  11095. return ExprError();
  11096. }
  11097. // Either we found no viable overloaded operator or we matched a
  11098. // built-in operator. In either case, fall through to trying to
  11099. // build a built-in operation.
  11100. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11101. }
  11102. /// Create a binary operation that may resolve to an overloaded
  11103. /// operator.
  11104. ///
  11105. /// \param OpLoc The location of the operator itself (e.g., '+').
  11106. ///
  11107. /// \param Opc The BinaryOperatorKind that describes this operator.
  11108. ///
  11109. /// \param Fns The set of non-member functions that will be
  11110. /// considered by overload resolution. The caller needs to build this
  11111. /// set based on the context using, e.g.,
  11112. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  11113. /// set should not contain any member functions; those will be added
  11114. /// by CreateOverloadedBinOp().
  11115. ///
  11116. /// \param LHS Left-hand argument.
  11117. /// \param RHS Right-hand argument.
  11118. ExprResult
  11119. Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  11120. BinaryOperatorKind Opc,
  11121. const UnresolvedSetImpl &Fns,
  11122. Expr *LHS, Expr *RHS, bool PerformADL) {
  11123. Expr *Args[2] = { LHS, RHS };
  11124. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  11125. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  11126. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  11127. // If either side is type-dependent, create an appropriate dependent
  11128. // expression.
  11129. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  11130. if (Fns.empty()) {
  11131. // If there are no functions to store, just build a dependent
  11132. // BinaryOperator or CompoundAssignment.
  11133. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  11134. return new (Context) BinaryOperator(
  11135. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  11136. OpLoc, FPFeatures);
  11137. return new (Context) CompoundAssignOperator(
  11138. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  11139. Context.DependentTy, Context.DependentTy, OpLoc,
  11140. FPFeatures);
  11141. }
  11142. // FIXME: save results of ADL from here?
  11143. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11144. // TODO: provide better source location info in DNLoc component.
  11145. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  11146. UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
  11147. Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
  11148. /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
  11149. return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
  11150. Context.DependentTy, VK_RValue, OpLoc,
  11151. FPFeatures);
  11152. }
  11153. // Always do placeholder-like conversions on the RHS.
  11154. if (checkPlaceholderForOverload(*this, Args[1]))
  11155. return ExprError();
  11156. // Do placeholder-like conversion on the LHS; note that we should
  11157. // not get here with a PseudoObject LHS.
  11158. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  11159. if (checkPlaceholderForOverload(*this, Args[0]))
  11160. return ExprError();
  11161. // If this is the assignment operator, we only perform overload resolution
  11162. // if the left-hand side is a class or enumeration type. This is actually
  11163. // a hack. The standard requires that we do overload resolution between the
  11164. // various built-in candidates, but as DR507 points out, this can lead to
  11165. // problems. So we do it this way, which pretty much follows what GCC does.
  11166. // Note that we go the traditional code path for compound assignment forms.
  11167. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  11168. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11169. // If this is the .* operator, which is not overloadable, just
  11170. // create a built-in binary operator.
  11171. if (Opc == BO_PtrMemD)
  11172. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11173. // Build an empty overload set.
  11174. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  11175. // Add the candidates from the given function set.
  11176. AddFunctionCandidates(Fns, Args, CandidateSet);
  11177. // Add operator candidates that are member functions.
  11178. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  11179. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  11180. // performed for an assignment operator (nor for operator[] nor operator->,
  11181. // which don't get here).
  11182. if (Opc != BO_Assign && PerformADL)
  11183. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  11184. /*ExplicitTemplateArgs*/ nullptr,
  11185. CandidateSet);
  11186. // Add builtin operator candidates.
  11187. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  11188. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11189. // Perform overload resolution.
  11190. OverloadCandidateSet::iterator Best;
  11191. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  11192. case OR_Success: {
  11193. // We found a built-in operator or an overloaded operator.
  11194. FunctionDecl *FnDecl = Best->Function;
  11195. if (FnDecl) {
  11196. Expr *Base = nullptr;
  11197. // We matched an overloaded operator. Build a call to that
  11198. // operator.
  11199. // Convert the arguments.
  11200. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11201. // Best->Access is only meaningful for class members.
  11202. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  11203. ExprResult Arg1 =
  11204. PerformCopyInitialization(
  11205. InitializedEntity::InitializeParameter(Context,
  11206. FnDecl->getParamDecl(0)),
  11207. SourceLocation(), Args[1]);
  11208. if (Arg1.isInvalid())
  11209. return ExprError();
  11210. ExprResult Arg0 =
  11211. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  11212. Best->FoundDecl, Method);
  11213. if (Arg0.isInvalid())
  11214. return ExprError();
  11215. Base = Args[0] = Arg0.getAs<Expr>();
  11216. Args[1] = RHS = Arg1.getAs<Expr>();
  11217. } else {
  11218. // Convert the arguments.
  11219. ExprResult Arg0 = PerformCopyInitialization(
  11220. InitializedEntity::InitializeParameter(Context,
  11221. FnDecl->getParamDecl(0)),
  11222. SourceLocation(), Args[0]);
  11223. if (Arg0.isInvalid())
  11224. return ExprError();
  11225. ExprResult Arg1 =
  11226. PerformCopyInitialization(
  11227. InitializedEntity::InitializeParameter(Context,
  11228. FnDecl->getParamDecl(1)),
  11229. SourceLocation(), Args[1]);
  11230. if (Arg1.isInvalid())
  11231. return ExprError();
  11232. Args[0] = LHS = Arg0.getAs<Expr>();
  11233. Args[1] = RHS = Arg1.getAs<Expr>();
  11234. }
  11235. // Build the actual expression node.
  11236. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  11237. Best->FoundDecl, Base,
  11238. HadMultipleCandidates, OpLoc);
  11239. if (FnExpr.isInvalid())
  11240. return ExprError();
  11241. // Determine the result type.
  11242. QualType ResultTy = FnDecl->getReturnType();
  11243. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11244. ResultTy = ResultTy.getNonLValueExprType(Context);
  11245. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  11246. Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
  11247. Best->IsADLCandidate);
  11248. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  11249. FnDecl))
  11250. return ExprError();
  11251. ArrayRef<const Expr *> ArgsArray(Args, 2);
  11252. const Expr *ImplicitThis = nullptr;
  11253. // Cut off the implicit 'this'.
  11254. if (isa<CXXMethodDecl>(FnDecl)) {
  11255. ImplicitThis = ArgsArray[0];
  11256. ArgsArray = ArgsArray.slice(1);
  11257. }
  11258. // Check for a self move.
  11259. if (Op == OO_Equal)
  11260. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  11261. checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
  11262. isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
  11263. VariadicDoesNotApply);
  11264. return MaybeBindToTemporary(TheCall);
  11265. } else {
  11266. // We matched a built-in operator. Convert the arguments, then
  11267. // break out so that we will build the appropriate built-in
  11268. // operator node.
  11269. ExprResult ArgsRes0 = PerformImplicitConversion(
  11270. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  11271. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11272. if (ArgsRes0.isInvalid())
  11273. return ExprError();
  11274. Args[0] = ArgsRes0.get();
  11275. ExprResult ArgsRes1 = PerformImplicitConversion(
  11276. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  11277. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11278. if (ArgsRes1.isInvalid())
  11279. return ExprError();
  11280. Args[1] = ArgsRes1.get();
  11281. break;
  11282. }
  11283. }
  11284. case OR_No_Viable_Function: {
  11285. // C++ [over.match.oper]p9:
  11286. // If the operator is the operator , [...] and there are no
  11287. // viable functions, then the operator is assumed to be the
  11288. // built-in operator and interpreted according to clause 5.
  11289. if (Opc == BO_Comma)
  11290. break;
  11291. // For class as left operand for assignment or compound assignment
  11292. // operator do not fall through to handling in built-in, but report that
  11293. // no overloaded assignment operator found
  11294. ExprResult Result = ExprError();
  11295. StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
  11296. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
  11297. Args, OpLoc);
  11298. if (Args[0]->getType()->isRecordType() &&
  11299. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  11300. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  11301. << BinaryOperator::getOpcodeStr(Opc)
  11302. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11303. if (Args[0]->getType()->isIncompleteType()) {
  11304. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  11305. << Args[0]->getType()
  11306. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11307. }
  11308. } else {
  11309. // This is an erroneous use of an operator which can be overloaded by
  11310. // a non-member function. Check for non-member operators which were
  11311. // defined too late to be candidates.
  11312. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  11313. // FIXME: Recover by calling the found function.
  11314. return ExprError();
  11315. // No viable function; try to create a built-in operation, which will
  11316. // produce an error. Then, show the non-viable candidates.
  11317. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11318. }
  11319. assert(Result.isInvalid() &&
  11320. "C++ binary operator overloading is missing candidates!");
  11321. CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
  11322. return Result;
  11323. }
  11324. case OR_Ambiguous:
  11325. CandidateSet.NoteCandidates(
  11326. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  11327. << BinaryOperator::getOpcodeStr(Opc)
  11328. << Args[0]->getType()
  11329. << Args[1]->getType()
  11330. << Args[0]->getSourceRange()
  11331. << Args[1]->getSourceRange()),
  11332. *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  11333. OpLoc);
  11334. return ExprError();
  11335. case OR_Deleted:
  11336. if (isImplicitlyDeleted(Best->Function)) {
  11337. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  11338. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  11339. << Context.getRecordType(Method->getParent())
  11340. << getSpecialMember(Method);
  11341. // The user probably meant to call this special member. Just
  11342. // explain why it's deleted.
  11343. NoteDeletedFunction(Method);
  11344. return ExprError();
  11345. }
  11346. CandidateSet.NoteCandidates(
  11347. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  11348. << BinaryOperator::getOpcodeStr(Opc)
  11349. << Args[0]->getSourceRange()
  11350. << Args[1]->getSourceRange()),
  11351. *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  11352. OpLoc);
  11353. return ExprError();
  11354. }
  11355. // We matched a built-in operator; build it.
  11356. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11357. }
  11358. ExprResult
  11359. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  11360. SourceLocation RLoc,
  11361. Expr *Base, Expr *Idx) {
  11362. Expr *Args[2] = { Base, Idx };
  11363. DeclarationName OpName =
  11364. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  11365. // If either side is type-dependent, create an appropriate dependent
  11366. // expression.
  11367. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  11368. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11369. // CHECKME: no 'operator' keyword?
  11370. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  11371. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  11372. UnresolvedLookupExpr *Fn
  11373. = UnresolvedLookupExpr::Create(Context, NamingClass,
  11374. NestedNameSpecifierLoc(), OpNameInfo,
  11375. /*ADL*/ true, /*Overloaded*/ false,
  11376. UnresolvedSetIterator(),
  11377. UnresolvedSetIterator());
  11378. // Can't add any actual overloads yet
  11379. return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
  11380. Context.DependentTy, VK_RValue, RLoc,
  11381. FPOptions());
  11382. }
  11383. // Handle placeholders on both operands.
  11384. if (checkPlaceholderForOverload(*this, Args[0]))
  11385. return ExprError();
  11386. if (checkPlaceholderForOverload(*this, Args[1]))
  11387. return ExprError();
  11388. // Build an empty overload set.
  11389. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  11390. // Subscript can only be overloaded as a member function.
  11391. // Add operator candidates that are member functions.
  11392. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  11393. // Add builtin operator candidates.
  11394. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  11395. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11396. // Perform overload resolution.
  11397. OverloadCandidateSet::iterator Best;
  11398. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  11399. case OR_Success: {
  11400. // We found a built-in operator or an overloaded operator.
  11401. FunctionDecl *FnDecl = Best->Function;
  11402. if (FnDecl) {
  11403. // We matched an overloaded operator. Build a call to that
  11404. // operator.
  11405. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  11406. // Convert the arguments.
  11407. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  11408. ExprResult Arg0 =
  11409. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  11410. Best->FoundDecl, Method);
  11411. if (Arg0.isInvalid())
  11412. return ExprError();
  11413. Args[0] = Arg0.get();
  11414. // Convert the arguments.
  11415. ExprResult InputInit
  11416. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11417. Context,
  11418. FnDecl->getParamDecl(0)),
  11419. SourceLocation(),
  11420. Args[1]);
  11421. if (InputInit.isInvalid())
  11422. return ExprError();
  11423. Args[1] = InputInit.getAs<Expr>();
  11424. // Build the actual expression node.
  11425. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  11426. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  11427. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  11428. Best->FoundDecl,
  11429. Base,
  11430. HadMultipleCandidates,
  11431. OpLocInfo.getLoc(),
  11432. OpLocInfo.getInfo());
  11433. if (FnExpr.isInvalid())
  11434. return ExprError();
  11435. // Determine the result type
  11436. QualType ResultTy = FnDecl->getReturnType();
  11437. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11438. ResultTy = ResultTy.getNonLValueExprType(Context);
  11439. CXXOperatorCallExpr *TheCall =
  11440. CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
  11441. Args, ResultTy, VK, RLoc, FPOptions());
  11442. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  11443. return ExprError();
  11444. if (CheckFunctionCall(Method, TheCall,
  11445. Method->getType()->castAs<FunctionProtoType>()))
  11446. return ExprError();
  11447. return MaybeBindToTemporary(TheCall);
  11448. } else {
  11449. // We matched a built-in operator. Convert the arguments, then
  11450. // break out so that we will build the appropriate built-in
  11451. // operator node.
  11452. ExprResult ArgsRes0 = PerformImplicitConversion(
  11453. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  11454. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11455. if (ArgsRes0.isInvalid())
  11456. return ExprError();
  11457. Args[0] = ArgsRes0.get();
  11458. ExprResult ArgsRes1 = PerformImplicitConversion(
  11459. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  11460. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11461. if (ArgsRes1.isInvalid())
  11462. return ExprError();
  11463. Args[1] = ArgsRes1.get();
  11464. break;
  11465. }
  11466. }
  11467. case OR_No_Viable_Function: {
  11468. PartialDiagnostic PD = CandidateSet.empty()
  11469. ? (PDiag(diag::err_ovl_no_oper)
  11470. << Args[0]->getType() << /*subscript*/ 0
  11471. << Args[0]->getSourceRange() << Args[1]->getSourceRange())
  11472. : (PDiag(diag::err_ovl_no_viable_subscript)
  11473. << Args[0]->getType() << Args[0]->getSourceRange()
  11474. << Args[1]->getSourceRange());
  11475. CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
  11476. OCD_AllCandidates, Args, "[]", LLoc);
  11477. return ExprError();
  11478. }
  11479. case OR_Ambiguous:
  11480. CandidateSet.NoteCandidates(
  11481. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  11482. << "[]" << Args[0]->getType()
  11483. << Args[1]->getType()
  11484. << Args[0]->getSourceRange()
  11485. << Args[1]->getSourceRange()),
  11486. *this, OCD_ViableCandidates, Args, "[]", LLoc);
  11487. return ExprError();
  11488. case OR_Deleted:
  11489. CandidateSet.NoteCandidates(
  11490. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
  11491. << "[]" << Args[0]->getSourceRange()
  11492. << Args[1]->getSourceRange()),
  11493. *this, OCD_AllCandidates, Args, "[]", LLoc);
  11494. return ExprError();
  11495. }
  11496. // We matched a built-in operator; build it.
  11497. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  11498. }
  11499. /// BuildCallToMemberFunction - Build a call to a member
  11500. /// function. MemExpr is the expression that refers to the member
  11501. /// function (and includes the object parameter), Args/NumArgs are the
  11502. /// arguments to the function call (not including the object
  11503. /// parameter). The caller needs to validate that the member
  11504. /// expression refers to a non-static member function or an overloaded
  11505. /// member function.
  11506. ExprResult
  11507. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  11508. SourceLocation LParenLoc,
  11509. MultiExprArg Args,
  11510. SourceLocation RParenLoc) {
  11511. assert(MemExprE->getType() == Context.BoundMemberTy ||
  11512. MemExprE->getType() == Context.OverloadTy);
  11513. // Dig out the member expression. This holds both the object
  11514. // argument and the member function we're referring to.
  11515. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  11516. // Determine whether this is a call to a pointer-to-member function.
  11517. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  11518. assert(op->getType() == Context.BoundMemberTy);
  11519. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  11520. QualType fnType =
  11521. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  11522. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  11523. QualType resultType = proto->getCallResultType(Context);
  11524. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  11525. // Check that the object type isn't more qualified than the
  11526. // member function we're calling.
  11527. Qualifiers funcQuals = proto->getMethodQuals();
  11528. QualType objectType = op->getLHS()->getType();
  11529. if (op->getOpcode() == BO_PtrMemI)
  11530. objectType = objectType->castAs<PointerType>()->getPointeeType();
  11531. Qualifiers objectQuals = objectType.getQualifiers();
  11532. Qualifiers difference = objectQuals - funcQuals;
  11533. difference.removeObjCGCAttr();
  11534. difference.removeAddressSpace();
  11535. if (difference) {
  11536. std::string qualsString = difference.getAsString();
  11537. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  11538. << fnType.getUnqualifiedType()
  11539. << qualsString
  11540. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  11541. }
  11542. CXXMemberCallExpr *call =
  11543. CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
  11544. valueKind, RParenLoc, proto->getNumParams());
  11545. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
  11546. call, nullptr))
  11547. return ExprError();
  11548. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  11549. return ExprError();
  11550. if (CheckOtherCall(call, proto))
  11551. return ExprError();
  11552. return MaybeBindToTemporary(call);
  11553. }
  11554. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  11555. return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
  11556. RParenLoc);
  11557. UnbridgedCastsSet UnbridgedCasts;
  11558. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  11559. return ExprError();
  11560. MemberExpr *MemExpr;
  11561. CXXMethodDecl *Method = nullptr;
  11562. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  11563. NestedNameSpecifier *Qualifier = nullptr;
  11564. if (isa<MemberExpr>(NakedMemExpr)) {
  11565. MemExpr = cast<MemberExpr>(NakedMemExpr);
  11566. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  11567. FoundDecl = MemExpr->getFoundDecl();
  11568. Qualifier = MemExpr->getQualifier();
  11569. UnbridgedCasts.restore();
  11570. } else {
  11571. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  11572. Qualifier = UnresExpr->getQualifier();
  11573. QualType ObjectType = UnresExpr->getBaseType();
  11574. Expr::Classification ObjectClassification
  11575. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  11576. : UnresExpr->getBase()->Classify(Context);
  11577. // Add overload candidates
  11578. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  11579. OverloadCandidateSet::CSK_Normal);
  11580. // FIXME: avoid copy.
  11581. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11582. if (UnresExpr->hasExplicitTemplateArgs()) {
  11583. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11584. TemplateArgs = &TemplateArgsBuffer;
  11585. }
  11586. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  11587. E = UnresExpr->decls_end(); I != E; ++I) {
  11588. NamedDecl *Func = *I;
  11589. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  11590. if (isa<UsingShadowDecl>(Func))
  11591. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  11592. // Microsoft supports direct constructor calls.
  11593. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  11594. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
  11595. CandidateSet,
  11596. /*SuppressUserConversions*/ false);
  11597. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  11598. // If explicit template arguments were provided, we can't call a
  11599. // non-template member function.
  11600. if (TemplateArgs)
  11601. continue;
  11602. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  11603. ObjectClassification, Args, CandidateSet,
  11604. /*SuppressUserConversions=*/false);
  11605. } else {
  11606. AddMethodTemplateCandidate(
  11607. cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
  11608. TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
  11609. /*SuppressUserConversions=*/false);
  11610. }
  11611. }
  11612. DeclarationName DeclName = UnresExpr->getMemberName();
  11613. UnbridgedCasts.restore();
  11614. OverloadCandidateSet::iterator Best;
  11615. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
  11616. Best)) {
  11617. case OR_Success:
  11618. Method = cast<CXXMethodDecl>(Best->Function);
  11619. FoundDecl = Best->FoundDecl;
  11620. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  11621. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  11622. return ExprError();
  11623. // If FoundDecl is different from Method (such as if one is a template
  11624. // and the other a specialization), make sure DiagnoseUseOfDecl is
  11625. // called on both.
  11626. // FIXME: This would be more comprehensively addressed by modifying
  11627. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  11628. // being used.
  11629. if (Method != FoundDecl.getDecl() &&
  11630. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  11631. return ExprError();
  11632. break;
  11633. case OR_No_Viable_Function:
  11634. CandidateSet.NoteCandidates(
  11635. PartialDiagnosticAt(
  11636. UnresExpr->getMemberLoc(),
  11637. PDiag(diag::err_ovl_no_viable_member_function_in_call)
  11638. << DeclName << MemExprE->getSourceRange()),
  11639. *this, OCD_AllCandidates, Args);
  11640. // FIXME: Leaking incoming expressions!
  11641. return ExprError();
  11642. case OR_Ambiguous:
  11643. CandidateSet.NoteCandidates(
  11644. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  11645. PDiag(diag::err_ovl_ambiguous_member_call)
  11646. << DeclName << MemExprE->getSourceRange()),
  11647. *this, OCD_AllCandidates, Args);
  11648. // FIXME: Leaking incoming expressions!
  11649. return ExprError();
  11650. case OR_Deleted:
  11651. CandidateSet.NoteCandidates(
  11652. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  11653. PDiag(diag::err_ovl_deleted_member_call)
  11654. << DeclName << MemExprE->getSourceRange()),
  11655. *this, OCD_AllCandidates, Args);
  11656. // FIXME: Leaking incoming expressions!
  11657. return ExprError();
  11658. }
  11659. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  11660. // If overload resolution picked a static member, build a
  11661. // non-member call based on that function.
  11662. if (Method->isStatic()) {
  11663. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  11664. RParenLoc);
  11665. }
  11666. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  11667. }
  11668. QualType ResultType = Method->getReturnType();
  11669. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  11670. ResultType = ResultType.getNonLValueExprType(Context);
  11671. assert(Method && "Member call to something that isn't a method?");
  11672. const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
  11673. CXXMemberCallExpr *TheCall =
  11674. CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
  11675. RParenLoc, Proto->getNumParams());
  11676. // Check for a valid return type.
  11677. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  11678. TheCall, Method))
  11679. return ExprError();
  11680. // Convert the object argument (for a non-static member function call).
  11681. // We only need to do this if there was actually an overload; otherwise
  11682. // it was done at lookup.
  11683. if (!Method->isStatic()) {
  11684. ExprResult ObjectArg =
  11685. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  11686. FoundDecl, Method);
  11687. if (ObjectArg.isInvalid())
  11688. return ExprError();
  11689. MemExpr->setBase(ObjectArg.get());
  11690. }
  11691. // Convert the rest of the arguments
  11692. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  11693. RParenLoc))
  11694. return ExprError();
  11695. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  11696. if (CheckFunctionCall(Method, TheCall, Proto))
  11697. return ExprError();
  11698. // In the case the method to call was not selected by the overloading
  11699. // resolution process, we still need to handle the enable_if attribute. Do
  11700. // that here, so it will not hide previous -- and more relevant -- errors.
  11701. if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
  11702. if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
  11703. Diag(MemE->getMemberLoc(),
  11704. diag::err_ovl_no_viable_member_function_in_call)
  11705. << Method << Method->getSourceRange();
  11706. Diag(Method->getLocation(),
  11707. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  11708. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  11709. return ExprError();
  11710. }
  11711. }
  11712. if ((isa<CXXConstructorDecl>(CurContext) ||
  11713. isa<CXXDestructorDecl>(CurContext)) &&
  11714. TheCall->getMethodDecl()->isPure()) {
  11715. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  11716. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
  11717. MemExpr->performsVirtualDispatch(getLangOpts())) {
  11718. Diag(MemExpr->getBeginLoc(),
  11719. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  11720. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  11721. << MD->getParent()->getDeclName();
  11722. Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
  11723. if (getLangOpts().AppleKext)
  11724. Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
  11725. << MD->getParent()->getDeclName() << MD->getDeclName();
  11726. }
  11727. }
  11728. if (CXXDestructorDecl *DD =
  11729. dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
  11730. // a->A::f() doesn't go through the vtable, except in AppleKext mode.
  11731. bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
  11732. CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
  11733. CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
  11734. MemExpr->getMemberLoc());
  11735. }
  11736. return MaybeBindToTemporary(TheCall);
  11737. }
  11738. /// BuildCallToObjectOfClassType - Build a call to an object of class
  11739. /// type (C++ [over.call.object]), which can end up invoking an
  11740. /// overloaded function call operator (@c operator()) or performing a
  11741. /// user-defined conversion on the object argument.
  11742. ExprResult
  11743. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  11744. SourceLocation LParenLoc,
  11745. MultiExprArg Args,
  11746. SourceLocation RParenLoc) {
  11747. if (checkPlaceholderForOverload(*this, Obj))
  11748. return ExprError();
  11749. ExprResult Object = Obj;
  11750. UnbridgedCastsSet UnbridgedCasts;
  11751. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  11752. return ExprError();
  11753. assert(Object.get()->getType()->isRecordType() &&
  11754. "Requires object type argument");
  11755. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  11756. // C++ [over.call.object]p1:
  11757. // If the primary-expression E in the function call syntax
  11758. // evaluates to a class object of type "cv T", then the set of
  11759. // candidate functions includes at least the function call
  11760. // operators of T. The function call operators of T are obtained by
  11761. // ordinary lookup of the name operator() in the context of
  11762. // (E).operator().
  11763. OverloadCandidateSet CandidateSet(LParenLoc,
  11764. OverloadCandidateSet::CSK_Operator);
  11765. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  11766. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  11767. diag::err_incomplete_object_call, Object.get()))
  11768. return true;
  11769. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  11770. LookupQualifiedName(R, Record->getDecl());
  11771. R.suppressDiagnostics();
  11772. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  11773. Oper != OperEnd; ++Oper) {
  11774. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  11775. Object.get()->Classify(Context), Args, CandidateSet,
  11776. /*SuppressUserConversion=*/false);
  11777. }
  11778. // C++ [over.call.object]p2:
  11779. // In addition, for each (non-explicit in C++0x) conversion function
  11780. // declared in T of the form
  11781. //
  11782. // operator conversion-type-id () cv-qualifier;
  11783. //
  11784. // where cv-qualifier is the same cv-qualification as, or a
  11785. // greater cv-qualification than, cv, and where conversion-type-id
  11786. // denotes the type "pointer to function of (P1,...,Pn) returning
  11787. // R", or the type "reference to pointer to function of
  11788. // (P1,...,Pn) returning R", or the type "reference to function
  11789. // of (P1,...,Pn) returning R", a surrogate call function [...]
  11790. // is also considered as a candidate function. Similarly,
  11791. // surrogate call functions are added to the set of candidate
  11792. // functions for each conversion function declared in an
  11793. // accessible base class provided the function is not hidden
  11794. // within T by another intervening declaration.
  11795. const auto &Conversions =
  11796. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  11797. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  11798. NamedDecl *D = *I;
  11799. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  11800. if (isa<UsingShadowDecl>(D))
  11801. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  11802. // Skip over templated conversion functions; they aren't
  11803. // surrogates.
  11804. if (isa<FunctionTemplateDecl>(D))
  11805. continue;
  11806. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  11807. if (!Conv->isExplicit()) {
  11808. // Strip the reference type (if any) and then the pointer type (if
  11809. // any) to get down to what might be a function type.
  11810. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  11811. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  11812. ConvType = ConvPtrType->getPointeeType();
  11813. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  11814. {
  11815. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  11816. Object.get(), Args, CandidateSet);
  11817. }
  11818. }
  11819. }
  11820. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11821. // Perform overload resolution.
  11822. OverloadCandidateSet::iterator Best;
  11823. switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
  11824. Best)) {
  11825. case OR_Success:
  11826. // Overload resolution succeeded; we'll build the appropriate call
  11827. // below.
  11828. break;
  11829. case OR_No_Viable_Function: {
  11830. PartialDiagnostic PD =
  11831. CandidateSet.empty()
  11832. ? (PDiag(diag::err_ovl_no_oper)
  11833. << Object.get()->getType() << /*call*/ 1
  11834. << Object.get()->getSourceRange())
  11835. : (PDiag(diag::err_ovl_no_viable_object_call)
  11836. << Object.get()->getType() << Object.get()->getSourceRange());
  11837. CandidateSet.NoteCandidates(
  11838. PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
  11839. OCD_AllCandidates, Args);
  11840. break;
  11841. }
  11842. case OR_Ambiguous:
  11843. CandidateSet.NoteCandidates(
  11844. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  11845. PDiag(diag::err_ovl_ambiguous_object_call)
  11846. << Object.get()->getType()
  11847. << Object.get()->getSourceRange()),
  11848. *this, OCD_ViableCandidates, Args);
  11849. break;
  11850. case OR_Deleted:
  11851. CandidateSet.NoteCandidates(
  11852. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  11853. PDiag(diag::err_ovl_deleted_object_call)
  11854. << Object.get()->getType()
  11855. << Object.get()->getSourceRange()),
  11856. *this, OCD_AllCandidates, Args);
  11857. break;
  11858. }
  11859. if (Best == CandidateSet.end())
  11860. return true;
  11861. UnbridgedCasts.restore();
  11862. if (Best->Function == nullptr) {
  11863. // Since there is no function declaration, this is one of the
  11864. // surrogate candidates. Dig out the conversion function.
  11865. CXXConversionDecl *Conv
  11866. = cast<CXXConversionDecl>(
  11867. Best->Conversions[0].UserDefined.ConversionFunction);
  11868. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  11869. Best->FoundDecl);
  11870. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  11871. return ExprError();
  11872. assert(Conv == Best->FoundDecl.getDecl() &&
  11873. "Found Decl & conversion-to-functionptr should be same, right?!");
  11874. // We selected one of the surrogate functions that converts the
  11875. // object parameter to a function pointer. Perform the conversion
  11876. // on the object argument, then let BuildCallExpr finish the job.
  11877. // Create an implicit member expr to refer to the conversion operator.
  11878. // and then call it.
  11879. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  11880. Conv, HadMultipleCandidates);
  11881. if (Call.isInvalid())
  11882. return ExprError();
  11883. // Record usage of conversion in an implicit cast.
  11884. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  11885. CK_UserDefinedConversion, Call.get(),
  11886. nullptr, VK_RValue);
  11887. return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  11888. }
  11889. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  11890. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  11891. // that calls this method, using Object for the implicit object
  11892. // parameter and passing along the remaining arguments.
  11893. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  11894. // An error diagnostic has already been printed when parsing the declaration.
  11895. if (Method->isInvalidDecl())
  11896. return ExprError();
  11897. const FunctionProtoType *Proto =
  11898. Method->getType()->getAs<FunctionProtoType>();
  11899. unsigned NumParams = Proto->getNumParams();
  11900. DeclarationNameInfo OpLocInfo(
  11901. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  11902. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  11903. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  11904. Obj, HadMultipleCandidates,
  11905. OpLocInfo.getLoc(),
  11906. OpLocInfo.getInfo());
  11907. if (NewFn.isInvalid())
  11908. return true;
  11909. // The number of argument slots to allocate in the call. If we have default
  11910. // arguments we need to allocate space for them as well. We additionally
  11911. // need one more slot for the object parameter.
  11912. unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
  11913. // Build the full argument list for the method call (the implicit object
  11914. // parameter is placed at the beginning of the list).
  11915. SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
  11916. bool IsError = false;
  11917. // Initialize the implicit object parameter.
  11918. ExprResult ObjRes =
  11919. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  11920. Best->FoundDecl, Method);
  11921. if (ObjRes.isInvalid())
  11922. IsError = true;
  11923. else
  11924. Object = ObjRes;
  11925. MethodArgs[0] = Object.get();
  11926. // Check the argument types.
  11927. for (unsigned i = 0; i != NumParams; i++) {
  11928. Expr *Arg;
  11929. if (i < Args.size()) {
  11930. Arg = Args[i];
  11931. // Pass the argument.
  11932. ExprResult InputInit
  11933. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11934. Context,
  11935. Method->getParamDecl(i)),
  11936. SourceLocation(), Arg);
  11937. IsError |= InputInit.isInvalid();
  11938. Arg = InputInit.getAs<Expr>();
  11939. } else {
  11940. ExprResult DefArg
  11941. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  11942. if (DefArg.isInvalid()) {
  11943. IsError = true;
  11944. break;
  11945. }
  11946. Arg = DefArg.getAs<Expr>();
  11947. }
  11948. MethodArgs[i + 1] = Arg;
  11949. }
  11950. // If this is a variadic call, handle args passed through "...".
  11951. if (Proto->isVariadic()) {
  11952. // Promote the arguments (C99 6.5.2.2p7).
  11953. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  11954. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  11955. nullptr);
  11956. IsError |= Arg.isInvalid();
  11957. MethodArgs[i + 1] = Arg.get();
  11958. }
  11959. }
  11960. if (IsError)
  11961. return true;
  11962. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  11963. // Once we've built TheCall, all of the expressions are properly owned.
  11964. QualType ResultTy = Method->getReturnType();
  11965. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11966. ResultTy = ResultTy.getNonLValueExprType(Context);
  11967. CXXOperatorCallExpr *TheCall =
  11968. CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
  11969. ResultTy, VK, RParenLoc, FPOptions());
  11970. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  11971. return true;
  11972. if (CheckFunctionCall(Method, TheCall, Proto))
  11973. return true;
  11974. return MaybeBindToTemporary(TheCall);
  11975. }
  11976. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  11977. /// (if one exists), where @c Base is an expression of class type and
  11978. /// @c Member is the name of the member we're trying to find.
  11979. ExprResult
  11980. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  11981. bool *NoArrowOperatorFound) {
  11982. assert(Base->getType()->isRecordType() &&
  11983. "left-hand side must have class type");
  11984. if (checkPlaceholderForOverload(*this, Base))
  11985. return ExprError();
  11986. SourceLocation Loc = Base->getExprLoc();
  11987. // C++ [over.ref]p1:
  11988. //
  11989. // [...] An expression x->m is interpreted as (x.operator->())->m
  11990. // for a class object x of type T if T::operator->() exists and if
  11991. // the operator is selected as the best match function by the
  11992. // overload resolution mechanism (13.3).
  11993. DeclarationName OpName =
  11994. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  11995. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  11996. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  11997. if (RequireCompleteType(Loc, Base->getType(),
  11998. diag::err_typecheck_incomplete_tag, Base))
  11999. return ExprError();
  12000. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  12001. LookupQualifiedName(R, BaseRecord->getDecl());
  12002. R.suppressDiagnostics();
  12003. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  12004. Oper != OperEnd; ++Oper) {
  12005. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  12006. None, CandidateSet, /*SuppressUserConversion=*/false);
  12007. }
  12008. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12009. // Perform overload resolution.
  12010. OverloadCandidateSet::iterator Best;
  12011. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  12012. case OR_Success:
  12013. // Overload resolution succeeded; we'll build the call below.
  12014. break;
  12015. case OR_No_Viable_Function: {
  12016. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
  12017. if (CandidateSet.empty()) {
  12018. QualType BaseType = Base->getType();
  12019. if (NoArrowOperatorFound) {
  12020. // Report this specific error to the caller instead of emitting a
  12021. // diagnostic, as requested.
  12022. *NoArrowOperatorFound = true;
  12023. return ExprError();
  12024. }
  12025. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  12026. << BaseType << Base->getSourceRange();
  12027. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  12028. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  12029. << FixItHint::CreateReplacement(OpLoc, ".");
  12030. }
  12031. } else
  12032. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  12033. << "operator->" << Base->getSourceRange();
  12034. CandidateSet.NoteCandidates(*this, Base, Cands);
  12035. return ExprError();
  12036. }
  12037. case OR_Ambiguous:
  12038. CandidateSet.NoteCandidates(
  12039. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
  12040. << "->" << Base->getType()
  12041. << Base->getSourceRange()),
  12042. *this, OCD_ViableCandidates, Base);
  12043. return ExprError();
  12044. case OR_Deleted:
  12045. CandidateSet.NoteCandidates(
  12046. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  12047. << "->" << Base->getSourceRange()),
  12048. *this, OCD_AllCandidates, Base);
  12049. return ExprError();
  12050. }
  12051. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  12052. // Convert the object parameter.
  12053. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  12054. ExprResult BaseResult =
  12055. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  12056. Best->FoundDecl, Method);
  12057. if (BaseResult.isInvalid())
  12058. return ExprError();
  12059. Base = BaseResult.get();
  12060. // Build the operator call.
  12061. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  12062. Base, HadMultipleCandidates, OpLoc);
  12063. if (FnExpr.isInvalid())
  12064. return ExprError();
  12065. QualType ResultTy = Method->getReturnType();
  12066. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12067. ResultTy = ResultTy.getNonLValueExprType(Context);
  12068. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  12069. Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
  12070. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  12071. return ExprError();
  12072. if (CheckFunctionCall(Method, TheCall,
  12073. Method->getType()->castAs<FunctionProtoType>()))
  12074. return ExprError();
  12075. return MaybeBindToTemporary(TheCall);
  12076. }
  12077. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  12078. /// a literal operator described by the provided lookup results.
  12079. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  12080. DeclarationNameInfo &SuffixInfo,
  12081. ArrayRef<Expr*> Args,
  12082. SourceLocation LitEndLoc,
  12083. TemplateArgumentListInfo *TemplateArgs) {
  12084. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  12085. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  12086. OverloadCandidateSet::CSK_Normal);
  12087. AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
  12088. /*SuppressUserConversions=*/true);
  12089. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12090. // Perform overload resolution. This will usually be trivial, but might need
  12091. // to perform substitutions for a literal operator template.
  12092. OverloadCandidateSet::iterator Best;
  12093. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  12094. case OR_Success:
  12095. case OR_Deleted:
  12096. break;
  12097. case OR_No_Viable_Function:
  12098. CandidateSet.NoteCandidates(
  12099. PartialDiagnosticAt(UDSuffixLoc,
  12100. PDiag(diag::err_ovl_no_viable_function_in_call)
  12101. << R.getLookupName()),
  12102. *this, OCD_AllCandidates, Args);
  12103. return ExprError();
  12104. case OR_Ambiguous:
  12105. CandidateSet.NoteCandidates(
  12106. PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
  12107. << R.getLookupName()),
  12108. *this, OCD_ViableCandidates, Args);
  12109. return ExprError();
  12110. }
  12111. FunctionDecl *FD = Best->Function;
  12112. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  12113. nullptr, HadMultipleCandidates,
  12114. SuffixInfo.getLoc(),
  12115. SuffixInfo.getInfo());
  12116. if (Fn.isInvalid())
  12117. return true;
  12118. // Check the argument types. This should almost always be a no-op, except
  12119. // that array-to-pointer decay is applied to string literals.
  12120. Expr *ConvArgs[2];
  12121. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  12122. ExprResult InputInit = PerformCopyInitialization(
  12123. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  12124. SourceLocation(), Args[ArgIdx]);
  12125. if (InputInit.isInvalid())
  12126. return true;
  12127. ConvArgs[ArgIdx] = InputInit.get();
  12128. }
  12129. QualType ResultTy = FD->getReturnType();
  12130. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12131. ResultTy = ResultTy.getNonLValueExprType(Context);
  12132. UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
  12133. Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
  12134. VK, LitEndLoc, UDSuffixLoc);
  12135. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  12136. return ExprError();
  12137. if (CheckFunctionCall(FD, UDL, nullptr))
  12138. return ExprError();
  12139. return MaybeBindToTemporary(UDL);
  12140. }
  12141. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  12142. /// given LookupResult is non-empty, it is assumed to describe a member which
  12143. /// will be invoked. Otherwise, the function will be found via argument
  12144. /// dependent lookup.
  12145. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  12146. /// otherwise CallExpr is set to ExprError() and some non-success value
  12147. /// is returned.
  12148. Sema::ForRangeStatus
  12149. Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
  12150. SourceLocation RangeLoc,
  12151. const DeclarationNameInfo &NameInfo,
  12152. LookupResult &MemberLookup,
  12153. OverloadCandidateSet *CandidateSet,
  12154. Expr *Range, ExprResult *CallExpr) {
  12155. Scope *S = nullptr;
  12156. CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
  12157. if (!MemberLookup.empty()) {
  12158. ExprResult MemberRef =
  12159. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  12160. /*IsPtr=*/false, CXXScopeSpec(),
  12161. /*TemplateKWLoc=*/SourceLocation(),
  12162. /*FirstQualifierInScope=*/nullptr,
  12163. MemberLookup,
  12164. /*TemplateArgs=*/nullptr, S);
  12165. if (MemberRef.isInvalid()) {
  12166. *CallExpr = ExprError();
  12167. return FRS_DiagnosticIssued;
  12168. }
  12169. *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  12170. if (CallExpr->isInvalid()) {
  12171. *CallExpr = ExprError();
  12172. return FRS_DiagnosticIssued;
  12173. }
  12174. } else {
  12175. UnresolvedSet<0> FoundNames;
  12176. UnresolvedLookupExpr *Fn =
  12177. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  12178. NestedNameSpecifierLoc(), NameInfo,
  12179. /*NeedsADL=*/true, /*Overloaded=*/false,
  12180. FoundNames.begin(), FoundNames.end());
  12181. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  12182. CandidateSet, CallExpr);
  12183. if (CandidateSet->empty() || CandidateSetError) {
  12184. *CallExpr = ExprError();
  12185. return FRS_NoViableFunction;
  12186. }
  12187. OverloadCandidateSet::iterator Best;
  12188. OverloadingResult OverloadResult =
  12189. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
  12190. if (OverloadResult == OR_No_Viable_Function) {
  12191. *CallExpr = ExprError();
  12192. return FRS_NoViableFunction;
  12193. }
  12194. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  12195. Loc, nullptr, CandidateSet, &Best,
  12196. OverloadResult,
  12197. /*AllowTypoCorrection=*/false);
  12198. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  12199. *CallExpr = ExprError();
  12200. return FRS_DiagnosticIssued;
  12201. }
  12202. }
  12203. return FRS_Success;
  12204. }
  12205. /// FixOverloadedFunctionReference - E is an expression that refers to
  12206. /// a C++ overloaded function (possibly with some parentheses and
  12207. /// perhaps a '&' around it). We have resolved the overloaded function
  12208. /// to the function declaration Fn, so patch up the expression E to
  12209. /// refer (possibly indirectly) to Fn. Returns the new expr.
  12210. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  12211. FunctionDecl *Fn) {
  12212. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  12213. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  12214. Found, Fn);
  12215. if (SubExpr == PE->getSubExpr())
  12216. return PE;
  12217. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  12218. }
  12219. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  12220. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  12221. Found, Fn);
  12222. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  12223. SubExpr->getType()) &&
  12224. "Implicit cast type cannot be determined from overload");
  12225. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  12226. if (SubExpr == ICE->getSubExpr())
  12227. return ICE;
  12228. return ImplicitCastExpr::Create(Context, ICE->getType(),
  12229. ICE->getCastKind(),
  12230. SubExpr, nullptr,
  12231. ICE->getValueKind());
  12232. }
  12233. if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  12234. if (!GSE->isResultDependent()) {
  12235. Expr *SubExpr =
  12236. FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
  12237. if (SubExpr == GSE->getResultExpr())
  12238. return GSE;
  12239. // Replace the resulting type information before rebuilding the generic
  12240. // selection expression.
  12241. ArrayRef<Expr *> A = GSE->getAssocExprs();
  12242. SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
  12243. unsigned ResultIdx = GSE->getResultIndex();
  12244. AssocExprs[ResultIdx] = SubExpr;
  12245. return GenericSelectionExpr::Create(
  12246. Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
  12247. GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
  12248. GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
  12249. ResultIdx);
  12250. }
  12251. // Rather than fall through to the unreachable, return the original generic
  12252. // selection expression.
  12253. return GSE;
  12254. }
  12255. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  12256. assert(UnOp->getOpcode() == UO_AddrOf &&
  12257. "Can only take the address of an overloaded function");
  12258. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  12259. if (Method->isStatic()) {
  12260. // Do nothing: static member functions aren't any different
  12261. // from non-member functions.
  12262. } else {
  12263. // Fix the subexpression, which really has to be an
  12264. // UnresolvedLookupExpr holding an overloaded member function
  12265. // or template.
  12266. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  12267. Found, Fn);
  12268. if (SubExpr == UnOp->getSubExpr())
  12269. return UnOp;
  12270. assert(isa<DeclRefExpr>(SubExpr)
  12271. && "fixed to something other than a decl ref");
  12272. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  12273. && "fixed to a member ref with no nested name qualifier");
  12274. // We have taken the address of a pointer to member
  12275. // function. Perform the computation here so that we get the
  12276. // appropriate pointer to member type.
  12277. QualType ClassType
  12278. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  12279. QualType MemPtrType
  12280. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  12281. // Under the MS ABI, lock down the inheritance model now.
  12282. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  12283. (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
  12284. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  12285. VK_RValue, OK_Ordinary,
  12286. UnOp->getOperatorLoc(), false);
  12287. }
  12288. }
  12289. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  12290. Found, Fn);
  12291. if (SubExpr == UnOp->getSubExpr())
  12292. return UnOp;
  12293. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  12294. Context.getPointerType(SubExpr->getType()),
  12295. VK_RValue, OK_Ordinary,
  12296. UnOp->getOperatorLoc(), false);
  12297. }
  12298. // C++ [except.spec]p17:
  12299. // An exception-specification is considered to be needed when:
  12300. // - in an expression the function is the unique lookup result or the
  12301. // selected member of a set of overloaded functions
  12302. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  12303. ResolveExceptionSpec(E->getExprLoc(), FPT);
  12304. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  12305. // FIXME: avoid copy.
  12306. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  12307. if (ULE->hasExplicitTemplateArgs()) {
  12308. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  12309. TemplateArgs = &TemplateArgsBuffer;
  12310. }
  12311. DeclRefExpr *DRE =
  12312. BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
  12313. ULE->getQualifierLoc(), Found.getDecl(),
  12314. ULE->getTemplateKeywordLoc(), TemplateArgs);
  12315. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  12316. return DRE;
  12317. }
  12318. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  12319. // FIXME: avoid copy.
  12320. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  12321. if (MemExpr->hasExplicitTemplateArgs()) {
  12322. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  12323. TemplateArgs = &TemplateArgsBuffer;
  12324. }
  12325. Expr *Base;
  12326. // If we're filling in a static method where we used to have an
  12327. // implicit member access, rewrite to a simple decl ref.
  12328. if (MemExpr->isImplicitAccess()) {
  12329. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  12330. DeclRefExpr *DRE = BuildDeclRefExpr(
  12331. Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
  12332. MemExpr->getQualifierLoc(), Found.getDecl(),
  12333. MemExpr->getTemplateKeywordLoc(), TemplateArgs);
  12334. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  12335. return DRE;
  12336. } else {
  12337. SourceLocation Loc = MemExpr->getMemberLoc();
  12338. if (MemExpr->getQualifier())
  12339. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  12340. Base =
  12341. BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
  12342. }
  12343. } else
  12344. Base = MemExpr->getBase();
  12345. ExprValueKind valueKind;
  12346. QualType type;
  12347. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  12348. valueKind = VK_LValue;
  12349. type = Fn->getType();
  12350. } else {
  12351. valueKind = VK_RValue;
  12352. type = Context.BoundMemberTy;
  12353. }
  12354. return BuildMemberExpr(
  12355. Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  12356. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  12357. /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
  12358. type, valueKind, OK_Ordinary, TemplateArgs);
  12359. }
  12360. llvm_unreachable("Invalid reference to overloaded function");
  12361. }
  12362. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  12363. DeclAccessPair Found,
  12364. FunctionDecl *Fn) {
  12365. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  12366. }