SemaOverload.cpp 507 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706
  1. //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file provides Sema routines for C++ overloading.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/Overload.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/TypeOrdering.h"
  21. #include "clang/Basic/Diagnostic.h"
  22. #include "clang/Basic/DiagnosticOptions.h"
  23. #include "clang/Basic/PartialDiagnostic.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/SemaInternal.h"
  28. #include "clang/Sema/Template.h"
  29. #include "clang/Sema/TemplateDeduction.h"
  30. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  31. #include "llvm/ADT/DenseSet.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include <algorithm>
  36. #include <cstdlib>
  37. using namespace clang;
  38. using namespace sema;
  39. /// A convenience routine for creating a decayed reference to a function.
  40. static ExprResult
  41. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
  42. bool HadMultipleCandidates,
  43. SourceLocation Loc = SourceLocation(),
  44. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  45. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  46. return ExprError();
  47. // If FoundDecl is different from Fn (such as if one is a template
  48. // and the other a specialization), make sure DiagnoseUseOfDecl is
  49. // called on both.
  50. // FIXME: This would be more comprehensively addressed by modifying
  51. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  52. // being used.
  53. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  54. return ExprError();
  55. DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
  56. VK_LValue, Loc, LocInfo);
  57. if (HadMultipleCandidates)
  58. DRE->setHadMultipleCandidates(true);
  59. S.MarkDeclRefReferenced(DRE);
  60. ExprResult E = DRE;
  61. E = S.DefaultFunctionArrayConversion(E.get());
  62. if (E.isInvalid())
  63. return ExprError();
  64. return E;
  65. }
  66. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  67. bool InOverloadResolution,
  68. StandardConversionSequence &SCS,
  69. bool CStyle,
  70. bool AllowObjCWritebackConversion);
  71. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  72. QualType &ToType,
  73. bool InOverloadResolution,
  74. StandardConversionSequence &SCS,
  75. bool CStyle);
  76. static OverloadingResult
  77. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  78. UserDefinedConversionSequence& User,
  79. OverloadCandidateSet& Conversions,
  80. bool AllowExplicit,
  81. bool AllowObjCConversionOnExplicit);
  82. static ImplicitConversionSequence::CompareKind
  83. CompareStandardConversionSequences(Sema &S,
  84. const StandardConversionSequence& SCS1,
  85. const StandardConversionSequence& SCS2);
  86. static ImplicitConversionSequence::CompareKind
  87. CompareQualificationConversions(Sema &S,
  88. const StandardConversionSequence& SCS1,
  89. const StandardConversionSequence& SCS2);
  90. static ImplicitConversionSequence::CompareKind
  91. CompareDerivedToBaseConversions(Sema &S,
  92. const StandardConversionSequence& SCS1,
  93. const StandardConversionSequence& SCS2);
  94. /// GetConversionRank - Retrieve the implicit conversion rank
  95. /// corresponding to the given implicit conversion kind.
  96. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  97. static const ImplicitConversionRank
  98. Rank[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  99. ICR_Exact_Match,
  100. ICR_Exact_Match,
  101. ICR_Exact_Match,
  102. ICR_Exact_Match,
  103. ICR_Exact_Match,
  104. ICR_Exact_Match,
  105. ICR_Promotion,
  106. ICR_Promotion,
  107. ICR_Promotion,
  108. ICR_Conversion,
  109. ICR_Conversion,
  110. ICR_Conversion,
  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_Complex_Real_Conversion,
  120. ICR_Conversion,
  121. ICR_Conversion,
  122. ICR_Writeback_Conversion
  123. // HLSL Change Starts: missing from original
  124. ,ICR_Conversion,
  125. // HLSL Change: new entries
  126. ICR_Conversion,
  127. ICR_Conversion,
  128. ICR_Conversion,
  129. ICR_Conversion,
  130. ICR_Conversion,
  131. ICR_Conversion,
  132. // HLSL Change Ends
  133. };
  134. static_assert(_countof(Rank) == ICK_Num_Conversion_Kinds,
  135. "Otherwise, GetConversionRank is out of sync with ImplicitConversionKind"); // HLSL Change
  136. assert((int)Kind < (int)ICK_Num_Conversion_Kinds); // HLSL Change
  137. return Rank[(int)Kind];
  138. }
  139. /// GetImplicitConversionName - Return the name of this kind of
  140. /// implicit conversion.
  141. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  142. static const char* const Name[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  143. "No conversion",
  144. "Lvalue-to-rvalue",
  145. "Array-to-pointer",
  146. "Function-to-pointer",
  147. "Noreturn adjustment",
  148. "Qualification",
  149. "Integral promotion",
  150. "Floating point promotion",
  151. "Complex promotion",
  152. "Integral conversion",
  153. "Floating conversion",
  154. "Complex conversion",
  155. "Floating-integral conversion",
  156. "Pointer conversion",
  157. "Pointer-to-member conversion",
  158. "Boolean conversion",
  159. "Compatible-types conversion",
  160. "Derived-to-base conversion",
  161. "Vector conversion",
  162. "Vector splat",
  163. "Complex-real conversion",
  164. "Block Pointer conversion",
  165. "Transparent Union Conversion",
  166. "Writeback conversion"
  167. // HLSL Change Starts
  168. ,"Zero constant to event conversion", // HLSL Change: missing value
  169. // HLSL Change: new values
  170. "HLSLVector/Matrix to scalar",
  171. "HLSLVector/Matrix conversion",
  172. "Flat assignment conversion",
  173. "HLSLVector/Matrix splat",
  174. "HLSLVector/Matrix truncation",
  175. "HLSL derived to base",
  176. // HLSL Change Ends
  177. };
  178. static_assert(_countof(Name) == ICK_Num_Conversion_Kinds,
  179. "Otherwise, GetImplicitConversionName is out of sync with ImplicitConversionKind"); // HLSL Change
  180. return Name[Kind];
  181. }
  182. /// StandardConversionSequence - Set the standard conversion
  183. /// sequence to the identity conversion.
  184. void StandardConversionSequence::setAsIdentityConversion() {
  185. First = ICK_Identity;
  186. Second = ICK_Identity;
  187. Third = ICK_Identity;
  188. DeprecatedStringLiteralToCharPtr = false;
  189. QualificationIncludesObjCLifetime = false;
  190. ReferenceBinding = false;
  191. DirectBinding = false;
  192. IsLvalueReference = true;
  193. BindsToFunctionLvalue = false;
  194. BindsToRvalue = false;
  195. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  196. ObjCLifetimeConversionBinding = false;
  197. CopyConstructor = nullptr;
  198. }
  199. /// getRank - Retrieve the rank of this standard conversion sequence
  200. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  201. /// implicit conversions.
  202. ImplicitConversionRank StandardConversionSequence::getRank() const {
  203. ImplicitConversionRank Rank = ICR_Exact_Match;
  204. if (GetConversionRank(First) > Rank)
  205. Rank = GetConversionRank(First);
  206. if (GetConversionRank(Second) > Rank)
  207. Rank = GetConversionRank(Second);
  208. if (GetConversionRank(ComponentConversion) > Rank) // HLSL Change
  209. Rank = GetConversionRank(ComponentConversion);
  210. if (GetConversionRank(Third) > Rank)
  211. Rank = GetConversionRank(Third);
  212. return Rank;
  213. }
  214. /// isPointerConversionToBool - Determines whether this conversion is
  215. /// a conversion of a pointer or pointer-to-member to bool. This is
  216. /// used as part of the ranking of standard conversion sequences
  217. /// (C++ 13.3.3.2p4).
  218. bool StandardConversionSequence::isPointerConversionToBool() const {
  219. // Note that FromType has not necessarily been transformed by the
  220. // array-to-pointer or function-to-pointer implicit conversions, so
  221. // check for their presence as well as checking whether FromType is
  222. // a pointer.
  223. if (getToType(1)->isBooleanType() &&
  224. (getFromType()->isPointerType() ||
  225. getFromType()->isObjCObjectPointerType() ||
  226. getFromType()->isBlockPointerType() ||
  227. getFromType()->isNullPtrType() ||
  228. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  229. return true;
  230. return false;
  231. }
  232. /// isPointerConversionToVoidPointer - Determines whether this
  233. /// conversion is a conversion of a pointer to a void pointer. This is
  234. /// used as part of the ranking of standard conversion sequences (C++
  235. /// 13.3.3.2p4).
  236. bool
  237. StandardConversionSequence::
  238. isPointerConversionToVoidPointer(ASTContext& Context) const {
  239. QualType FromType = getFromType();
  240. QualType ToType = getToType(1);
  241. // Note that FromType has not necessarily been transformed by the
  242. // array-to-pointer implicit conversion, so check for its presence
  243. // and redo the conversion to get a pointer.
  244. if (First == ICK_Array_To_Pointer)
  245. FromType = Context.getArrayDecayedType(FromType);
  246. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  247. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  248. return ToPtrType->getPointeeType()->isVoidType();
  249. return false;
  250. }
  251. /// Skip any implicit casts which could be either part of a narrowing conversion
  252. /// or after one in an implicit conversion.
  253. static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
  254. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  255. switch (ICE->getCastKind()) {
  256. case CK_NoOp:
  257. case CK_IntegralCast:
  258. case CK_IntegralToBoolean:
  259. case CK_IntegralToFloating:
  260. case CK_FloatingToIntegral:
  261. case CK_FloatingToBoolean:
  262. case CK_FloatingCast:
  263. Converted = ICE->getSubExpr();
  264. continue;
  265. default:
  266. return Converted;
  267. }
  268. }
  269. return Converted;
  270. }
  271. /// Check if this standard conversion sequence represents a narrowing
  272. /// conversion, according to C++11 [dcl.init.list]p7.
  273. ///
  274. /// \param Ctx The AST context.
  275. /// \param Converted The result of applying this standard conversion sequence.
  276. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  277. /// value of the expression prior to the narrowing conversion.
  278. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  279. /// type of the expression prior to the narrowing conversion.
  280. NarrowingKind
  281. StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
  282. const Expr *Converted,
  283. APValue &ConstantValue,
  284. QualType &ConstantType) const {
  285. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  286. // C++11 [dcl.init.list]p7:
  287. // A narrowing conversion is an implicit conversion ...
  288. QualType FromType = getToType(0);
  289. QualType ToType = getToType(1);
  290. switch (Second) {
  291. // 'bool' is an integral type; dispatch to the right place to handle it.
  292. case ICK_Boolean_Conversion:
  293. if (FromType->isRealFloatingType())
  294. goto FloatingIntegralConversion;
  295. if (FromType->isIntegralOrUnscopedEnumerationType())
  296. goto IntegralConversion;
  297. // Boolean conversions can be from pointers and pointers to members
  298. // [conv.bool], and those aren't considered narrowing conversions.
  299. return NK_Not_Narrowing;
  300. // -- from a floating-point type to an integer type, or
  301. //
  302. // -- from an integer type or unscoped enumeration type to a floating-point
  303. // type, except where the source is a constant expression and the actual
  304. // value after conversion will fit into the target type and will produce
  305. // the original value when converted back to the original type, or
  306. case ICK_Floating_Integral:
  307. FloatingIntegralConversion:
  308. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  309. return NK_Type_Narrowing;
  310. } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
  311. llvm::APSInt IntConstantValue;
  312. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  313. if (Initializer &&
  314. Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  315. // Convert the integer to the floating type.
  316. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  317. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  318. llvm::APFloat::rmNearestTiesToEven);
  319. // And back.
  320. llvm::APSInt ConvertedValue = IntConstantValue;
  321. bool ignored;
  322. Result.convertToInteger(ConvertedValue,
  323. llvm::APFloat::rmTowardZero, &ignored);
  324. // If the resulting value is different, this was a narrowing conversion.
  325. if (IntConstantValue != ConvertedValue) {
  326. ConstantValue = APValue(IntConstantValue);
  327. ConstantType = Initializer->getType();
  328. return NK_Constant_Narrowing;
  329. }
  330. } else {
  331. // Variables are always narrowings.
  332. return NK_Variable_Narrowing;
  333. }
  334. }
  335. return NK_Not_Narrowing;
  336. // -- from long double to double or float, or from double to float, except
  337. // where the source is a constant expression and the actual value after
  338. // conversion is within the range of values that can be represented (even
  339. // if it cannot be represented exactly), or
  340. case ICK_Floating_Conversion:
  341. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  342. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  343. // FromType is larger than ToType.
  344. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  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 (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  385. // Such conversions on variables are always narrowing.
  386. return NK_Variable_Narrowing;
  387. }
  388. bool Narrowing = false;
  389. if (FromWidth < ToWidth) {
  390. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  391. // narrowing.
  392. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  393. Narrowing = true;
  394. } else {
  395. // Add a bit to the InitializerValue so we don't have to worry about
  396. // signed vs. unsigned comparisons.
  397. InitializerValue = InitializerValue.extend(
  398. InitializerValue.getBitWidth() + 1);
  399. // Convert the initializer to and from the target width and signed-ness.
  400. llvm::APSInt ConvertedValue = InitializerValue;
  401. ConvertedValue = ConvertedValue.trunc(ToWidth);
  402. ConvertedValue.setIsSigned(ToSigned);
  403. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  404. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  405. // If the result is different, this was a narrowing conversion.
  406. if (ConvertedValue != InitializerValue)
  407. Narrowing = true;
  408. }
  409. if (Narrowing) {
  410. ConstantType = Initializer->getType();
  411. ConstantValue = APValue(InitializerValue);
  412. return NK_Constant_Narrowing;
  413. }
  414. }
  415. return NK_Not_Narrowing;
  416. }
  417. default:
  418. // Other kinds of conversions are not narrowings.
  419. return NK_Not_Narrowing;
  420. }
  421. }
  422. /// dump - Print this standard conversion sequence to standard
  423. /// error. Useful for debugging overloading issues.
  424. void StandardConversionSequence::dump() const {
  425. raw_ostream &OS = llvm::errs();
  426. bool PrintedSomething = false;
  427. if (First != ICK_Identity) {
  428. OS << GetImplicitConversionName(First);
  429. PrintedSomething = true;
  430. }
  431. if (Second != ICK_Identity) {
  432. if (PrintedSomething) {
  433. OS << " -> ";
  434. }
  435. OS << GetImplicitConversionName(Second);
  436. if (CopyConstructor) {
  437. OS << " (by copy constructor)";
  438. } else if (DirectBinding) {
  439. OS << " (direct reference binding)";
  440. } else if (ReferenceBinding) {
  441. OS << " (reference binding)";
  442. }
  443. PrintedSomething = true;
  444. }
  445. // HLSL Change Starts
  446. if (ComponentConversion != ICK_Identity) {
  447. if (PrintedSomething) {
  448. OS << " -> ";
  449. }
  450. OS << GetImplicitConversionName(ComponentConversion);
  451. PrintedSomething = true;
  452. }
  453. // HLSL Change Ends
  454. if (Third != ICK_Identity) {
  455. if (PrintedSomething) {
  456. OS << " -> ";
  457. }
  458. OS << GetImplicitConversionName(Third);
  459. PrintedSomething = true;
  460. }
  461. if (!PrintedSomething) {
  462. OS << "No conversions required";
  463. }
  464. }
  465. /// dump - Print this user-defined conversion sequence to standard
  466. /// error. Useful for debugging overloading issues.
  467. void UserDefinedConversionSequence::dump() const {
  468. raw_ostream &OS = llvm::errs();
  469. if (Before.First || Before.Second || Before.Third) {
  470. Before.dump();
  471. OS << " -> ";
  472. }
  473. if (ConversionFunction)
  474. OS << '\'' << *ConversionFunction << '\'';
  475. else
  476. OS << "aggregate initialization";
  477. if (After.First || After.Second || After.Third) {
  478. OS << " -> ";
  479. After.dump();
  480. }
  481. }
  482. /// dump - Print this implicit conversion sequence to standard
  483. /// error. Useful for debugging overloading issues.
  484. void ImplicitConversionSequence::dump() const {
  485. raw_ostream &OS = llvm::errs();
  486. if (isStdInitializerListElement())
  487. OS << "Worst std::initializer_list element conversion: ";
  488. switch (ConversionKind) {
  489. case StandardConversion:
  490. OS << "Standard conversion: ";
  491. Standard.dump();
  492. break;
  493. case UserDefinedConversion:
  494. OS << "User-defined conversion: ";
  495. UserDefined.dump();
  496. break;
  497. case EllipsisConversion:
  498. OS << "Ellipsis conversion";
  499. break;
  500. case AmbiguousConversion:
  501. OS << "Ambiguous conversion";
  502. break;
  503. case BadConversion:
  504. OS << "Bad conversion";
  505. break;
  506. }
  507. OS << "\n";
  508. }
  509. void AmbiguousConversionSequence::construct() {
  510. new (&conversions()) ConversionSet();
  511. }
  512. void AmbiguousConversionSequence::destruct() {
  513. conversions().~ConversionSet();
  514. }
  515. void
  516. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  517. FromTypePtr = O.FromTypePtr;
  518. ToTypePtr = O.ToTypePtr;
  519. new (&conversions()) ConversionSet(O.conversions());
  520. }
  521. namespace {
  522. // Structure used by DeductionFailureInfo to store
  523. // template argument information.
  524. struct DFIArguments {
  525. TemplateArgument FirstArg;
  526. TemplateArgument SecondArg;
  527. };
  528. // Structure used by DeductionFailureInfo to store
  529. // template parameter and template argument information.
  530. struct DFIParamWithArguments : DFIArguments {
  531. TemplateParameter Param;
  532. };
  533. }
  534. /// \brief 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. Result.Data = nullptr;
  544. switch (TDK) {
  545. case Sema::TDK_Success:
  546. case Sema::TDK_Invalid:
  547. case Sema::TDK_InstantiationDepth:
  548. case Sema::TDK_TooManyArguments:
  549. case Sema::TDK_TooFewArguments:
  550. break;
  551. case Sema::TDK_Incomplete:
  552. case Sema::TDK_InvalidExplicitArguments:
  553. Result.Data = Info.Param.getOpaqueValue();
  554. break;
  555. case Sema::TDK_NonDeducedMismatch: {
  556. // FIXME: Should allocate from normal heap so that we can free this later.
  557. DFIArguments *Saved = new (Context) DFIArguments;
  558. Saved->FirstArg = Info.FirstArg;
  559. Saved->SecondArg = Info.SecondArg;
  560. Result.Data = Saved;
  561. break;
  562. }
  563. case Sema::TDK_Inconsistent:
  564. case Sema::TDK_Underqualified: {
  565. // FIXME: Should allocate from normal heap so that we can free this later.
  566. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  567. Saved->Param = Info.Param;
  568. Saved->FirstArg = Info.FirstArg;
  569. Saved->SecondArg = Info.SecondArg;
  570. Result.Data = Saved;
  571. break;
  572. }
  573. case Sema::TDK_SubstitutionFailure:
  574. Result.Data = Info.take();
  575. if (Info.hasSFINAEDiagnostic()) {
  576. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  577. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  578. Info.takeSFINAEDiagnostic(*Diag);
  579. Result.HasDiagnostic = true;
  580. }
  581. break;
  582. case Sema::TDK_FailedOverloadResolution:
  583. Result.Data = Info.Expression;
  584. break;
  585. case Sema::TDK_MiscellaneousDeductionFailure:
  586. break;
  587. }
  588. return Result;
  589. }
  590. void DeductionFailureInfo::Destroy() {
  591. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  592. case Sema::TDK_Success:
  593. case Sema::TDK_Invalid:
  594. case Sema::TDK_InstantiationDepth:
  595. case Sema::TDK_Incomplete:
  596. case Sema::TDK_TooManyArguments:
  597. case Sema::TDK_TooFewArguments:
  598. case Sema::TDK_InvalidExplicitArguments:
  599. case Sema::TDK_FailedOverloadResolution:
  600. break;
  601. case Sema::TDK_Inconsistent:
  602. case Sema::TDK_Underqualified:
  603. case Sema::TDK_NonDeducedMismatch:
  604. // FIXME: Destroy the data?
  605. Data = nullptr;
  606. break;
  607. case Sema::TDK_SubstitutionFailure:
  608. // FIXME: Destroy the template argument list?
  609. Data = nullptr;
  610. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  611. Diag->~PartialDiagnosticAt();
  612. HasDiagnostic = false;
  613. }
  614. break;
  615. // Unhandled
  616. case Sema::TDK_MiscellaneousDeductionFailure:
  617. break;
  618. }
  619. }
  620. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  621. if (HasDiagnostic)
  622. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  623. return nullptr;
  624. }
  625. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  626. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  627. case Sema::TDK_Success:
  628. case Sema::TDK_Invalid:
  629. case Sema::TDK_InstantiationDepth:
  630. case Sema::TDK_TooManyArguments:
  631. case Sema::TDK_TooFewArguments:
  632. case Sema::TDK_SubstitutionFailure:
  633. case Sema::TDK_NonDeducedMismatch:
  634. case Sema::TDK_FailedOverloadResolution:
  635. return TemplateParameter();
  636. case Sema::TDK_Incomplete:
  637. case Sema::TDK_InvalidExplicitArguments:
  638. return TemplateParameter::getFromOpaqueValue(Data);
  639. case Sema::TDK_Inconsistent:
  640. case Sema::TDK_Underqualified:
  641. return static_cast<DFIParamWithArguments*>(Data)->Param;
  642. // Unhandled
  643. case Sema::TDK_MiscellaneousDeductionFailure:
  644. break;
  645. }
  646. return TemplateParameter();
  647. }
  648. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  649. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  650. case Sema::TDK_Success:
  651. case Sema::TDK_Invalid:
  652. case Sema::TDK_InstantiationDepth:
  653. case Sema::TDK_TooManyArguments:
  654. case Sema::TDK_TooFewArguments:
  655. case Sema::TDK_Incomplete:
  656. case Sema::TDK_InvalidExplicitArguments:
  657. case Sema::TDK_Inconsistent:
  658. case Sema::TDK_Underqualified:
  659. case Sema::TDK_NonDeducedMismatch:
  660. case Sema::TDK_FailedOverloadResolution:
  661. return nullptr;
  662. case Sema::TDK_SubstitutionFailure:
  663. return static_cast<TemplateArgumentList*>(Data);
  664. // Unhandled
  665. case Sema::TDK_MiscellaneousDeductionFailure:
  666. break;
  667. }
  668. return nullptr;
  669. }
  670. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  671. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  672. case Sema::TDK_Success:
  673. case Sema::TDK_Invalid:
  674. case Sema::TDK_InstantiationDepth:
  675. case Sema::TDK_Incomplete:
  676. case Sema::TDK_TooManyArguments:
  677. case Sema::TDK_TooFewArguments:
  678. case Sema::TDK_InvalidExplicitArguments:
  679. case Sema::TDK_SubstitutionFailure:
  680. case Sema::TDK_FailedOverloadResolution:
  681. return nullptr;
  682. case Sema::TDK_Inconsistent:
  683. case Sema::TDK_Underqualified:
  684. case Sema::TDK_NonDeducedMismatch:
  685. return &static_cast<DFIArguments*>(Data)->FirstArg;
  686. // Unhandled
  687. case Sema::TDK_MiscellaneousDeductionFailure:
  688. break;
  689. }
  690. return nullptr;
  691. }
  692. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  693. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  694. case Sema::TDK_Success:
  695. case Sema::TDK_Invalid:
  696. case Sema::TDK_InstantiationDepth:
  697. case Sema::TDK_Incomplete:
  698. case Sema::TDK_TooManyArguments:
  699. case Sema::TDK_TooFewArguments:
  700. case Sema::TDK_InvalidExplicitArguments:
  701. case Sema::TDK_SubstitutionFailure:
  702. case Sema::TDK_FailedOverloadResolution:
  703. return nullptr;
  704. case Sema::TDK_Inconsistent:
  705. case Sema::TDK_Underqualified:
  706. case Sema::TDK_NonDeducedMismatch:
  707. return &static_cast<DFIArguments*>(Data)->SecondArg;
  708. // Unhandled
  709. case Sema::TDK_MiscellaneousDeductionFailure:
  710. break;
  711. }
  712. return nullptr;
  713. }
  714. Expr *DeductionFailureInfo::getExpr() {
  715. if (static_cast<Sema::TemplateDeductionResult>(Result) ==
  716. Sema::TDK_FailedOverloadResolution)
  717. return static_cast<Expr*>(Data);
  718. return nullptr;
  719. }
  720. void OverloadCandidateSet::destroyCandidates() {
  721. for (iterator i = begin(), e = end(); i != e; ++i) {
  722. for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
  723. i->Conversions[ii].~ImplicitConversionSequence();
  724. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  725. i->DeductionFailure.Destroy();
  726. }
  727. }
  728. void OverloadCandidateSet::clear() {
  729. destroyCandidates();
  730. NumInlineSequences = 0;
  731. Candidates.clear();
  732. Functions.clear();
  733. }
  734. namespace {
  735. class UnbridgedCastsSet {
  736. struct Entry {
  737. Expr **Addr;
  738. Expr *Saved;
  739. };
  740. SmallVector<Entry, 2> Entries;
  741. public:
  742. void save(Sema &S, Expr *&E) {
  743. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  744. Entry entry = { &E, E };
  745. Entries.push_back(entry);
  746. E = S.stripARCUnbridgedCast(E);
  747. }
  748. void restore() {
  749. for (SmallVectorImpl<Entry>::iterator
  750. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  751. *i->Addr = i->Saved;
  752. }
  753. };
  754. }
  755. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  756. /// preprocessing on the given expression.
  757. ///
  758. /// \param unbridgedCasts a collection to which to add unbridged casts;
  759. /// without this, they will be immediately diagnosed as errors
  760. ///
  761. /// Return true on unrecoverable error.
  762. static bool
  763. checkPlaceholderForOverload(Sema &S, Expr *&E,
  764. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  765. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  766. // We can't handle overloaded expressions here because overload
  767. // resolution might reasonably tweak them.
  768. if (placeholder->getKind() == BuiltinType::Overload) return false;
  769. // If the context potentially accepts unbridged ARC casts, strip
  770. // the unbridged cast and add it to the collection for later restoration.
  771. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  772. unbridgedCasts) {
  773. unbridgedCasts->save(S, E);
  774. return false;
  775. }
  776. // Go ahead and check everything else.
  777. ExprResult result = S.CheckPlaceholderExpr(E);
  778. if (result.isInvalid())
  779. return true;
  780. E = result.get();
  781. return false;
  782. }
  783. // Nothing to do.
  784. return false;
  785. }
  786. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  787. /// placeholders.
  788. static bool checkArgPlaceholdersForOverload(Sema &S,
  789. MultiExprArg Args,
  790. UnbridgedCastsSet &unbridged) {
  791. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  792. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  793. return true;
  794. return false;
  795. }
  796. // IsOverload - Determine whether the given New declaration is an
  797. // overload of the declarations in Old. This routine returns false if
  798. // New and Old cannot be overloaded, e.g., if New has the same
  799. // signature as some function in Old (C++ 1.3.10) or if the Old
  800. // declarations aren't functions (or function templates) at all. When
  801. // it does return false, MatchedDecl will point to the decl that New
  802. // cannot be overloaded with. This decl may be a UsingShadowDecl on
  803. // top of the underlying declaration.
  804. //
  805. // Example: Given the following input:
  806. //
  807. // void f(int, float); // #1
  808. // void f(int, int); // #2
  809. // int f(int, int); // #3
  810. //
  811. // When we process #1, there is no previous declaration of "f",
  812. // so IsOverload will not be used.
  813. //
  814. // When we process #2, Old contains only the FunctionDecl for #1. By
  815. // comparing the parameter types, we see that #1 and #2 are overloaded
  816. // (since they have different signatures), so this routine returns
  817. // false; MatchedDecl is unchanged.
  818. //
  819. // When we process #3, Old is an overload set containing #1 and #2. We
  820. // compare the signatures of #3 to #1 (they're overloaded, so we do
  821. // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
  822. // identical (return types of functions are not part of the
  823. // signature), IsOverload returns false and MatchedDecl will be set to
  824. // point to the FunctionDecl for #2.
  825. //
  826. // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
  827. // into a class by a using declaration. The rules for whether to hide
  828. // shadow declarations ignore some properties which otherwise figure
  829. // into a function template's signature.
  830. Sema::OverloadKind
  831. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  832. NamedDecl *&Match, bool NewIsUsingDecl) {
  833. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  834. I != E; ++I) {
  835. NamedDecl *OldD = *I;
  836. bool OldIsUsingDecl = false;
  837. if (isa<UsingShadowDecl>(OldD)) {
  838. OldIsUsingDecl = true;
  839. // We can always introduce two using declarations into the same
  840. // context, even if they have identical signatures.
  841. if (NewIsUsingDecl) continue;
  842. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  843. }
  844. // If either declaration was introduced by a using declaration,
  845. // we'll need to use slightly different rules for matching.
  846. // Essentially, these rules are the normal rules, except that
  847. // function templates hide function templates with different
  848. // return types or template parameter lists.
  849. bool UseMemberUsingDeclRules =
  850. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  851. !New->getFriendObjectKind();
  852. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  853. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  854. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  855. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  856. continue;
  857. }
  858. if (!isa<FunctionTemplateDecl>(OldD) &&
  859. !shouldLinkPossiblyHiddenDecl(*I, New))
  860. continue;
  861. Match = *I;
  862. return Ovl_Match;
  863. }
  864. } else if (isa<UsingDecl>(OldD)) {
  865. // We can overload with these, which can show up when doing
  866. // redeclaration checks for UsingDecls.
  867. assert(Old.getLookupKind() == LookupUsingDeclName);
  868. } else if (isa<TagDecl>(OldD)) {
  869. // We can always overload with tags by hiding them.
  870. } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
  871. // Optimistically assume that an unresolved using decl will
  872. // overload; if it doesn't, we'll have to diagnose during
  873. // template instantiation.
  874. } else {
  875. // (C++ 13p1):
  876. // Only function declarations can be overloaded; object and type
  877. // declarations cannot be overloaded.
  878. Match = *I;
  879. return Ovl_NonFunction;
  880. }
  881. }
  882. return Ovl_Overload;
  883. }
  884. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  885. bool UseUsingDeclRules) {
  886. // C++ [basic.start.main]p2: This function shall not be overloaded.
  887. if (New->isMain())
  888. return false;
  889. // MSVCRT user defined entry points cannot be overloaded.
  890. if (New->isMSVCRTEntryPoint())
  891. return false;
  892. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  893. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  894. // C++ [temp.fct]p2:
  895. // A function template can be overloaded with other function templates
  896. // and with normal (non-template) functions.
  897. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  898. return true;
  899. // Is the function New an overload of the function Old?
  900. QualType OldQType = Context.getCanonicalType(Old->getType());
  901. QualType NewQType = Context.getCanonicalType(New->getType());
  902. // Compare the signatures (C++ 1.3.10) of the two functions to
  903. // determine whether they are overloads. If we find any mismatch
  904. // in the signature, they are overloads.
  905. // If either of these functions is a K&R-style function (no
  906. // prototype), then we consider them to have matching signatures.
  907. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  908. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  909. return false;
  910. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  911. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  912. // The signature of a function includes the types of its
  913. // parameters (C++ 1.3.10), which includes the presence or absence
  914. // of the ellipsis; see C++ DR 357).
  915. if (OldQType != NewQType &&
  916. (OldType->getNumParams() != NewType->getNumParams() ||
  917. OldType->isVariadic() != NewType->isVariadic() ||
  918. !FunctionParamTypesAreEqual(OldType, NewType)))
  919. return true;
  920. // C++ [temp.over.link]p4:
  921. // The signature of a function template consists of its function
  922. // signature, its return type and its template parameter list. The names
  923. // of the template parameters are significant only for establishing the
  924. // relationship between the template parameters and the rest of the
  925. // signature.
  926. //
  927. // We check the return type and template parameter lists for function
  928. // templates first; the remaining checks follow.
  929. //
  930. // However, we don't consider either of these when deciding whether
  931. // a member introduced by a shadow declaration is hidden.
  932. if (!UseUsingDeclRules && NewTemplate &&
  933. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  934. OldTemplate->getTemplateParameters(),
  935. false, TPL_TemplateMatch) ||
  936. OldType->getReturnType() != NewType->getReturnType()))
  937. return true;
  938. // If the function is a class member, its signature includes the
  939. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  940. //
  941. // As part of this, also check whether one of the member functions
  942. // is static, in which case they are not overloads (C++
  943. // 13.1p2). While not part of the definition of the signature,
  944. // this check is important to determine whether these functions
  945. // can be overloaded.
  946. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  947. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  948. if (OldMethod && NewMethod &&
  949. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  950. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  951. if (!UseUsingDeclRules &&
  952. (OldMethod->getRefQualifier() == RQ_None ||
  953. NewMethod->getRefQualifier() == RQ_None)) {
  954. // C++0x [over.load]p2:
  955. // - Member function declarations with the same name and the same
  956. // parameter-type-list as well as member function template
  957. // declarations with the same name, the same parameter-type-list, and
  958. // the same template parameter lists cannot be overloaded if any of
  959. // them, but not all, have a ref-qualifier (8.3.5).
  960. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  961. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  962. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  963. }
  964. return true;
  965. }
  966. // We may not have applied the implicit const for a constexpr member
  967. // function yet (because we haven't yet resolved whether this is a static
  968. // or non-static member function). Add it now, on the assumption that this
  969. // is a redeclaration of OldMethod.
  970. unsigned OldQuals = OldMethod->getTypeQualifiers();
  971. unsigned NewQuals = NewMethod->getTypeQualifiers();
  972. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  973. !isa<CXXConstructorDecl>(NewMethod))
  974. NewQuals |= Qualifiers::Const;
  975. // We do not allow overloading based off of '__restrict'.
  976. OldQuals &= ~Qualifiers::Restrict;
  977. NewQuals &= ~Qualifiers::Restrict;
  978. if (OldQuals != NewQuals)
  979. return true;
  980. }
  981. // enable_if attributes are an order-sensitive part of the signature.
  982. for (specific_attr_iterator<EnableIfAttr>
  983. NewI = New->specific_attr_begin<EnableIfAttr>(),
  984. NewE = New->specific_attr_end<EnableIfAttr>(),
  985. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  986. OldE = Old->specific_attr_end<EnableIfAttr>();
  987. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  988. if (NewI == NewE || OldI == OldE)
  989. return true;
  990. llvm::FoldingSetNodeID NewID, OldID;
  991. NewI->getCond()->Profile(NewID, Context, true);
  992. OldI->getCond()->Profile(OldID, Context, true);
  993. if (NewID != OldID)
  994. return true;
  995. }
  996. // The signatures match; this is not an overload.
  997. return false;
  998. }
  999. /// \brief Checks availability of the function depending on the current
  1000. /// function context. Inside an unavailable function, unavailability is ignored.
  1001. ///
  1002. /// \returns true if \arg FD is unavailable and current context is inside
  1003. /// an available function, false otherwise.
  1004. bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
  1005. return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
  1006. }
  1007. /// \brief Tries a user-defined conversion from From to ToType.
  1008. ///
  1009. /// Produces an implicit conversion sequence for when a standard conversion
  1010. /// is not an option. See TryImplicitConversion for more information.
  1011. static ImplicitConversionSequence
  1012. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1013. bool SuppressUserConversions,
  1014. bool AllowExplicit,
  1015. bool InOverloadResolution,
  1016. bool CStyle,
  1017. bool AllowObjCWritebackConversion,
  1018. bool AllowObjCConversionOnExplicit) {
  1019. ImplicitConversionSequence ICS;
  1020. if (SuppressUserConversions || S.getLangOpts().HLSL) { // HLSL Change - no user conversions
  1021. // We're not in the case above, so there is no conversion that
  1022. // we can perform.
  1023. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1024. return ICS;
  1025. }
  1026. // Attempt user-defined conversion.
  1027. OverloadCandidateSet Conversions(From->getExprLoc(),
  1028. OverloadCandidateSet::CSK_Normal);
  1029. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1030. Conversions, AllowExplicit,
  1031. AllowObjCConversionOnExplicit)) {
  1032. case OR_Success:
  1033. case OR_Deleted:
  1034. ICS.setUserDefined();
  1035. ICS.UserDefined.Before.setAsIdentityConversion();
  1036. // C++ [over.ics.user]p4:
  1037. // A conversion of an expression of class type to the same class
  1038. // type is given Exact Match rank, and a conversion of an
  1039. // expression of class type to a base class of that type is
  1040. // given Conversion rank, in spite of the fact that a copy
  1041. // constructor (i.e., a user-defined conversion function) is
  1042. // called for those cases.
  1043. if (CXXConstructorDecl *Constructor
  1044. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1045. QualType FromCanon
  1046. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1047. QualType ToCanon
  1048. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1049. if (Constructor->isCopyConstructor() &&
  1050. (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
  1051. // Turn this into a "standard" conversion sequence, so that it
  1052. // gets ranked with standard conversion sequences.
  1053. ICS.setStandard();
  1054. ICS.Standard.setAsIdentityConversion();
  1055. ICS.Standard.setFromType(From->getType());
  1056. ICS.Standard.setAllToTypes(ToType);
  1057. ICS.Standard.CopyConstructor = Constructor;
  1058. if (ToCanon != FromCanon)
  1059. ICS.Standard.Second = ICK_Derived_To_Base;
  1060. }
  1061. }
  1062. break;
  1063. case OR_Ambiguous:
  1064. ICS.setAmbiguous();
  1065. ICS.Ambiguous.setFromType(From->getType());
  1066. ICS.Ambiguous.setToType(ToType);
  1067. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1068. Cand != Conversions.end(); ++Cand)
  1069. if (Cand->Viable)
  1070. ICS.Ambiguous.addConversion(Cand->Function);
  1071. break;
  1072. // Fall through.
  1073. case OR_No_Viable_Function:
  1074. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1075. break;
  1076. }
  1077. return ICS;
  1078. }
  1079. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1080. /// from the given expression (Expr) to the given type (ToType). This
  1081. /// function returns an implicit conversion sequence that can be used
  1082. /// to perform the initialization. Given
  1083. ///
  1084. /// void f(float f);
  1085. /// void g(int i) { f(i); }
  1086. ///
  1087. /// this routine would produce an implicit conversion sequence to
  1088. /// describe the initialization of f from i, which will be a standard
  1089. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1090. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1091. //
  1092. /// Note that this routine only determines how the conversion can be
  1093. /// performed; it does not actually perform the conversion. As such,
  1094. /// it will not produce any diagnostics if no conversion is available,
  1095. /// but will instead return an implicit conversion sequence of kind
  1096. /// "BadConversion".
  1097. ///
  1098. /// If @p SuppressUserConversions, then user-defined conversions are
  1099. /// not permitted.
  1100. /// If @p AllowExplicit, then explicit user-defined conversions are
  1101. /// permitted.
  1102. ///
  1103. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1104. /// writeback conversion, which allows __autoreleasing id* parameters to
  1105. /// be initialized with __strong id* or __weak id* arguments.
  1106. static ImplicitConversionSequence
  1107. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1108. bool SuppressUserConversions,
  1109. bool AllowExplicit,
  1110. bool InOverloadResolution,
  1111. bool CStyle,
  1112. bool AllowObjCWritebackConversion,
  1113. bool AllowObjCConversionOnExplicit) {
  1114. ImplicitConversionSequence ICS;
  1115. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1116. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1117. ICS.setStandard();
  1118. return ICS;
  1119. }
  1120. if (!S.getLangOpts().CPlusPlus) {
  1121. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1122. return ICS;
  1123. }
  1124. // C++ [over.ics.user]p4:
  1125. // A conversion of an expression of class type to the same class
  1126. // type is given Exact Match rank, and a conversion of an
  1127. // expression of class type to a base class of that type is
  1128. // given Conversion rank, in spite of the fact that a copy/move
  1129. // constructor (i.e., a user-defined conversion function) is
  1130. // called for those cases.
  1131. QualType FromType = From->getType();
  1132. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1133. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1134. S.IsDerivedFrom(FromType, ToType))) {
  1135. ICS.setStandard();
  1136. ICS.Standard.setAsIdentityConversion();
  1137. ICS.Standard.setFromType(FromType);
  1138. ICS.Standard.setAllToTypes(ToType);
  1139. // We don't actually check at this point whether there is a valid
  1140. // copy/move constructor, since overloading just assumes that it
  1141. // exists. When we actually perform initialization, we'll find the
  1142. // appropriate constructor to copy the returned object, if needed.
  1143. ICS.Standard.CopyConstructor = nullptr;
  1144. // Determine whether this is considered a derived-to-base conversion.
  1145. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1146. ICS.Standard.Second = ICK_Derived_To_Base;
  1147. return ICS;
  1148. }
  1149. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1150. AllowExplicit, InOverloadResolution, CStyle,
  1151. AllowObjCWritebackConversion,
  1152. AllowObjCConversionOnExplicit);
  1153. }
  1154. ImplicitConversionSequence
  1155. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1156. bool SuppressUserConversions,
  1157. bool AllowExplicit,
  1158. bool InOverloadResolution,
  1159. bool CStyle,
  1160. bool AllowObjCWritebackConversion) {
  1161. return ::TryImplicitConversion(*this, From, ToType,
  1162. SuppressUserConversions, AllowExplicit,
  1163. InOverloadResolution, CStyle,
  1164. AllowObjCWritebackConversion,
  1165. /*AllowObjCConversionOnExplicit=*/false);
  1166. }
  1167. /// PerformImplicitConversion - Perform an implicit conversion of the
  1168. /// expression From to the type ToType. Returns the
  1169. /// converted expression. Flavor is the kind of conversion we're
  1170. /// performing, used in the error message. If @p AllowExplicit,
  1171. /// explicit user-defined conversions are permitted.
  1172. ExprResult
  1173. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1174. AssignmentAction Action, bool AllowExplicit) {
  1175. ImplicitConversionSequence ICS;
  1176. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1177. }
  1178. ExprResult
  1179. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1180. AssignmentAction Action, bool AllowExplicit,
  1181. ImplicitConversionSequence& ICS) {
  1182. if (checkPlaceholderForOverload(*this, From))
  1183. return ExprError();
  1184. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1185. bool AllowObjCWritebackConversion
  1186. = getLangOpts().ObjCAutoRefCount &&
  1187. (Action == AA_Passing || Action == AA_Sending);
  1188. if (getLangOpts().ObjC1)
  1189. CheckObjCBridgeRelatedConversions(From->getLocStart(),
  1190. ToType, From->getType(), From);
  1191. ICS = ::TryImplicitConversion(*this, From, ToType,
  1192. /*SuppressUserConversions=*/false,
  1193. AllowExplicit,
  1194. /*InOverloadResolution=*/false,
  1195. /*CStyle=*/false,
  1196. AllowObjCWritebackConversion,
  1197. /*AllowObjCConversionOnExplicit=*/false);
  1198. return PerformImplicitConversion(From, ToType, ICS, Action);
  1199. }
  1200. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1201. /// conversion that strips "noreturn" off the nested function type.
  1202. bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
  1203. QualType &ResultTy) {
  1204. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1205. return false;
  1206. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1207. // where F adds one of the following at most once:
  1208. // - a pointer
  1209. // - a member pointer
  1210. // - a block pointer
  1211. CanQualType CanTo = Context.getCanonicalType(ToType);
  1212. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1213. Type::TypeClass TyClass = CanTo->getTypeClass();
  1214. if (TyClass != CanFrom->getTypeClass()) return false;
  1215. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1216. if (TyClass == Type::Pointer) {
  1217. CanTo = CanTo.getAs<PointerType>()->getPointeeType();
  1218. CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
  1219. } else if (TyClass == Type::BlockPointer) {
  1220. CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
  1221. CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
  1222. } else if (TyClass == Type::MemberPointer) {
  1223. CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
  1224. CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
  1225. } else {
  1226. return false;
  1227. }
  1228. TyClass = CanTo->getTypeClass();
  1229. if (TyClass != CanFrom->getTypeClass()) return false;
  1230. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1231. return false;
  1232. }
  1233. const FunctionType *FromFn = cast<FunctionType>(CanFrom);
  1234. FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
  1235. if (!EInfo.getNoReturn()) return false;
  1236. FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
  1237. assert(QualType(FromFn, 0).isCanonical());
  1238. if (QualType(FromFn, 0) != CanTo) return false;
  1239. ResultTy = ToType;
  1240. return true;
  1241. }
  1242. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1243. /// vector conversion.
  1244. ///
  1245. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1246. /// conversion.
  1247. static bool IsVectorConversion(Sema &S, QualType FromType,
  1248. QualType ToType, ImplicitConversionKind &ICK) {
  1249. // We need at least one of these types to be a vector type to have a vector
  1250. // conversion.
  1251. if (!ToType->isVectorType() && !FromType->isVectorType())
  1252. return false;
  1253. // Identical types require no conversions.
  1254. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1255. return false;
  1256. // There are no conversions between extended vector types, only identity.
  1257. if (ToType->isExtVectorType()) {
  1258. // There are no conversions between extended vector types other than the
  1259. // identity conversion.
  1260. if (FromType->isExtVectorType())
  1261. return false;
  1262. // Vector splat from any arithmetic type to a vector.
  1263. if (FromType->isArithmeticType()) {
  1264. ICK = ICK_Vector_Splat;
  1265. return true;
  1266. }
  1267. }
  1268. // We can perform the conversion between vector types in the following cases:
  1269. // 1)vector types are equivalent AltiVec and GCC vector types
  1270. // 2)lax vector conversions are permitted and the vector types are of the
  1271. // same size
  1272. if (ToType->isVectorType() && FromType->isVectorType()) {
  1273. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1274. S.isLaxVectorConversion(FromType, ToType)) {
  1275. ICK = ICK_Vector_Conversion;
  1276. return true;
  1277. }
  1278. }
  1279. return false;
  1280. }
  1281. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1282. bool InOverloadResolution,
  1283. StandardConversionSequence &SCS,
  1284. bool CStyle);
  1285. /// IsStandardConversion - Determines whether there is a standard
  1286. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1287. /// expression From to the type ToType. Standard conversion sequences
  1288. /// only consider non-class types; for conversions that involve class
  1289. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1290. /// contain the standard conversion sequence required to perform this
  1291. /// conversion and this routine will return true. Otherwise, this
  1292. /// routine will return false and the value of SCS is unspecified.
  1293. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1294. bool InOverloadResolution,
  1295. StandardConversionSequence &SCS,
  1296. bool CStyle,
  1297. bool AllowObjCWritebackConversion) {
  1298. QualType FromType = From->getType();
  1299. // Standard conversions (C++ [conv])
  1300. SCS.setAsIdentityConversion();
  1301. SCS.IncompatibleObjC = false;
  1302. SCS.setFromType(FromType);
  1303. SCS.CopyConstructor = nullptr;
  1304. // HLSL Change Begins
  1305. if (S.getLangOpts().HLSL) {
  1306. return hlsl::CanConvert(&S, SourceLocation(), From, ToType, /*explicitConversion=*/false, &SCS);
  1307. }
  1308. // HLSL Change Ends
  1309. // There are no standard conversions for class types in C++, so
  1310. // abort early. When overloading in C, however, we do permit
  1311. if (FromType->isRecordType() || ToType->isRecordType()) {
  1312. if (S.getLangOpts().CPlusPlus)
  1313. return false;
  1314. // When we're overloading in C, we allow, as standard conversions,
  1315. }
  1316. // The first conversion can be an lvalue-to-rvalue conversion,
  1317. // array-to-pointer conversion, or function-to-pointer conversion
  1318. // (C++ 4p1).
  1319. if (FromType == S.Context.OverloadTy) {
  1320. DeclAccessPair AccessPair;
  1321. if (FunctionDecl *Fn
  1322. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1323. AccessPair)) {
  1324. // We were able to resolve the address of the overloaded function,
  1325. // so we can convert to the type of that function.
  1326. FromType = Fn->getType();
  1327. SCS.setFromType(FromType);
  1328. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1329. // if the type matches (identity) or we are converting to bool
  1330. if (!S.Context.hasSameUnqualifiedType(
  1331. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1332. QualType resultTy;
  1333. // if the function type matches except for [[noreturn]], it's ok
  1334. if (!S.IsNoReturnConversion(FromType,
  1335. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1336. // otherwise, only a boolean conversion is standard
  1337. if (!ToType->isBooleanType())
  1338. return false;
  1339. }
  1340. // Check if the "from" expression is taking the address of an overloaded
  1341. // function and recompute the FromType accordingly. Take advantage of the
  1342. // fact that non-static member functions *must* have such an address-of
  1343. // expression.
  1344. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1345. if (Method && !Method->isStatic()) {
  1346. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1347. "Non-unary operator on non-static member address");
  1348. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1349. == UO_AddrOf &&
  1350. "Non-address-of operator on non-static member address");
  1351. const Type *ClassType
  1352. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1353. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1354. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1355. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1356. UO_AddrOf &&
  1357. "Non-address-of operator for overloaded function expression");
  1358. FromType = S.Context.getPointerType(FromType);
  1359. }
  1360. // Check that we've computed the proper type after overload resolution.
  1361. assert(S.Context.hasSameType(
  1362. FromType,
  1363. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1364. } else {
  1365. return false;
  1366. }
  1367. }
  1368. // Lvalue-to-rvalue conversion (C++11 4.1):
  1369. // A glvalue (3.10) of a non-function, non-array type T can
  1370. // be converted to a prvalue.
  1371. bool argIsLValue = From->isGLValue();
  1372. if (argIsLValue &&
  1373. !FromType->isFunctionType() && (!FromType->isArrayType() || S.getLangOpts().HLSL) && // HLSL Change - HLSL allows arrays
  1374. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1375. SCS.First = ICK_Lvalue_To_Rvalue;
  1376. // C11 6.3.2.1p2:
  1377. // ... if the lvalue has atomic type, the value has the non-atomic version
  1378. // of the type of the lvalue ...
  1379. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1380. FromType = Atomic->getValueType();
  1381. // If T is a non-class type, the type of the rvalue is the
  1382. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1383. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1384. // just strip the qualifiers because they don't matter.
  1385. FromType = FromType.getUnqualifiedType();
  1386. } else if (FromType->isArrayType()) {
  1387. // Array-to-pointer conversion (C++ 4.2)
  1388. SCS.First = ICK_Array_To_Pointer;
  1389. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1390. // bound of T" can be converted to an rvalue of type "pointer to
  1391. // T" (C++ 4.2p1).
  1392. FromType = S.Context.getArrayDecayedType(FromType);
  1393. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1394. // This conversion is deprecated in C++03 (D.4)
  1395. SCS.DeprecatedStringLiteralToCharPtr = true;
  1396. // For the purpose of ranking in overload resolution
  1397. // (13.3.3.1.1), this conversion is considered an
  1398. // array-to-pointer conversion followed by a qualification
  1399. // conversion (4.4). (C++ 4.2p2)
  1400. SCS.Second = ICK_Identity;
  1401. SCS.Third = ICK_Qualification;
  1402. SCS.QualificationIncludesObjCLifetime = false;
  1403. SCS.setAllToTypes(FromType);
  1404. return true;
  1405. }
  1406. } else if (FromType->isFunctionType() && argIsLValue) {
  1407. // Function-to-pointer conversion (C++ 4.3).
  1408. SCS.First = ICK_Function_To_Pointer;
  1409. // An lvalue of function type T can be converted to an rvalue of
  1410. // type "pointer to T." The result is a pointer to the
  1411. // function. (C++ 4.3p1).
  1412. FromType = S.Context.getPointerType(FromType);
  1413. } else {
  1414. // We don't require any conversions for the first step.
  1415. SCS.First = ICK_Identity;
  1416. }
  1417. SCS.setToType(0, FromType);
  1418. // The second conversion can be an integral promotion, floating
  1419. // point promotion, integral conversion, floating point conversion,
  1420. // floating-integral conversion, pointer conversion,
  1421. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1422. // For overloading in C, this can also be a "compatible-type"
  1423. // conversion.
  1424. bool IncompatibleObjC = false;
  1425. ImplicitConversionKind SecondICK = ICK_Identity;
  1426. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1427. // The unqualified versions of the types are the same: there's no
  1428. // conversion to do.
  1429. SCS.Second = ICK_Identity;
  1430. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1431. // Integral promotion (C++ 4.5).
  1432. SCS.Second = ICK_Integral_Promotion;
  1433. FromType = ToType.getUnqualifiedType();
  1434. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1435. // Floating point promotion (C++ 4.6).
  1436. SCS.Second = ICK_Floating_Promotion;
  1437. FromType = ToType.getUnqualifiedType();
  1438. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1439. // Complex promotion (Clang extension)
  1440. SCS.Second = ICK_Complex_Promotion;
  1441. FromType = ToType.getUnqualifiedType();
  1442. } else if (ToType->isBooleanType() &&
  1443. (FromType->isArithmeticType() ||
  1444. FromType->isAnyPointerType() ||
  1445. FromType->isBlockPointerType() ||
  1446. FromType->isMemberPointerType() ||
  1447. FromType->isNullPtrType())) {
  1448. // Boolean conversions (C++ 4.12).
  1449. SCS.Second = ICK_Boolean_Conversion;
  1450. FromType = S.Context.BoolTy;
  1451. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1452. ToType->isIntegralType(S.Context)) {
  1453. // Integral conversions (C++ 4.7).
  1454. SCS.Second = ICK_Integral_Conversion;
  1455. FromType = ToType.getUnqualifiedType();
  1456. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1457. // Complex conversions (C99 6.3.1.6)
  1458. SCS.Second = ICK_Complex_Conversion;
  1459. FromType = ToType.getUnqualifiedType();
  1460. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1461. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1462. // Complex-real conversions (C99 6.3.1.7)
  1463. SCS.Second = ICK_Complex_Real;
  1464. FromType = ToType.getUnqualifiedType();
  1465. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1466. // Floating point conversions (C++ 4.8).
  1467. SCS.Second = ICK_Floating_Conversion;
  1468. FromType = ToType.getUnqualifiedType();
  1469. } else if ((FromType->isRealFloatingType() &&
  1470. ToType->isIntegralType(S.Context)) ||
  1471. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1472. ToType->isRealFloatingType())) {
  1473. // Floating-integral conversions (C++ 4.9).
  1474. SCS.Second = ICK_Floating_Integral;
  1475. FromType = ToType.getUnqualifiedType();
  1476. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1477. SCS.Second = ICK_Block_Pointer_Conversion;
  1478. } else if (AllowObjCWritebackConversion &&
  1479. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1480. SCS.Second = ICK_Writeback_Conversion;
  1481. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1482. FromType, IncompatibleObjC)) {
  1483. // Pointer conversions (C++ 4.10).
  1484. SCS.Second = ICK_Pointer_Conversion;
  1485. SCS.IncompatibleObjC = IncompatibleObjC;
  1486. FromType = FromType.getUnqualifiedType();
  1487. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1488. InOverloadResolution, FromType)) {
  1489. // Pointer to member conversions (4.11).
  1490. SCS.Second = ICK_Pointer_Member;
  1491. } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
  1492. SCS.Second = SecondICK;
  1493. FromType = ToType.getUnqualifiedType();
  1494. } else if (!S.getLangOpts().CPlusPlus &&
  1495. S.Context.typesAreCompatible(ToType, FromType)) {
  1496. // Compatible conversions (Clang extension for C function overloading)
  1497. SCS.Second = ICK_Compatible_Conversion;
  1498. FromType = ToType.getUnqualifiedType();
  1499. } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
  1500. // Treat a conversion that strips "noreturn" as an identity conversion.
  1501. SCS.Second = ICK_NoReturn_Adjustment;
  1502. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1503. InOverloadResolution,
  1504. SCS, CStyle)) {
  1505. SCS.Second = ICK_TransparentUnionConversion;
  1506. FromType = ToType;
  1507. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1508. CStyle)) {
  1509. // tryAtomicConversion has updated the standard conversion sequence
  1510. // appropriately.
  1511. return true;
  1512. } else if (ToType->isEventT() &&
  1513. From->isIntegerConstantExpr(S.getASTContext()) &&
  1514. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1515. SCS.Second = ICK_Zero_Event_Conversion;
  1516. FromType = ToType;
  1517. } else {
  1518. // No second conversion required.
  1519. SCS.Second = ICK_Identity;
  1520. }
  1521. SCS.setToType(1, FromType);
  1522. QualType CanonFrom;
  1523. QualType CanonTo;
  1524. // The third conversion can be a qualification conversion (C++ 4p1).
  1525. bool ObjCLifetimeConversion;
  1526. if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1527. ObjCLifetimeConversion)) {
  1528. SCS.Third = ICK_Qualification;
  1529. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1530. FromType = ToType;
  1531. CanonFrom = S.Context.getCanonicalType(FromType);
  1532. CanonTo = S.Context.getCanonicalType(ToType);
  1533. } else {
  1534. // No conversion required
  1535. SCS.Third = ICK_Identity;
  1536. // C++ [over.best.ics]p6:
  1537. // [...] Any difference in top-level cv-qualification is
  1538. // subsumed by the initialization itself and does not constitute
  1539. // a conversion. [...]
  1540. CanonFrom = S.Context.getCanonicalType(FromType);
  1541. CanonTo = S.Context.getCanonicalType(ToType);
  1542. if (CanonFrom.getLocalUnqualifiedType()
  1543. == CanonTo.getLocalUnqualifiedType() &&
  1544. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1545. FromType = ToType;
  1546. CanonFrom = CanonTo;
  1547. }
  1548. }
  1549. SCS.setToType(2, FromType);
  1550. // If we have not converted the argument type to the parameter type,
  1551. // this is a bad conversion sequence.
  1552. if (CanonFrom != CanonTo)
  1553. return false;
  1554. return true;
  1555. }
  1556. static bool
  1557. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1558. QualType &ToType,
  1559. bool InOverloadResolution,
  1560. StandardConversionSequence &SCS,
  1561. bool CStyle) {
  1562. const RecordType *UT = ToType->getAsUnionType();
  1563. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1564. return false;
  1565. // The field to initialize within the transparent union.
  1566. RecordDecl *UD = UT->getDecl();
  1567. // It's compatible if the expression matches any of the fields.
  1568. for (const auto *it : UD->fields()) {
  1569. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1570. CStyle, /*ObjCWritebackConversion=*/false)) {
  1571. ToType = it->getType();
  1572. return true;
  1573. }
  1574. }
  1575. return false;
  1576. }
  1577. /// IsIntegralPromotion - Determines whether the conversion from the
  1578. /// expression From (whose potentially-adjusted type is FromType) to
  1579. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1580. /// sets PromotedType to the promoted type.
  1581. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1582. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1583. // All integers are built-in.
  1584. if (!To) {
  1585. return false;
  1586. }
  1587. // An rvalue of type char, signed char, unsigned char, short int, or
  1588. // unsigned short int can be converted to an rvalue of type int if
  1589. // int can represent all the values of the source type; otherwise,
  1590. // the source rvalue can be converted to an rvalue of type unsigned
  1591. // int (C++ 4.5p1).
  1592. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1593. !FromType->isEnumeralType()) {
  1594. if (// We can promote any signed, promotable integer type to an int
  1595. (FromType->isSignedIntegerType() ||
  1596. // We can promote any unsigned integer type whose size is
  1597. // less than int to an int.
  1598. (!FromType->isSignedIntegerType() &&
  1599. Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
  1600. return To->getKind() == BuiltinType::Int;
  1601. }
  1602. return To->getKind() == BuiltinType::UInt;
  1603. }
  1604. // C++11 [conv.prom]p3:
  1605. // A prvalue of an unscoped enumeration type whose underlying type is not
  1606. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1607. // following types that can represent all the values of the enumeration
  1608. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1609. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1610. // long long int. If none of the types in that list can represent all the
  1611. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1612. // type can be converted to an rvalue a prvalue of the extended integer type
  1613. // with lowest integer conversion rank (4.13) greater than the rank of long
  1614. // long in which all the values of the enumeration can be represented. If
  1615. // there are two such extended types, the signed one is chosen.
  1616. // C++11 [conv.prom]p4:
  1617. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  1618. // can be converted to a prvalue of its underlying type. Moreover, if
  1619. // integral promotion can be applied to its underlying type, a prvalue of an
  1620. // unscoped enumeration type whose underlying type is fixed can also be
  1621. // converted to a prvalue of the promoted underlying type.
  1622. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1623. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1624. // provided for a scoped enumeration.
  1625. if (FromEnumType->getDecl()->isScoped())
  1626. return false;
  1627. // We can perform an integral promotion to the underlying type of the enum,
  1628. // even if that's not the promoted type. Note that the check for promoting
  1629. // the underlying type is based on the type alone, and does not consider
  1630. // the bitfield-ness of the actual source expression.
  1631. if (FromEnumType->getDecl()->isFixed()) {
  1632. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  1633. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  1634. IsIntegralPromotion(nullptr, Underlying, ToType);
  1635. }
  1636. // We have already pre-calculated the promotion type, so this is trivial.
  1637. if (ToType->isIntegerType() &&
  1638. !RequireCompleteType(From->getLocStart(), FromType, 0))
  1639. return Context.hasSameUnqualifiedType(
  1640. ToType, FromEnumType->getDecl()->getPromotionType());
  1641. }
  1642. // C++0x [conv.prom]p2:
  1643. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1644. // to an rvalue a prvalue of the first of the following types that can
  1645. // represent all the values of its underlying type: int, unsigned int,
  1646. // long int, unsigned long int, long long int, or unsigned long long int.
  1647. // If none of the types in that list can represent all the values of its
  1648. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1649. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1650. // type.
  1651. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1652. ToType->isIntegerType()) {
  1653. // Determine whether the type we're converting from is signed or
  1654. // unsigned.
  1655. bool FromIsSigned = FromType->isSignedIntegerType();
  1656. uint64_t FromSize = Context.getTypeSize(FromType);
  1657. // The types we'll try to promote to, in the appropriate
  1658. // order. Try each of these types.
  1659. QualType PromoteTypes[6] = {
  1660. Context.IntTy, Context.UnsignedIntTy,
  1661. Context.LongTy, Context.UnsignedLongTy ,
  1662. Context.LongLongTy, Context.UnsignedLongLongTy
  1663. };
  1664. for (int Idx = 0; Idx < 6; ++Idx) {
  1665. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1666. if (FromSize < ToSize ||
  1667. (FromSize == ToSize &&
  1668. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1669. // We found the type that we can promote to. If this is the
  1670. // type we wanted, we have a promotion. Otherwise, no
  1671. // promotion.
  1672. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1673. }
  1674. }
  1675. }
  1676. // An rvalue for an integral bit-field (9.6) can be converted to an
  1677. // rvalue of type int if int can represent all the values of the
  1678. // bit-field; otherwise, it can be converted to unsigned int if
  1679. // unsigned int can represent all the values of the bit-field. If
  1680. // the bit-field is larger yet, no integral promotion applies to
  1681. // it. If the bit-field has an enumerated type, it is treated as any
  1682. // other value of that type for promotion purposes (C++ 4.5p3).
  1683. // FIXME: We should delay checking of bit-fields until we actually perform the
  1684. // conversion.
  1685. if (From) {
  1686. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  1687. llvm::APSInt BitWidth;
  1688. if (FromType->isIntegralType(Context) &&
  1689. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1690. llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1691. ToSize = Context.getTypeSize(ToType);
  1692. // Are we promoting to an int from a bitfield that fits in an int?
  1693. if (BitWidth < ToSize ||
  1694. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1695. return To->getKind() == BuiltinType::Int;
  1696. }
  1697. // Are we promoting to an unsigned int from an unsigned bitfield
  1698. // that fits into an unsigned int?
  1699. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1700. return To->getKind() == BuiltinType::UInt;
  1701. }
  1702. return false;
  1703. }
  1704. }
  1705. }
  1706. // An rvalue of type bool can be converted to an rvalue of type int,
  1707. // with false becoming zero and true becoming one (C++ 4.5p4).
  1708. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1709. return true;
  1710. }
  1711. return false;
  1712. }
  1713. /// IsFloatingPointPromotion - Determines whether the conversion from
  1714. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1715. /// returns true and sets PromotedType to the promoted type.
  1716. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1717. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1718. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1719. /// An rvalue of type float can be converted to an rvalue of type
  1720. /// double. (C++ 4.6p1).
  1721. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1722. ToBuiltin->getKind() == BuiltinType::Double)
  1723. return true;
  1724. // C99 6.3.1.5p1:
  1725. // When a float is promoted to double or long double, or a
  1726. // double is promoted to long double [...].
  1727. if (!getLangOpts().CPlusPlus &&
  1728. (FromBuiltin->getKind() == BuiltinType::Float ||
  1729. FromBuiltin->getKind() == BuiltinType::Double) &&
  1730. (ToBuiltin->getKind() == BuiltinType::LongDouble))
  1731. return true;
  1732. // Half can be promoted to float.
  1733. if (!getLangOpts().NativeHalfType &&
  1734. FromBuiltin->getKind() == BuiltinType::Half &&
  1735. ToBuiltin->getKind() == BuiltinType::Float)
  1736. return true;
  1737. // HLSL Change Starts
  1738. // TODO: Update this for new builtin types min16float, min16int, min16uint.
  1739. if (getLangOpts().HLSL) {
  1740. if (FromBuiltin->getKind() == BuiltinType::LitFloat &&
  1741. (ToBuiltin->getKind() == BuiltinType::Min10Float ||
  1742. ToBuiltin->getKind() == BuiltinType::HalfFloat ||
  1743. ToBuiltin->getKind() == BuiltinType::Float ||
  1744. ToBuiltin->getKind() == BuiltinType::Half ||
  1745. ToBuiltin->getKind() == BuiltinType::Double))
  1746. return true;
  1747. if (FromBuiltin->getKind() == BuiltinType::Min10Float &&
  1748. (ToBuiltin->getKind() == BuiltinType::Float ||
  1749. ToBuiltin->getKind() == BuiltinType::HalfFloat ||
  1750. ToBuiltin->getKind() == BuiltinType::Half ||
  1751. ToBuiltin->getKind() == BuiltinType::Double))
  1752. return true;
  1753. }
  1754. // HLSL Change Ends
  1755. }
  1756. return false;
  1757. }
  1758. /// \brief Determine if a conversion is a complex promotion.
  1759. ///
  1760. /// A complex promotion is defined as a complex -> complex conversion
  1761. /// where the conversion between the underlying real types is a
  1762. /// floating-point or integral promotion.
  1763. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1764. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1765. if (!FromComplex)
  1766. return false;
  1767. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1768. if (!ToComplex)
  1769. return false;
  1770. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1771. ToComplex->getElementType()) ||
  1772. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  1773. ToComplex->getElementType());
  1774. }
  1775. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1776. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1777. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1778. /// if non-empty, will be a pointer to ToType that may or may not have
  1779. /// the right set of qualifiers on its pointee.
  1780. ///
  1781. static QualType
  1782. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  1783. QualType ToPointee, QualType ToType,
  1784. ASTContext &Context,
  1785. bool StripObjCLifetime = false) {
  1786. assert((FromPtr->getTypeClass() == Type::Pointer ||
  1787. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  1788. "Invalid similarly-qualified pointer type");
  1789. /// Conversions to 'id' subsume cv-qualifier conversions.
  1790. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  1791. return ToType.getUnqualifiedType();
  1792. QualType CanonFromPointee
  1793. = Context.getCanonicalType(FromPtr->getPointeeType());
  1794. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  1795. Qualifiers Quals = CanonFromPointee.getQualifiers();
  1796. if (StripObjCLifetime)
  1797. Quals.removeObjCLifetime();
  1798. // Exact qualifier match -> return the pointer type we're converting to.
  1799. if (CanonToPointee.getLocalQualifiers() == Quals) {
  1800. // ToType is exactly what we need. Return it.
  1801. if (!ToType.isNull())
  1802. return ToType.getUnqualifiedType();
  1803. // Build a pointer to ToPointee. It has the right qualifiers
  1804. // already.
  1805. if (isa<ObjCObjectPointerType>(ToType))
  1806. return Context.getObjCObjectPointerType(ToPointee);
  1807. return Context.getPointerType(ToPointee);
  1808. }
  1809. // Just build a canonical type that has the right qualifiers.
  1810. QualType QualifiedCanonToPointee
  1811. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  1812. if (isa<ObjCObjectPointerType>(ToType))
  1813. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  1814. return Context.getPointerType(QualifiedCanonToPointee);
  1815. }
  1816. static bool isNullPointerConstantForConversion(Expr *Expr,
  1817. bool InOverloadResolution,
  1818. ASTContext &Context) {
  1819. // Handle value-dependent integral null pointer constants correctly.
  1820. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  1821. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  1822. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  1823. return !InOverloadResolution;
  1824. return Expr->isNullPointerConstant(Context,
  1825. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  1826. : Expr::NPC_ValueDependentIsNull);
  1827. }
  1828. /// IsPointerConversion - Determines whether the conversion of the
  1829. /// expression From, which has the (possibly adjusted) type FromType,
  1830. /// can be converted to the type ToType via a pointer conversion (C++
  1831. /// 4.10). If so, returns true and places the converted type (that
  1832. /// might differ from ToType in its cv-qualifiers at some level) into
  1833. /// ConvertedType.
  1834. ///
  1835. /// This routine also supports conversions to and from block pointers
  1836. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  1837. /// pointers to interfaces. FIXME: Once we've determined the
  1838. /// appropriate overloading rules for Objective-C, we may want to
  1839. /// split the Objective-C checks into a different routine; however,
  1840. /// GCC seems to consider all of these conversions to be pointer
  1841. /// conversions, so for now they live here. IncompatibleObjC will be
  1842. /// set if the conversion is an allowed Objective-C conversion that
  1843. /// should result in a warning.
  1844. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  1845. bool InOverloadResolution,
  1846. QualType& ConvertedType,
  1847. bool &IncompatibleObjC) {
  1848. IncompatibleObjC = false;
  1849. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  1850. IncompatibleObjC))
  1851. return true;
  1852. // Conversion from a null pointer constant to any Objective-C pointer type.
  1853. if (ToType->isObjCObjectPointerType() &&
  1854. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1855. ConvertedType = ToType;
  1856. return true;
  1857. }
  1858. // Blocks: Block pointers can be converted to void*.
  1859. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  1860. ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
  1861. ConvertedType = ToType;
  1862. return true;
  1863. }
  1864. // Blocks: A null pointer constant can be converted to a block
  1865. // pointer type.
  1866. if (ToType->isBlockPointerType() &&
  1867. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1868. ConvertedType = ToType;
  1869. return true;
  1870. }
  1871. // If the left-hand-side is nullptr_t, the right side can be a null
  1872. // pointer constant.
  1873. if (ToType->isNullPtrType() &&
  1874. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1875. ConvertedType = ToType;
  1876. return true;
  1877. }
  1878. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  1879. if (!ToTypePtr)
  1880. return false;
  1881. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  1882. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1883. ConvertedType = ToType;
  1884. return true;
  1885. }
  1886. // Beyond this point, both types need to be pointers
  1887. // , including objective-c pointers.
  1888. QualType ToPointeeType = ToTypePtr->getPointeeType();
  1889. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  1890. !getLangOpts().ObjCAutoRefCount) {
  1891. ConvertedType = BuildSimilarlyQualifiedPointerType(
  1892. FromType->getAs<ObjCObjectPointerType>(),
  1893. ToPointeeType,
  1894. ToType, Context);
  1895. return true;
  1896. }
  1897. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  1898. if (!FromTypePtr)
  1899. return false;
  1900. QualType FromPointeeType = FromTypePtr->getPointeeType();
  1901. // If the unqualified pointee types are the same, this can't be a
  1902. // pointer conversion, so don't do all of the work below.
  1903. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  1904. return false;
  1905. // An rvalue of type "pointer to cv T," where T is an object type,
  1906. // can be converted to an rvalue of type "pointer to cv void" (C++
  1907. // 4.10p2).
  1908. if (FromPointeeType->isIncompleteOrObjectType() &&
  1909. ToPointeeType->isVoidType()) {
  1910. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1911. ToPointeeType,
  1912. ToType, Context,
  1913. /*StripObjCLifetime=*/true);
  1914. return true;
  1915. }
  1916. // MSVC allows implicit function to void* type conversion.
  1917. if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
  1918. ToPointeeType->isVoidType()) {
  1919. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1920. ToPointeeType,
  1921. ToType, Context);
  1922. return true;
  1923. }
  1924. // When we're overloading in C, we allow a special kind of pointer
  1925. // conversion for compatible-but-not-identical pointee types.
  1926. if (!getLangOpts().CPlusPlus &&
  1927. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  1928. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1929. ToPointeeType,
  1930. ToType, Context);
  1931. return true;
  1932. }
  1933. // C++ [conv.ptr]p3:
  1934. //
  1935. // An rvalue of type "pointer to cv D," where D is a class type,
  1936. // can be converted to an rvalue of type "pointer to cv B," where
  1937. // B is a base class (clause 10) of D. If B is an inaccessible
  1938. // (clause 11) or ambiguous (10.2) base class of D, a program that
  1939. // necessitates this conversion is ill-formed. The result of the
  1940. // conversion is a pointer to the base class sub-object of the
  1941. // derived class object. The null pointer value is converted to
  1942. // the null pointer value of the destination type.
  1943. //
  1944. // Note that we do not check for ambiguity or inaccessibility
  1945. // here. That is handled by CheckPointerConversion.
  1946. if (getLangOpts().CPlusPlus &&
  1947. FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  1948. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  1949. !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
  1950. IsDerivedFrom(FromPointeeType, ToPointeeType)) {
  1951. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1952. ToPointeeType,
  1953. ToType, Context);
  1954. return true;
  1955. }
  1956. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  1957. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  1958. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1959. ToPointeeType,
  1960. ToType, Context);
  1961. return true;
  1962. }
  1963. return false;
  1964. }
  1965. /// \brief Adopt the given qualifiers for the given type.
  1966. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  1967. Qualifiers TQs = T.getQualifiers();
  1968. // Check whether qualifiers already match.
  1969. if (TQs == Qs)
  1970. return T;
  1971. if (Qs.compatiblyIncludes(TQs))
  1972. return Context.getQualifiedType(T, Qs);
  1973. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  1974. }
  1975. /// isObjCPointerConversion - Determines whether this is an
  1976. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  1977. /// with the same arguments and return values.
  1978. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  1979. QualType& ConvertedType,
  1980. bool &IncompatibleObjC) {
  1981. if (!getLangOpts().ObjC1)
  1982. return false;
  1983. // The set of qualifiers on the type we're converting from.
  1984. Qualifiers FromQualifiers = FromType.getQualifiers();
  1985. // First, we handle all conversions on ObjC object pointer types.
  1986. const ObjCObjectPointerType* ToObjCPtr =
  1987. ToType->getAs<ObjCObjectPointerType>();
  1988. const ObjCObjectPointerType *FromObjCPtr =
  1989. FromType->getAs<ObjCObjectPointerType>();
  1990. if (ToObjCPtr && FromObjCPtr) {
  1991. // If the pointee types are the same (ignoring qualifications),
  1992. // then this is not a pointer conversion.
  1993. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  1994. FromObjCPtr->getPointeeType()))
  1995. return false;
  1996. // Conversion between Objective-C pointers.
  1997. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  1998. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  1999. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  2000. if (getLangOpts().CPlusPlus && LHS && RHS &&
  2001. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  2002. FromObjCPtr->getPointeeType()))
  2003. return false;
  2004. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2005. ToObjCPtr->getPointeeType(),
  2006. ToType, Context);
  2007. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2008. return true;
  2009. }
  2010. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2011. // Okay: this is some kind of implicit downcast of Objective-C
  2012. // interfaces, which is permitted. However, we're going to
  2013. // complain about it.
  2014. IncompatibleObjC = true;
  2015. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2016. ToObjCPtr->getPointeeType(),
  2017. ToType, Context);
  2018. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2019. return true;
  2020. }
  2021. }
  2022. // Beyond this point, both types need to be C pointers or block pointers.
  2023. QualType ToPointeeType;
  2024. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2025. ToPointeeType = ToCPtr->getPointeeType();
  2026. else if (const BlockPointerType *ToBlockPtr =
  2027. ToType->getAs<BlockPointerType>()) {
  2028. // Objective C++: We're able to convert from a pointer to any object
  2029. // to a block pointer type.
  2030. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2031. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2032. return true;
  2033. }
  2034. ToPointeeType = ToBlockPtr->getPointeeType();
  2035. }
  2036. else if (FromType->getAs<BlockPointerType>() &&
  2037. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2038. // Objective C++: We're able to convert from a block pointer type to a
  2039. // pointer to any object.
  2040. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2041. return true;
  2042. }
  2043. else
  2044. return false;
  2045. QualType FromPointeeType;
  2046. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2047. FromPointeeType = FromCPtr->getPointeeType();
  2048. else if (const BlockPointerType *FromBlockPtr =
  2049. FromType->getAs<BlockPointerType>())
  2050. FromPointeeType = FromBlockPtr->getPointeeType();
  2051. else
  2052. return false;
  2053. // If we have pointers to pointers, recursively check whether this
  2054. // is an Objective-C conversion.
  2055. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2056. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2057. IncompatibleObjC)) {
  2058. // We always complain about this conversion.
  2059. IncompatibleObjC = true;
  2060. ConvertedType = Context.getPointerType(ConvertedType);
  2061. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2062. return true;
  2063. }
  2064. // Allow conversion of pointee being objective-c pointer to another one;
  2065. // as in I* to id.
  2066. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2067. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2068. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2069. IncompatibleObjC)) {
  2070. ConvertedType = Context.getPointerType(ConvertedType);
  2071. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2072. return true;
  2073. }
  2074. // If we have pointers to functions or blocks, check whether the only
  2075. // differences in the argument and result types are in Objective-C
  2076. // pointer conversions. If so, we permit the conversion (but
  2077. // complain about it).
  2078. const FunctionProtoType *FromFunctionType
  2079. = FromPointeeType->getAs<FunctionProtoType>();
  2080. const FunctionProtoType *ToFunctionType
  2081. = ToPointeeType->getAs<FunctionProtoType>();
  2082. if (FromFunctionType && ToFunctionType) {
  2083. // If the function types are exactly the same, this isn't an
  2084. // Objective-C pointer conversion.
  2085. if (Context.getCanonicalType(FromPointeeType)
  2086. == Context.getCanonicalType(ToPointeeType))
  2087. return false;
  2088. // Perform the quick checks that will tell us whether these
  2089. // function types are obviously different.
  2090. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2091. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2092. FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
  2093. return false;
  2094. bool HasObjCConversion = false;
  2095. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2096. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2097. // Okay, the types match exactly. Nothing to do.
  2098. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2099. ToFunctionType->getReturnType(),
  2100. ConvertedType, IncompatibleObjC)) {
  2101. // Okay, we have an Objective-C pointer conversion.
  2102. HasObjCConversion = true;
  2103. } else {
  2104. // Function types are too different. Abort.
  2105. return false;
  2106. }
  2107. // Check argument types.
  2108. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2109. ArgIdx != NumArgs; ++ArgIdx) {
  2110. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2111. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2112. if (Context.getCanonicalType(FromArgType)
  2113. == Context.getCanonicalType(ToArgType)) {
  2114. // Okay, the types match exactly. Nothing to do.
  2115. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2116. ConvertedType, IncompatibleObjC)) {
  2117. // Okay, we have an Objective-C pointer conversion.
  2118. HasObjCConversion = true;
  2119. } else {
  2120. // Argument types are too different. Abort.
  2121. return false;
  2122. }
  2123. }
  2124. if (HasObjCConversion) {
  2125. // We had an Objective-C conversion. Allow this pointer
  2126. // conversion, but complain about it.
  2127. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2128. IncompatibleObjC = true;
  2129. return true;
  2130. }
  2131. }
  2132. return false;
  2133. }
  2134. /// \brief Determine whether this is an Objective-C writeback conversion,
  2135. /// used for parameter passing when performing automatic reference counting.
  2136. ///
  2137. /// \param FromType The type we're converting form.
  2138. ///
  2139. /// \param ToType The type we're converting to.
  2140. ///
  2141. /// \param ConvertedType The type that will be produced after applying
  2142. /// this conversion.
  2143. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2144. QualType &ConvertedType) {
  2145. if (!getLangOpts().ObjCAutoRefCount ||
  2146. Context.hasSameUnqualifiedType(FromType, ToType))
  2147. return false;
  2148. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2149. QualType ToPointee;
  2150. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2151. ToPointee = ToPointer->getPointeeType();
  2152. else
  2153. return false;
  2154. Qualifiers ToQuals = ToPointee.getQualifiers();
  2155. if (!ToPointee->isObjCLifetimeType() ||
  2156. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2157. !ToQuals.withoutObjCLifetime().empty())
  2158. return false;
  2159. // Argument must be a pointer to __strong to __weak.
  2160. QualType FromPointee;
  2161. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2162. FromPointee = FromPointer->getPointeeType();
  2163. else
  2164. return false;
  2165. Qualifiers FromQuals = FromPointee.getQualifiers();
  2166. if (!FromPointee->isObjCLifetimeType() ||
  2167. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2168. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2169. return false;
  2170. // Make sure that we have compatible qualifiers.
  2171. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2172. if (!ToQuals.compatiblyIncludes(FromQuals))
  2173. return false;
  2174. // Remove qualifiers from the pointee type we're converting from; they
  2175. // aren't used in the compatibility check belong, and we'll be adding back
  2176. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2177. FromPointee = FromPointee.getUnqualifiedType();
  2178. // The unqualified form of the pointee types must be compatible.
  2179. ToPointee = ToPointee.getUnqualifiedType();
  2180. bool IncompatibleObjC;
  2181. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2182. FromPointee = ToPointee;
  2183. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2184. IncompatibleObjC))
  2185. return false;
  2186. /// \brief Construct the type we're converting to, which is a pointer to
  2187. /// __autoreleasing pointee.
  2188. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2189. ConvertedType = Context.getPointerType(FromPointee);
  2190. return true;
  2191. }
  2192. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2193. QualType& ConvertedType) {
  2194. QualType ToPointeeType;
  2195. if (const BlockPointerType *ToBlockPtr =
  2196. ToType->getAs<BlockPointerType>())
  2197. ToPointeeType = ToBlockPtr->getPointeeType();
  2198. else
  2199. return false;
  2200. QualType FromPointeeType;
  2201. if (const BlockPointerType *FromBlockPtr =
  2202. FromType->getAs<BlockPointerType>())
  2203. FromPointeeType = FromBlockPtr->getPointeeType();
  2204. else
  2205. return false;
  2206. // We have pointer to blocks, check whether the only
  2207. // differences in the argument and result types are in Objective-C
  2208. // pointer conversions. If so, we permit the conversion.
  2209. const FunctionProtoType *FromFunctionType
  2210. = FromPointeeType->getAs<FunctionProtoType>();
  2211. const FunctionProtoType *ToFunctionType
  2212. = ToPointeeType->getAs<FunctionProtoType>();
  2213. if (!FromFunctionType || !ToFunctionType)
  2214. return false;
  2215. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2216. return true;
  2217. // Perform the quick checks that will tell us whether these
  2218. // function types are obviously different.
  2219. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2220. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2221. return false;
  2222. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2223. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2224. if (FromEInfo != ToEInfo)
  2225. return false;
  2226. bool IncompatibleObjC = false;
  2227. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2228. ToFunctionType->getReturnType())) {
  2229. // Okay, the types match exactly. Nothing to do.
  2230. } else {
  2231. QualType RHS = FromFunctionType->getReturnType();
  2232. QualType LHS = ToFunctionType->getReturnType();
  2233. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2234. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2235. LHS = LHS.getUnqualifiedType();
  2236. if (Context.hasSameType(RHS,LHS)) {
  2237. // OK exact match.
  2238. } else if (isObjCPointerConversion(RHS, LHS,
  2239. ConvertedType, IncompatibleObjC)) {
  2240. if (IncompatibleObjC)
  2241. return false;
  2242. // Okay, we have an Objective-C pointer conversion.
  2243. }
  2244. else
  2245. return false;
  2246. }
  2247. // Check argument types.
  2248. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2249. ArgIdx != NumArgs; ++ArgIdx) {
  2250. IncompatibleObjC = false;
  2251. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2252. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2253. if (Context.hasSameType(FromArgType, ToArgType)) {
  2254. // Okay, the types match exactly. Nothing to do.
  2255. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2256. ConvertedType, IncompatibleObjC)) {
  2257. if (IncompatibleObjC)
  2258. return false;
  2259. // Okay, we have an Objective-C pointer conversion.
  2260. } else
  2261. // Argument types are too different. Abort.
  2262. return false;
  2263. }
  2264. if (LangOpts.ObjCAutoRefCount &&
  2265. !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
  2266. ToFunctionType))
  2267. return false;
  2268. ConvertedType = ToType;
  2269. return true;
  2270. }
  2271. enum {
  2272. ft_default,
  2273. ft_different_class,
  2274. ft_parameter_arity,
  2275. ft_parameter_mismatch,
  2276. ft_return_type,
  2277. ft_qualifer_mismatch
  2278. };
  2279. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2280. /// function types. Catches different number of parameter, mismatch in
  2281. /// parameter types, and different return types.
  2282. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2283. QualType FromType, QualType ToType) {
  2284. // If either type is not valid, include no extra info.
  2285. if (FromType.isNull() || ToType.isNull()) {
  2286. PDiag << ft_default;
  2287. return;
  2288. }
  2289. // Get the function type from the pointers.
  2290. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2291. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2292. *ToMember = ToType->getAs<MemberPointerType>();
  2293. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2294. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2295. << QualType(FromMember->getClass(), 0);
  2296. return;
  2297. }
  2298. FromType = FromMember->getPointeeType();
  2299. ToType = ToMember->getPointeeType();
  2300. }
  2301. if (FromType->isPointerType())
  2302. FromType = FromType->getPointeeType();
  2303. if (ToType->isPointerType())
  2304. ToType = ToType->getPointeeType();
  2305. // Remove references.
  2306. FromType = FromType.getNonReferenceType();
  2307. ToType = ToType.getNonReferenceType();
  2308. // Don't print extra info for non-specialized template functions.
  2309. if (FromType->isInstantiationDependentType() &&
  2310. !FromType->getAs<TemplateSpecializationType>()) {
  2311. PDiag << ft_default;
  2312. return;
  2313. }
  2314. // No extra info for same types.
  2315. if (Context.hasSameType(FromType, ToType)) {
  2316. PDiag << ft_default;
  2317. return;
  2318. }
  2319. const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
  2320. *ToFunction = ToType->getAs<FunctionProtoType>();
  2321. // Both types need to be function types.
  2322. if (!FromFunction || !ToFunction) {
  2323. PDiag << ft_default;
  2324. return;
  2325. }
  2326. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2327. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2328. << FromFunction->getNumParams();
  2329. return;
  2330. }
  2331. // Handle different parameter types.
  2332. unsigned ArgPos;
  2333. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2334. PDiag << ft_parameter_mismatch << ArgPos + 1
  2335. << ToFunction->getParamType(ArgPos)
  2336. << FromFunction->getParamType(ArgPos);
  2337. return;
  2338. }
  2339. // Handle different return type.
  2340. if (!Context.hasSameType(FromFunction->getReturnType(),
  2341. ToFunction->getReturnType())) {
  2342. PDiag << ft_return_type << ToFunction->getReturnType()
  2343. << FromFunction->getReturnType();
  2344. return;
  2345. }
  2346. unsigned FromQuals = FromFunction->getTypeQuals(),
  2347. ToQuals = ToFunction->getTypeQuals();
  2348. if (FromQuals != ToQuals) {
  2349. PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
  2350. return;
  2351. }
  2352. // Unable to find a difference, so add no extra info.
  2353. PDiag << ft_default;
  2354. }
  2355. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2356. /// for equality of their argument types. Caller has already checked that
  2357. /// they have same number of arguments. If the parameters are different,
  2358. /// ArgPos will have the parameter index of the first different parameter.
  2359. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2360. const FunctionProtoType *NewType,
  2361. unsigned *ArgPos) {
  2362. int index = 0;
  2363. for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
  2364. N = NewType->param_type_begin(),
  2365. E = OldType->param_type_end();
  2366. O && (O != E); ++O, ++N) {
  2367. if (!Context.hasSameType(O->getUnqualifiedType(),
  2368. N->getUnqualifiedType())
  2369. || OldType->getParamMods()[index] != NewType->getParamMods()[index]) { // HLSL Change - check param mods
  2370. index++;
  2371. if (ArgPos)
  2372. *ArgPos = O - OldType->param_type_begin();
  2373. return false;
  2374. }
  2375. }
  2376. return true;
  2377. }
  2378. /// CheckPointerConversion - Check the pointer conversion from the
  2379. /// expression From to the type ToType. This routine checks for
  2380. /// ambiguous or inaccessible derived-to-base pointer
  2381. /// conversions for which IsPointerConversion has already returned
  2382. /// true. It returns true and produces a diagnostic if there was an
  2383. /// error, or returns false otherwise.
  2384. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2385. CastKind &Kind,
  2386. CXXCastPath& BasePath,
  2387. bool IgnoreBaseAccess) {
  2388. QualType FromType = From->getType();
  2389. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2390. Kind = CK_BitCast;
  2391. if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2392. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2393. Expr::NPCK_ZeroExpression) {
  2394. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2395. DiagRuntimeBehavior(From->getExprLoc(), From,
  2396. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2397. << ToType << From->getSourceRange());
  2398. else if (!isUnevaluatedContext())
  2399. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2400. << ToType << From->getSourceRange();
  2401. }
  2402. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2403. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2404. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2405. ToPointeeType = ToPtrType->getPointeeType();
  2406. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2407. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2408. // We must have a derived-to-base conversion. Check an
  2409. // ambiguous or inaccessible conversion.
  2410. if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
  2411. From->getExprLoc(),
  2412. From->getSourceRange(), &BasePath,
  2413. IgnoreBaseAccess))
  2414. return true;
  2415. // The conversion was successful.
  2416. Kind = CK_DerivedToBase;
  2417. }
  2418. }
  2419. } else if (const ObjCObjectPointerType *ToPtrType =
  2420. ToType->getAs<ObjCObjectPointerType>()) {
  2421. if (const ObjCObjectPointerType *FromPtrType =
  2422. FromType->getAs<ObjCObjectPointerType>()) {
  2423. // Objective-C++ conversions are always okay.
  2424. // FIXME: We should have a different class of conversions for the
  2425. // Objective-C++ implicit conversions.
  2426. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2427. return false;
  2428. } else if (FromType->isBlockPointerType()) {
  2429. Kind = CK_BlockPointerToObjCPointerCast;
  2430. } else {
  2431. Kind = CK_CPointerToObjCPointerCast;
  2432. }
  2433. } else if (ToType->isBlockPointerType()) {
  2434. if (!FromType->isBlockPointerType())
  2435. Kind = CK_AnyPointerToBlockPointerCast;
  2436. }
  2437. // We shouldn't fall into this case unless it's valid for other
  2438. // reasons.
  2439. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2440. Kind = CK_NullToPointer;
  2441. return false;
  2442. }
  2443. /// IsMemberPointerConversion - Determines whether the conversion of the
  2444. /// expression From, which has the (possibly adjusted) type FromType, can be
  2445. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2446. /// If so, returns true and places the converted type (that might differ from
  2447. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2448. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2449. QualType ToType,
  2450. bool InOverloadResolution,
  2451. QualType &ConvertedType) {
  2452. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2453. if (!ToTypePtr)
  2454. return false;
  2455. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2456. if (From->isNullPointerConstant(Context,
  2457. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2458. : Expr::NPC_ValueDependentIsNull)) {
  2459. ConvertedType = ToType;
  2460. return true;
  2461. }
  2462. // Otherwise, both types have to be member pointers.
  2463. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2464. if (!FromTypePtr)
  2465. return false;
  2466. // A pointer to member of B can be converted to a pointer to member of D,
  2467. // where D is derived from B (C++ 4.11p2).
  2468. QualType FromClass(FromTypePtr->getClass(), 0);
  2469. QualType ToClass(ToTypePtr->getClass(), 0);
  2470. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2471. !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
  2472. IsDerivedFrom(ToClass, FromClass)) {
  2473. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2474. ToClass.getTypePtr());
  2475. return true;
  2476. }
  2477. return false;
  2478. }
  2479. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2480. /// expression From to the type ToType. This routine checks for ambiguous or
  2481. /// virtual or inaccessible base-to-derived member pointer conversions
  2482. /// for which IsMemberPointerConversion has already returned true. It returns
  2483. /// true and produces a diagnostic if there was an error, or returns false
  2484. /// otherwise.
  2485. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2486. CastKind &Kind,
  2487. CXXCastPath &BasePath,
  2488. bool IgnoreBaseAccess) {
  2489. QualType FromType = From->getType();
  2490. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2491. if (!FromPtrType) {
  2492. // This must be a null pointer to member pointer conversion
  2493. assert(From->isNullPointerConstant(Context,
  2494. Expr::NPC_ValueDependentIsNull) &&
  2495. "Expr must be null pointer constant!");
  2496. Kind = CK_NullToMemberPointer;
  2497. return false;
  2498. }
  2499. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2500. assert(ToPtrType && "No member pointer cast has a target type "
  2501. "that is not a member pointer.");
  2502. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2503. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2504. // FIXME: What about dependent types?
  2505. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2506. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2507. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2508. /*DetectVirtual=*/true);
  2509. bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
  2510. assert(DerivationOkay &&
  2511. "Should not have been called if derivation isn't OK.");
  2512. (void)DerivationOkay;
  2513. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2514. getUnqualifiedType())) {
  2515. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2516. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2517. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2518. return true;
  2519. }
  2520. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2521. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2522. << FromClass << ToClass << QualType(VBase, 0)
  2523. << From->getSourceRange();
  2524. return true;
  2525. }
  2526. if (!IgnoreBaseAccess)
  2527. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2528. Paths.front(),
  2529. diag::err_downcast_from_inaccessible_base);
  2530. // Must be a base to derived member conversion.
  2531. BuildBasePathArray(Paths, BasePath);
  2532. Kind = CK_BaseToDerivedMemberPointer;
  2533. return false;
  2534. }
  2535. /// Determine whether the lifetime conversion between the two given
  2536. /// qualifiers sets is nontrivial.
  2537. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2538. Qualifiers ToQuals) {
  2539. // Converting anything to const __unsafe_unretained is trivial.
  2540. if (ToQuals.hasConst() &&
  2541. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2542. return false;
  2543. return true;
  2544. }
  2545. /// IsQualificationConversion - Determines whether the conversion from
  2546. /// an rvalue of type FromType to ToType is a qualification conversion
  2547. /// (C++ 4.4).
  2548. ///
  2549. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2550. /// when the qualification conversion involves a change in the Objective-C
  2551. /// object lifetime.
  2552. bool
  2553. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2554. bool CStyle, bool &ObjCLifetimeConversion) {
  2555. FromType = Context.getCanonicalType(FromType);
  2556. ToType = Context.getCanonicalType(ToType);
  2557. ObjCLifetimeConversion = false;
  2558. // If FromType and ToType are the same type, this is not a
  2559. // qualification conversion.
  2560. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2561. return false;
  2562. // (C++ 4.4p4):
  2563. // A conversion can add cv-qualifiers at levels other than the first
  2564. // in multi-level pointers, subject to the following rules: [...]
  2565. bool PreviousToQualsIncludeConst = true;
  2566. bool UnwrappedAnyPointer = false;
  2567. while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
  2568. // Within each iteration of the loop, we check the qualifiers to
  2569. // determine if this still looks like a qualification
  2570. // conversion. Then, if all is well, we unwrap one more level of
  2571. // pointers or pointers-to-members and do it all again
  2572. // until there are no more pointers or pointers-to-members left to
  2573. // unwrap.
  2574. UnwrappedAnyPointer = true;
  2575. Qualifiers FromQuals = FromType.getQualifiers();
  2576. Qualifiers ToQuals = ToType.getQualifiers();
  2577. // Objective-C ARC:
  2578. // Check Objective-C lifetime conversions.
  2579. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2580. UnwrappedAnyPointer) {
  2581. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2582. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2583. ObjCLifetimeConversion = true;
  2584. FromQuals.removeObjCLifetime();
  2585. ToQuals.removeObjCLifetime();
  2586. } else {
  2587. // Qualification conversions cannot cast between different
  2588. // Objective-C lifetime qualifiers.
  2589. return false;
  2590. }
  2591. }
  2592. // Allow addition/removal of GC attributes but not changing GC attributes.
  2593. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2594. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2595. FromQuals.removeObjCGCAttr();
  2596. ToQuals.removeObjCGCAttr();
  2597. }
  2598. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2599. // 2,j, and similarly for volatile.
  2600. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2601. return false;
  2602. // -- if the cv 1,j and cv 2,j are different, then const is in
  2603. // every cv for 0 < k < j.
  2604. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2605. && !PreviousToQualsIncludeConst)
  2606. return false;
  2607. // Keep track of whether all prior cv-qualifiers in the "to" type
  2608. // include const.
  2609. PreviousToQualsIncludeConst
  2610. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2611. }
  2612. // We are left with FromType and ToType being the pointee types
  2613. // after unwrapping the original FromType and ToType the same number
  2614. // of types. If we unwrapped any pointers, and if FromType and
  2615. // ToType have the same unqualified type (since we checked
  2616. // qualifiers above), then this is a qualification conversion.
  2617. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2618. }
  2619. /// \brief - Determine whether this is a conversion from a scalar type to an
  2620. /// atomic type.
  2621. ///
  2622. /// If successful, updates \c SCS's second and third steps in the conversion
  2623. /// sequence to finish the conversion.
  2624. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2625. bool InOverloadResolution,
  2626. StandardConversionSequence &SCS,
  2627. bool CStyle) {
  2628. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2629. if (!ToAtomic)
  2630. return false;
  2631. StandardConversionSequence InnerSCS;
  2632. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2633. InOverloadResolution, InnerSCS,
  2634. CStyle, /*AllowObjCWritebackConversion=*/false))
  2635. return false;
  2636. SCS.Second = InnerSCS.Second;
  2637. SCS.setToType(1, InnerSCS.getToType(1));
  2638. SCS.Third = InnerSCS.Third;
  2639. SCS.QualificationIncludesObjCLifetime
  2640. = InnerSCS.QualificationIncludesObjCLifetime;
  2641. SCS.setToType(2, InnerSCS.getToType(2));
  2642. return true;
  2643. }
  2644. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2645. CXXConstructorDecl *Constructor,
  2646. QualType Type) {
  2647. const FunctionProtoType *CtorType =
  2648. Constructor->getType()->getAs<FunctionProtoType>();
  2649. if (CtorType->getNumParams() > 0) {
  2650. QualType FirstArg = CtorType->getParamType(0);
  2651. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2652. return true;
  2653. }
  2654. return false;
  2655. }
  2656. static OverloadingResult
  2657. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2658. CXXRecordDecl *To,
  2659. UserDefinedConversionSequence &User,
  2660. OverloadCandidateSet &CandidateSet,
  2661. bool AllowExplicit) {
  2662. DeclContext::lookup_result R = S.LookupConstructors(To);
  2663. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2664. Con != ConEnd; ++Con) {
  2665. NamedDecl *D = *Con;
  2666. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2667. // Find the constructor (which may be a template).
  2668. CXXConstructorDecl *Constructor = nullptr;
  2669. FunctionTemplateDecl *ConstructorTmpl
  2670. = dyn_cast<FunctionTemplateDecl>(D);
  2671. if (ConstructorTmpl)
  2672. Constructor
  2673. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2674. else
  2675. Constructor = cast<CXXConstructorDecl>(D);
  2676. bool Usable = !Constructor->isInvalidDecl() &&
  2677. S.isInitListConstructor(Constructor) &&
  2678. (AllowExplicit || !Constructor->isExplicit());
  2679. if (Usable) {
  2680. // If the first argument is (a reference to) the target type,
  2681. // suppress conversions.
  2682. bool SuppressUserConversions =
  2683. isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
  2684. if (ConstructorTmpl)
  2685. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2686. /*ExplicitArgs*/ nullptr,
  2687. From, CandidateSet,
  2688. SuppressUserConversions);
  2689. else
  2690. S.AddOverloadCandidate(Constructor, FoundDecl,
  2691. From, CandidateSet,
  2692. SuppressUserConversions);
  2693. }
  2694. }
  2695. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2696. OverloadCandidateSet::iterator Best;
  2697. switch (auto Result =
  2698. CandidateSet.BestViableFunction(S, From->getLocStart(),
  2699. Best, true)) {
  2700. case OR_Deleted:
  2701. case OR_Success: {
  2702. // Record the standard conversion we used and the conversion function.
  2703. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2704. QualType ThisType = Constructor->getThisType(S.Context);
  2705. // Initializer lists don't have conversions as such.
  2706. User.Before.setAsIdentityConversion();
  2707. User.HadMultipleCandidates = HadMultipleCandidates;
  2708. User.ConversionFunction = Constructor;
  2709. User.FoundConversionFunction = Best->FoundDecl;
  2710. User.After.setAsIdentityConversion();
  2711. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2712. User.After.setAllToTypes(ToType);
  2713. return Result;
  2714. }
  2715. case OR_No_Viable_Function:
  2716. return OR_No_Viable_Function;
  2717. case OR_Ambiguous:
  2718. return OR_Ambiguous;
  2719. }
  2720. llvm_unreachable("Invalid OverloadResult!");
  2721. }
  2722. /// Determines whether there is a user-defined conversion sequence
  2723. /// (C++ [over.ics.user]) that converts expression From to the type
  2724. /// ToType. If such a conversion exists, User will contain the
  2725. /// user-defined conversion sequence that performs such a conversion
  2726. /// and this routine will return true. Otherwise, this routine returns
  2727. /// false and User is unspecified.
  2728. ///
  2729. /// \param AllowExplicit true if the conversion should consider C++0x
  2730. /// "explicit" conversion functions as well as non-explicit conversion
  2731. /// functions (C++0x [class.conv.fct]p2).
  2732. ///
  2733. /// \param AllowObjCConversionOnExplicit true if the conversion should
  2734. /// allow an extra Objective-C pointer conversion on uses of explicit
  2735. /// constructors. Requires \c AllowExplicit to also be set.
  2736. static OverloadingResult
  2737. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2738. UserDefinedConversionSequence &User,
  2739. OverloadCandidateSet &CandidateSet,
  2740. bool AllowExplicit,
  2741. bool AllowObjCConversionOnExplicit) {
  2742. assert(AllowExplicit || !AllowObjCConversionOnExplicit);
  2743. // Whether we will only visit constructors.
  2744. bool ConstructorsOnly = false;
  2745. // If the type we are conversion to is a class type, enumerate its
  2746. // constructors.
  2747. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2748. // C++ [over.match.ctor]p1:
  2749. // When objects of class type are direct-initialized (8.5), or
  2750. // copy-initialized from an expression of the same or a
  2751. // derived class type (8.5), overload resolution selects the
  2752. // constructor. [...] For copy-initialization, the candidate
  2753. // functions are all the converting constructors (12.3.1) of
  2754. // that class. The argument list is the expression-list within
  2755. // the parentheses of the initializer.
  2756. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  2757. (From->getType()->getAs<RecordType>() &&
  2758. S.IsDerivedFrom(From->getType(), ToType)))
  2759. ConstructorsOnly = true;
  2760. S.RequireCompleteType(From->getExprLoc(), ToType, 0);
  2761. // RequireCompleteType may have returned true due to some invalid decl
  2762. // during template instantiation, but ToType may be complete enough now
  2763. // to try to recover.
  2764. if (ToType->isIncompleteType()) {
  2765. // We're not going to find any constructors.
  2766. } else if (CXXRecordDecl *ToRecordDecl
  2767. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  2768. Expr **Args = &From;
  2769. unsigned NumArgs = 1;
  2770. bool ListInitializing = false;
  2771. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  2772. // But first, see if there is an init-list-constructor that will work.
  2773. OverloadingResult Result = IsInitializerListConstructorConversion(
  2774. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  2775. if (Result != OR_No_Viable_Function)
  2776. return Result;
  2777. // Never mind.
  2778. CandidateSet.clear();
  2779. // If we're list-initializing, we pass the individual elements as
  2780. // arguments, not the entire list.
  2781. Args = InitList->getInits();
  2782. NumArgs = InitList->getNumInits();
  2783. ListInitializing = true;
  2784. }
  2785. DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
  2786. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2787. Con != ConEnd; ++Con) {
  2788. NamedDecl *D = *Con;
  2789. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2790. // Find the constructor (which may be a template).
  2791. CXXConstructorDecl *Constructor = nullptr;
  2792. FunctionTemplateDecl *ConstructorTmpl
  2793. = dyn_cast<FunctionTemplateDecl>(D);
  2794. if (ConstructorTmpl)
  2795. Constructor
  2796. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2797. else
  2798. Constructor = cast<CXXConstructorDecl>(D);
  2799. bool Usable = !Constructor->isInvalidDecl();
  2800. if (ListInitializing)
  2801. Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
  2802. else
  2803. Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
  2804. if (Usable) {
  2805. bool SuppressUserConversions = !ConstructorsOnly;
  2806. if (SuppressUserConversions && ListInitializing) {
  2807. SuppressUserConversions = false;
  2808. if (NumArgs == 1) {
  2809. // If the first argument is (a reference to) the target type,
  2810. // suppress conversions.
  2811. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2812. S.Context, Constructor, ToType);
  2813. }
  2814. }
  2815. if (ConstructorTmpl)
  2816. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2817. /*ExplicitArgs*/ nullptr,
  2818. llvm::makeArrayRef(Args, NumArgs),
  2819. CandidateSet, SuppressUserConversions);
  2820. else
  2821. // Allow one user-defined conversion when user specifies a
  2822. // From->ToType conversion via an static cast (c-style, etc).
  2823. S.AddOverloadCandidate(Constructor, FoundDecl,
  2824. llvm::makeArrayRef(Args, NumArgs),
  2825. CandidateSet, SuppressUserConversions);
  2826. }
  2827. }
  2828. }
  2829. }
  2830. // Enumerate conversion functions, if we're allowed to.
  2831. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  2832. } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
  2833. // No conversion functions from incomplete types.
  2834. } else if (const RecordType *FromRecordType
  2835. = From->getType()->getAs<RecordType>()) {
  2836. if (CXXRecordDecl *FromRecordDecl
  2837. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  2838. // Add all of the conversion functions as candidates.
  2839. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  2840. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  2841. DeclAccessPair FoundDecl = I.getPair();
  2842. NamedDecl *D = FoundDecl.getDecl();
  2843. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  2844. if (isa<UsingShadowDecl>(D))
  2845. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2846. CXXConversionDecl *Conv;
  2847. FunctionTemplateDecl *ConvTemplate;
  2848. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  2849. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  2850. else
  2851. Conv = cast<CXXConversionDecl>(D);
  2852. if (AllowExplicit || !Conv->isExplicit()) {
  2853. if (ConvTemplate)
  2854. S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
  2855. ActingContext, From, ToType,
  2856. CandidateSet,
  2857. AllowObjCConversionOnExplicit);
  2858. else
  2859. S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
  2860. From, ToType, CandidateSet,
  2861. AllowObjCConversionOnExplicit);
  2862. }
  2863. }
  2864. }
  2865. }
  2866. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2867. OverloadCandidateSet::iterator Best;
  2868. switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
  2869. Best, true)) {
  2870. case OR_Success:
  2871. case OR_Deleted:
  2872. // Record the standard conversion we used and the conversion function.
  2873. if (CXXConstructorDecl *Constructor
  2874. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  2875. // C++ [over.ics.user]p1:
  2876. // If the user-defined conversion is specified by a
  2877. // constructor (12.3.1), the initial standard conversion
  2878. // sequence converts the source type to the type required by
  2879. // the argument of the constructor.
  2880. //
  2881. QualType ThisType = Constructor->getThisType(S.Context);
  2882. if (isa<InitListExpr>(From)) {
  2883. // Initializer lists don't have conversions as such.
  2884. User.Before.setAsIdentityConversion();
  2885. } else {
  2886. if (Best->Conversions[0].isEllipsis())
  2887. User.EllipsisConversion = true;
  2888. else {
  2889. User.Before = Best->Conversions[0].Standard;
  2890. User.EllipsisConversion = false;
  2891. }
  2892. }
  2893. User.HadMultipleCandidates = HadMultipleCandidates;
  2894. User.ConversionFunction = Constructor;
  2895. User.FoundConversionFunction = Best->FoundDecl;
  2896. User.After.setAsIdentityConversion();
  2897. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2898. User.After.setAllToTypes(ToType);
  2899. return Result;
  2900. }
  2901. if (CXXConversionDecl *Conversion
  2902. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  2903. // C++ [over.ics.user]p1:
  2904. //
  2905. // [...] If the user-defined conversion is specified by a
  2906. // conversion function (12.3.2), the initial standard
  2907. // conversion sequence converts the source type to the
  2908. // implicit object parameter of the conversion function.
  2909. User.Before = Best->Conversions[0].Standard;
  2910. User.HadMultipleCandidates = HadMultipleCandidates;
  2911. User.ConversionFunction = Conversion;
  2912. User.FoundConversionFunction = Best->FoundDecl;
  2913. User.EllipsisConversion = false;
  2914. // C++ [over.ics.user]p2:
  2915. // The second standard conversion sequence converts the
  2916. // result of the user-defined conversion to the target type
  2917. // for the sequence. Since an implicit conversion sequence
  2918. // is an initialization, the special rules for
  2919. // initialization by user-defined conversion apply when
  2920. // selecting the best user-defined conversion for a
  2921. // user-defined conversion sequence (see 13.3.3 and
  2922. // 13.3.3.1).
  2923. User.After = Best->FinalConversion;
  2924. return Result;
  2925. }
  2926. llvm_unreachable("Not a constructor or conversion function?");
  2927. case OR_No_Viable_Function:
  2928. return OR_No_Viable_Function;
  2929. case OR_Ambiguous:
  2930. return OR_Ambiguous;
  2931. }
  2932. llvm_unreachable("Invalid OverloadResult!");
  2933. }
  2934. bool
  2935. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  2936. ImplicitConversionSequence ICS;
  2937. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  2938. OverloadCandidateSet::CSK_Normal);
  2939. OverloadingResult OvResult =
  2940. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  2941. CandidateSet, false, false);
  2942. if (OvResult == OR_Ambiguous)
  2943. Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
  2944. << From->getType() << ToType << From->getSourceRange();
  2945. else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
  2946. if (!RequireCompleteType(From->getLocStart(), ToType,
  2947. diag::err_typecheck_nonviable_condition_incomplete,
  2948. From->getType(), From->getSourceRange()))
  2949. Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
  2950. << From->getType() << From->getSourceRange() << ToType;
  2951. } else
  2952. return false;
  2953. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
  2954. return true;
  2955. }
  2956. /// \brief Compare the user-defined conversion functions or constructors
  2957. /// of two user-defined conversion sequences to determine whether any ordering
  2958. /// is possible.
  2959. static ImplicitConversionSequence::CompareKind
  2960. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  2961. FunctionDecl *Function2) {
  2962. if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
  2963. return ImplicitConversionSequence::Indistinguishable;
  2964. // Objective-C++:
  2965. // If both conversion functions are implicitly-declared conversions from
  2966. // a lambda closure type to a function pointer and a block pointer,
  2967. // respectively, always prefer the conversion to a function pointer,
  2968. // because the function pointer is more lightweight and is more likely
  2969. // to keep code working.
  2970. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  2971. if (!Conv1)
  2972. return ImplicitConversionSequence::Indistinguishable;
  2973. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  2974. if (!Conv2)
  2975. return ImplicitConversionSequence::Indistinguishable;
  2976. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  2977. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  2978. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  2979. if (Block1 != Block2)
  2980. return Block1 ? ImplicitConversionSequence::Worse
  2981. : ImplicitConversionSequence::Better;
  2982. }
  2983. return ImplicitConversionSequence::Indistinguishable;
  2984. }
  2985. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  2986. const ImplicitConversionSequence &ICS) {
  2987. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  2988. (ICS.isUserDefined() &&
  2989. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  2990. }
  2991. /// CompareImplicitConversionSequences - Compare two implicit
  2992. /// conversion sequences to determine whether one is better than the
  2993. /// other or if they are indistinguishable (C++ 13.3.3.2).
  2994. static ImplicitConversionSequence::CompareKind
  2995. CompareImplicitConversionSequences(Sema &S,
  2996. const ImplicitConversionSequence& ICS1,
  2997. const ImplicitConversionSequence& ICS2)
  2998. {
  2999. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  3000. // conversion sequences (as defined in 13.3.3.1)
  3001. // -- a standard conversion sequence (13.3.3.1.1) is a better
  3002. // conversion sequence than a user-defined conversion sequence or
  3003. // an ellipsis conversion sequence, and
  3004. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3005. // conversion sequence than an ellipsis conversion sequence
  3006. // (13.3.3.1.3).
  3007. //
  3008. // C++0x [over.best.ics]p10:
  3009. // For the purpose of ranking implicit conversion sequences as
  3010. // described in 13.3.3.2, the ambiguous conversion sequence is
  3011. // treated as a user-defined sequence that is indistinguishable
  3012. // from any other user-defined conversion sequence.
  3013. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3014. // been removed from C++11. We still accept this conversion, if it happens at
  3015. // the best viable function. Otherwise, this conversion is considered worse
  3016. // than ellipsis conversion. Consider this as an extension; this is not in the
  3017. // standard. For example:
  3018. //
  3019. // int &f(...); // #1
  3020. // void f(char*); // #2
  3021. // void g() { int &r = f("foo"); }
  3022. //
  3023. // In C++03, we pick #2 as the best viable function.
  3024. // In C++11, we pick #1 as the best viable function, because ellipsis
  3025. // conversion is better than string-literal to char* conversion (since there
  3026. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3027. // convert arguments, #2 would be the best viable function in C++11.
  3028. // If the best viable function has this conversion, a warning will be issued
  3029. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3030. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3031. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3032. hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
  3033. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3034. ? ImplicitConversionSequence::Worse
  3035. : ImplicitConversionSequence::Better;
  3036. // HLSL Change Starts
  3037. // This ranking happens in HLSL as part of diagnostics; otherwise the specific ranking is used.
  3038. if (S.getLangOpts().HLSL) {
  3039. if (!ICS1.isInitialized() || !ICS2.isInitialized())
  3040. return ImplicitConversionSequence::Indistinguishable;
  3041. }
  3042. // HLSL Change Ends
  3043. if (ICS1.getKindRank() < ICS2.getKindRank())
  3044. return ImplicitConversionSequence::Better;
  3045. if (ICS2.getKindRank() < ICS1.getKindRank())
  3046. return ImplicitConversionSequence::Worse;
  3047. // The following checks require both conversion sequences to be of
  3048. // the same kind.
  3049. if (ICS1.getKind() != ICS2.getKind())
  3050. return ImplicitConversionSequence::Indistinguishable;
  3051. ImplicitConversionSequence::CompareKind Result =
  3052. ImplicitConversionSequence::Indistinguishable;
  3053. // Two implicit conversion sequences of the same form are
  3054. // indistinguishable conversion sequences unless one of the
  3055. // following rules apply: (C++ 13.3.3.2p3):
  3056. // List-initialization sequence L1 is a better conversion sequence than
  3057. // list-initialization sequence L2 if:
  3058. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3059. // if not that,
  3060. // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
  3061. // and N1 is smaller than N2.,
  3062. // even if one of the other rules in this paragraph would otherwise apply.
  3063. if (!ICS1.isBad()) {
  3064. if (ICS1.isStdInitializerListElement() &&
  3065. !ICS2.isStdInitializerListElement())
  3066. return ImplicitConversionSequence::Better;
  3067. if (!ICS1.isStdInitializerListElement() &&
  3068. ICS2.isStdInitializerListElement())
  3069. return ImplicitConversionSequence::Worse;
  3070. }
  3071. if (ICS1.isStandard())
  3072. // Standard conversion sequence S1 is a better conversion sequence than
  3073. // standard conversion sequence S2 if [...]
  3074. Result = CompareStandardConversionSequences(S,
  3075. ICS1.Standard, ICS2.Standard);
  3076. else if (ICS1.isUserDefined()) {
  3077. // User-defined conversion sequence U1 is a better conversion
  3078. // sequence than another user-defined conversion sequence U2 if
  3079. // they contain the same user-defined conversion function or
  3080. // constructor and if the second standard conversion sequence of
  3081. // U1 is better than the second standard conversion sequence of
  3082. // U2 (C++ 13.3.3.2p3).
  3083. if (ICS1.UserDefined.ConversionFunction ==
  3084. ICS2.UserDefined.ConversionFunction)
  3085. Result = CompareStandardConversionSequences(S,
  3086. ICS1.UserDefined.After,
  3087. ICS2.UserDefined.After);
  3088. else
  3089. Result = compareConversionFunctions(S,
  3090. ICS1.UserDefined.ConversionFunction,
  3091. ICS2.UserDefined.ConversionFunction);
  3092. }
  3093. return Result;
  3094. }
  3095. static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
  3096. while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3097. Qualifiers Quals;
  3098. T1 = Context.getUnqualifiedArrayType(T1, Quals);
  3099. T2 = Context.getUnqualifiedArrayType(T2, Quals);
  3100. }
  3101. return Context.hasSameUnqualifiedType(T1, T2);
  3102. }
  3103. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3104. // determine if one is a proper subset of the other.
  3105. static ImplicitConversionSequence::CompareKind
  3106. compareStandardConversionSubsets(ASTContext &Context,
  3107. const StandardConversionSequence& SCS1,
  3108. const StandardConversionSequence& SCS2) {
  3109. ImplicitConversionSequence::CompareKind Result
  3110. = ImplicitConversionSequence::Indistinguishable;
  3111. // the identity conversion sequence is considered to be a subsequence of
  3112. // any non-identity conversion sequence
  3113. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3114. return ImplicitConversionSequence::Better;
  3115. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3116. return ImplicitConversionSequence::Worse;
  3117. if (SCS1.Second != SCS2.Second) {
  3118. if (SCS1.Second == ICK_Identity)
  3119. Result = ImplicitConversionSequence::Better;
  3120. else if (SCS2.Second == ICK_Identity)
  3121. Result = ImplicitConversionSequence::Worse;
  3122. else
  3123. return ImplicitConversionSequence::Indistinguishable;
  3124. } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
  3125. return ImplicitConversionSequence::Indistinguishable;
  3126. if (SCS1.Third == SCS2.Third) {
  3127. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3128. : ImplicitConversionSequence::Indistinguishable;
  3129. }
  3130. if (SCS1.Third == ICK_Identity)
  3131. return Result == ImplicitConversionSequence::Worse
  3132. ? ImplicitConversionSequence::Indistinguishable
  3133. : ImplicitConversionSequence::Better;
  3134. if (SCS2.Third == ICK_Identity)
  3135. return Result == ImplicitConversionSequence::Better
  3136. ? ImplicitConversionSequence::Indistinguishable
  3137. : ImplicitConversionSequence::Worse;
  3138. return ImplicitConversionSequence::Indistinguishable;
  3139. }
  3140. /// \brief Determine whether one of the given reference bindings is better
  3141. /// than the other based on what kind of bindings they are.
  3142. static bool
  3143. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3144. const StandardConversionSequence &SCS2) {
  3145. // C++0x [over.ics.rank]p3b4:
  3146. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3147. // implicit object parameter of a non-static member function declared
  3148. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3149. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3150. // lvalue reference to a function lvalue and S2 binds an rvalue
  3151. // reference*.
  3152. //
  3153. // FIXME: Rvalue references. We're going rogue with the above edits,
  3154. // because the semantics in the current C++0x working paper (N3225 at the
  3155. // time of this writing) break the standard definition of std::forward
  3156. // and std::reference_wrapper when dealing with references to functions.
  3157. // Proposed wording changes submitted to CWG for consideration.
  3158. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3159. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3160. return false;
  3161. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3162. SCS2.IsLvalueReference) ||
  3163. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3164. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3165. }
  3166. /// CompareStandardConversionSequences - Compare two standard
  3167. /// conversion sequences to determine whether one is better than the
  3168. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3169. static ImplicitConversionSequence::CompareKind
  3170. CompareStandardConversionSequences(Sema &S,
  3171. const StandardConversionSequence& SCS1,
  3172. const StandardConversionSequence& SCS2)
  3173. {
  3174. // Standard conversion sequence S1 is a better conversion sequence
  3175. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3176. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3177. // sequences in the canonical form defined by 13.3.3.1.1,
  3178. // excluding any Lvalue Transformation; the identity conversion
  3179. // sequence is considered to be a subsequence of any
  3180. // non-identity conversion sequence) or, if not that,
  3181. if (ImplicitConversionSequence::CompareKind CK
  3182. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3183. return CK;
  3184. // -- the rank of S1 is better than the rank of S2 (by the rules
  3185. // defined below), or, if not that,
  3186. ImplicitConversionRank Rank1 = SCS1.getRank();
  3187. ImplicitConversionRank Rank2 = SCS2.getRank();
  3188. if (Rank1 < Rank2)
  3189. return ImplicitConversionSequence::Better;
  3190. else if (Rank2 < Rank1)
  3191. return ImplicitConversionSequence::Worse;
  3192. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3193. // are indistinguishable unless one of the following rules
  3194. // applies:
  3195. // A conversion that is not a conversion of a pointer, or
  3196. // pointer to member, to bool is better than another conversion
  3197. // that is such a conversion.
  3198. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3199. return SCS2.isPointerConversionToBool()
  3200. ? ImplicitConversionSequence::Better
  3201. : ImplicitConversionSequence::Worse;
  3202. // C++ [over.ics.rank]p4b2:
  3203. //
  3204. // If class B is derived directly or indirectly from class A,
  3205. // conversion of B* to A* is better than conversion of B* to
  3206. // void*, and conversion of A* to void* is better than conversion
  3207. // of B* to void*.
  3208. bool SCS1ConvertsToVoid
  3209. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3210. bool SCS2ConvertsToVoid
  3211. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3212. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3213. // Exactly one of the conversion sequences is a conversion to
  3214. // a void pointer; it's the worse conversion.
  3215. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3216. : ImplicitConversionSequence::Worse;
  3217. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3218. // Neither conversion sequence converts to a void pointer; compare
  3219. // their derived-to-base conversions.
  3220. if (ImplicitConversionSequence::CompareKind DerivedCK
  3221. = CompareDerivedToBaseConversions(S, SCS1, SCS2))
  3222. return DerivedCK;
  3223. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3224. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3225. // Both conversion sequences are conversions to void
  3226. // pointers. Compare the source types to determine if there's an
  3227. // inheritance relationship in their sources.
  3228. QualType FromType1 = SCS1.getFromType();
  3229. QualType FromType2 = SCS2.getFromType();
  3230. // Adjust the types we're converting from via the array-to-pointer
  3231. // conversion, if we need to.
  3232. if (SCS1.First == ICK_Array_To_Pointer)
  3233. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3234. if (SCS2.First == ICK_Array_To_Pointer)
  3235. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3236. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3237. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3238. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3239. return ImplicitConversionSequence::Better;
  3240. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3241. return ImplicitConversionSequence::Worse;
  3242. // Objective-C++: If one interface is more specific than the
  3243. // other, it is the better one.
  3244. const ObjCObjectPointerType* FromObjCPtr1
  3245. = FromType1->getAs<ObjCObjectPointerType>();
  3246. const ObjCObjectPointerType* FromObjCPtr2
  3247. = FromType2->getAs<ObjCObjectPointerType>();
  3248. if (FromObjCPtr1 && FromObjCPtr2) {
  3249. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3250. FromObjCPtr2);
  3251. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3252. FromObjCPtr1);
  3253. if (AssignLeft != AssignRight) {
  3254. return AssignLeft? ImplicitConversionSequence::Better
  3255. : ImplicitConversionSequence::Worse;
  3256. }
  3257. }
  3258. }
  3259. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3260. // bullet 3).
  3261. if (ImplicitConversionSequence::CompareKind QualCK
  3262. = CompareQualificationConversions(S, SCS1, SCS2))
  3263. return QualCK;
  3264. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3265. // Check for a better reference binding based on the kind of bindings.
  3266. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3267. return ImplicitConversionSequence::Better;
  3268. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3269. return ImplicitConversionSequence::Worse;
  3270. // C++ [over.ics.rank]p3b4:
  3271. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3272. // which the references refer are the same type except for
  3273. // top-level cv-qualifiers, and the type to which the reference
  3274. // initialized by S2 refers is more cv-qualified than the type
  3275. // to which the reference initialized by S1 refers.
  3276. QualType T1 = SCS1.getToType(2);
  3277. QualType T2 = SCS2.getToType(2);
  3278. T1 = S.Context.getCanonicalType(T1);
  3279. T2 = S.Context.getCanonicalType(T2);
  3280. Qualifiers T1Quals, T2Quals;
  3281. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3282. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3283. if (UnqualT1 == UnqualT2) {
  3284. // Objective-C++ ARC: If the references refer to objects with different
  3285. // lifetimes, prefer bindings that don't change lifetime.
  3286. if (SCS1.ObjCLifetimeConversionBinding !=
  3287. SCS2.ObjCLifetimeConversionBinding) {
  3288. return SCS1.ObjCLifetimeConversionBinding
  3289. ? ImplicitConversionSequence::Worse
  3290. : ImplicitConversionSequence::Better;
  3291. }
  3292. // If the type is an array type, promote the element qualifiers to the
  3293. // type for comparison.
  3294. if (isa<ArrayType>(T1) && T1Quals)
  3295. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3296. if (isa<ArrayType>(T2) && T2Quals)
  3297. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3298. if (T2.isMoreQualifiedThan(T1))
  3299. return ImplicitConversionSequence::Better;
  3300. else if (T1.isMoreQualifiedThan(T2))
  3301. return ImplicitConversionSequence::Worse;
  3302. }
  3303. }
  3304. // In Microsoft mode, prefer an integral conversion to a
  3305. // floating-to-integral conversion if the integral conversion
  3306. // is between types of the same size.
  3307. // For example:
  3308. // void f(float);
  3309. // void f(int);
  3310. // int main {
  3311. // long a;
  3312. // f(a);
  3313. // }
  3314. // Here, MSVC will call f(int) instead of generating a compile error
  3315. // as clang will do in standard mode.
  3316. if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
  3317. SCS2.Second == ICK_Floating_Integral &&
  3318. S.Context.getTypeSize(SCS1.getFromType()) ==
  3319. S.Context.getTypeSize(SCS1.getToType(2)))
  3320. return ImplicitConversionSequence::Better;
  3321. return ImplicitConversionSequence::Indistinguishable;
  3322. }
  3323. /// CompareQualificationConversions - Compares two standard conversion
  3324. /// sequences to determine whether they can be ranked based on their
  3325. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3326. static ImplicitConversionSequence::CompareKind
  3327. CompareQualificationConversions(Sema &S,
  3328. const StandardConversionSequence& SCS1,
  3329. const StandardConversionSequence& SCS2) {
  3330. // C++ 13.3.3.2p3:
  3331. // -- S1 and S2 differ only in their qualification conversion and
  3332. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3333. // cv-qualification signature of type T1 is a proper subset of
  3334. // the cv-qualification signature of type T2, and S1 is not the
  3335. // deprecated string literal array-to-pointer conversion (4.2).
  3336. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3337. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3338. return ImplicitConversionSequence::Indistinguishable;
  3339. // FIXME: the example in the standard doesn't use a qualification
  3340. // conversion (!)
  3341. QualType T1 = SCS1.getToType(2);
  3342. QualType T2 = SCS2.getToType(2);
  3343. T1 = S.Context.getCanonicalType(T1);
  3344. T2 = S.Context.getCanonicalType(T2);
  3345. Qualifiers T1Quals, T2Quals;
  3346. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3347. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3348. // If the types are the same, we won't learn anything by unwrapped
  3349. // them.
  3350. if (UnqualT1 == UnqualT2)
  3351. return ImplicitConversionSequence::Indistinguishable;
  3352. // If the type is an array type, promote the element qualifiers to the type
  3353. // for comparison.
  3354. if (isa<ArrayType>(T1) && T1Quals)
  3355. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3356. if (isa<ArrayType>(T2) && T2Quals)
  3357. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3358. ImplicitConversionSequence::CompareKind Result
  3359. = ImplicitConversionSequence::Indistinguishable;
  3360. // Objective-C++ ARC:
  3361. // Prefer qualification conversions not involving a change in lifetime
  3362. // to qualification conversions that do not change lifetime.
  3363. if (SCS1.QualificationIncludesObjCLifetime !=
  3364. SCS2.QualificationIncludesObjCLifetime) {
  3365. Result = SCS1.QualificationIncludesObjCLifetime
  3366. ? ImplicitConversionSequence::Worse
  3367. : ImplicitConversionSequence::Better;
  3368. }
  3369. while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3370. // Within each iteration of the loop, we check the qualifiers to
  3371. // determine if this still looks like a qualification
  3372. // conversion. Then, if all is well, we unwrap one more level of
  3373. // pointers or pointers-to-members and do it all again
  3374. // until there are no more pointers or pointers-to-members left
  3375. // to unwrap. This essentially mimics what
  3376. // IsQualificationConversion does, but here we're checking for a
  3377. // strict subset of qualifiers.
  3378. if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
  3379. // The qualifiers are the same, so this doesn't tell us anything
  3380. // about how the sequences rank.
  3381. ;
  3382. else if (T2.isMoreQualifiedThan(T1)) {
  3383. // T1 has fewer qualifiers, so it could be the better sequence.
  3384. if (Result == ImplicitConversionSequence::Worse)
  3385. // Neither has qualifiers that are a subset of the other's
  3386. // qualifiers.
  3387. return ImplicitConversionSequence::Indistinguishable;
  3388. Result = ImplicitConversionSequence::Better;
  3389. } else if (T1.isMoreQualifiedThan(T2)) {
  3390. // T2 has fewer qualifiers, so it could be the better sequence.
  3391. if (Result == ImplicitConversionSequence::Better)
  3392. // Neither has qualifiers that are a subset of the other's
  3393. // qualifiers.
  3394. return ImplicitConversionSequence::Indistinguishable;
  3395. Result = ImplicitConversionSequence::Worse;
  3396. } else {
  3397. // Qualifiers are disjoint.
  3398. return ImplicitConversionSequence::Indistinguishable;
  3399. }
  3400. // If the types after this point are equivalent, we're done.
  3401. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3402. break;
  3403. }
  3404. // Check that the winning standard conversion sequence isn't using
  3405. // the deprecated string literal array to pointer conversion.
  3406. switch (Result) {
  3407. case ImplicitConversionSequence::Better:
  3408. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3409. Result = ImplicitConversionSequence::Indistinguishable;
  3410. break;
  3411. case ImplicitConversionSequence::Indistinguishable:
  3412. break;
  3413. case ImplicitConversionSequence::Worse:
  3414. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3415. Result = ImplicitConversionSequence::Indistinguishable;
  3416. break;
  3417. }
  3418. return Result;
  3419. }
  3420. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3421. /// sequences to determine whether they can be ranked based on their
  3422. /// various kinds of derived-to-base conversions (C++
  3423. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3424. /// conversions between Objective-C interface types.
  3425. static ImplicitConversionSequence::CompareKind
  3426. CompareDerivedToBaseConversions(Sema &S,
  3427. const StandardConversionSequence& SCS1,
  3428. const StandardConversionSequence& SCS2) {
  3429. QualType FromType1 = SCS1.getFromType();
  3430. QualType ToType1 = SCS1.getToType(1);
  3431. QualType FromType2 = SCS2.getFromType();
  3432. QualType ToType2 = SCS2.getToType(1);
  3433. // Adjust the types we're converting from via the array-to-pointer
  3434. // conversion, if we need to.
  3435. if (SCS1.First == ICK_Array_To_Pointer)
  3436. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3437. if (SCS2.First == ICK_Array_To_Pointer)
  3438. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3439. // Canonicalize all of the types.
  3440. FromType1 = S.Context.getCanonicalType(FromType1);
  3441. ToType1 = S.Context.getCanonicalType(ToType1);
  3442. FromType2 = S.Context.getCanonicalType(FromType2);
  3443. ToType2 = S.Context.getCanonicalType(ToType2);
  3444. // C++ [over.ics.rank]p4b3:
  3445. //
  3446. // If class B is derived directly or indirectly from class A and
  3447. // class C is derived directly or indirectly from B,
  3448. //
  3449. // Compare based on pointer conversions.
  3450. if (SCS1.Second == ICK_Pointer_Conversion &&
  3451. SCS2.Second == ICK_Pointer_Conversion &&
  3452. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3453. FromType1->isPointerType() && FromType2->isPointerType() &&
  3454. ToType1->isPointerType() && ToType2->isPointerType()) {
  3455. QualType FromPointee1
  3456. = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3457. QualType ToPointee1
  3458. = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3459. QualType FromPointee2
  3460. = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3461. QualType ToPointee2
  3462. = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3463. // -- conversion of C* to B* is better than conversion of C* to A*,
  3464. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3465. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3466. return ImplicitConversionSequence::Better;
  3467. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3468. return ImplicitConversionSequence::Worse;
  3469. }
  3470. // -- conversion of B* to A* is better than conversion of C* to A*,
  3471. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3472. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3473. return ImplicitConversionSequence::Better;
  3474. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3475. return ImplicitConversionSequence::Worse;
  3476. }
  3477. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3478. SCS2.Second == ICK_Pointer_Conversion) {
  3479. const ObjCObjectPointerType *FromPtr1
  3480. = FromType1->getAs<ObjCObjectPointerType>();
  3481. const ObjCObjectPointerType *FromPtr2
  3482. = FromType2->getAs<ObjCObjectPointerType>();
  3483. const ObjCObjectPointerType *ToPtr1
  3484. = ToType1->getAs<ObjCObjectPointerType>();
  3485. const ObjCObjectPointerType *ToPtr2
  3486. = ToType2->getAs<ObjCObjectPointerType>();
  3487. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3488. // Apply the same conversion ranking rules for Objective-C pointer types
  3489. // that we do for C++ pointers to class types. However, we employ the
  3490. // Objective-C pseudo-subtyping relationship used for assignment of
  3491. // Objective-C pointer types.
  3492. bool FromAssignLeft
  3493. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3494. bool FromAssignRight
  3495. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3496. bool ToAssignLeft
  3497. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3498. bool ToAssignRight
  3499. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3500. // A conversion to an a non-id object pointer type or qualified 'id'
  3501. // type is better than a conversion to 'id'.
  3502. if (ToPtr1->isObjCIdType() &&
  3503. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3504. return ImplicitConversionSequence::Worse;
  3505. if (ToPtr2->isObjCIdType() &&
  3506. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3507. return ImplicitConversionSequence::Better;
  3508. // A conversion to a non-id object pointer type is better than a
  3509. // conversion to a qualified 'id' type
  3510. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3511. return ImplicitConversionSequence::Worse;
  3512. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3513. return ImplicitConversionSequence::Better;
  3514. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3515. // type is better than a conversion to 'Class'.
  3516. if (ToPtr1->isObjCClassType() &&
  3517. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3518. return ImplicitConversionSequence::Worse;
  3519. if (ToPtr2->isObjCClassType() &&
  3520. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3521. return ImplicitConversionSequence::Better;
  3522. // A conversion to a non-Class object pointer type is better than a
  3523. // conversion to a qualified 'Class' type.
  3524. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3525. return ImplicitConversionSequence::Worse;
  3526. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3527. return ImplicitConversionSequence::Better;
  3528. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3529. if (S.Context.hasSameType(FromType1, FromType2) &&
  3530. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3531. (ToAssignLeft != ToAssignRight))
  3532. return ToAssignLeft? ImplicitConversionSequence::Worse
  3533. : ImplicitConversionSequence::Better;
  3534. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3535. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3536. (FromAssignLeft != FromAssignRight))
  3537. return FromAssignLeft? ImplicitConversionSequence::Better
  3538. : ImplicitConversionSequence::Worse;
  3539. }
  3540. }
  3541. // Ranking of member-pointer types.
  3542. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3543. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3544. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3545. const MemberPointerType * FromMemPointer1 =
  3546. FromType1->getAs<MemberPointerType>();
  3547. const MemberPointerType * ToMemPointer1 =
  3548. ToType1->getAs<MemberPointerType>();
  3549. const MemberPointerType * FromMemPointer2 =
  3550. FromType2->getAs<MemberPointerType>();
  3551. const MemberPointerType * ToMemPointer2 =
  3552. ToType2->getAs<MemberPointerType>();
  3553. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3554. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3555. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3556. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3557. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3558. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3559. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3560. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3561. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3562. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3563. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3564. return ImplicitConversionSequence::Worse;
  3565. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3566. return ImplicitConversionSequence::Better;
  3567. }
  3568. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3569. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3570. if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3571. return ImplicitConversionSequence::Better;
  3572. else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3573. return ImplicitConversionSequence::Worse;
  3574. }
  3575. }
  3576. if (SCS1.Second == ICK_Derived_To_Base) {
  3577. // -- conversion of C to B is better than conversion of C to A,
  3578. // -- binding of an expression of type C to a reference of type
  3579. // B& is better than binding an expression of type C to a
  3580. // reference of type A&,
  3581. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3582. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3583. if (S.IsDerivedFrom(ToType1, ToType2))
  3584. return ImplicitConversionSequence::Better;
  3585. else if (S.IsDerivedFrom(ToType2, ToType1))
  3586. return ImplicitConversionSequence::Worse;
  3587. }
  3588. // -- conversion of B to A is better than conversion of C to A.
  3589. // -- binding of an expression of type B to a reference of type
  3590. // A& is better than binding an expression of type C to a
  3591. // reference of type A&,
  3592. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3593. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3594. if (S.IsDerivedFrom(FromType2, FromType1))
  3595. return ImplicitConversionSequence::Better;
  3596. else if (S.IsDerivedFrom(FromType1, FromType2))
  3597. return ImplicitConversionSequence::Worse;
  3598. }
  3599. }
  3600. return ImplicitConversionSequence::Indistinguishable;
  3601. }
  3602. /// \brief Determine whether the given type is valid, e.g., it is not an invalid
  3603. /// C++ class.
  3604. static bool isTypeValid(QualType T) {
  3605. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3606. return !Record->isInvalidDecl();
  3607. return true;
  3608. }
  3609. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3610. /// determine whether they are reference-related,
  3611. /// reference-compatible, reference-compatible with added
  3612. /// qualification, or incompatible, for use in C++ initialization by
  3613. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3614. /// type, and the first type (T1) is the pointee type of the reference
  3615. /// type being initialized.
  3616. Sema::ReferenceCompareResult
  3617. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3618. QualType OrigT1, QualType OrigT2,
  3619. bool &DerivedToBase,
  3620. bool &ObjCConversion,
  3621. bool &ObjCLifetimeConversion) {
  3622. assert(!OrigT1->isReferenceType() &&
  3623. "T1 must be the pointee type of the reference type");
  3624. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3625. QualType T1 = Context.getCanonicalType(OrigT1);
  3626. QualType T2 = Context.getCanonicalType(OrigT2);
  3627. Qualifiers T1Quals, T2Quals;
  3628. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3629. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3630. // C++ [dcl.init.ref]p4:
  3631. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3632. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3633. // T1 is a base class of T2.
  3634. DerivedToBase = false;
  3635. ObjCConversion = false;
  3636. ObjCLifetimeConversion = false;
  3637. if (UnqualT1 == UnqualT2) {
  3638. // Nothing to do.
  3639. } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
  3640. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3641. IsDerivedFrom(UnqualT2, UnqualT1))
  3642. DerivedToBase = true;
  3643. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3644. UnqualT2->isObjCObjectOrInterfaceType() &&
  3645. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3646. ObjCConversion = true;
  3647. else
  3648. return Ref_Incompatible;
  3649. // At this point, we know that T1 and T2 are reference-related (at
  3650. // least).
  3651. // If the type is an array type, promote the element qualifiers to the type
  3652. // for comparison.
  3653. if (isa<ArrayType>(T1) && T1Quals)
  3654. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3655. if (isa<ArrayType>(T2) && T2Quals)
  3656. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3657. // C++ [dcl.init.ref]p4:
  3658. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3659. // reference-related to T2 and cv1 is the same cv-qualification
  3660. // as, or greater cv-qualification than, cv2. For purposes of
  3661. // overload resolution, cases for which cv1 is greater
  3662. // cv-qualification than cv2 are identified as
  3663. // reference-compatible with added qualification (see 13.3.3.2).
  3664. //
  3665. // Note that we also require equivalence of Objective-C GC and address-space
  3666. // qualifiers when performing these computations, so that e.g., an int in
  3667. // address space 1 is not reference-compatible with an int in address
  3668. // space 2.
  3669. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3670. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3671. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3672. ObjCLifetimeConversion = true;
  3673. T1Quals.removeObjCLifetime();
  3674. T2Quals.removeObjCLifetime();
  3675. }
  3676. if (T1Quals == T2Quals)
  3677. return Ref_Compatible;
  3678. else if (T1Quals.compatiblyIncludes(T2Quals))
  3679. return Ref_Compatible_With_Added_Qualification;
  3680. else
  3681. return Ref_Related;
  3682. }
  3683. /// \brief Look for a user-defined conversion to an value reference-compatible
  3684. /// with DeclType. Return true if something definite is found.
  3685. static bool
  3686. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  3687. QualType DeclType, SourceLocation DeclLoc,
  3688. Expr *Init, QualType T2, bool AllowRvalues,
  3689. bool AllowExplicit) {
  3690. assert(T2->isRecordType() && "Can only find conversions of record types.");
  3691. CXXRecordDecl *T2RecordDecl
  3692. = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
  3693. OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
  3694. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3695. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3696. NamedDecl *D = *I;
  3697. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3698. if (isa<UsingShadowDecl>(D))
  3699. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3700. FunctionTemplateDecl *ConvTemplate
  3701. = dyn_cast<FunctionTemplateDecl>(D);
  3702. CXXConversionDecl *Conv;
  3703. if (ConvTemplate)
  3704. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3705. else
  3706. Conv = cast<CXXConversionDecl>(D);
  3707. // If this is an explicit conversion, and we're not allowed to consider
  3708. // explicit conversions, skip it.
  3709. if (!AllowExplicit && Conv->isExplicit())
  3710. continue;
  3711. if (AllowRvalues) {
  3712. bool DerivedToBase = false;
  3713. bool ObjCConversion = false;
  3714. bool ObjCLifetimeConversion = false;
  3715. // If we are initializing an rvalue reference, don't permit conversion
  3716. // functions that return lvalues.
  3717. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  3718. const ReferenceType *RefType
  3719. = Conv->getConversionType()->getAs<LValueReferenceType>();
  3720. if (RefType && !RefType->getPointeeType()->isFunctionType())
  3721. continue;
  3722. }
  3723. if (!ConvTemplate &&
  3724. S.CompareReferenceRelationship(
  3725. DeclLoc,
  3726. Conv->getConversionType().getNonReferenceType()
  3727. .getUnqualifiedType(),
  3728. DeclType.getNonReferenceType().getUnqualifiedType(),
  3729. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  3730. Sema::Ref_Incompatible)
  3731. continue;
  3732. } else {
  3733. // If the conversion function doesn't return a reference type,
  3734. // it can't be considered for this conversion. An rvalue reference
  3735. // is only acceptable if its referencee is a function type.
  3736. const ReferenceType *RefType =
  3737. Conv->getConversionType()->getAs<ReferenceType>();
  3738. if (!RefType ||
  3739. (!RefType->isLValueReferenceType() &&
  3740. !RefType->getPointeeType()->isFunctionType()))
  3741. continue;
  3742. }
  3743. if (ConvTemplate)
  3744. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
  3745. Init, DeclType, CandidateSet,
  3746. /*AllowObjCConversionOnExplicit=*/false);
  3747. else
  3748. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
  3749. DeclType, CandidateSet,
  3750. /*AllowObjCConversionOnExplicit=*/false);
  3751. }
  3752. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3753. OverloadCandidateSet::iterator Best;
  3754. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  3755. case OR_Success:
  3756. // C++ [over.ics.ref]p1:
  3757. //
  3758. // [...] If the parameter binds directly to the result of
  3759. // applying a conversion function to the argument
  3760. // expression, the implicit conversion sequence is a
  3761. // user-defined conversion sequence (13.3.3.1.2), with the
  3762. // second standard conversion sequence either an identity
  3763. // conversion or, if the conversion function returns an
  3764. // entity of a type that is a derived class of the parameter
  3765. // type, a derived-to-base Conversion.
  3766. if (!Best->FinalConversion.DirectBinding)
  3767. return false;
  3768. ICS.setUserDefined();
  3769. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  3770. ICS.UserDefined.After = Best->FinalConversion;
  3771. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  3772. ICS.UserDefined.ConversionFunction = Best->Function;
  3773. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  3774. ICS.UserDefined.EllipsisConversion = false;
  3775. assert(ICS.UserDefined.After.ReferenceBinding &&
  3776. ICS.UserDefined.After.DirectBinding &&
  3777. "Expected a direct reference binding!");
  3778. return true;
  3779. case OR_Ambiguous:
  3780. ICS.setAmbiguous();
  3781. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  3782. Cand != CandidateSet.end(); ++Cand)
  3783. if (Cand->Viable)
  3784. ICS.Ambiguous.addConversion(Cand->Function);
  3785. return true;
  3786. case OR_No_Viable_Function:
  3787. case OR_Deleted:
  3788. // There was no suitable conversion, or we found a deleted
  3789. // conversion; continue with other checks.
  3790. return false;
  3791. }
  3792. llvm_unreachable("Invalid OverloadResult!");
  3793. }
  3794. /// \brief Compute an implicit conversion sequence for reference
  3795. /// initialization.
  3796. static ImplicitConversionSequence
  3797. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  3798. SourceLocation DeclLoc,
  3799. bool SuppressUserConversions,
  3800. bool AllowExplicit) {
  3801. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  3802. // Most paths end in a failed conversion.
  3803. ImplicitConversionSequence ICS;
  3804. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3805. QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
  3806. QualType T2 = Init->getType();
  3807. // If the initializer is the address of an overloaded function, try
  3808. // to resolve the overloaded function. If all goes well, T2 is the
  3809. // type of the resulting function.
  3810. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  3811. DeclAccessPair Found;
  3812. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  3813. false, Found))
  3814. T2 = Fn->getType();
  3815. }
  3816. // Compute some basic properties of the types and the initializer.
  3817. bool isRValRef = DeclType->isRValueReferenceType();
  3818. bool DerivedToBase = false;
  3819. bool ObjCConversion = false;
  3820. bool ObjCLifetimeConversion = false;
  3821. Expr::Classification InitCategory = Init->Classify(S.Context);
  3822. Sema::ReferenceCompareResult RefRelationship
  3823. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  3824. ObjCConversion, ObjCLifetimeConversion);
  3825. // C++0x [dcl.init.ref]p5:
  3826. // A reference to type "cv1 T1" is initialized by an expression
  3827. // of type "cv2 T2" as follows:
  3828. // -- If reference is an lvalue reference and the initializer expression
  3829. if (!isRValRef) {
  3830. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  3831. // reference-compatible with "cv2 T2," or
  3832. //
  3833. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  3834. if (InitCategory.isLValue() &&
  3835. RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
  3836. // C++ [over.ics.ref]p1:
  3837. // When a parameter of reference type binds directly (8.5.3)
  3838. // to an argument expression, the implicit conversion sequence
  3839. // is the identity conversion, unless the argument expression
  3840. // has a type that is a derived class of the parameter type,
  3841. // in which case the implicit conversion sequence is a
  3842. // derived-to-base Conversion (13.3.3.1).
  3843. ICS.setStandard();
  3844. ICS.Standard.First = ICK_Identity;
  3845. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3846. : ObjCConversion? ICK_Compatible_Conversion
  3847. : ICK_Identity;
  3848. ICS.Standard.Third = ICK_Identity;
  3849. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3850. ICS.Standard.setToType(0, T2);
  3851. ICS.Standard.setToType(1, T1);
  3852. ICS.Standard.setToType(2, T1);
  3853. ICS.Standard.ReferenceBinding = true;
  3854. ICS.Standard.DirectBinding = true;
  3855. ICS.Standard.IsLvalueReference = !isRValRef;
  3856. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3857. ICS.Standard.BindsToRvalue = false;
  3858. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3859. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3860. ICS.Standard.CopyConstructor = nullptr;
  3861. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3862. // Nothing more to do: the inaccessibility/ambiguity check for
  3863. // derived-to-base conversions is suppressed when we're
  3864. // computing the implicit conversion sequence (C++
  3865. // [over.best.ics]p2).
  3866. return ICS;
  3867. }
  3868. // -- has a class type (i.e., T2 is a class type), where T1 is
  3869. // not reference-related to T2, and can be implicitly
  3870. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  3871. // is reference-compatible with "cv3 T3" 92) (this
  3872. // conversion is selected by enumerating the applicable
  3873. // conversion functions (13.3.1.6) and choosing the best
  3874. // one through overload resolution (13.3)),
  3875. if (!SuppressUserConversions && T2->isRecordType() &&
  3876. !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3877. RefRelationship == Sema::Ref_Incompatible) {
  3878. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3879. Init, T2, /*AllowRvalues=*/false,
  3880. AllowExplicit))
  3881. return ICS;
  3882. }
  3883. }
  3884. // -- Otherwise, the reference shall be an lvalue reference to a
  3885. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3886. // shall be an rvalue reference.
  3887. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  3888. return ICS;
  3889. // -- If the initializer expression
  3890. //
  3891. // -- is an xvalue, class prvalue, array prvalue or function
  3892. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  3893. if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
  3894. (InitCategory.isXValue() ||
  3895. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  3896. (InitCategory.isLValue() && T2->isFunctionType()))) {
  3897. ICS.setStandard();
  3898. ICS.Standard.First = ICK_Identity;
  3899. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3900. : ObjCConversion? ICK_Compatible_Conversion
  3901. : ICK_Identity;
  3902. ICS.Standard.Third = ICK_Identity;
  3903. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3904. ICS.Standard.setToType(0, T2);
  3905. ICS.Standard.setToType(1, T1);
  3906. ICS.Standard.setToType(2, T1);
  3907. ICS.Standard.ReferenceBinding = true;
  3908. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  3909. // binding unless we're binding to a class prvalue.
  3910. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  3911. // allow the use of rvalue references in C++98/03 for the benefit of
  3912. // standard library implementors; therefore, we need the xvalue check here.
  3913. ICS.Standard.DirectBinding =
  3914. S.getLangOpts().CPlusPlus11 ||
  3915. !(InitCategory.isPRValue() || T2->isRecordType());
  3916. ICS.Standard.IsLvalueReference = !isRValRef;
  3917. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3918. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  3919. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3920. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3921. ICS.Standard.CopyConstructor = nullptr;
  3922. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3923. return ICS;
  3924. }
  3925. // -- has a class type (i.e., T2 is a class type), where T1 is not
  3926. // reference-related to T2, and can be implicitly converted to
  3927. // an xvalue, class prvalue, or function lvalue of type
  3928. // "cv3 T3", where "cv1 T1" is reference-compatible with
  3929. // "cv3 T3",
  3930. //
  3931. // then the reference is bound to the value of the initializer
  3932. // expression in the first case and to the result of the conversion
  3933. // in the second case (or, in either case, to an appropriate base
  3934. // class subobject).
  3935. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3936. T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3937. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3938. Init, T2, /*AllowRvalues=*/true,
  3939. AllowExplicit)) {
  3940. // In the second case, if the reference is an rvalue reference
  3941. // and the second standard conversion sequence of the
  3942. // user-defined conversion sequence includes an lvalue-to-rvalue
  3943. // conversion, the program is ill-formed.
  3944. if (ICS.isUserDefined() && isRValRef &&
  3945. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  3946. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3947. return ICS;
  3948. }
  3949. // A temporary of function type cannot be created; don't even try.
  3950. if (T1->isFunctionType())
  3951. return ICS;
  3952. // -- Otherwise, a temporary of type "cv1 T1" is created and
  3953. // initialized from the initializer expression using the
  3954. // rules for a non-reference copy initialization (8.5). The
  3955. // reference is then bound to the temporary. If T1 is
  3956. // reference-related to T2, cv1 must be the same
  3957. // cv-qualification as, or greater cv-qualification than,
  3958. // cv2; otherwise, the program is ill-formed.
  3959. if (RefRelationship == Sema::Ref_Related) {
  3960. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  3961. // we would be reference-compatible or reference-compatible with
  3962. // added qualification. But that wasn't the case, so the reference
  3963. // initialization fails.
  3964. //
  3965. // Note that we only want to check address spaces and cvr-qualifiers here.
  3966. // ObjC GC and lifetime qualifiers aren't important.
  3967. Qualifiers T1Quals = T1.getQualifiers();
  3968. Qualifiers T2Quals = T2.getQualifiers();
  3969. T1Quals.removeObjCGCAttr();
  3970. T1Quals.removeObjCLifetime();
  3971. T2Quals.removeObjCGCAttr();
  3972. T2Quals.removeObjCLifetime();
  3973. if (!T1Quals.compatiblyIncludes(T2Quals))
  3974. return ICS;
  3975. }
  3976. // If at least one of the types is a class type, the types are not
  3977. // related, and we aren't allowed any user conversions, the
  3978. // reference binding fails. This case is important for breaking
  3979. // recursion, since TryImplicitConversion below will attempt to
  3980. // create a temporary through the use of a copy constructor.
  3981. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3982. (T1->isRecordType() || T2->isRecordType()))
  3983. return ICS;
  3984. // If T1 is reference-related to T2 and the reference is an rvalue
  3985. // reference, the initializer expression shall not be an lvalue.
  3986. if (RefRelationship >= Sema::Ref_Related &&
  3987. isRValRef && Init->Classify(S.Context).isLValue())
  3988. return ICS;
  3989. // C++ [over.ics.ref]p2:
  3990. // When a parameter of reference type is not bound directly to
  3991. // an argument expression, the conversion sequence is the one
  3992. // required to convert the argument expression to the
  3993. // underlying type of the reference according to
  3994. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  3995. // to copy-initializing a temporary of the underlying type with
  3996. // the argument expression. Any difference in top-level
  3997. // cv-qualification is subsumed by the initialization itself
  3998. // and does not constitute a conversion.
  3999. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4000. /*AllowExplicit=*/false,
  4001. /*InOverloadResolution=*/false,
  4002. /*CStyle=*/false,
  4003. /*AllowObjCWritebackConversion=*/false,
  4004. /*AllowObjCConversionOnExplicit=*/false);
  4005. // Of course, that's still a reference binding.
  4006. if (ICS.isStandard()) {
  4007. ICS.Standard.ReferenceBinding = true;
  4008. ICS.Standard.IsLvalueReference = !isRValRef;
  4009. ICS.Standard.BindsToFunctionLvalue = false;
  4010. ICS.Standard.BindsToRvalue = true;
  4011. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4012. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4013. } else if (ICS.isUserDefined()) {
  4014. const ReferenceType *LValRefType =
  4015. ICS.UserDefined.ConversionFunction->getReturnType()
  4016. ->getAs<LValueReferenceType>();
  4017. // C++ [over.ics.ref]p3:
  4018. // Except for an implicit object parameter, for which see 13.3.1, a
  4019. // standard conversion sequence cannot be formed if it requires [...]
  4020. // binding an rvalue reference to an lvalue other than a function
  4021. // lvalue.
  4022. // Note that the function case is not possible here.
  4023. if (DeclType->isRValueReferenceType() && LValRefType) {
  4024. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4025. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4026. // reference to an rvalue!
  4027. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4028. return ICS;
  4029. }
  4030. ICS.UserDefined.Before.setAsIdentityConversion();
  4031. ICS.UserDefined.After.ReferenceBinding = true;
  4032. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4033. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4034. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4035. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4036. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4037. }
  4038. return ICS;
  4039. }
  4040. static ImplicitConversionSequence
  4041. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4042. bool SuppressUserConversions,
  4043. bool InOverloadResolution,
  4044. bool AllowObjCWritebackConversion,
  4045. bool AllowExplicit = false);
  4046. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4047. /// initializer list From.
  4048. static ImplicitConversionSequence
  4049. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4050. bool SuppressUserConversions,
  4051. bool InOverloadResolution,
  4052. bool AllowObjCWritebackConversion) {
  4053. // C++11 [over.ics.list]p1:
  4054. // When an argument is an initializer list, it is not an expression and
  4055. // special rules apply for converting it to a parameter type.
  4056. ImplicitConversionSequence Result;
  4057. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4058. // We need a complete type for what follows. Incomplete types can never be
  4059. // initialized from init lists.
  4060. if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
  4061. return Result;
  4062. // Per DR1467:
  4063. // If the parameter type is a class X and the initializer list has a single
  4064. // element of type cv U, where U is X or a class derived from X, the
  4065. // implicit conversion sequence is the one required to convert the element
  4066. // to the parameter type.
  4067. //
  4068. // Otherwise, if the parameter type is a character array [... ]
  4069. // and the initializer list has a single element that is an
  4070. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4071. // implicit conversion sequence is the identity conversion.
  4072. if (From->getNumInits() == 1) {
  4073. if (ToType->isRecordType()) {
  4074. QualType InitType = From->getInit(0)->getType();
  4075. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4076. S.IsDerivedFrom(InitType, ToType))
  4077. return TryCopyInitialization(S, From->getInit(0), ToType,
  4078. SuppressUserConversions,
  4079. InOverloadResolution,
  4080. AllowObjCWritebackConversion);
  4081. }
  4082. // FIXME: Check the other conditions here: array of character type,
  4083. // initializer is a string literal.
  4084. if (ToType->isArrayType()) {
  4085. InitializedEntity Entity =
  4086. InitializedEntity::InitializeParameter(S.Context, ToType,
  4087. /*Consumed=*/false);
  4088. if (S.CanPerformCopyInitialization(Entity, From)) {
  4089. Result.setStandard();
  4090. Result.Standard.setAsIdentityConversion();
  4091. Result.Standard.setFromType(ToType);
  4092. Result.Standard.setAllToTypes(ToType);
  4093. return Result;
  4094. }
  4095. }
  4096. }
  4097. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4098. // C++11 [over.ics.list]p2:
  4099. // If the parameter type is std::initializer_list<X> or "array of X" and
  4100. // all the elements can be implicitly converted to X, the implicit
  4101. // conversion sequence is the worst conversion necessary to convert an
  4102. // element of the list to X.
  4103. //
  4104. // C++14 [over.ics.list]p3:
  4105. // Otherwise, if the parameter type is "array of N X", if the initializer
  4106. // list has exactly N elements or if it has fewer than N elements and X is
  4107. // default-constructible, and if all the elements of the initializer list
  4108. // can be implicitly converted to X, the implicit conversion sequence is
  4109. // the worst conversion necessary to convert an element of the list to X.
  4110. //
  4111. // FIXME: We're missing a lot of these checks.
  4112. bool toStdInitializerList = false;
  4113. QualType X;
  4114. if (ToType->isArrayType())
  4115. X = S.Context.getAsArrayType(ToType)->getElementType();
  4116. else
  4117. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4118. if (!X.isNull()) {
  4119. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4120. Expr *Init = From->getInit(i);
  4121. ImplicitConversionSequence ICS =
  4122. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4123. InOverloadResolution,
  4124. AllowObjCWritebackConversion);
  4125. // If a single element isn't convertible, fail.
  4126. if (ICS.isBad()) {
  4127. Result = ICS;
  4128. break;
  4129. }
  4130. // Otherwise, look for the worst conversion.
  4131. if (Result.isBad() ||
  4132. CompareImplicitConversionSequences(S, ICS, Result) ==
  4133. ImplicitConversionSequence::Worse)
  4134. Result = ICS;
  4135. }
  4136. // For an empty list, we won't have computed any conversion sequence.
  4137. // Introduce the identity conversion sequence.
  4138. if (From->getNumInits() == 0) {
  4139. Result.setStandard();
  4140. Result.Standard.setAsIdentityConversion();
  4141. Result.Standard.setFromType(ToType);
  4142. Result.Standard.setAllToTypes(ToType);
  4143. }
  4144. Result.setStdInitializerListElement(toStdInitializerList);
  4145. return Result;
  4146. }
  4147. // C++14 [over.ics.list]p4:
  4148. // C++11 [over.ics.list]p3:
  4149. // Otherwise, if the parameter is a non-aggregate class X and overload
  4150. // resolution chooses a single best constructor [...] the implicit
  4151. // conversion sequence is a user-defined conversion sequence. If multiple
  4152. // constructors are viable but none is better than the others, the
  4153. // implicit conversion sequence is a user-defined conversion sequence.
  4154. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4155. // This function can deal with initializer lists.
  4156. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4157. /*AllowExplicit=*/false,
  4158. InOverloadResolution, /*CStyle=*/false,
  4159. AllowObjCWritebackConversion,
  4160. /*AllowObjCConversionOnExplicit=*/false);
  4161. }
  4162. // C++14 [over.ics.list]p5:
  4163. // C++11 [over.ics.list]p4:
  4164. // Otherwise, if the parameter has an aggregate type which can be
  4165. // initialized from the initializer list [...] the implicit conversion
  4166. // sequence is a user-defined conversion sequence.
  4167. if (ToType->isAggregateType()) {
  4168. // Type is an aggregate, argument is an init list. At this point it comes
  4169. // down to checking whether the initialization works.
  4170. // FIXME: Find out whether this parameter is consumed or not.
  4171. InitializedEntity Entity =
  4172. InitializedEntity::InitializeParameter(S.Context, ToType,
  4173. /*Consumed=*/false);
  4174. if (S.CanPerformCopyInitialization(Entity, From)) {
  4175. Result.setUserDefined();
  4176. Result.UserDefined.Before.setAsIdentityConversion();
  4177. // Initializer lists don't have a type.
  4178. Result.UserDefined.Before.setFromType(QualType());
  4179. Result.UserDefined.Before.setAllToTypes(QualType());
  4180. Result.UserDefined.After.setAsIdentityConversion();
  4181. Result.UserDefined.After.setFromType(ToType);
  4182. Result.UserDefined.After.setAllToTypes(ToType);
  4183. Result.UserDefined.ConversionFunction = nullptr;
  4184. }
  4185. return Result;
  4186. }
  4187. // C++14 [over.ics.list]p6:
  4188. // C++11 [over.ics.list]p5:
  4189. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4190. if (ToType->isReferenceType()) {
  4191. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4192. // mention initializer lists in any way. So we go by what list-
  4193. // initialization would do and try to extrapolate from that.
  4194. QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
  4195. // If the initializer list has a single element that is reference-related
  4196. // to the parameter type, we initialize the reference from that.
  4197. if (From->getNumInits() == 1) {
  4198. Expr *Init = From->getInit(0);
  4199. QualType T2 = Init->getType();
  4200. // If the initializer is the address of an overloaded function, try
  4201. // to resolve the overloaded function. If all goes well, T2 is the
  4202. // type of the resulting function.
  4203. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4204. DeclAccessPair Found;
  4205. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4206. Init, ToType, false, Found))
  4207. T2 = Fn->getType();
  4208. }
  4209. // Compute some basic properties of the types and the initializer.
  4210. bool dummy1 = false;
  4211. bool dummy2 = false;
  4212. bool dummy3 = false;
  4213. Sema::ReferenceCompareResult RefRelationship
  4214. = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
  4215. dummy2, dummy3);
  4216. if (RefRelationship >= Sema::Ref_Related) {
  4217. return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
  4218. SuppressUserConversions,
  4219. /*AllowExplicit=*/false);
  4220. }
  4221. }
  4222. // Otherwise, we bind the reference to a temporary created from the
  4223. // initializer list.
  4224. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4225. InOverloadResolution,
  4226. AllowObjCWritebackConversion);
  4227. if (Result.isFailure())
  4228. return Result;
  4229. assert(!Result.isEllipsis() &&
  4230. "Sub-initialization cannot result in ellipsis conversion.");
  4231. // Can we even bind to a temporary?
  4232. if (ToType->isRValueReferenceType() ||
  4233. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4234. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4235. Result.UserDefined.After;
  4236. SCS.ReferenceBinding = true;
  4237. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4238. SCS.BindsToRvalue = true;
  4239. SCS.BindsToFunctionLvalue = false;
  4240. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4241. SCS.ObjCLifetimeConversionBinding = false;
  4242. } else
  4243. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4244. From, ToType);
  4245. return Result;
  4246. }
  4247. // C++14 [over.ics.list]p7:
  4248. // C++11 [over.ics.list]p6:
  4249. // Otherwise, if the parameter type is not a class:
  4250. if (!ToType->isRecordType()) {
  4251. // - if the initializer list has one element that is not itself an
  4252. // initializer list, the implicit conversion sequence is the one
  4253. // required to convert the element to the parameter type.
  4254. unsigned NumInits = From->getNumInits();
  4255. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4256. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4257. SuppressUserConversions,
  4258. InOverloadResolution,
  4259. AllowObjCWritebackConversion);
  4260. // - if the initializer list has no elements, the implicit conversion
  4261. // sequence is the identity conversion.
  4262. else if (NumInits == 0) {
  4263. Result.setStandard();
  4264. Result.Standard.setAsIdentityConversion();
  4265. Result.Standard.setFromType(ToType);
  4266. Result.Standard.setAllToTypes(ToType);
  4267. }
  4268. return Result;
  4269. }
  4270. // C++14 [over.ics.list]p8:
  4271. // C++11 [over.ics.list]p7:
  4272. // In all cases other than those enumerated above, no conversion is possible
  4273. return Result;
  4274. }
  4275. /// TryCopyInitialization - Try to copy-initialize a value of type
  4276. /// ToType from the expression From. Return the implicit conversion
  4277. /// sequence required to pass this argument, which may be a bad
  4278. /// conversion sequence (meaning that the argument cannot be passed to
  4279. /// a parameter of this type). If @p SuppressUserConversions, then we
  4280. /// do not permit any user-defined conversion sequences.
  4281. static ImplicitConversionSequence
  4282. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4283. bool SuppressUserConversions,
  4284. bool InOverloadResolution,
  4285. bool AllowObjCWritebackConversion,
  4286. bool AllowExplicit) {
  4287. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4288. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4289. InOverloadResolution,AllowObjCWritebackConversion);
  4290. // HLSL Change Starts
  4291. if (S.getLangOpts().HLSL) {
  4292. // Note that this is incorrect. Copy initialization isn't syntactically
  4293. // allowed in HLSL, but C++ uses it to perform matching for argments to
  4294. // parameters.
  4295. //
  4296. // The correct fix should go to implicit conversions, but because the type
  4297. // system isn't currently up to spec, it's easier to isolate the behavior by
  4298. // putting this only on this path.
  4299. const bool ListInitFalse = false;
  4300. const bool SuppressDiagTrue = true;
  4301. const Sema::CheckedConversionKind kind = Sema::CCK_ImplicitConversion;
  4302. ImplicitConversionSequence ICS;
  4303. ICS.setStandard();
  4304. unsigned msg;
  4305. CastKind castKind;
  4306. CXXCastPath castPath;
  4307. ExprResult E(From);
  4308. if (::hlsl::TryStaticCastForHLSL(
  4309. &S, E, ToType, kind, From->getSourceRange(), msg, castKind,
  4310. castPath, ListInitFalse, SuppressDiagTrue, &ICS.Standard)) {
  4311. return ICS;
  4312. }
  4313. }
  4314. // HLSL Change Ends
  4315. if (ToType->isReferenceType())
  4316. return TryReferenceInit(S, From, ToType,
  4317. /*FIXME:*/From->getLocStart(),
  4318. SuppressUserConversions,
  4319. AllowExplicit);
  4320. return TryImplicitConversion(S, From, ToType,
  4321. SuppressUserConversions,
  4322. /*AllowExplicit=*/false,
  4323. InOverloadResolution,
  4324. /*CStyle=*/false,
  4325. AllowObjCWritebackConversion,
  4326. /*AllowObjCConversionOnExplicit=*/false);
  4327. }
  4328. static bool TryCopyInitialization(const CanQualType FromQTy,
  4329. const CanQualType ToQTy,
  4330. Sema &S,
  4331. SourceLocation Loc,
  4332. ExprValueKind FromVK) {
  4333. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4334. ImplicitConversionSequence ICS =
  4335. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4336. return !ICS.isBad();
  4337. }
  4338. /// TryObjectArgumentInitialization - Try to initialize the object
  4339. /// parameter of the given member function (@c Method) from the
  4340. /// expression @p From.
  4341. static ImplicitConversionSequence
  4342. TryObjectArgumentInitialization(Sema &S, QualType FromType,
  4343. Expr::Classification FromClassification,
  4344. CXXMethodDecl *Method,
  4345. CXXRecordDecl *ActingContext) {
  4346. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4347. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4348. // const volatile object.
  4349. unsigned Quals = isa<CXXDestructorDecl>(Method) ?
  4350. Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
  4351. QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
  4352. // Set up the conversion sequence as a "bad" conversion, to allow us
  4353. // to exit early.
  4354. ImplicitConversionSequence ICS;
  4355. // We need to have an object of class type.
  4356. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4357. FromType = PT->getPointeeType();
  4358. // When we had a pointer, it's implicitly dereferenced, so we
  4359. // better have an lvalue.
  4360. assert(FromClassification.isLValue());
  4361. }
  4362. assert(FromType->isRecordType());
  4363. // C++0x [over.match.funcs]p4:
  4364. // For non-static member functions, the type of the implicit object
  4365. // parameter is
  4366. //
  4367. // - "lvalue reference to cv X" for functions declared without a
  4368. // ref-qualifier or with the & ref-qualifier
  4369. // - "rvalue reference to cv X" for functions declared with the &&
  4370. // ref-qualifier
  4371. //
  4372. // where X is the class of which the function is a member and cv is the
  4373. // cv-qualification on the member function declaration.
  4374. //
  4375. // However, when finding an implicit conversion sequence for the argument, we
  4376. // are not allowed to create temporaries or perform user-defined conversions
  4377. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4378. // reference binding here, that allows class rvalues to bind to
  4379. // non-constant references.
  4380. // First check the qualifiers.
  4381. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4382. // HLSL Change Starts - for calls other than subscript overloads, disregard const
  4383. FromTypeCanon.removeLocalRestrict(); // HLSL Change - disregard restrict.
  4384. if (!S.getLangOpts().HLSL ||
  4385. (Method != nullptr && Method->getDeclName() == S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  4386. // HLSL Change Ends
  4387. if (ImplicitParamType.getCVRQualifiers()
  4388. != FromTypeCanon.getLocalCVRQualifiers() &&
  4389. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4390. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4391. FromType, ImplicitParamType);
  4392. return ICS;
  4393. }
  4394. } // HLSL Change - end branch
  4395. // Check that we have either the same type or a derived type. It
  4396. // affects the conversion rank.
  4397. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4398. ImplicitConversionKind SecondKind;
  4399. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4400. SecondKind = ICK_Identity;
  4401. } else if (S.IsDerivedFrom(FromType, ClassType))
  4402. SecondKind = ICK_Derived_To_Base;
  4403. else {
  4404. ICS.setBad(BadConversionSequence::unrelated_class,
  4405. FromType, ImplicitParamType);
  4406. return ICS;
  4407. }
  4408. // Check the ref-qualifier.
  4409. switch (Method->getRefQualifier()) {
  4410. case RQ_None:
  4411. // Do nothing; we don't care about lvalueness or rvalueness.
  4412. break;
  4413. case RQ_LValue:
  4414. if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
  4415. // non-const lvalue reference cannot bind to an rvalue
  4416. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4417. ImplicitParamType);
  4418. return ICS;
  4419. }
  4420. break;
  4421. case RQ_RValue:
  4422. if (!FromClassification.isRValue()) {
  4423. // rvalue reference cannot bind to an lvalue
  4424. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4425. ImplicitParamType);
  4426. return ICS;
  4427. }
  4428. break;
  4429. }
  4430. // Success. Mark this as a reference binding.
  4431. ICS.setStandard();
  4432. ICS.Standard.setAsIdentityConversion();
  4433. ICS.Standard.Second = SecondKind;
  4434. ICS.Standard.setFromType(FromType);
  4435. ICS.Standard.setAllToTypes(ImplicitParamType);
  4436. ICS.Standard.ReferenceBinding = true;
  4437. ICS.Standard.DirectBinding = true;
  4438. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4439. ICS.Standard.BindsToFunctionLvalue = false;
  4440. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4441. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4442. = (Method->getRefQualifier() == RQ_None);
  4443. ICS.Standard.ComponentConversion = ICK_Identity;
  4444. return ICS;
  4445. }
  4446. // HLSL Change Starts
  4447. static void
  4448. InitCallParamConversions(Sema &S, const FunctionProtoType *Proto,
  4449. ParmVarDecl *Param, unsigned ArgIdx, Expr *Arg,
  4450. bool SuppressUserConversions,
  4451. bool InOverloadResolution, bool AllowExplicit,
  4452. ImplicitConversionSequence &InConversion,
  4453. ImplicitConversionSequence &OutConversion) {
  4454. hlsl::ParameterModifier paramMods = Proto->getParamMods()[ArgIdx];
  4455. QualType ParamType = Proto->getParamType(ArgIdx);
  4456. if (paramMods.isAnyIn()) {
  4457. InConversion =
  4458. TryCopyInitialization(S, Arg, ParamType, SuppressUserConversions,
  4459. InOverloadResolution, false, AllowExplicit);
  4460. }
  4461. if (paramMods.isAnyOut()) {
  4462. // TryCopyInitialization takes an expression but there isn't one at this
  4463. // point - we're just trying to figure out whether the result value can be
  4464. // converted back into the argument.
  4465. if (Arg->getType().isConstant(S.getASTContext()) || !Arg->isLValue()) {
  4466. OutConversion.setBad(
  4467. BadConversionSequence::FailureKind::rvalue_ref_to_lvalue, ParamType,
  4468. Arg->getType());
  4469. return;
  4470. }
  4471. Expr *OutFrom = DeclRefExpr::Create(
  4472. S.getASTContext(), NestedNameSpecifierLoc(), SourceLocation(), Param,
  4473. true, Param->getLocation(), ParamType.getNonReferenceType(), VK_RValue, nullptr);
  4474. OutConversion = TryCopyInitialization(
  4475. S, OutFrom, Arg->getType(), SuppressUserConversions,
  4476. InOverloadResolution, false, AllowExplicit);
  4477. }
  4478. }
  4479. // HLSL Change Ends
  4480. /// PerformObjectArgumentInitialization - Perform initialization of
  4481. /// the implicit object parameter for the given Method with the given
  4482. /// expression.
  4483. ExprResult
  4484. Sema::PerformObjectArgumentInitialization(Expr *From,
  4485. NestedNameSpecifier *Qualifier,
  4486. NamedDecl *FoundDecl,
  4487. CXXMethodDecl *Method) {
  4488. QualType FromRecordType, DestType;
  4489. QualType ImplicitParamRecordType =
  4490. Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
  4491. Expr::Classification FromClassification;
  4492. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4493. FromRecordType = PT->getPointeeType();
  4494. DestType = Method->getThisType(Context);
  4495. FromClassification = Expr::Classification::makeSimpleLValue();
  4496. } else {
  4497. FromRecordType = From->getType();
  4498. DestType = ImplicitParamRecordType;
  4499. FromClassification = From->Classify(Context);
  4500. }
  4501. // Note that we always use the true parent context when performing
  4502. // the actual argument initialization.
  4503. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4504. *this, From->getType(), FromClassification, Method, Method->getParent());
  4505. if (ICS.isBad()) {
  4506. if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
  4507. Qualifiers FromQs = FromRecordType.getQualifiers();
  4508. Qualifiers ToQs = DestType.getQualifiers();
  4509. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4510. if (CVR) {
  4511. Diag(From->getLocStart(),
  4512. diag::err_member_function_call_bad_cvr)
  4513. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4514. << From->getSourceRange();
  4515. Diag(Method->getLocation(), diag::note_previous_decl)
  4516. << Method->getDeclName();
  4517. return ExprError();
  4518. }
  4519. }
  4520. return Diag(From->getLocStart(),
  4521. diag::err_implicit_object_parameter_init)
  4522. << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
  4523. }
  4524. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4525. ExprResult FromRes =
  4526. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4527. if (FromRes.isInvalid())
  4528. return ExprError();
  4529. From = FromRes.get();
  4530. }
  4531. if (!Context.hasSameType(From->getType(), DestType))
  4532. From = ImpCastExprToType(From, DestType, CK_NoOp,
  4533. From->getValueKind()).get();
  4534. return From;
  4535. }
  4536. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4537. /// expression From to bool (C++0x [conv]p3).
  4538. static ImplicitConversionSequence
  4539. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4540. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4541. /*SuppressUserConversions=*/false,
  4542. /*AllowExplicit=*/true,
  4543. /*InOverloadResolution=*/false,
  4544. /*CStyle=*/false,
  4545. /*AllowObjCWritebackConversion=*/false,
  4546. /*AllowObjCConversionOnExplicit=*/false);
  4547. }
  4548. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4549. /// of the expression From to bool (C++0x [conv]p3).
  4550. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4551. if (checkPlaceholderForOverload(*this, From))
  4552. return ExprError();
  4553. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4554. if (!ICS.isBad())
  4555. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4556. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4557. return Diag(From->getLocStart(),
  4558. diag::err_typecheck_bool_condition)
  4559. << From->getType() << From->getSourceRange();
  4560. return ExprError();
  4561. }
  4562. /// Check that the specified conversion is permitted in a converted constant
  4563. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4564. /// is acceptable.
  4565. static bool CheckConvertedConstantConversions(Sema &S,
  4566. StandardConversionSequence &SCS) {
  4567. // Since we know that the target type is an integral or unscoped enumeration
  4568. // type, most conversion kinds are impossible. All possible First and Third
  4569. // conversions are fine.
  4570. switch (SCS.Second) {
  4571. case ICK_Identity:
  4572. case ICK_NoReturn_Adjustment:
  4573. case ICK_Integral_Promotion:
  4574. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4575. return true;
  4576. case ICK_Boolean_Conversion:
  4577. // Conversion from an integral or unscoped enumeration type to bool is
  4578. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4579. // conversion, so we allow it in a converted constant expression.
  4580. //
  4581. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4582. // a lot of popular code. We should at least add a warning for this
  4583. // (non-conforming) extension.
  4584. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4585. SCS.getToType(2)->isBooleanType();
  4586. case ICK_Pointer_Conversion:
  4587. case ICK_Pointer_Member:
  4588. // C++1z: null pointer conversions and null member pointer conversions are
  4589. // only permitted if the source type is std::nullptr_t.
  4590. return SCS.getFromType()->isNullPtrType();
  4591. case ICK_Floating_Promotion:
  4592. case ICK_Complex_Promotion:
  4593. case ICK_Floating_Conversion:
  4594. case ICK_Complex_Conversion:
  4595. case ICK_Floating_Integral:
  4596. case ICK_Compatible_Conversion:
  4597. case ICK_Derived_To_Base:
  4598. case ICK_Vector_Conversion:
  4599. case ICK_Vector_Splat:
  4600. case ICK_Complex_Real:
  4601. case ICK_Block_Pointer_Conversion:
  4602. case ICK_TransparentUnionConversion:
  4603. case ICK_Writeback_Conversion:
  4604. case ICK_Zero_Event_Conversion:
  4605. case ICK_Flat_Conversion: // HLSL Change
  4606. return false;
  4607. case ICK_Lvalue_To_Rvalue:
  4608. case ICK_Array_To_Pointer:
  4609. case ICK_Function_To_Pointer:
  4610. llvm_unreachable("found a first conversion kind in Second");
  4611. case ICK_Qualification:
  4612. llvm_unreachable("found a third conversion kind in Second");
  4613. case ICK_Num_Conversion_Kinds:
  4614. break;
  4615. }
  4616. llvm_unreachable("unknown conversion kind");
  4617. }
  4618. /// CheckConvertedConstantExpression - Check that the expression From is a
  4619. /// converted constant expression of type T, perform the conversion and produce
  4620. /// the converted expression, per C++11 [expr.const]p3.
  4621. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4622. QualType T, APValue &Value,
  4623. Sema::CCEKind CCE,
  4624. bool RequireInt) {
  4625. assert((S.getLangOpts().CPlusPlus11 || S.getLangOpts().HLSLVersion >= 2017) &&
  4626. "converted constant expression outside C++11");
  4627. if (checkPlaceholderForOverload(S, From))
  4628. return ExprError();
  4629. // C++1z [expr.const]p3:
  4630. // A converted constant expression of type T is an expression,
  4631. // implicitly converted to type T, where the converted
  4632. // expression is a constant expression and the implicit conversion
  4633. // sequence contains only [... list of conversions ...].
  4634. ImplicitConversionSequence ICS =
  4635. TryCopyInitialization(S, From, T,
  4636. /*SuppressUserConversions=*/false,
  4637. /*InOverloadResolution=*/false,
  4638. /*AllowObjcWritebackConversion=*/false,
  4639. /*AllowExplicit=*/false);
  4640. StandardConversionSequence *SCS = nullptr;
  4641. switch (ICS.getKind()) {
  4642. case ImplicitConversionSequence::StandardConversion:
  4643. SCS = &ICS.Standard;
  4644. break;
  4645. case ImplicitConversionSequence::UserDefinedConversion:
  4646. // We are converting to a non-class type, so the Before sequence
  4647. // must be trivial.
  4648. SCS = &ICS.UserDefined.After;
  4649. break;
  4650. case ImplicitConversionSequence::AmbiguousConversion:
  4651. case ImplicitConversionSequence::BadConversion:
  4652. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4653. return S.Diag(From->getLocStart(),
  4654. diag::err_typecheck_converted_constant_expression)
  4655. << From->getType() << From->getSourceRange() << T;
  4656. return ExprError();
  4657. case ImplicitConversionSequence::EllipsisConversion:
  4658. llvm_unreachable("ellipsis conversion in converted constant expression");
  4659. }
  4660. // Check that we would only use permitted conversions.
  4661. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4662. return S.Diag(From->getLocStart(),
  4663. diag::err_typecheck_converted_constant_expression_disallowed)
  4664. << From->getType() << From->getSourceRange() << T;
  4665. }
  4666. // [...] and where the reference binding (if any) binds directly.
  4667. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4668. return S.Diag(From->getLocStart(),
  4669. diag::err_typecheck_converted_constant_expression_indirect)
  4670. << From->getType() << From->getSourceRange() << T;
  4671. }
  4672. ExprResult Result =
  4673. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4674. if (Result.isInvalid())
  4675. return Result;
  4676. // Check for a narrowing implicit conversion.
  4677. APValue PreNarrowingValue;
  4678. QualType PreNarrowingType;
  4679. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4680. PreNarrowingType)) {
  4681. case NK_Variable_Narrowing:
  4682. // Implicit conversion to a narrower type, and the value is not a constant
  4683. // expression. We'll diagnose this in a moment.
  4684. case NK_Not_Narrowing:
  4685. break;
  4686. case NK_Constant_Narrowing:
  4687. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4688. << CCE << /*Constant*/1
  4689. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  4690. break;
  4691. case NK_Type_Narrowing:
  4692. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4693. << CCE << /*Constant*/0 << From->getType() << T;
  4694. break;
  4695. }
  4696. // Check the expression is a constant expression.
  4697. SmallVector<PartialDiagnosticAt, 8> Notes;
  4698. Expr::EvalResult Eval;
  4699. Eval.Diag = &Notes;
  4700. if ((T->isReferenceType()
  4701. ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
  4702. : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
  4703. (RequireInt && !Eval.Val.isInt())) {
  4704. // The expression can't be folded, so we can't keep it at this position in
  4705. // the AST.
  4706. Result = ExprError();
  4707. } else {
  4708. Value = Eval.Val;
  4709. if (Notes.empty()) {
  4710. // It's a constant expression.
  4711. return Result;
  4712. }
  4713. }
  4714. // It's not a constant expression. Produce an appropriate diagnostic.
  4715. if (Notes.size() == 1 &&
  4716. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  4717. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  4718. else {
  4719. S.Diag(From->getLocStart(), diag::err_expr_not_cce)
  4720. << CCE << From->getSourceRange();
  4721. for (unsigned I = 0; I < Notes.size(); ++I)
  4722. S.Diag(Notes[I].first, Notes[I].second);
  4723. }
  4724. return ExprError();
  4725. }
  4726. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4727. APValue &Value, CCEKind CCE) {
  4728. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  4729. }
  4730. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4731. llvm::APSInt &Value,
  4732. CCEKind CCE) {
  4733. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  4734. APValue V;
  4735. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  4736. if (!R.isInvalid())
  4737. Value = V.getInt();
  4738. return R;
  4739. }
  4740. /// dropPointerConversions - If the given standard conversion sequence
  4741. /// involves any pointer conversions, remove them. This may change
  4742. /// the result type of the conversion sequence.
  4743. static void dropPointerConversion(StandardConversionSequence &SCS) {
  4744. if (SCS.Second == ICK_Pointer_Conversion) {
  4745. SCS.Second = ICK_Identity;
  4746. SCS.Third = ICK_Identity;
  4747. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  4748. }
  4749. }
  4750. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  4751. /// convert the expression From to an Objective-C pointer type.
  4752. static ImplicitConversionSequence
  4753. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  4754. // Do an implicit conversion to 'id'.
  4755. QualType Ty = S.Context.getObjCIdType();
  4756. ImplicitConversionSequence ICS
  4757. = TryImplicitConversion(S, From, Ty,
  4758. // FIXME: Are these flags correct?
  4759. /*SuppressUserConversions=*/false,
  4760. /*AllowExplicit=*/true,
  4761. /*InOverloadResolution=*/false,
  4762. /*CStyle=*/false,
  4763. /*AllowObjCWritebackConversion=*/false,
  4764. /*AllowObjCConversionOnExplicit=*/true);
  4765. // Strip off any final conversions to 'id'.
  4766. switch (ICS.getKind()) {
  4767. case ImplicitConversionSequence::BadConversion:
  4768. case ImplicitConversionSequence::AmbiguousConversion:
  4769. case ImplicitConversionSequence::EllipsisConversion:
  4770. break;
  4771. case ImplicitConversionSequence::UserDefinedConversion:
  4772. dropPointerConversion(ICS.UserDefined.After);
  4773. break;
  4774. case ImplicitConversionSequence::StandardConversion:
  4775. dropPointerConversion(ICS.Standard);
  4776. break;
  4777. }
  4778. return ICS;
  4779. }
  4780. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  4781. /// conversion of the expression From to an Objective-C pointer type.
  4782. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  4783. if (checkPlaceholderForOverload(*this, From))
  4784. return ExprError();
  4785. QualType Ty = Context.getObjCIdType();
  4786. ImplicitConversionSequence ICS =
  4787. TryContextuallyConvertToObjCPointer(*this, From);
  4788. if (!ICS.isBad())
  4789. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  4790. return ExprError();
  4791. }
  4792. /// Determine whether the provided type is an integral type, or an enumeration
  4793. /// type of a permitted flavor.
  4794. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  4795. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  4796. : T->isIntegralOrUnscopedEnumerationType();
  4797. }
  4798. static ExprResult
  4799. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  4800. Sema::ContextualImplicitConverter &Converter,
  4801. QualType T, UnresolvedSetImpl &ViableConversions) {
  4802. if (Converter.Suppress)
  4803. return ExprError();
  4804. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  4805. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4806. CXXConversionDecl *Conv =
  4807. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  4808. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  4809. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  4810. }
  4811. return From;
  4812. }
  4813. static bool
  4814. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4815. Sema::ContextualImplicitConverter &Converter,
  4816. QualType T, bool HadMultipleCandidates,
  4817. UnresolvedSetImpl &ExplicitConversions) {
  4818. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  4819. DeclAccessPair Found = ExplicitConversions[0];
  4820. CXXConversionDecl *Conversion =
  4821. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4822. // The user probably meant to invoke the given explicit
  4823. // conversion; use it.
  4824. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  4825. std::string TypeStr;
  4826. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  4827. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  4828. << FixItHint::CreateInsertion(From->getLocStart(),
  4829. "static_cast<" + TypeStr + ">(")
  4830. << FixItHint::CreateInsertion(
  4831. SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
  4832. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  4833. // If we aren't in a SFINAE context, build a call to the
  4834. // explicit conversion function.
  4835. if (SemaRef.isSFINAEContext())
  4836. return true;
  4837. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4838. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4839. HadMultipleCandidates);
  4840. if (Result.isInvalid())
  4841. return true;
  4842. // Record usage of conversion in an implicit cast.
  4843. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4844. CK_UserDefinedConversion, Result.get(),
  4845. nullptr, Result.get()->getValueKind());
  4846. }
  4847. return false;
  4848. }
  4849. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4850. Sema::ContextualImplicitConverter &Converter,
  4851. QualType T, bool HadMultipleCandidates,
  4852. DeclAccessPair &Found) {
  4853. CXXConversionDecl *Conversion =
  4854. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4855. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4856. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  4857. if (!Converter.SuppressConversion) {
  4858. if (SemaRef.isSFINAEContext())
  4859. return true;
  4860. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  4861. << From->getSourceRange();
  4862. }
  4863. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4864. HadMultipleCandidates);
  4865. if (Result.isInvalid())
  4866. return true;
  4867. // Record usage of conversion in an implicit cast.
  4868. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4869. CK_UserDefinedConversion, Result.get(),
  4870. nullptr, Result.get()->getValueKind());
  4871. return false;
  4872. }
  4873. static ExprResult finishContextualImplicitConversion(
  4874. Sema &SemaRef, SourceLocation Loc, Expr *From,
  4875. Sema::ContextualImplicitConverter &Converter) {
  4876. if (!Converter.match(From->getType()) && !Converter.Suppress)
  4877. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  4878. << From->getSourceRange();
  4879. return SemaRef.DefaultLvalueConversion(From);
  4880. }
  4881. static void
  4882. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  4883. UnresolvedSetImpl &ViableConversions,
  4884. OverloadCandidateSet &CandidateSet) {
  4885. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4886. DeclAccessPair FoundDecl = ViableConversions[I];
  4887. NamedDecl *D = FoundDecl.getDecl();
  4888. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  4889. if (isa<UsingShadowDecl>(D))
  4890. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4891. CXXConversionDecl *Conv;
  4892. FunctionTemplateDecl *ConvTemplate;
  4893. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  4894. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4895. else
  4896. Conv = cast<CXXConversionDecl>(D);
  4897. if (ConvTemplate)
  4898. SemaRef.AddTemplateConversionCandidate(
  4899. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  4900. /*AllowObjCConversionOnExplicit=*/false);
  4901. else
  4902. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  4903. ToType, CandidateSet,
  4904. /*AllowObjCConversionOnExplicit=*/false);
  4905. }
  4906. }
  4907. /// \brief Attempt to convert the given expression to a type which is accepted
  4908. /// by the given converter.
  4909. ///
  4910. /// This routine will attempt to convert an expression of class type to a
  4911. /// type accepted by the specified converter. In C++11 and before, the class
  4912. /// must have a single non-explicit conversion function converting to a matching
  4913. /// type. In C++1y, there can be multiple such conversion functions, but only
  4914. /// one target type.
  4915. ///
  4916. /// \param Loc The source location of the construct that requires the
  4917. /// conversion.
  4918. ///
  4919. /// \param From The expression we're converting from.
  4920. ///
  4921. /// \param Converter Used to control and diagnose the conversion process.
  4922. ///
  4923. /// \returns The expression, converted to an integral or enumeration type if
  4924. /// successful.
  4925. ExprResult Sema::PerformContextualImplicitConversion(
  4926. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  4927. // We can't perform any more checking for type-dependent expressions.
  4928. if (From->isTypeDependent())
  4929. return From;
  4930. // Process placeholders immediately.
  4931. if (From->hasPlaceholderType()) {
  4932. ExprResult result = CheckPlaceholderExpr(From);
  4933. if (result.isInvalid())
  4934. return result;
  4935. From = result.get();
  4936. }
  4937. // If the expression already has a matching type, we're golden.
  4938. QualType T = From->getType();
  4939. if (Converter.match(T))
  4940. return DefaultLvalueConversion(From);
  4941. // FIXME: Check for missing '()' if T is a function type?
  4942. // We can only perform contextual implicit conversions on objects of class
  4943. // type.
  4944. const RecordType *RecordTy = T->getAs<RecordType>();
  4945. if (!RecordTy || !getLangOpts().CPlusPlus) {
  4946. if (!Converter.Suppress)
  4947. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  4948. return From;
  4949. }
  4950. // We must have a complete class type.
  4951. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  4952. ContextualImplicitConverter &Converter;
  4953. Expr *From;
  4954. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  4955. : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
  4956. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  4957. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  4958. }
  4959. } IncompleteDiagnoser(Converter, From);
  4960. if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
  4961. return From;
  4962. // Look for a conversion to an integral or enumeration type.
  4963. UnresolvedSet<4>
  4964. ViableConversions; // These are *potentially* viable in C++1y.
  4965. UnresolvedSet<4> ExplicitConversions;
  4966. const auto &Conversions =
  4967. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  4968. bool HadMultipleCandidates =
  4969. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  4970. // To check that there is only one target type, in C++1y:
  4971. QualType ToType;
  4972. bool HasUniqueTargetType = true;
  4973. // Collect explicit or viable (potentially in C++1y) conversions.
  4974. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4975. NamedDecl *D = (*I)->getUnderlyingDecl();
  4976. CXXConversionDecl *Conversion;
  4977. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4978. if (ConvTemplate) {
  4979. if (getLangOpts().CPlusPlus14)
  4980. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4981. else
  4982. continue; // C++11 does not consider conversion operator templates(?).
  4983. } else
  4984. Conversion = cast<CXXConversionDecl>(D);
  4985. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  4986. "Conversion operator templates are considered potentially "
  4987. "viable in C++1y");
  4988. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  4989. if (Converter.match(CurToType) || ConvTemplate) {
  4990. if (Conversion->isExplicit()) {
  4991. // FIXME: For C++1y, do we need this restriction?
  4992. // cf. diagnoseNoViableConversion()
  4993. if (!ConvTemplate)
  4994. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  4995. } else {
  4996. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  4997. if (ToType.isNull())
  4998. ToType = CurToType.getUnqualifiedType();
  4999. else if (HasUniqueTargetType &&
  5000. (CurToType.getUnqualifiedType() != ToType))
  5001. HasUniqueTargetType = false;
  5002. }
  5003. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5004. }
  5005. }
  5006. }
  5007. if (getLangOpts().CPlusPlus14) {
  5008. // C++1y [conv]p6:
  5009. // ... An expression e of class type E appearing in such a context
  5010. // is said to be contextually implicitly converted to a specified
  5011. // type T and is well-formed if and only if e can be implicitly
  5012. // converted to a type T that is determined as follows: E is searched
  5013. // for conversion functions whose return type is cv T or reference to
  5014. // cv T such that T is allowed by the context. There shall be
  5015. // exactly one such T.
  5016. // If no unique T is found:
  5017. if (ToType.isNull()) {
  5018. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5019. HadMultipleCandidates,
  5020. ExplicitConversions))
  5021. return ExprError();
  5022. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5023. }
  5024. // If more than one unique Ts are found:
  5025. if (!HasUniqueTargetType)
  5026. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5027. ViableConversions);
  5028. // If one unique T is found:
  5029. // First, build a candidate set from the previously recorded
  5030. // potentially viable conversions.
  5031. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5032. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5033. CandidateSet);
  5034. // Then, perform overload resolution over the candidate set.
  5035. OverloadCandidateSet::iterator Best;
  5036. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5037. case OR_Success: {
  5038. // Apply this conversion.
  5039. DeclAccessPair Found =
  5040. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5041. if (recordConversion(*this, Loc, From, Converter, T,
  5042. HadMultipleCandidates, Found))
  5043. return ExprError();
  5044. break;
  5045. }
  5046. case OR_Ambiguous:
  5047. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5048. ViableConversions);
  5049. case OR_No_Viable_Function:
  5050. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5051. HadMultipleCandidates,
  5052. ExplicitConversions))
  5053. return ExprError();
  5054. // fall through 'OR_Deleted' case.
  5055. case OR_Deleted:
  5056. // We'll complain below about a non-integral condition type.
  5057. break;
  5058. }
  5059. } else {
  5060. switch (ViableConversions.size()) {
  5061. case 0: {
  5062. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5063. HadMultipleCandidates,
  5064. ExplicitConversions))
  5065. return ExprError();
  5066. // We'll complain below about a non-integral condition type.
  5067. break;
  5068. }
  5069. case 1: {
  5070. // Apply this conversion.
  5071. DeclAccessPair Found = ViableConversions[0];
  5072. if (recordConversion(*this, Loc, From, Converter, T,
  5073. HadMultipleCandidates, Found))
  5074. return ExprError();
  5075. break;
  5076. }
  5077. default:
  5078. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5079. ViableConversions);
  5080. }
  5081. }
  5082. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5083. }
  5084. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5085. /// an acceptable non-member overloaded operator for a call whose
  5086. /// arguments have types T1 (and, if non-empty, T2). This routine
  5087. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5088. /// enumeration types.
  5089. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5090. FunctionDecl *Fn,
  5091. ArrayRef<Expr *> Args) {
  5092. QualType T1 = Args[0]->getType();
  5093. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5094. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5095. return true;
  5096. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5097. return true;
  5098. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5099. if (Proto->getNumParams() < 1)
  5100. return false;
  5101. if (T1->isEnumeralType()) {
  5102. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5103. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5104. return true;
  5105. }
  5106. if (Proto->getNumParams() < 2)
  5107. return false;
  5108. if (!T2.isNull() && T2->isEnumeralType()) {
  5109. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5110. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5111. return true;
  5112. }
  5113. return false;
  5114. }
  5115. /// AddOverloadCandidate - Adds the given function to the set of
  5116. /// candidate functions, using the given function call arguments. If
  5117. /// @p SuppressUserConversions, then don't allow user-defined
  5118. /// conversions via constructors or conversion operators.
  5119. ///
  5120. /// \param PartialOverloading true if we are performing "partial" overloading
  5121. /// based on an incomplete set of function arguments. This feature is used by
  5122. /// code completion.
  5123. void
  5124. Sema::AddOverloadCandidate(FunctionDecl *Function,
  5125. DeclAccessPair FoundDecl,
  5126. ArrayRef<Expr *> Args,
  5127. OverloadCandidateSet &CandidateSet,
  5128. bool SuppressUserConversions,
  5129. bool PartialOverloading,
  5130. bool AllowExplicit) {
  5131. const FunctionProtoType *Proto
  5132. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5133. assert(Proto && "Functions without a prototype cannot be overloaded");
  5134. assert(!Function->getDescribedFunctionTemplate() &&
  5135. "Use AddTemplateOverloadCandidate for function templates");
  5136. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5137. if (!isa<CXXConstructorDecl>(Method)) {
  5138. // If we get here, it's because we're calling a member function
  5139. // that is named without a member access expression (e.g.,
  5140. // "this->f") that was either written explicitly or created
  5141. // implicitly. This can happen with a qualified call to a member
  5142. // function, e.g., X::f(). We use an empty type for the implied
  5143. // object argument (C++ [over.call.func]p3), and the acting context
  5144. // is irrelevant.
  5145. AddMethodCandidate(Method, FoundDecl, Method->getParent(),
  5146. QualType(), Expr::Classification::makeSimpleLValue(),
  5147. Args, CandidateSet, SuppressUserConversions,
  5148. PartialOverloading);
  5149. return;
  5150. }
  5151. // We treat a constructor like a non-member function, since its object
  5152. // argument doesn't participate in overload resolution.
  5153. }
  5154. if (!CandidateSet.isNewCandidate(Function))
  5155. return;
  5156. // C++ [over.match.oper]p3:
  5157. // if no operand has a class type, only those non-member functions in the
  5158. // lookup set that have a first parameter of type T1 or "reference to
  5159. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5160. // is a right operand) a second parameter of type T2 or "reference to
  5161. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5162. // candidate functions.
  5163. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5164. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5165. return;
  5166. // C++11 [class.copy]p11: [DR1402]
  5167. // A defaulted move constructor that is defined as deleted is ignored by
  5168. // overload resolution.
  5169. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5170. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5171. Constructor->isMoveConstructor())
  5172. return;
  5173. // Overload resolution is always an unevaluated context.
  5174. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5175. // Add this candidate
  5176. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  5177. Candidate.FoundDecl = FoundDecl;
  5178. Candidate.Function = Function;
  5179. Candidate.Viable = true;
  5180. Candidate.IsSurrogate = false;
  5181. Candidate.IgnoreObjectArgument = false;
  5182. Candidate.ExplicitCallArguments = Args.size();
  5183. if (Constructor) {
  5184. // C++ [class.copy]p3:
  5185. // A member function template is never instantiated to perform the copy
  5186. // of a class object to an object of its class type.
  5187. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5188. if (Args.size() == 1 &&
  5189. Constructor->isSpecializationCopyingObject() &&
  5190. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5191. IsDerivedFrom(Args[0]->getType(), ClassType))) {
  5192. Candidate.Viable = false;
  5193. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5194. return;
  5195. }
  5196. }
  5197. unsigned NumParams = Proto->getNumParams();
  5198. // (C++ 13.3.2p2): A candidate function having fewer than m
  5199. // parameters is viable only if it has an ellipsis in its parameter
  5200. // list (8.3.5).
  5201. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5202. !Proto->isVariadic()) {
  5203. Candidate.Viable = false;
  5204. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5205. return;
  5206. }
  5207. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5208. // is viable only if the (m+1)st parameter has a default argument
  5209. // (8.3.6). For the purposes of overload resolution, the
  5210. // parameter list is truncated on the right, so that there are
  5211. // exactly m parameters.
  5212. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5213. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5214. // Not enough arguments.
  5215. Candidate.Viable = false;
  5216. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5217. return;
  5218. }
  5219. // (CUDA B.1): Check for invalid calls between targets.
  5220. if (getLangOpts().CUDA)
  5221. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5222. // Skip the check for callers that are implicit members, because in this
  5223. // case we may not yet know what the member's target is; the target is
  5224. // inferred for the member automatically, based on the bases and fields of
  5225. // the class.
  5226. if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
  5227. Candidate.Viable = false;
  5228. Candidate.FailureKind = ovl_fail_bad_target;
  5229. return;
  5230. }
  5231. // Determine the implicit conversion sequences for each of the
  5232. // arguments.
  5233. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5234. if (ArgIdx < NumParams) {
  5235. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5236. // exist for each argument an implicit conversion sequence
  5237. // (13.3.3.1) that converts that argument to the corresponding
  5238. // parameter of F.
  5239. // HLSL Change Starts
  5240. if (getLangOpts().HLSL) {
  5241. InitCallParamConversions(
  5242. *this, Proto, Function->getParamDecl(ArgIdx), ArgIdx, Args[ArgIdx],
  5243. SuppressUserConversions, true, AllowExplicit,
  5244. Candidate.Conversions[ArgIdx], Candidate.OutConversions[ArgIdx]);
  5245. } else {
  5246. QualType ParamType = Proto->getParamType(ArgIdx);
  5247. Candidate.Conversions[ArgIdx]
  5248. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5249. SuppressUserConversions,
  5250. /*InOverloadResolution=*/true,
  5251. /*AllowObjCWritebackConversion=*/
  5252. getLangOpts().ObjCAutoRefCount,
  5253. AllowExplicit);
  5254. }
  5255. // HLSL Change Ends
  5256. if ((Candidate.Conversions[ArgIdx].isInitialized() && Candidate.Conversions[ArgIdx].isBad())
  5257. || (Candidate.OutConversions[ArgIdx].isInitialized() && Candidate.OutConversions[ArgIdx].isBad())) { // HLSL Change - add out conversion, check initialized
  5258. Candidate.Viable = false;
  5259. Candidate.FailureKind = ovl_fail_bad_conversion;
  5260. return;
  5261. }
  5262. } else {
  5263. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5264. // argument for which there is no corresponding parameter is
  5265. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5266. Candidate.Conversions[ArgIdx].setEllipsis();
  5267. }
  5268. }
  5269. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5270. Candidate.Viable = false;
  5271. Candidate.FailureKind = ovl_fail_enable_if;
  5272. Candidate.DeductionFailure.Data = FailedAttr;
  5273. return;
  5274. }
  5275. }
  5276. ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
  5277. bool IsInstance) {
  5278. SmallVector<ObjCMethodDecl*, 4> Methods;
  5279. if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
  5280. return nullptr;
  5281. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5282. bool Match = true;
  5283. ObjCMethodDecl *Method = Methods[b];
  5284. unsigned NumNamedArgs = Sel.getNumArgs();
  5285. // Method might have more arguments than selector indicates. This is due
  5286. // to addition of c-style arguments in method.
  5287. if (Method->param_size() > NumNamedArgs)
  5288. NumNamedArgs = Method->param_size();
  5289. if (Args.size() < NumNamedArgs)
  5290. continue;
  5291. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5292. // We can't do any type-checking on a type-dependent argument.
  5293. if (Args[i]->isTypeDependent()) {
  5294. Match = false;
  5295. break;
  5296. }
  5297. ParmVarDecl *param = Method->parameters()[i];
  5298. Expr *argExpr = Args[i];
  5299. assert(argExpr && "SelectBestMethod(): missing expression");
  5300. // Strip the unbridged-cast placeholder expression off unless it's
  5301. // a consumed argument.
  5302. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5303. !param->hasAttr<CFConsumedAttr>())
  5304. argExpr = stripARCUnbridgedCast(argExpr);
  5305. // If the parameter is __unknown_anytype, move on to the next method.
  5306. if (param->getType() == Context.UnknownAnyTy) {
  5307. Match = false;
  5308. break;
  5309. }
  5310. ImplicitConversionSequence ConversionState
  5311. = TryCopyInitialization(*this, argExpr, param->getType(),
  5312. /*SuppressUserConversions*/false,
  5313. /*InOverloadResolution=*/true,
  5314. /*AllowObjCWritebackConversion=*/
  5315. getLangOpts().ObjCAutoRefCount,
  5316. /*AllowExplicit*/false);
  5317. if (ConversionState.isBad()) {
  5318. Match = false;
  5319. break;
  5320. }
  5321. }
  5322. // Promote additional arguments to variadic methods.
  5323. if (Match && Method->isVariadic()) {
  5324. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5325. if (Args[i]->isTypeDependent()) {
  5326. Match = false;
  5327. break;
  5328. }
  5329. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5330. nullptr);
  5331. if (Arg.isInvalid()) {
  5332. Match = false;
  5333. break;
  5334. }
  5335. }
  5336. } else {
  5337. // Check for extra arguments to non-variadic methods.
  5338. if (Args.size() != NumNamedArgs)
  5339. Match = false;
  5340. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5341. // Special case when selectors have no argument. In this case, select
  5342. // one with the most general result type of 'id'.
  5343. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5344. QualType ReturnT = Methods[b]->getReturnType();
  5345. if (ReturnT->isObjCIdType())
  5346. return Methods[b];
  5347. }
  5348. }
  5349. }
  5350. if (Match)
  5351. return Method;
  5352. }
  5353. return nullptr;
  5354. }
  5355. static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
  5356. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5357. bool MissingImplicitThis) {
  5358. // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
  5359. // we need to find the first failing one.
  5360. if (!Function->hasAttrs())
  5361. return nullptr;
  5362. AttrVec Attrs = Function->getAttrs();
  5363. AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
  5364. IsNotEnableIfAttr);
  5365. if (Attrs.begin() == E)
  5366. return nullptr;
  5367. std::reverse(Attrs.begin(), E);
  5368. SFINAETrap Trap(*this);
  5369. // Convert the arguments.
  5370. SmallVector<Expr *, 16> ConvertedArgs;
  5371. bool InitializationFailed = false;
  5372. bool ContainsValueDependentExpr = false;
  5373. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5374. if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
  5375. !cast<CXXMethodDecl>(Function)->isStatic() &&
  5376. !isa<CXXConstructorDecl>(Function)) {
  5377. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5378. ExprResult R =
  5379. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  5380. Method, Method);
  5381. if (R.isInvalid()) {
  5382. InitializationFailed = true;
  5383. break;
  5384. }
  5385. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5386. ConvertedArgs.push_back(R.get());
  5387. } else {
  5388. ExprResult R =
  5389. PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5390. Context,
  5391. Function->getParamDecl(i)),
  5392. SourceLocation(),
  5393. Args[i]);
  5394. if (R.isInvalid()) {
  5395. InitializationFailed = true;
  5396. break;
  5397. }
  5398. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5399. ConvertedArgs.push_back(R.get());
  5400. }
  5401. }
  5402. if (InitializationFailed || Trap.hasErrorOccurred())
  5403. return cast<EnableIfAttr>(Attrs[0]);
  5404. for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
  5405. APValue Result;
  5406. EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
  5407. if (EIA->getCond()->isValueDependent()) {
  5408. // Don't even try now, we'll examine it after instantiation.
  5409. continue;
  5410. }
  5411. if (!EIA->getCond()->EvaluateWithSubstitution(
  5412. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
  5413. if (!ContainsValueDependentExpr)
  5414. return EIA;
  5415. } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
  5416. return EIA;
  5417. }
  5418. }
  5419. return nullptr;
  5420. }
  5421. /// \brief Add all of the function declarations in the given function set to
  5422. /// the overload candidate set.
  5423. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5424. ArrayRef<Expr *> Args,
  5425. OverloadCandidateSet& CandidateSet,
  5426. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5427. bool SuppressUserConversions,
  5428. bool PartialOverloading) {
  5429. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5430. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5431. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  5432. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  5433. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5434. cast<CXXMethodDecl>(FD)->getParent(),
  5435. Args[0]->getType(), Args[0]->Classify(Context),
  5436. Args.slice(1), CandidateSet,
  5437. SuppressUserConversions, PartialOverloading);
  5438. else
  5439. AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
  5440. SuppressUserConversions, PartialOverloading);
  5441. } else {
  5442. FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
  5443. if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
  5444. !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
  5445. AddMethodTemplateCandidate(FunTmpl, F.getPair(),
  5446. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5447. ExplicitTemplateArgs,
  5448. Args[0]->getType(),
  5449. Args[0]->Classify(Context), Args.slice(1),
  5450. CandidateSet, SuppressUserConversions,
  5451. PartialOverloading);
  5452. else
  5453. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  5454. ExplicitTemplateArgs, Args,
  5455. CandidateSet, SuppressUserConversions,
  5456. PartialOverloading);
  5457. }
  5458. }
  5459. }
  5460. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5461. /// method) as a method candidate to the given overload set.
  5462. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
  5463. QualType ObjectType,
  5464. Expr::Classification ObjectClassification,
  5465. ArrayRef<Expr *> Args,
  5466. OverloadCandidateSet& CandidateSet,
  5467. bool SuppressUserConversions) {
  5468. NamedDecl *Decl = FoundDecl.getDecl();
  5469. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5470. if (isa<UsingShadowDecl>(Decl))
  5471. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5472. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5473. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5474. "Expected a member function template");
  5475. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5476. /*ExplicitArgs*/ nullptr,
  5477. ObjectType, ObjectClassification,
  5478. Args, CandidateSet,
  5479. SuppressUserConversions);
  5480. } else {
  5481. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5482. ObjectType, ObjectClassification,
  5483. Args,
  5484. CandidateSet, SuppressUserConversions);
  5485. }
  5486. }
  5487. /// AddMethodCandidate - Adds the given C++ member function to the set
  5488. /// of candidate functions, using the given function call arguments
  5489. /// and the object argument (@c Object). For example, in a call
  5490. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5491. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5492. /// allow user-defined conversions via constructors or conversion
  5493. /// operators.
  5494. void
  5495. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5496. CXXRecordDecl *ActingContext, QualType ObjectType,
  5497. Expr::Classification ObjectClassification,
  5498. ArrayRef<Expr *> Args,
  5499. OverloadCandidateSet &CandidateSet,
  5500. bool SuppressUserConversions,
  5501. bool PartialOverloading) {
  5502. const FunctionProtoType *Proto
  5503. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5504. assert(Proto && "Methods without a prototype cannot be overloaded");
  5505. assert(!isa<CXXConstructorDecl>(Method) &&
  5506. "Use AddOverloadCandidate for constructors");
  5507. if (!CandidateSet.isNewCandidate(Method))
  5508. return;
  5509. // C++11 [class.copy]p23: [DR1402]
  5510. // A defaulted move assignment operator that is defined as deleted is
  5511. // ignored by overload resolution.
  5512. if (Method->isDefaulted() && Method->isDeleted() &&
  5513. Method->isMoveAssignmentOperator())
  5514. return;
  5515. // Overload resolution is always an unevaluated context.
  5516. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5517. // Add this candidate
  5518. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5519. Candidate.FoundDecl = FoundDecl;
  5520. Candidate.Function = Method;
  5521. Candidate.IsSurrogate = false;
  5522. Candidate.IgnoreObjectArgument = false;
  5523. Candidate.ExplicitCallArguments = Args.size();
  5524. unsigned NumParams = Proto->getNumParams();
  5525. // (C++ 13.3.2p2): A candidate function having fewer than m
  5526. // parameters is viable only if it has an ellipsis in its parameter
  5527. // list (8.3.5).
  5528. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5529. !Proto->isVariadic()) {
  5530. Candidate.Viable = false;
  5531. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5532. return;
  5533. }
  5534. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5535. // is viable only if the (m+1)st parameter has a default argument
  5536. // (8.3.6). For the purposes of overload resolution, the
  5537. // parameter list is truncated on the right, so that there are
  5538. // exactly m parameters.
  5539. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  5540. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5541. // Not enough arguments.
  5542. Candidate.Viable = false;
  5543. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5544. return;
  5545. }
  5546. Candidate.Viable = true;
  5547. if (Method->isStatic() || ObjectType.isNull())
  5548. // The implicit object argument is ignored.
  5549. Candidate.IgnoreObjectArgument = true;
  5550. else {
  5551. // Determine the implicit conversion sequence for the object
  5552. // parameter.
  5553. Candidate.Conversions[0]
  5554. = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
  5555. Method, ActingContext);
  5556. if (Candidate.Conversions[0].isBad()) {
  5557. Candidate.Viable = false;
  5558. Candidate.FailureKind = ovl_fail_bad_conversion;
  5559. return;
  5560. }
  5561. }
  5562. // (CUDA B.1): Check for invalid calls between targets.
  5563. if (getLangOpts().CUDA)
  5564. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5565. if (CheckCUDATarget(Caller, Method)) {
  5566. Candidate.Viable = false;
  5567. Candidate.FailureKind = ovl_fail_bad_target;
  5568. return;
  5569. }
  5570. // Determine the implicit conversion sequences for each of the
  5571. // arguments.
  5572. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5573. if (ArgIdx < NumParams) {
  5574. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5575. // exist for each argument an implicit conversion sequence
  5576. // (13.3.3.1) that converts that argument to the corresponding
  5577. // parameter of F.
  5578. QualType ParamType = Proto->getParamType(ArgIdx);
  5579. // HLSL Change Starts
  5580. if (getLangOpts().HLSL && Method->getDeclName() == Context.DeclarationNames.getCXXOperatorName(OO_Subscript)) {
  5581. Candidate.Conversions[ArgIdx + 1] = hlsl::TrySubscriptIndexInitialization(
  5582. this, Args[ArgIdx], ParamType);
  5583. goto EvaluateCandidate;
  5584. }
  5585. // HLSL Change Ends
  5586. Candidate.Conversions[ArgIdx + 1]
  5587. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5588. SuppressUserConversions,
  5589. /*InOverloadResolution=*/true,
  5590. /*AllowObjCWritebackConversion=*/
  5591. getLangOpts().ObjCAutoRefCount);
  5592. EvaluateCandidate:// HLSL Change - present alterantive to TryCopyInitialization
  5593. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  5594. Candidate.Viable = false;
  5595. Candidate.FailureKind = ovl_fail_bad_conversion;
  5596. return;
  5597. }
  5598. } else {
  5599. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5600. // argument for which there is no corresponding parameter is
  5601. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  5602. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  5603. }
  5604. }
  5605. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  5606. Candidate.Viable = false;
  5607. Candidate.FailureKind = ovl_fail_enable_if;
  5608. Candidate.DeductionFailure.Data = FailedAttr;
  5609. return;
  5610. }
  5611. }
  5612. /// \brief Add a C++ member function template as a candidate to the candidate
  5613. /// set, using template argument deduction to produce an appropriate member
  5614. /// function template specialization.
  5615. void
  5616. Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
  5617. DeclAccessPair FoundDecl,
  5618. CXXRecordDecl *ActingContext,
  5619. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5620. QualType ObjectType,
  5621. Expr::Classification ObjectClassification,
  5622. ArrayRef<Expr *> Args,
  5623. OverloadCandidateSet& CandidateSet,
  5624. bool SuppressUserConversions,
  5625. bool PartialOverloading) {
  5626. if (!CandidateSet.isNewCandidate(MethodTmpl))
  5627. return;
  5628. // C++ [over.match.funcs]p7:
  5629. // In each case where a candidate is a function template, candidate
  5630. // function template specializations are generated using template argument
  5631. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5632. // candidate functions in the usual way.113) A given name can refer to one
  5633. // or more function templates and also to a set of overloaded non-template
  5634. // functions. In such a case, the candidate functions generated from each
  5635. // function template are combined with the set of non-template candidate
  5636. // functions.
  5637. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5638. FunctionDecl *Specialization = nullptr;
  5639. if (TemplateDeductionResult Result
  5640. = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
  5641. Specialization, Info, PartialOverloading)) {
  5642. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5643. Candidate.FoundDecl = FoundDecl;
  5644. Candidate.Function = MethodTmpl->getTemplatedDecl();
  5645. Candidate.Viable = false;
  5646. Candidate.FailureKind = ovl_fail_bad_deduction;
  5647. Candidate.IsSurrogate = false;
  5648. Candidate.IgnoreObjectArgument = false;
  5649. Candidate.ExplicitCallArguments = Args.size();
  5650. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5651. Info);
  5652. return;
  5653. }
  5654. // Add the function template specialization produced by template argument
  5655. // deduction as a candidate.
  5656. assert(Specialization && "Missing member function template specialization?");
  5657. assert(isa<CXXMethodDecl>(Specialization) &&
  5658. "Specialization is not a member function?");
  5659. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  5660. ActingContext, ObjectType, ObjectClassification, Args,
  5661. CandidateSet, SuppressUserConversions, PartialOverloading);
  5662. }
  5663. /// \brief Add a C++ function template specialization as a candidate
  5664. /// in the candidate set, using template argument deduction to produce
  5665. /// an appropriate function template specialization.
  5666. void
  5667. Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
  5668. DeclAccessPair FoundDecl,
  5669. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5670. ArrayRef<Expr *> Args,
  5671. OverloadCandidateSet& CandidateSet,
  5672. bool SuppressUserConversions,
  5673. bool PartialOverloading) {
  5674. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5675. return;
  5676. // C++ [over.match.funcs]p7:
  5677. // In each case where a candidate is a function template, candidate
  5678. // function template specializations are generated using template argument
  5679. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5680. // candidate functions in the usual way.113) A given name can refer to one
  5681. // or more function templates and also to a set of overloaded non-template
  5682. // functions. In such a case, the candidate functions generated from each
  5683. // function template are combined with the set of non-template candidate
  5684. // functions.
  5685. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5686. FunctionDecl *Specialization = nullptr;
  5687. if (TemplateDeductionResult Result
  5688. = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
  5689. Specialization, Info, PartialOverloading)) {
  5690. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5691. Candidate.FoundDecl = FoundDecl;
  5692. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5693. Candidate.Viable = false;
  5694. Candidate.FailureKind = ovl_fail_bad_deduction;
  5695. Candidate.IsSurrogate = false;
  5696. Candidate.IgnoreObjectArgument = false;
  5697. Candidate.ExplicitCallArguments = Args.size();
  5698. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5699. Info);
  5700. return;
  5701. }
  5702. // Add the function template specialization produced by template argument
  5703. // deduction as a candidate.
  5704. assert(Specialization && "Missing function template specialization?");
  5705. AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
  5706. SuppressUserConversions, PartialOverloading);
  5707. }
  5708. /// Determine whether this is an allowable conversion from the result
  5709. /// of an explicit conversion operator to the expected type, per C++
  5710. /// [over.match.conv]p1 and [over.match.ref]p1.
  5711. ///
  5712. /// \param ConvType The return type of the conversion function.
  5713. ///
  5714. /// \param ToType The type we are converting to.
  5715. ///
  5716. /// \param AllowObjCPointerConversion Allow a conversion from one
  5717. /// Objective-C pointer to another.
  5718. ///
  5719. /// \returns true if the conversion is allowable, false otherwise.
  5720. static bool isAllowableExplicitConversion(Sema &S,
  5721. QualType ConvType, QualType ToType,
  5722. bool AllowObjCPointerConversion) {
  5723. QualType ToNonRefType = ToType.getNonReferenceType();
  5724. // Easy case: the types are the same.
  5725. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  5726. return true;
  5727. // Allow qualification conversions.
  5728. bool ObjCLifetimeConversion;
  5729. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  5730. ObjCLifetimeConversion))
  5731. return true;
  5732. // If we're not allowed to consider Objective-C pointer conversions,
  5733. // we're done.
  5734. if (!AllowObjCPointerConversion)
  5735. return false;
  5736. // Is this an Objective-C pointer conversion?
  5737. bool IncompatibleObjC = false;
  5738. QualType ConvertedType;
  5739. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  5740. IncompatibleObjC);
  5741. }
  5742. /// AddConversionCandidate - Add a C++ conversion function as a
  5743. /// candidate in the candidate set (C++ [over.match.conv],
  5744. /// C++ [over.match.copy]). From is the expression we're converting from,
  5745. /// and ToType is the type that we're eventually trying to convert to
  5746. /// (which may or may not be the same type as the type that the
  5747. /// conversion function produces).
  5748. void
  5749. Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
  5750. DeclAccessPair FoundDecl,
  5751. CXXRecordDecl *ActingContext,
  5752. Expr *From, QualType ToType,
  5753. OverloadCandidateSet& CandidateSet,
  5754. bool AllowObjCConversionOnExplicit) {
  5755. assert(!Conversion->getDescribedFunctionTemplate() &&
  5756. "Conversion function templates use AddTemplateConversionCandidate");
  5757. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  5758. if (!CandidateSet.isNewCandidate(Conversion))
  5759. return;
  5760. // If the conversion function has an undeduced return type, trigger its
  5761. // deduction now.
  5762. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  5763. if (DeduceReturnType(Conversion, From->getExprLoc()))
  5764. return;
  5765. ConvType = Conversion->getConversionType().getNonReferenceType();
  5766. }
  5767. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  5768. // operator is only a candidate if its return type is the target type or
  5769. // can be converted to the target type with a qualification conversion.
  5770. if (Conversion->isExplicit() &&
  5771. !isAllowableExplicitConversion(*this, ConvType, ToType,
  5772. AllowObjCConversionOnExplicit))
  5773. return;
  5774. // Overload resolution is always an unevaluated context.
  5775. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5776. // Add this candidate
  5777. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  5778. Candidate.FoundDecl = FoundDecl;
  5779. Candidate.Function = Conversion;
  5780. Candidate.IsSurrogate = false;
  5781. Candidate.IgnoreObjectArgument = false;
  5782. Candidate.FinalConversion.setAsIdentityConversion();
  5783. Candidate.FinalConversion.setFromType(ConvType);
  5784. Candidate.FinalConversion.setAllToTypes(ToType);
  5785. Candidate.Viable = true;
  5786. Candidate.ExplicitCallArguments = 1;
  5787. // C++ [over.match.funcs]p4:
  5788. // For conversion functions, the function is considered to be a member of
  5789. // the class of the implicit implied object argument for the purpose of
  5790. // defining the type of the implicit object parameter.
  5791. //
  5792. // Determine the implicit conversion sequence for the implicit
  5793. // object parameter.
  5794. QualType ImplicitParamType = From->getType();
  5795. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  5796. ImplicitParamType = FromPtrType->getPointeeType();
  5797. CXXRecordDecl *ConversionContext
  5798. = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
  5799. Candidate.Conversions[0]
  5800. = TryObjectArgumentInitialization(*this, From->getType(),
  5801. From->Classify(Context),
  5802. Conversion, ConversionContext);
  5803. if (Candidate.Conversions[0].isBad()) {
  5804. Candidate.Viable = false;
  5805. Candidate.FailureKind = ovl_fail_bad_conversion;
  5806. return;
  5807. }
  5808. // We won't go through a user-defined type conversion function to convert a
  5809. // derived to base as such conversions are given Conversion Rank. They only
  5810. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  5811. QualType FromCanon
  5812. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  5813. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  5814. if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
  5815. Candidate.Viable = false;
  5816. Candidate.FailureKind = ovl_fail_trivial_conversion;
  5817. return;
  5818. }
  5819. // To determine what the conversion from the result of calling the
  5820. // conversion function to the type we're eventually trying to
  5821. // convert to (ToType), we need to synthesize a call to the
  5822. // conversion function and attempt copy initialization from it. This
  5823. // makes sure that we get the right semantics with respect to
  5824. // lvalues/rvalues and the type. Fortunately, we can allocate this
  5825. // call on the stack and we don't need its arguments to be
  5826. // well-formed.
  5827. DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
  5828. VK_LValue, From->getLocStart());
  5829. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  5830. Context.getPointerType(Conversion->getType()),
  5831. CK_FunctionToPointerDecay,
  5832. &ConversionRef, VK_RValue);
  5833. QualType ConversionType = Conversion->getConversionType();
  5834. if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
  5835. Candidate.Viable = false;
  5836. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5837. return;
  5838. }
  5839. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  5840. // Note that it is safe to allocate CallExpr on the stack here because
  5841. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  5842. // allocator).
  5843. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  5844. CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
  5845. From->getLocStart());
  5846. ImplicitConversionSequence ICS =
  5847. TryCopyInitialization(*this, &Call, ToType,
  5848. /*SuppressUserConversions=*/true,
  5849. /*InOverloadResolution=*/false,
  5850. /*AllowObjCWritebackConversion=*/false);
  5851. switch (ICS.getKind()) {
  5852. case ImplicitConversionSequence::StandardConversion:
  5853. Candidate.FinalConversion = ICS.Standard;
  5854. // C++ [over.ics.user]p3:
  5855. // If the user-defined conversion is specified by a specialization of a
  5856. // conversion function template, the second standard conversion sequence
  5857. // shall have exact match rank.
  5858. if (Conversion->getPrimaryTemplate() &&
  5859. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  5860. Candidate.Viable = false;
  5861. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  5862. return;
  5863. }
  5864. // C++0x [dcl.init.ref]p5:
  5865. // In the second case, if the reference is an rvalue reference and
  5866. // the second standard conversion sequence of the user-defined
  5867. // conversion sequence includes an lvalue-to-rvalue conversion, the
  5868. // program is ill-formed.
  5869. if (ToType->isRValueReferenceType() &&
  5870. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5871. Candidate.Viable = false;
  5872. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5873. return;
  5874. }
  5875. break;
  5876. case ImplicitConversionSequence::BadConversion:
  5877. Candidate.Viable = false;
  5878. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5879. return;
  5880. default:
  5881. llvm_unreachable(
  5882. "Can only end up with a standard conversion sequence or failure");
  5883. }
  5884. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  5885. Candidate.Viable = false;
  5886. Candidate.FailureKind = ovl_fail_enable_if;
  5887. Candidate.DeductionFailure.Data = FailedAttr;
  5888. return;
  5889. }
  5890. }
  5891. /// \brief Adds a conversion function template specialization
  5892. /// candidate to the overload set, using template argument deduction
  5893. /// to deduce the template arguments of the conversion function
  5894. /// template from the type that we are converting to (C++
  5895. /// [temp.deduct.conv]).
  5896. void
  5897. Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
  5898. DeclAccessPair FoundDecl,
  5899. CXXRecordDecl *ActingDC,
  5900. Expr *From, QualType ToType,
  5901. OverloadCandidateSet &CandidateSet,
  5902. bool AllowObjCConversionOnExplicit) {
  5903. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  5904. "Only conversion function templates permitted here");
  5905. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5906. return;
  5907. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5908. CXXConversionDecl *Specialization = nullptr;
  5909. if (TemplateDeductionResult Result
  5910. = DeduceTemplateArguments(FunctionTemplate, ToType,
  5911. Specialization, Info)) {
  5912. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5913. Candidate.FoundDecl = FoundDecl;
  5914. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5915. Candidate.Viable = false;
  5916. Candidate.FailureKind = ovl_fail_bad_deduction;
  5917. Candidate.IsSurrogate = false;
  5918. Candidate.IgnoreObjectArgument = false;
  5919. Candidate.ExplicitCallArguments = 1;
  5920. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5921. Info);
  5922. return;
  5923. }
  5924. // Add the conversion function template specialization produced by
  5925. // template argument deduction as a candidate.
  5926. assert(Specialization && "Missing function template specialization?");
  5927. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  5928. CandidateSet, AllowObjCConversionOnExplicit);
  5929. }
  5930. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  5931. /// converts the given @c Object to a function pointer via the
  5932. /// conversion function @c Conversion, and then attempts to call it
  5933. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  5934. /// the type of function that we'll eventually be calling.
  5935. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  5936. DeclAccessPair FoundDecl,
  5937. CXXRecordDecl *ActingContext,
  5938. const FunctionProtoType *Proto,
  5939. Expr *Object,
  5940. ArrayRef<Expr *> Args,
  5941. OverloadCandidateSet& CandidateSet) {
  5942. if (!CandidateSet.isNewCandidate(Conversion))
  5943. return;
  5944. // Overload resolution is always an unevaluated context.
  5945. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5946. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5947. Candidate.FoundDecl = FoundDecl;
  5948. Candidate.Function = nullptr;
  5949. Candidate.Surrogate = Conversion;
  5950. Candidate.Viable = true;
  5951. Candidate.IsSurrogate = true;
  5952. Candidate.IgnoreObjectArgument = false;
  5953. Candidate.ExplicitCallArguments = Args.size();
  5954. // Determine the implicit conversion sequence for the implicit
  5955. // object parameter.
  5956. ImplicitConversionSequence ObjectInit
  5957. = TryObjectArgumentInitialization(*this, Object->getType(),
  5958. Object->Classify(Context),
  5959. Conversion, ActingContext);
  5960. if (ObjectInit.isBad()) {
  5961. Candidate.Viable = false;
  5962. Candidate.FailureKind = ovl_fail_bad_conversion;
  5963. Candidate.Conversions[0] = ObjectInit;
  5964. return;
  5965. }
  5966. // The first conversion is actually a user-defined conversion whose
  5967. // first conversion is ObjectInit's standard conversion (which is
  5968. // effectively a reference binding). Record it as such.
  5969. Candidate.Conversions[0].setUserDefined();
  5970. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  5971. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  5972. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  5973. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  5974. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  5975. Candidate.Conversions[0].UserDefined.After
  5976. = Candidate.Conversions[0].UserDefined.Before;
  5977. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  5978. // Find the
  5979. unsigned NumParams = Proto->getNumParams();
  5980. // (C++ 13.3.2p2): A candidate function having fewer than m
  5981. // parameters is viable only if it has an ellipsis in its parameter
  5982. // list (8.3.5).
  5983. if (Args.size() > NumParams && !Proto->isVariadic()) {
  5984. Candidate.Viable = false;
  5985. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5986. return;
  5987. }
  5988. // Function types don't have any default arguments, so just check if
  5989. // we have enough arguments.
  5990. if (Args.size() < NumParams) {
  5991. // Not enough arguments.
  5992. Candidate.Viable = false;
  5993. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5994. return;
  5995. }
  5996. // Determine the implicit conversion sequences for each of the
  5997. // arguments.
  5998. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  5999. if (ArgIdx < NumParams) {
  6000. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6001. // exist for each argument an implicit conversion sequence
  6002. // (13.3.3.1) that converts that argument to the corresponding
  6003. // parameter of F.
  6004. QualType ParamType = Proto->getParamType(ArgIdx);
  6005. Candidate.Conversions[ArgIdx + 1]
  6006. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6007. /*SuppressUserConversions=*/false,
  6008. /*InOverloadResolution=*/false,
  6009. /*AllowObjCWritebackConversion=*/
  6010. getLangOpts().ObjCAutoRefCount);
  6011. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6012. Candidate.Viable = false;
  6013. Candidate.FailureKind = ovl_fail_bad_conversion;
  6014. return;
  6015. }
  6016. } else {
  6017. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6018. // argument for which there is no corresponding parameter is
  6019. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6020. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6021. }
  6022. }
  6023. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6024. Candidate.Viable = false;
  6025. Candidate.FailureKind = ovl_fail_enable_if;
  6026. Candidate.DeductionFailure.Data = FailedAttr;
  6027. return;
  6028. }
  6029. }
  6030. /// \brief Add overload candidates for overloaded operators that are
  6031. /// member functions.
  6032. ///
  6033. /// Add the overloaded operator candidates that are member functions
  6034. /// for the operator Op that was used in an operator expression such
  6035. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6036. /// CandidateSet will store the added overload candidates. (C++
  6037. /// [over.match.oper]).
  6038. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6039. SourceLocation OpLoc,
  6040. ArrayRef<Expr *> Args,
  6041. OverloadCandidateSet& CandidateSet,
  6042. SourceRange OpRange) {
  6043. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6044. // C++ [over.match.oper]p3:
  6045. // For a unary operator @ with an operand of a type whose
  6046. // cv-unqualified version is T1, and for a binary operator @ with
  6047. // a left operand of a type whose cv-unqualified version is T1 and
  6048. // a right operand of a type whose cv-unqualified version is T2,
  6049. // three sets of candidate functions, designated member
  6050. // candidates, non-member candidates and built-in candidates, are
  6051. // constructed as follows:
  6052. QualType T1 = Args[0]->getType();
  6053. // -- If T1 is a complete class type or a class currently being
  6054. // defined, the set of member candidates is the result of the
  6055. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6056. // the set of member candidates is empty.
  6057. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6058. // Complete the type if it can be completed.
  6059. RequireCompleteType(OpLoc, T1, 0);
  6060. // If the type is neither complete nor being defined, bail out now.
  6061. if (!T1Rec->getDecl()->getDefinition())
  6062. return;
  6063. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6064. LookupQualifiedName(Operators, T1Rec->getDecl());
  6065. Operators.suppressDiagnostics();
  6066. for (LookupResult::iterator Oper = Operators.begin(),
  6067. OperEnd = Operators.end();
  6068. Oper != OperEnd;
  6069. ++Oper)
  6070. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6071. Args[0]->Classify(Context),
  6072. Args.slice(1),
  6073. CandidateSet,
  6074. /* SuppressUserConversions = */ false);
  6075. }
  6076. }
  6077. /// AddBuiltinCandidate - Add a candidate for a built-in
  6078. /// operator. ResultTy and ParamTys are the result and parameter types
  6079. /// of the built-in candidate, respectively. Args and NumArgs are the
  6080. /// arguments being passed to the candidate. IsAssignmentOperator
  6081. /// should be true when this built-in candidate is an assignment
  6082. /// operator. NumContextualBoolArguments is the number of arguments
  6083. /// (at the beginning of the argument list) that will be contextually
  6084. /// converted to bool.
  6085. void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
  6086. ArrayRef<Expr *> Args,
  6087. OverloadCandidateSet& CandidateSet,
  6088. bool IsAssignmentOperator,
  6089. unsigned NumContextualBoolArguments) {
  6090. // Overload resolution is always an unevaluated context.
  6091. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  6092. // Add this candidate
  6093. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6094. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6095. Candidate.Function = nullptr;
  6096. Candidate.IsSurrogate = false;
  6097. Candidate.IgnoreObjectArgument = false;
  6098. Candidate.BuiltinTypes.ResultTy = ResultTy;
  6099. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  6100. Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
  6101. // Determine the implicit conversion sequences for each of the
  6102. // arguments.
  6103. Candidate.Viable = true;
  6104. Candidate.ExplicitCallArguments = Args.size();
  6105. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6106. // C++ [over.match.oper]p4:
  6107. // For the built-in assignment operators, conversions of the
  6108. // left operand are restricted as follows:
  6109. // -- no temporaries are introduced to hold the left operand, and
  6110. // -- no user-defined conversions are applied to the left
  6111. // operand to achieve a type match with the left-most
  6112. // parameter of a built-in candidate.
  6113. //
  6114. // We block these conversions by turning off user-defined
  6115. // conversions, since that is the only way that initialization of
  6116. // a reference to a non-class type can occur from something that
  6117. // is not of the same type.
  6118. if (ArgIdx < NumContextualBoolArguments) {
  6119. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6120. "Contextual conversion to bool requires bool type");
  6121. Candidate.Conversions[ArgIdx]
  6122. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6123. } else {
  6124. Candidate.Conversions[ArgIdx]
  6125. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6126. ArgIdx == 0 && IsAssignmentOperator,
  6127. /*InOverloadResolution=*/false,
  6128. /*AllowObjCWritebackConversion=*/
  6129. getLangOpts().ObjCAutoRefCount);
  6130. }
  6131. if (Candidate.Conversions[ArgIdx].isBad()) {
  6132. Candidate.Viable = false;
  6133. Candidate.FailureKind = ovl_fail_bad_conversion;
  6134. break;
  6135. }
  6136. }
  6137. }
  6138. namespace {
  6139. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6140. /// candidate operator functions for built-in operators (C++
  6141. /// [over.built]). The types are separated into pointer types and
  6142. /// enumeration types.
  6143. class BuiltinCandidateTypeSet {
  6144. /// TypeSet - A set of types.
  6145. typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
  6146. /// PointerTypes - The set of pointer types that will be used in the
  6147. /// built-in candidates.
  6148. TypeSet PointerTypes;
  6149. /// MemberPointerTypes - The set of member pointer types that will be
  6150. /// used in the built-in candidates.
  6151. TypeSet MemberPointerTypes;
  6152. /// EnumerationTypes - The set of enumeration types that will be
  6153. /// used in the built-in candidates.
  6154. TypeSet EnumerationTypes;
  6155. /// \brief The set of vector types that will be used in the built-in
  6156. /// candidates.
  6157. TypeSet VectorTypes;
  6158. /// \brief A flag indicating non-record types are viable candidates
  6159. bool HasNonRecordTypes;
  6160. /// \brief A flag indicating whether either arithmetic or enumeration types
  6161. /// were present in the candidate set.
  6162. bool HasArithmeticOrEnumeralTypes;
  6163. /// \brief A flag indicating whether the nullptr type was present in the
  6164. /// candidate set.
  6165. bool HasNullPtrType;
  6166. /// Sema - The semantic analysis instance where we are building the
  6167. /// candidate type set.
  6168. Sema &SemaRef;
  6169. /// Context - The AST context in which we will build the type sets.
  6170. ASTContext &Context;
  6171. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6172. const Qualifiers &VisibleQuals);
  6173. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6174. public:
  6175. /// iterator - Iterates through the types that are part of the set.
  6176. typedef TypeSet::iterator iterator;
  6177. BuiltinCandidateTypeSet(Sema &SemaRef)
  6178. : HasNonRecordTypes(false),
  6179. HasArithmeticOrEnumeralTypes(false),
  6180. HasNullPtrType(false),
  6181. SemaRef(SemaRef),
  6182. Context(SemaRef.Context) { }
  6183. void AddTypesConvertedFrom(QualType Ty,
  6184. SourceLocation Loc,
  6185. bool AllowUserConversions,
  6186. bool AllowExplicitConversions,
  6187. const Qualifiers &VisibleTypeConversionsQuals);
  6188. /// pointer_begin - First pointer type found;
  6189. iterator pointer_begin() { return PointerTypes.begin(); }
  6190. /// pointer_end - Past the last pointer type found;
  6191. iterator pointer_end() { return PointerTypes.end(); }
  6192. /// member_pointer_begin - First member pointer type found;
  6193. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6194. /// member_pointer_end - Past the last member pointer type found;
  6195. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6196. /// enumeration_begin - First enumeration type found;
  6197. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6198. /// enumeration_end - Past the last enumeration type found;
  6199. iterator enumeration_end() { return EnumerationTypes.end(); }
  6200. iterator vector_begin() { return VectorTypes.begin(); }
  6201. iterator vector_end() { return VectorTypes.end(); }
  6202. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6203. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6204. bool hasNullPtrType() const { return HasNullPtrType; }
  6205. };
  6206. } // end anonymous namespace
  6207. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6208. /// the set of pointer types along with any more-qualified variants of
  6209. /// that type. For example, if @p Ty is "int const *", this routine
  6210. /// will add "int const *", "int const volatile *", "int const
  6211. /// restrict *", and "int const volatile restrict *" to the set of
  6212. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6213. /// false otherwise.
  6214. ///
  6215. /// FIXME: what to do about extended qualifiers?
  6216. bool
  6217. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6218. const Qualifiers &VisibleQuals) {
  6219. // Insert this type.
  6220. if (!PointerTypes.insert(Ty).second)
  6221. return false;
  6222. QualType PointeeTy;
  6223. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6224. bool buildObjCPtr = false;
  6225. if (!PointerTy) {
  6226. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6227. PointeeTy = PTy->getPointeeType();
  6228. buildObjCPtr = true;
  6229. } else {
  6230. PointeeTy = PointerTy->getPointeeType();
  6231. }
  6232. // Don't add qualified variants of arrays. For one, they're not allowed
  6233. // (the qualifier would sink to the element type), and for another, the
  6234. // only overload situation where it matters is subscript or pointer +- int,
  6235. // and those shouldn't have qualifier variants anyway.
  6236. if (PointeeTy->isArrayType())
  6237. return true;
  6238. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6239. bool hasVolatile = VisibleQuals.hasVolatile();
  6240. bool hasRestrict = VisibleQuals.hasRestrict();
  6241. // Iterate through all strict supersets of BaseCVR.
  6242. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6243. if ((CVR | BaseCVR) != CVR) continue;
  6244. // Skip over volatile if no volatile found anywhere in the types.
  6245. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6246. // Skip over restrict if no restrict found anywhere in the types, or if
  6247. // the type cannot be restrict-qualified.
  6248. if ((CVR & Qualifiers::Restrict) &&
  6249. (!hasRestrict ||
  6250. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6251. continue;
  6252. // Build qualified pointee type.
  6253. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6254. // Build qualified pointer type.
  6255. QualType QPointerTy;
  6256. if (!buildObjCPtr)
  6257. QPointerTy = Context.getPointerType(QPointeeTy);
  6258. else
  6259. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6260. // Insert qualified pointer type.
  6261. PointerTypes.insert(QPointerTy);
  6262. }
  6263. return true;
  6264. }
  6265. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6266. /// to the set of pointer types along with any more-qualified variants of
  6267. /// that type. For example, if @p Ty is "int const *", this routine
  6268. /// will add "int const *", "int const volatile *", "int const
  6269. /// restrict *", and "int const volatile restrict *" to the set of
  6270. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6271. /// false otherwise.
  6272. ///
  6273. /// FIXME: what to do about extended qualifiers?
  6274. bool
  6275. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6276. QualType Ty) {
  6277. // Insert this type.
  6278. if (!MemberPointerTypes.insert(Ty).second)
  6279. return false;
  6280. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6281. assert(PointerTy && "type was not a member pointer type!");
  6282. QualType PointeeTy = PointerTy->getPointeeType();
  6283. // Don't add qualified variants of arrays. For one, they're not allowed
  6284. // (the qualifier would sink to the element type), and for another, the
  6285. // only overload situation where it matters is subscript or pointer +- int,
  6286. // and those shouldn't have qualifier variants anyway.
  6287. if (PointeeTy->isArrayType())
  6288. return true;
  6289. const Type *ClassTy = PointerTy->getClass();
  6290. // Iterate through all strict supersets of the pointee type's CVR
  6291. // qualifiers.
  6292. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6293. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6294. if ((CVR | BaseCVR) != CVR) continue;
  6295. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6296. MemberPointerTypes.insert(
  6297. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6298. }
  6299. return true;
  6300. }
  6301. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6302. /// Ty can be implicit converted to the given set of @p Types. We're
  6303. /// primarily interested in pointer types and enumeration types. We also
  6304. /// take member pointer types, for the conditional operator.
  6305. /// AllowUserConversions is true if we should look at the conversion
  6306. /// functions of a class type, and AllowExplicitConversions if we
  6307. /// should also include the explicit conversion functions of a class
  6308. /// type.
  6309. void
  6310. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6311. SourceLocation Loc,
  6312. bool AllowUserConversions,
  6313. bool AllowExplicitConversions,
  6314. const Qualifiers &VisibleQuals) {
  6315. // Only deal with canonical types.
  6316. Ty = Context.getCanonicalType(Ty);
  6317. // Look through reference types; they aren't part of the type of an
  6318. // expression for the purposes of conversions.
  6319. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6320. Ty = RefTy->getPointeeType();
  6321. // If we're dealing with an array type, decay to the pointer.
  6322. if (Ty->isArrayType())
  6323. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6324. // Otherwise, we don't care about qualifiers on the type.
  6325. Ty = Ty.getLocalUnqualifiedType();
  6326. // Flag if we ever add a non-record type.
  6327. const RecordType *TyRec = Ty->getAs<RecordType>();
  6328. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6329. // Flag if we encounter an arithmetic type.
  6330. HasArithmeticOrEnumeralTypes =
  6331. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6332. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6333. PointerTypes.insert(Ty);
  6334. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6335. // Insert our type, and its more-qualified variants, into the set
  6336. // of types.
  6337. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6338. return;
  6339. } else if (Ty->isMemberPointerType()) {
  6340. // Member pointers are far easier, since the pointee can't be converted.
  6341. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6342. return;
  6343. } else if (Ty->isEnumeralType()) {
  6344. HasArithmeticOrEnumeralTypes = true;
  6345. EnumerationTypes.insert(Ty);
  6346. } else if (Ty->isVectorType()) {
  6347. // We treat vector types as arithmetic types in many contexts as an
  6348. // extension.
  6349. HasArithmeticOrEnumeralTypes = true;
  6350. VectorTypes.insert(Ty);
  6351. } else if (Ty->isNullPtrType()) {
  6352. HasNullPtrType = true;
  6353. } else if (AllowUserConversions && TyRec) {
  6354. // No conversion functions in incomplete types.
  6355. if (SemaRef.RequireCompleteType(Loc, Ty, 0))
  6356. return;
  6357. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6358. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6359. if (isa<UsingShadowDecl>(D))
  6360. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6361. // Skip conversion function templates; they don't tell us anything
  6362. // about which builtin types we can convert to.
  6363. if (isa<FunctionTemplateDecl>(D))
  6364. continue;
  6365. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6366. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6367. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6368. VisibleQuals);
  6369. }
  6370. }
  6371. }
  6372. }
  6373. /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
  6374. /// the volatile- and non-volatile-qualified assignment operators for the
  6375. /// given type to the candidate set.
  6376. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  6377. QualType T,
  6378. ArrayRef<Expr *> Args,
  6379. OverloadCandidateSet &CandidateSet) {
  6380. QualType ParamTypes[2];
  6381. // T& operator=(T&, T)
  6382. ParamTypes[0] = S.Context.getLValueReferenceType(T);
  6383. ParamTypes[1] = T;
  6384. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6385. /*IsAssignmentOperator=*/true);
  6386. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  6387. // volatile T& operator=(volatile T&, T)
  6388. ParamTypes[0]
  6389. = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
  6390. ParamTypes[1] = T;
  6391. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6392. /*IsAssignmentOperator=*/true);
  6393. }
  6394. }
  6395. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  6396. /// if any, found in visible type conversion functions found in ArgExpr's type.
  6397. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  6398. Qualifiers VRQuals;
  6399. const RecordType *TyRec;
  6400. if (const MemberPointerType *RHSMPType =
  6401. ArgExpr->getType()->getAs<MemberPointerType>())
  6402. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  6403. else
  6404. TyRec = ArgExpr->getType()->getAs<RecordType>();
  6405. if (!TyRec) {
  6406. // Just to be safe, assume the worst case.
  6407. VRQuals.addVolatile();
  6408. VRQuals.addRestrict();
  6409. return VRQuals;
  6410. }
  6411. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6412. if (!ClassDecl->hasDefinition())
  6413. return VRQuals;
  6414. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6415. if (isa<UsingShadowDecl>(D))
  6416. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6417. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  6418. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  6419. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  6420. CanTy = ResTypeRef->getPointeeType();
  6421. // Need to go down the pointer/mempointer chain and add qualifiers
  6422. // as see them.
  6423. bool done = false;
  6424. while (!done) {
  6425. if (CanTy.isRestrictQualified())
  6426. VRQuals.addRestrict();
  6427. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  6428. CanTy = ResTypePtr->getPointeeType();
  6429. else if (const MemberPointerType *ResTypeMPtr =
  6430. CanTy->getAs<MemberPointerType>())
  6431. CanTy = ResTypeMPtr->getPointeeType();
  6432. else
  6433. done = true;
  6434. if (CanTy.isVolatileQualified())
  6435. VRQuals.addVolatile();
  6436. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  6437. return VRQuals;
  6438. }
  6439. }
  6440. }
  6441. return VRQuals;
  6442. }
  6443. namespace {
  6444. /// \brief Helper class to manage the addition of builtin operator overload
  6445. /// candidates. It provides shared state and utility methods used throughout
  6446. /// the process, as well as a helper method to add each group of builtin
  6447. /// operator overloads from the standard to a candidate set.
  6448. class BuiltinOperatorOverloadBuilder {
  6449. // Common instance state available to all overload candidate addition methods.
  6450. Sema &S;
  6451. ArrayRef<Expr *> Args;
  6452. Qualifiers VisibleTypeConversionsQuals;
  6453. bool HasArithmeticOrEnumeralCandidateType;
  6454. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  6455. OverloadCandidateSet &CandidateSet;
  6456. // Define some constants used to index and iterate over the arithemetic types
  6457. // provided via the getArithmeticType() method below.
  6458. // The "promoted arithmetic types" are the arithmetic
  6459. // types are that preserved by promotion (C++ [over.built]p2).
  6460. static const unsigned FirstIntegralType = 3;
  6461. static const unsigned LastIntegralType = 20;
  6462. static const unsigned FirstPromotedIntegralType = 3,
  6463. LastPromotedIntegralType = 11;
  6464. static const unsigned FirstPromotedArithmeticType = 0,
  6465. LastPromotedArithmeticType = 11;
  6466. static const unsigned NumArithmeticTypes = 20;
  6467. /// \brief Get the canonical type for a given arithmetic type index.
  6468. CanQualType getArithmeticType(unsigned index) {
  6469. assert(index < NumArithmeticTypes);
  6470. static CanQualType ASTContext::* const
  6471. ArithmeticTypes[NumArithmeticTypes] = {
  6472. // Start of promoted types.
  6473. &ASTContext::FloatTy,
  6474. &ASTContext::DoubleTy,
  6475. &ASTContext::LongDoubleTy,
  6476. // Start of integral types.
  6477. &ASTContext::IntTy,
  6478. &ASTContext::LongTy,
  6479. &ASTContext::LongLongTy,
  6480. &ASTContext::Int128Ty,
  6481. &ASTContext::UnsignedIntTy,
  6482. &ASTContext::UnsignedLongTy,
  6483. &ASTContext::UnsignedLongLongTy,
  6484. &ASTContext::UnsignedInt128Ty,
  6485. // End of promoted types.
  6486. &ASTContext::BoolTy,
  6487. &ASTContext::CharTy,
  6488. &ASTContext::WCharTy,
  6489. &ASTContext::Char16Ty,
  6490. &ASTContext::Char32Ty,
  6491. &ASTContext::SignedCharTy,
  6492. &ASTContext::ShortTy,
  6493. &ASTContext::UnsignedCharTy,
  6494. &ASTContext::UnsignedShortTy,
  6495. // End of integral types.
  6496. // FIXME: What about complex? What about half?
  6497. };
  6498. return S.Context.*ArithmeticTypes[index];
  6499. }
  6500. /// \brief Gets the canonical type resulting from the usual arithemetic
  6501. /// converions for the given arithmetic types.
  6502. CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
  6503. // Accelerator table for performing the usual arithmetic conversions.
  6504. // The rules are basically:
  6505. // - if either is floating-point, use the wider floating-point
  6506. // - if same signedness, use the higher rank
  6507. // - if same size, use unsigned of the higher rank
  6508. // - use the larger type
  6509. // These rules, together with the axiom that higher ranks are
  6510. // never smaller, are sufficient to precompute all of these results
  6511. // *except* when dealing with signed types of higher rank.
  6512. // (we could precompute SLL x UI for all known platforms, but it's
  6513. // better not to make any assumptions).
  6514. // We assume that int128 has a higher rank than long long on all platforms.
  6515. enum PromotedType {
  6516. Dep=-1,
  6517. Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
  6518. };
  6519. static const PromotedType ConversionsTable[LastPromotedArithmeticType]
  6520. [LastPromotedArithmeticType] = {
  6521. /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
  6522. /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
  6523. /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
  6524. /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
  6525. /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
  6526. /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
  6527. /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
  6528. /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
  6529. /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
  6530. /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
  6531. /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
  6532. };
  6533. assert(L < LastPromotedArithmeticType);
  6534. assert(R < LastPromotedArithmeticType);
  6535. int Idx = ConversionsTable[L][R];
  6536. // Fast path: the table gives us a concrete answer.
  6537. if (Idx != Dep) return getArithmeticType(Idx);
  6538. // Slow path: we need to compare widths.
  6539. // An invariant is that the signed type has higher rank.
  6540. CanQualType LT = getArithmeticType(L),
  6541. RT = getArithmeticType(R);
  6542. unsigned LW = S.Context.getIntWidth(LT),
  6543. RW = S.Context.getIntWidth(RT);
  6544. // If they're different widths, use the signed type.
  6545. if (LW > RW) return LT;
  6546. else if (LW < RW) return RT;
  6547. // Otherwise, use the unsigned type of the signed type's rank.
  6548. if (L == SL || R == SL) return S.Context.UnsignedLongTy;
  6549. assert(L == SLL || R == SLL);
  6550. return S.Context.UnsignedLongLongTy;
  6551. }
  6552. /// \brief Helper method to factor out the common pattern of adding overloads
  6553. /// for '++' and '--' builtin operators.
  6554. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  6555. bool HasVolatile,
  6556. bool HasRestrict) {
  6557. QualType ParamTypes[2] = {
  6558. S.Context.getLValueReferenceType(CandidateTy),
  6559. S.Context.IntTy
  6560. };
  6561. // Non-volatile version.
  6562. if (Args.size() == 1)
  6563. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6564. else
  6565. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6566. // Use a heuristic to reduce number of builtin candidates in the set:
  6567. // add volatile version only if there are conversions to a volatile type.
  6568. if (HasVolatile) {
  6569. ParamTypes[0] =
  6570. S.Context.getLValueReferenceType(
  6571. S.Context.getVolatileType(CandidateTy));
  6572. if (Args.size() == 1)
  6573. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6574. else
  6575. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6576. }
  6577. // Add restrict version only if there are conversions to a restrict type
  6578. // and our candidate type is a non-restrict-qualified pointer.
  6579. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  6580. !CandidateTy.isRestrictQualified()) {
  6581. ParamTypes[0]
  6582. = S.Context.getLValueReferenceType(
  6583. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  6584. if (Args.size() == 1)
  6585. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6586. else
  6587. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6588. if (HasVolatile) {
  6589. ParamTypes[0]
  6590. = S.Context.getLValueReferenceType(
  6591. S.Context.getCVRQualifiedType(CandidateTy,
  6592. (Qualifiers::Volatile |
  6593. Qualifiers::Restrict)));
  6594. if (Args.size() == 1)
  6595. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6596. else
  6597. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6598. }
  6599. }
  6600. }
  6601. public:
  6602. BuiltinOperatorOverloadBuilder(
  6603. Sema &S, ArrayRef<Expr *> Args,
  6604. Qualifiers VisibleTypeConversionsQuals,
  6605. bool HasArithmeticOrEnumeralCandidateType,
  6606. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  6607. OverloadCandidateSet &CandidateSet)
  6608. : S(S), Args(Args),
  6609. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  6610. HasArithmeticOrEnumeralCandidateType(
  6611. HasArithmeticOrEnumeralCandidateType),
  6612. CandidateTypes(CandidateTypes),
  6613. CandidateSet(CandidateSet) {
  6614. // Validate some of our static helper constants in debug builds.
  6615. assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
  6616. "Invalid first promoted integral type");
  6617. assert(getArithmeticType(LastPromotedIntegralType - 1)
  6618. == S.Context.UnsignedInt128Ty &&
  6619. "Invalid last promoted integral type");
  6620. assert(getArithmeticType(FirstPromotedArithmeticType)
  6621. == S.Context.FloatTy &&
  6622. "Invalid first promoted arithmetic type");
  6623. assert(getArithmeticType(LastPromotedArithmeticType - 1)
  6624. == S.Context.UnsignedInt128Ty &&
  6625. "Invalid last promoted arithmetic type");
  6626. }
  6627. // C++ [over.built]p3:
  6628. //
  6629. // For every pair (T, VQ), where T is an arithmetic type, and VQ
  6630. // is either volatile or empty, there exist candidate operator
  6631. // functions of the form
  6632. //
  6633. // VQ T& operator++(VQ T&);
  6634. // T operator++(VQ T&, int);
  6635. //
  6636. // C++ [over.built]p4:
  6637. //
  6638. // For every pair (T, VQ), where T is an arithmetic type other
  6639. // than bool, and VQ is either volatile or empty, there exist
  6640. // candidate operator functions of the form
  6641. //
  6642. // VQ T& operator--(VQ T&);
  6643. // T operator--(VQ T&, int);
  6644. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  6645. if (!HasArithmeticOrEnumeralCandidateType)
  6646. return;
  6647. for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
  6648. Arith < NumArithmeticTypes; ++Arith) {
  6649. addPlusPlusMinusMinusStyleOverloads(
  6650. getArithmeticType(Arith),
  6651. VisibleTypeConversionsQuals.hasVolatile(),
  6652. VisibleTypeConversionsQuals.hasRestrict());
  6653. }
  6654. }
  6655. // C++ [over.built]p5:
  6656. //
  6657. // For every pair (T, VQ), where T is a cv-qualified or
  6658. // cv-unqualified object type, and VQ is either volatile or
  6659. // empty, there exist candidate operator functions of the form
  6660. //
  6661. // T*VQ& operator++(T*VQ&);
  6662. // T*VQ& operator--(T*VQ&);
  6663. // T* operator++(T*VQ&, int);
  6664. // T* operator--(T*VQ&, int);
  6665. void addPlusPlusMinusMinusPointerOverloads() {
  6666. for (BuiltinCandidateTypeSet::iterator
  6667. Ptr = CandidateTypes[0].pointer_begin(),
  6668. PtrEnd = CandidateTypes[0].pointer_end();
  6669. Ptr != PtrEnd; ++Ptr) {
  6670. // Skip pointer types that aren't pointers to object types.
  6671. if (!(*Ptr)->getPointeeType()->isObjectType())
  6672. continue;
  6673. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  6674. (!(*Ptr).isVolatileQualified() &&
  6675. VisibleTypeConversionsQuals.hasVolatile()),
  6676. (!(*Ptr).isRestrictQualified() &&
  6677. VisibleTypeConversionsQuals.hasRestrict()));
  6678. }
  6679. }
  6680. // C++ [over.built]p6:
  6681. // For every cv-qualified or cv-unqualified object type T, there
  6682. // exist candidate operator functions of the form
  6683. //
  6684. // T& operator*(T*);
  6685. //
  6686. // C++ [over.built]p7:
  6687. // For every function type T that does not have cv-qualifiers or a
  6688. // ref-qualifier, there exist candidate operator functions of the form
  6689. // T& operator*(T*);
  6690. void addUnaryStarPointerOverloads() {
  6691. for (BuiltinCandidateTypeSet::iterator
  6692. Ptr = CandidateTypes[0].pointer_begin(),
  6693. PtrEnd = CandidateTypes[0].pointer_end();
  6694. Ptr != PtrEnd; ++Ptr) {
  6695. QualType ParamTy = *Ptr;
  6696. QualType PointeeTy = ParamTy->getPointeeType();
  6697. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  6698. continue;
  6699. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  6700. if (Proto->getTypeQuals() || Proto->getRefQualifier())
  6701. continue;
  6702. S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
  6703. &ParamTy, Args, CandidateSet);
  6704. }
  6705. }
  6706. // C++ [over.built]p9:
  6707. // For every promoted arithmetic type T, there exist candidate
  6708. // operator functions of the form
  6709. //
  6710. // T operator+(T);
  6711. // T operator-(T);
  6712. void addUnaryPlusOrMinusArithmeticOverloads() {
  6713. if (!HasArithmeticOrEnumeralCandidateType)
  6714. return;
  6715. for (unsigned Arith = FirstPromotedArithmeticType;
  6716. Arith < LastPromotedArithmeticType; ++Arith) {
  6717. QualType ArithTy = getArithmeticType(Arith);
  6718. S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
  6719. }
  6720. // Extension: We also add these operators for vector types.
  6721. for (BuiltinCandidateTypeSet::iterator
  6722. Vec = CandidateTypes[0].vector_begin(),
  6723. VecEnd = CandidateTypes[0].vector_end();
  6724. Vec != VecEnd; ++Vec) {
  6725. QualType VecTy = *Vec;
  6726. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6727. }
  6728. }
  6729. // C++ [over.built]p8:
  6730. // For every type T, there exist candidate operator functions of
  6731. // the form
  6732. //
  6733. // T* operator+(T*);
  6734. void addUnaryPlusPointerOverloads() {
  6735. for (BuiltinCandidateTypeSet::iterator
  6736. Ptr = CandidateTypes[0].pointer_begin(),
  6737. PtrEnd = CandidateTypes[0].pointer_end();
  6738. Ptr != PtrEnd; ++Ptr) {
  6739. QualType ParamTy = *Ptr;
  6740. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
  6741. }
  6742. }
  6743. // C++ [over.built]p10:
  6744. // For every promoted integral type T, there exist candidate
  6745. // operator functions of the form
  6746. //
  6747. // T operator~(T);
  6748. void addUnaryTildePromotedIntegralOverloads() {
  6749. if (!HasArithmeticOrEnumeralCandidateType)
  6750. return;
  6751. for (unsigned Int = FirstPromotedIntegralType;
  6752. Int < LastPromotedIntegralType; ++Int) {
  6753. QualType IntTy = getArithmeticType(Int);
  6754. S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
  6755. }
  6756. // Extension: We also add this operator for vector types.
  6757. for (BuiltinCandidateTypeSet::iterator
  6758. Vec = CandidateTypes[0].vector_begin(),
  6759. VecEnd = CandidateTypes[0].vector_end();
  6760. Vec != VecEnd; ++Vec) {
  6761. QualType VecTy = *Vec;
  6762. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6763. }
  6764. }
  6765. // C++ [over.match.oper]p16:
  6766. // For every pointer to member type T, there exist candidate operator
  6767. // functions of the form
  6768. //
  6769. // bool operator==(T,T);
  6770. // bool operator!=(T,T);
  6771. void addEqualEqualOrNotEqualMemberPointerOverloads() {
  6772. /// Set of (canonical) types that we've already handled.
  6773. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6774. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6775. for (BuiltinCandidateTypeSet::iterator
  6776. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6777. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6778. MemPtr != MemPtrEnd;
  6779. ++MemPtr) {
  6780. // Don't add the same builtin candidate twice.
  6781. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  6782. continue;
  6783. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  6784. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6785. }
  6786. }
  6787. }
  6788. // C++ [over.built]p15:
  6789. //
  6790. // For every T, where T is an enumeration type, a pointer type, or
  6791. // std::nullptr_t, there exist candidate operator functions of the form
  6792. //
  6793. // bool operator<(T, T);
  6794. // bool operator>(T, T);
  6795. // bool operator<=(T, T);
  6796. // bool operator>=(T, T);
  6797. // bool operator==(T, T);
  6798. // bool operator!=(T, T);
  6799. void addRelationalPointerOrEnumeralOverloads() {
  6800. // C++ [over.match.oper]p3:
  6801. // [...]the built-in candidates include all of the candidate operator
  6802. // functions defined in 13.6 that, compared to the given operator, [...]
  6803. // do not have the same parameter-type-list as any non-template non-member
  6804. // candidate.
  6805. //
  6806. // Note that in practice, this only affects enumeration types because there
  6807. // aren't any built-in candidates of record type, and a user-defined operator
  6808. // must have an operand of record or enumeration type. Also, the only other
  6809. // overloaded operator with enumeration arguments, operator=,
  6810. // cannot be overloaded for enumeration types, so this is the only place
  6811. // where we must suppress candidates like this.
  6812. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  6813. UserDefinedBinaryOperators;
  6814. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6815. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  6816. CandidateTypes[ArgIdx].enumeration_end()) {
  6817. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  6818. CEnd = CandidateSet.end();
  6819. C != CEnd; ++C) {
  6820. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  6821. continue;
  6822. if (C->Function->isFunctionTemplateSpecialization())
  6823. continue;
  6824. QualType FirstParamType =
  6825. C->Function->getParamDecl(0)->getType().getUnqualifiedType();
  6826. QualType SecondParamType =
  6827. C->Function->getParamDecl(1)->getType().getUnqualifiedType();
  6828. // Skip if either parameter isn't of enumeral type.
  6829. if (!FirstParamType->isEnumeralType() ||
  6830. !SecondParamType->isEnumeralType())
  6831. continue;
  6832. // Add this operator to the set of known user-defined operators.
  6833. UserDefinedBinaryOperators.insert(
  6834. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  6835. S.Context.getCanonicalType(SecondParamType)));
  6836. }
  6837. }
  6838. }
  6839. /// Set of (canonical) types that we've already handled.
  6840. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6841. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6842. for (BuiltinCandidateTypeSet::iterator
  6843. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  6844. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  6845. Ptr != PtrEnd; ++Ptr) {
  6846. // Don't add the same builtin candidate twice.
  6847. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6848. continue;
  6849. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6850. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6851. }
  6852. for (BuiltinCandidateTypeSet::iterator
  6853. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6854. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6855. Enum != EnumEnd; ++Enum) {
  6856. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  6857. // Don't add the same builtin candidate twice, or if a user defined
  6858. // candidate exists.
  6859. if (!AddedTypes.insert(CanonType).second ||
  6860. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  6861. CanonType)))
  6862. continue;
  6863. QualType ParamTypes[2] = { *Enum, *Enum };
  6864. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6865. }
  6866. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  6867. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  6868. if (AddedTypes.insert(NullPtrTy).second &&
  6869. !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
  6870. NullPtrTy))) {
  6871. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  6872. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
  6873. CandidateSet);
  6874. }
  6875. }
  6876. }
  6877. }
  6878. // C++ [over.built]p13:
  6879. //
  6880. // For every cv-qualified or cv-unqualified object type T
  6881. // there exist candidate operator functions of the form
  6882. //
  6883. // T* operator+(T*, ptrdiff_t);
  6884. // T& operator[](T*, ptrdiff_t); [BELOW]
  6885. // T* operator-(T*, ptrdiff_t);
  6886. // T* operator+(ptrdiff_t, T*);
  6887. // T& operator[](ptrdiff_t, T*); [BELOW]
  6888. //
  6889. // C++ [over.built]p14:
  6890. //
  6891. // For every T, where T is a pointer to object type, there
  6892. // exist candidate operator functions of the form
  6893. //
  6894. // ptrdiff_t operator-(T, T);
  6895. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  6896. /// Set of (canonical) types that we've already handled.
  6897. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6898. for (int Arg = 0; Arg < 2; ++Arg) {
  6899. QualType AsymetricParamTypes[2] = {
  6900. S.Context.getPointerDiffType(),
  6901. S.Context.getPointerDiffType(),
  6902. };
  6903. for (BuiltinCandidateTypeSet::iterator
  6904. Ptr = CandidateTypes[Arg].pointer_begin(),
  6905. PtrEnd = CandidateTypes[Arg].pointer_end();
  6906. Ptr != PtrEnd; ++Ptr) {
  6907. QualType PointeeTy = (*Ptr)->getPointeeType();
  6908. if (!PointeeTy->isObjectType())
  6909. continue;
  6910. AsymetricParamTypes[Arg] = *Ptr;
  6911. if (Arg == 0 || Op == OO_Plus) {
  6912. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  6913. // T* operator+(ptrdiff_t, T*);
  6914. S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
  6915. }
  6916. if (Op == OO_Minus) {
  6917. // ptrdiff_t operator-(T, T);
  6918. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6919. continue;
  6920. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6921. S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
  6922. Args, CandidateSet);
  6923. }
  6924. }
  6925. }
  6926. }
  6927. // C++ [over.built]p12:
  6928. //
  6929. // For every pair of promoted arithmetic types L and R, there
  6930. // exist candidate operator functions of the form
  6931. //
  6932. // LR operator*(L, R);
  6933. // LR operator/(L, R);
  6934. // LR operator+(L, R);
  6935. // LR operator-(L, R);
  6936. // bool operator<(L, R);
  6937. // bool operator>(L, R);
  6938. // bool operator<=(L, R);
  6939. // bool operator>=(L, R);
  6940. // bool operator==(L, R);
  6941. // bool operator!=(L, R);
  6942. //
  6943. // where LR is the result of the usual arithmetic conversions
  6944. // between types L and R.
  6945. //
  6946. // C++ [over.built]p24:
  6947. //
  6948. // For every pair of promoted arithmetic types L and R, there exist
  6949. // candidate operator functions of the form
  6950. //
  6951. // LR operator?(bool, L, R);
  6952. //
  6953. // where LR is the result of the usual arithmetic conversions
  6954. // between types L and R.
  6955. // Our candidates ignore the first parameter.
  6956. void addGenericBinaryArithmeticOverloads(bool isComparison) {
  6957. if (!HasArithmeticOrEnumeralCandidateType)
  6958. return;
  6959. for (unsigned Left = FirstPromotedArithmeticType;
  6960. Left < LastPromotedArithmeticType; ++Left) {
  6961. for (unsigned Right = FirstPromotedArithmeticType;
  6962. Right < LastPromotedArithmeticType; ++Right) {
  6963. QualType LandR[2] = { getArithmeticType(Left),
  6964. getArithmeticType(Right) };
  6965. QualType Result =
  6966. isComparison ? S.Context.BoolTy
  6967. : getUsualArithmeticConversions(Left, Right);
  6968. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6969. }
  6970. }
  6971. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  6972. // conditional operator for vector types.
  6973. for (BuiltinCandidateTypeSet::iterator
  6974. Vec1 = CandidateTypes[0].vector_begin(),
  6975. Vec1End = CandidateTypes[0].vector_end();
  6976. Vec1 != Vec1End; ++Vec1) {
  6977. for (BuiltinCandidateTypeSet::iterator
  6978. Vec2 = CandidateTypes[1].vector_begin(),
  6979. Vec2End = CandidateTypes[1].vector_end();
  6980. Vec2 != Vec2End; ++Vec2) {
  6981. QualType LandR[2] = { *Vec1, *Vec2 };
  6982. QualType Result = S.Context.BoolTy;
  6983. if (!isComparison) {
  6984. if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
  6985. Result = *Vec1;
  6986. else
  6987. Result = *Vec2;
  6988. }
  6989. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6990. }
  6991. }
  6992. }
  6993. // C++ [over.built]p17:
  6994. //
  6995. // For every pair of promoted integral types L and R, there
  6996. // exist candidate operator functions of the form
  6997. //
  6998. // LR operator%(L, R);
  6999. // LR operator&(L, R);
  7000. // LR operator^(L, R);
  7001. // LR operator|(L, R);
  7002. // L operator<<(L, R);
  7003. // L operator>>(L, R);
  7004. //
  7005. // where LR is the result of the usual arithmetic conversions
  7006. // between types L and R.
  7007. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7008. if (!HasArithmeticOrEnumeralCandidateType)
  7009. return;
  7010. for (unsigned Left = FirstPromotedIntegralType;
  7011. Left < LastPromotedIntegralType; ++Left) {
  7012. for (unsigned Right = FirstPromotedIntegralType;
  7013. Right < LastPromotedIntegralType; ++Right) {
  7014. QualType LandR[2] = { getArithmeticType(Left),
  7015. getArithmeticType(Right) };
  7016. QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
  7017. ? LandR[0]
  7018. : getUsualArithmeticConversions(Left, Right);
  7019. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  7020. }
  7021. }
  7022. }
  7023. // C++ [over.built]p20:
  7024. //
  7025. // For every pair (T, VQ), where T is an enumeration or
  7026. // pointer to member type and VQ is either volatile or
  7027. // empty, there exist candidate operator functions of the form
  7028. //
  7029. // VQ T& operator=(VQ T&, T);
  7030. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7031. /// Set of (canonical) types that we've already handled.
  7032. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7033. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7034. for (BuiltinCandidateTypeSet::iterator
  7035. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7036. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7037. Enum != EnumEnd; ++Enum) {
  7038. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7039. continue;
  7040. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7041. }
  7042. for (BuiltinCandidateTypeSet::iterator
  7043. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7044. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7045. MemPtr != MemPtrEnd; ++MemPtr) {
  7046. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7047. continue;
  7048. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7049. }
  7050. }
  7051. }
  7052. // C++ [over.built]p19:
  7053. //
  7054. // For every pair (T, VQ), where T is any type and VQ is either
  7055. // volatile or empty, there exist candidate operator functions
  7056. // of the form
  7057. //
  7058. // T*VQ& operator=(T*VQ&, T*);
  7059. //
  7060. // C++ [over.built]p21:
  7061. //
  7062. // For every pair (T, VQ), where T is a cv-qualified or
  7063. // cv-unqualified object type and VQ is either volatile or
  7064. // empty, there exist candidate operator functions of the form
  7065. //
  7066. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7067. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7068. void addAssignmentPointerOverloads(bool isEqualOp) {
  7069. /// Set of (canonical) types that we've already handled.
  7070. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7071. for (BuiltinCandidateTypeSet::iterator
  7072. Ptr = CandidateTypes[0].pointer_begin(),
  7073. PtrEnd = CandidateTypes[0].pointer_end();
  7074. Ptr != PtrEnd; ++Ptr) {
  7075. // If this is operator=, keep track of the builtin candidates we added.
  7076. if (isEqualOp)
  7077. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7078. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7079. continue;
  7080. // non-volatile version
  7081. QualType ParamTypes[2] = {
  7082. S.Context.getLValueReferenceType(*Ptr),
  7083. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7084. };
  7085. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7086. /*IsAssigmentOperator=*/ isEqualOp);
  7087. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7088. VisibleTypeConversionsQuals.hasVolatile();
  7089. if (NeedVolatile) {
  7090. // volatile version
  7091. ParamTypes[0] =
  7092. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7093. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7094. /*IsAssigmentOperator=*/isEqualOp);
  7095. }
  7096. if (!(*Ptr).isRestrictQualified() &&
  7097. VisibleTypeConversionsQuals.hasRestrict()) {
  7098. // restrict version
  7099. ParamTypes[0]
  7100. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7101. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7102. /*IsAssigmentOperator=*/isEqualOp);
  7103. if (NeedVolatile) {
  7104. // volatile restrict version
  7105. ParamTypes[0]
  7106. = S.Context.getLValueReferenceType(
  7107. S.Context.getCVRQualifiedType(*Ptr,
  7108. (Qualifiers::Volatile |
  7109. Qualifiers::Restrict)));
  7110. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7111. /*IsAssigmentOperator=*/isEqualOp);
  7112. }
  7113. }
  7114. }
  7115. if (isEqualOp) {
  7116. for (BuiltinCandidateTypeSet::iterator
  7117. Ptr = CandidateTypes[1].pointer_begin(),
  7118. PtrEnd = CandidateTypes[1].pointer_end();
  7119. Ptr != PtrEnd; ++Ptr) {
  7120. // Make sure we don't add the same candidate twice.
  7121. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7122. continue;
  7123. QualType ParamTypes[2] = {
  7124. S.Context.getLValueReferenceType(*Ptr),
  7125. *Ptr,
  7126. };
  7127. // non-volatile version
  7128. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7129. /*IsAssigmentOperator=*/true);
  7130. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7131. VisibleTypeConversionsQuals.hasVolatile();
  7132. if (NeedVolatile) {
  7133. // volatile version
  7134. ParamTypes[0] =
  7135. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7136. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7137. /*IsAssigmentOperator=*/true);
  7138. }
  7139. if (!(*Ptr).isRestrictQualified() &&
  7140. VisibleTypeConversionsQuals.hasRestrict()) {
  7141. // restrict version
  7142. ParamTypes[0]
  7143. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7144. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7145. /*IsAssigmentOperator=*/true);
  7146. if (NeedVolatile) {
  7147. // volatile restrict version
  7148. ParamTypes[0]
  7149. = S.Context.getLValueReferenceType(
  7150. S.Context.getCVRQualifiedType(*Ptr,
  7151. (Qualifiers::Volatile |
  7152. Qualifiers::Restrict)));
  7153. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7154. /*IsAssigmentOperator=*/true);
  7155. }
  7156. }
  7157. }
  7158. }
  7159. }
  7160. // C++ [over.built]p18:
  7161. //
  7162. // For every triple (L, VQ, R), where L is an arithmetic type,
  7163. // VQ is either volatile or empty, and R is a promoted
  7164. // arithmetic type, there exist candidate operator functions of
  7165. // the form
  7166. //
  7167. // VQ L& operator=(VQ L&, R);
  7168. // VQ L& operator*=(VQ L&, R);
  7169. // VQ L& operator/=(VQ L&, R);
  7170. // VQ L& operator+=(VQ L&, R);
  7171. // VQ L& operator-=(VQ L&, R);
  7172. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7173. if (!HasArithmeticOrEnumeralCandidateType)
  7174. return;
  7175. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7176. for (unsigned Right = FirstPromotedArithmeticType;
  7177. Right < LastPromotedArithmeticType; ++Right) {
  7178. QualType ParamTypes[2];
  7179. ParamTypes[1] = getArithmeticType(Right);
  7180. // Add this built-in operator as a candidate (VQ is empty).
  7181. ParamTypes[0] =
  7182. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7183. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7184. /*IsAssigmentOperator=*/isEqualOp);
  7185. // Add this built-in operator as a candidate (VQ is 'volatile').
  7186. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7187. ParamTypes[0] =
  7188. S.Context.getVolatileType(getArithmeticType(Left));
  7189. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7190. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7191. /*IsAssigmentOperator=*/isEqualOp);
  7192. }
  7193. }
  7194. }
  7195. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7196. for (BuiltinCandidateTypeSet::iterator
  7197. Vec1 = CandidateTypes[0].vector_begin(),
  7198. Vec1End = CandidateTypes[0].vector_end();
  7199. Vec1 != Vec1End; ++Vec1) {
  7200. for (BuiltinCandidateTypeSet::iterator
  7201. Vec2 = CandidateTypes[1].vector_begin(),
  7202. Vec2End = CandidateTypes[1].vector_end();
  7203. Vec2 != Vec2End; ++Vec2) {
  7204. QualType ParamTypes[2];
  7205. ParamTypes[1] = *Vec2;
  7206. // Add this built-in operator as a candidate (VQ is empty).
  7207. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7208. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7209. /*IsAssigmentOperator=*/isEqualOp);
  7210. // Add this built-in operator as a candidate (VQ is 'volatile').
  7211. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7212. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7213. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7214. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7215. /*IsAssigmentOperator=*/isEqualOp);
  7216. }
  7217. }
  7218. }
  7219. }
  7220. // C++ [over.built]p22:
  7221. //
  7222. // For every triple (L, VQ, R), where L is an integral type, VQ
  7223. // is either volatile or empty, and R is a promoted integral
  7224. // type, there exist candidate operator functions of the form
  7225. //
  7226. // VQ L& operator%=(VQ L&, R);
  7227. // VQ L& operator<<=(VQ L&, R);
  7228. // VQ L& operator>>=(VQ L&, R);
  7229. // VQ L& operator&=(VQ L&, R);
  7230. // VQ L& operator^=(VQ L&, R);
  7231. // VQ L& operator|=(VQ L&, R);
  7232. void addAssignmentIntegralOverloads() {
  7233. if (!HasArithmeticOrEnumeralCandidateType)
  7234. return;
  7235. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7236. for (unsigned Right = FirstPromotedIntegralType;
  7237. Right < LastPromotedIntegralType; ++Right) {
  7238. QualType ParamTypes[2];
  7239. ParamTypes[1] = getArithmeticType(Right);
  7240. // Add this built-in operator as a candidate (VQ is empty).
  7241. ParamTypes[0] =
  7242. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7243. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7244. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7245. // Add this built-in operator as a candidate (VQ is 'volatile').
  7246. ParamTypes[0] = getArithmeticType(Left);
  7247. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7248. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7249. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7250. }
  7251. }
  7252. }
  7253. }
  7254. // C++ [over.operator]p23:
  7255. //
  7256. // There also exist candidate operator functions of the form
  7257. //
  7258. // bool operator!(bool);
  7259. // bool operator&&(bool, bool);
  7260. // bool operator||(bool, bool);
  7261. void addExclaimOverload() {
  7262. QualType ParamTy = S.Context.BoolTy;
  7263. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
  7264. /*IsAssignmentOperator=*/false,
  7265. /*NumContextualBoolArguments=*/1);
  7266. }
  7267. void addAmpAmpOrPipePipeOverload() {
  7268. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7269. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
  7270. /*IsAssignmentOperator=*/false,
  7271. /*NumContextualBoolArguments=*/2);
  7272. }
  7273. // C++ [over.built]p13:
  7274. //
  7275. // For every cv-qualified or cv-unqualified object type T there
  7276. // exist candidate operator functions of the form
  7277. //
  7278. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7279. // T& operator[](T*, ptrdiff_t);
  7280. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7281. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7282. // T& operator[](ptrdiff_t, T*);
  7283. void addSubscriptOverloads() {
  7284. for (BuiltinCandidateTypeSet::iterator
  7285. Ptr = CandidateTypes[0].pointer_begin(),
  7286. PtrEnd = CandidateTypes[0].pointer_end();
  7287. Ptr != PtrEnd; ++Ptr) {
  7288. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7289. QualType PointeeType = (*Ptr)->getPointeeType();
  7290. if (!PointeeType->isObjectType())
  7291. continue;
  7292. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7293. // T& operator[](T*, ptrdiff_t)
  7294. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7295. }
  7296. for (BuiltinCandidateTypeSet::iterator
  7297. Ptr = CandidateTypes[1].pointer_begin(),
  7298. PtrEnd = CandidateTypes[1].pointer_end();
  7299. Ptr != PtrEnd; ++Ptr) {
  7300. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7301. QualType PointeeType = (*Ptr)->getPointeeType();
  7302. if (!PointeeType->isObjectType())
  7303. continue;
  7304. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7305. // T& operator[](ptrdiff_t, T*)
  7306. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7307. }
  7308. }
  7309. // C++ [over.built]p11:
  7310. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7311. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7312. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7313. // there exist candidate operator functions of the form
  7314. //
  7315. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7316. //
  7317. // where CV12 is the union of CV1 and CV2.
  7318. void addArrowStarOverloads() {
  7319. for (BuiltinCandidateTypeSet::iterator
  7320. Ptr = CandidateTypes[0].pointer_begin(),
  7321. PtrEnd = CandidateTypes[0].pointer_end();
  7322. Ptr != PtrEnd; ++Ptr) {
  7323. QualType C1Ty = (*Ptr);
  7324. QualType C1;
  7325. QualifierCollector Q1;
  7326. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7327. if (!isa<RecordType>(C1))
  7328. continue;
  7329. // heuristic to reduce number of builtin candidates in the set.
  7330. // Add volatile/restrict version only if there are conversions to a
  7331. // volatile/restrict type.
  7332. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7333. continue;
  7334. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7335. continue;
  7336. for (BuiltinCandidateTypeSet::iterator
  7337. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7338. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7339. MemPtr != MemPtrEnd; ++MemPtr) {
  7340. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7341. QualType C2 = QualType(mptr->getClass(), 0);
  7342. C2 = C2.getUnqualifiedType();
  7343. if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
  7344. break;
  7345. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7346. // build CV12 T&
  7347. QualType T = mptr->getPointeeType();
  7348. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7349. T.isVolatileQualified())
  7350. continue;
  7351. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7352. T.isRestrictQualified())
  7353. continue;
  7354. T = Q1.apply(S.Context, T);
  7355. QualType ResultTy = S.Context.getLValueReferenceType(T);
  7356. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7357. }
  7358. }
  7359. }
  7360. // Note that we don't consider the first argument, since it has been
  7361. // contextually converted to bool long ago. The candidates below are
  7362. // therefore added as binary.
  7363. //
  7364. // C++ [over.built]p25:
  7365. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7366. // enumeration type, there exist candidate operator functions of the form
  7367. //
  7368. // T operator?(bool, T, T);
  7369. //
  7370. void addConditionalOperatorOverloads() {
  7371. /// Set of (canonical) types that we've already handled.
  7372. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7373. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7374. for (BuiltinCandidateTypeSet::iterator
  7375. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7376. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7377. Ptr != PtrEnd; ++Ptr) {
  7378. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7379. continue;
  7380. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7381. S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
  7382. }
  7383. for (BuiltinCandidateTypeSet::iterator
  7384. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7385. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7386. MemPtr != MemPtrEnd; ++MemPtr) {
  7387. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7388. continue;
  7389. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7390. S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
  7391. }
  7392. if (S.getLangOpts().CPlusPlus11) {
  7393. for (BuiltinCandidateTypeSet::iterator
  7394. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7395. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7396. Enum != EnumEnd; ++Enum) {
  7397. if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
  7398. continue;
  7399. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7400. continue;
  7401. QualType ParamTypes[2] = { *Enum, *Enum };
  7402. S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
  7403. }
  7404. }
  7405. }
  7406. }
  7407. };
  7408. } // end anonymous namespace
  7409. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  7410. /// operator overloads to the candidate set (C++ [over.built]), based
  7411. /// on the operator @p Op and the arguments given. For example, if the
  7412. /// operator is a binary '+', this routine might add "int
  7413. /// operator+(int, int)" to cover integer addition.
  7414. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  7415. SourceLocation OpLoc,
  7416. ArrayRef<Expr *> Args,
  7417. OverloadCandidateSet &CandidateSet) {
  7418. // Find all of the types that the arguments can convert to, but only
  7419. // if the operator we're looking at has built-in operator candidates
  7420. // that make use of these types. Also record whether we encounter non-record
  7421. // candidate types or either arithmetic or enumeral candidate types.
  7422. Qualifiers VisibleTypeConversionsQuals;
  7423. VisibleTypeConversionsQuals.addConst();
  7424. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  7425. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  7426. bool HasNonRecordCandidateType = false;
  7427. bool HasArithmeticOrEnumeralCandidateType = false;
  7428. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  7429. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7430. CandidateTypes.emplace_back(*this);
  7431. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  7432. OpLoc,
  7433. true,
  7434. (Op == OO_Exclaim ||
  7435. Op == OO_AmpAmp ||
  7436. Op == OO_PipePipe),
  7437. VisibleTypeConversionsQuals);
  7438. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  7439. CandidateTypes[ArgIdx].hasNonRecordTypes();
  7440. HasArithmeticOrEnumeralCandidateType =
  7441. HasArithmeticOrEnumeralCandidateType ||
  7442. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  7443. }
  7444. // Exit early when no non-record types have been added to the candidate set
  7445. // for any of the arguments to the operator.
  7446. //
  7447. // We can't exit early for !, ||, or &&, since there we have always have
  7448. // 'bool' overloads.
  7449. if (!HasNonRecordCandidateType &&
  7450. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  7451. return;
  7452. // Setup an object to manage the common state for building overloads.
  7453. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  7454. VisibleTypeConversionsQuals,
  7455. HasArithmeticOrEnumeralCandidateType,
  7456. CandidateTypes, CandidateSet);
  7457. // Dispatch over the operation to add in only those overloads which apply.
  7458. switch (Op) {
  7459. case OO_None:
  7460. case NUM_OVERLOADED_OPERATORS:
  7461. llvm_unreachable("Expected an overloaded operator");
  7462. case OO_New:
  7463. case OO_Delete:
  7464. case OO_Array_New:
  7465. case OO_Array_Delete:
  7466. case OO_Call:
  7467. llvm_unreachable(
  7468. "Special operators don't use AddBuiltinOperatorCandidates");
  7469. case OO_Comma:
  7470. case OO_Arrow:
  7471. // C++ [over.match.oper]p3:
  7472. // -- For the operator ',', the unary operator '&', or the
  7473. // operator '->', the built-in candidates set is empty.
  7474. break;
  7475. case OO_Plus: // '+' is either unary or binary
  7476. if (Args.size() == 1)
  7477. OpBuilder.addUnaryPlusPointerOverloads();
  7478. // Fall through.
  7479. case OO_Minus: // '-' is either unary or binary
  7480. if (Args.size() == 1) {
  7481. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  7482. } else {
  7483. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  7484. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7485. }
  7486. break;
  7487. case OO_Star: // '*' is either unary or binary
  7488. if (Args.size() == 1)
  7489. OpBuilder.addUnaryStarPointerOverloads();
  7490. else
  7491. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7492. break;
  7493. case OO_Slash:
  7494. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7495. break;
  7496. case OO_PlusPlus:
  7497. case OO_MinusMinus:
  7498. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  7499. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  7500. break;
  7501. case OO_EqualEqual:
  7502. case OO_ExclaimEqual:
  7503. OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
  7504. // Fall through.
  7505. case OO_Less:
  7506. case OO_Greater:
  7507. case OO_LessEqual:
  7508. case OO_GreaterEqual:
  7509. OpBuilder.addRelationalPointerOrEnumeralOverloads();
  7510. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
  7511. break;
  7512. case OO_Percent:
  7513. case OO_Caret:
  7514. case OO_Pipe:
  7515. case OO_LessLess:
  7516. case OO_GreaterGreater:
  7517. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7518. break;
  7519. case OO_Amp: // '&' is either unary or binary
  7520. if (Args.size() == 1)
  7521. // C++ [over.match.oper]p3:
  7522. // -- For the operator ',', the unary operator '&', or the
  7523. // operator '->', the built-in candidates set is empty.
  7524. break;
  7525. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7526. break;
  7527. case OO_Tilde:
  7528. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  7529. break;
  7530. case OO_Equal:
  7531. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  7532. // Fall through.
  7533. case OO_PlusEqual:
  7534. case OO_MinusEqual:
  7535. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  7536. // Fall through.
  7537. case OO_StarEqual:
  7538. case OO_SlashEqual:
  7539. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  7540. break;
  7541. case OO_PercentEqual:
  7542. case OO_LessLessEqual:
  7543. case OO_GreaterGreaterEqual:
  7544. case OO_AmpEqual:
  7545. case OO_CaretEqual:
  7546. case OO_PipeEqual:
  7547. OpBuilder.addAssignmentIntegralOverloads();
  7548. break;
  7549. case OO_Exclaim:
  7550. OpBuilder.addExclaimOverload();
  7551. break;
  7552. case OO_AmpAmp:
  7553. case OO_PipePipe:
  7554. OpBuilder.addAmpAmpOrPipePipeOverload();
  7555. break;
  7556. case OO_Subscript:
  7557. OpBuilder.addSubscriptOverloads();
  7558. break;
  7559. case OO_ArrowStar:
  7560. OpBuilder.addArrowStarOverloads();
  7561. break;
  7562. case OO_Conditional:
  7563. OpBuilder.addConditionalOperatorOverloads();
  7564. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7565. break;
  7566. }
  7567. }
  7568. /// \brief Add function candidates found via argument-dependent lookup
  7569. /// to the set of overloading candidates.
  7570. ///
  7571. /// This routine performs argument-dependent name lookup based on the
  7572. /// given function name (which may also be an operator name) and adds
  7573. /// all of the overload candidates found by ADL to the overload
  7574. /// candidate set (C++ [basic.lookup.argdep]).
  7575. void
  7576. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  7577. SourceLocation Loc,
  7578. ArrayRef<Expr *> Args,
  7579. TemplateArgumentListInfo *ExplicitTemplateArgs,
  7580. OverloadCandidateSet& CandidateSet,
  7581. bool PartialOverloading) {
  7582. ADLResult Fns;
  7583. // FIXME: This approach for uniquing ADL results (and removing
  7584. // redundant candidates from the set) relies on pointer-equality,
  7585. // which means we need to key off the canonical decl. However,
  7586. // always going back to the canonical decl might not get us the
  7587. // right set of default arguments. What default arguments are
  7588. // we supposed to consider on ADL candidates, anyway?
  7589. // FIXME: Pass in the explicit template arguments?
  7590. ArgumentDependentLookup(Name, Loc, Args, Fns);
  7591. // Erase all of the candidates we already knew about.
  7592. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  7593. CandEnd = CandidateSet.end();
  7594. Cand != CandEnd; ++Cand)
  7595. if (Cand->Function) {
  7596. Fns.erase(Cand->Function);
  7597. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  7598. Fns.erase(FunTmpl);
  7599. }
  7600. // For each of the ADL candidates we found, add it to the overload
  7601. // set.
  7602. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  7603. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  7604. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  7605. if (ExplicitTemplateArgs)
  7606. continue;
  7607. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
  7608. PartialOverloading);
  7609. } else
  7610. AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
  7611. FoundDecl, ExplicitTemplateArgs,
  7612. Args, CandidateSet, PartialOverloading);
  7613. }
  7614. }
  7615. /// isBetterOverloadCandidate - Determines whether the first overload
  7616. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  7617. bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
  7618. const OverloadCandidate &Cand2,
  7619. SourceLocation Loc,
  7620. bool UserDefinedConversion) {
  7621. // Define viable functions to be better candidates than non-viable
  7622. // functions.
  7623. if (!Cand2.Viable)
  7624. return Cand1.Viable;
  7625. else if (!Cand1.Viable)
  7626. return false;
  7627. // C++ [over.match.best]p1:
  7628. //
  7629. // -- if F is a static member function, ICS1(F) is defined such
  7630. // that ICS1(F) is neither better nor worse than ICS1(G) for
  7631. // any function G, and, symmetrically, ICS1(G) is neither
  7632. // better nor worse than ICS1(F).
  7633. unsigned StartArg = 0;
  7634. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  7635. StartArg = 1;
  7636. // C++ [over.match.best]p1:
  7637. // A viable function F1 is defined to be a better function than another
  7638. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  7639. // conversion sequence than ICSi(F2), and then...
  7640. unsigned NumArgs = Cand1.NumConversions;
  7641. assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
  7642. bool HasBetterConversion = false;
  7643. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  7644. switch (CompareImplicitConversionSequences(S,
  7645. Cand1.Conversions[ArgIdx],
  7646. Cand2.Conversions[ArgIdx])) {
  7647. case ImplicitConversionSequence::Better:
  7648. // Cand1 has a better conversion sequence.
  7649. HasBetterConversion = true;
  7650. break;
  7651. case ImplicitConversionSequence::Worse:
  7652. // Cand1 can't be better than Cand2.
  7653. return false;
  7654. case ImplicitConversionSequence::Indistinguishable:
  7655. // Do nothing.
  7656. break;
  7657. }
  7658. }
  7659. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  7660. // ICSj(F2), or, if not that,
  7661. if (HasBetterConversion)
  7662. return true;
  7663. // -- the context is an initialization by user-defined conversion
  7664. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  7665. // from the return type of F1 to the destination type (i.e.,
  7666. // the type of the entity being initialized) is a better
  7667. // conversion sequence than the standard conversion sequence
  7668. // from the return type of F2 to the destination type.
  7669. if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
  7670. isa<CXXConversionDecl>(Cand1.Function) &&
  7671. isa<CXXConversionDecl>(Cand2.Function)) {
  7672. // First check whether we prefer one of the conversion functions over the
  7673. // other. This only distinguishes the results in non-standard, extension
  7674. // cases such as the conversion from a lambda closure type to a function
  7675. // pointer or block.
  7676. ImplicitConversionSequence::CompareKind Result =
  7677. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  7678. if (Result == ImplicitConversionSequence::Indistinguishable)
  7679. Result = CompareStandardConversionSequences(S,
  7680. Cand1.FinalConversion,
  7681. Cand2.FinalConversion);
  7682. if (Result != ImplicitConversionSequence::Indistinguishable)
  7683. return Result == ImplicitConversionSequence::Better;
  7684. // FIXME: Compare kind of reference binding if conversion functions
  7685. // convert to a reference type used in direct reference binding, per
  7686. // C++14 [over.match.best]p1 section 2 bullet 3.
  7687. }
  7688. // -- F1 is a non-template function and F2 is a function template
  7689. // specialization, or, if not that,
  7690. bool Cand1IsSpecialization = Cand1.Function &&
  7691. Cand1.Function->getPrimaryTemplate();
  7692. bool Cand2IsSpecialization = Cand2.Function &&
  7693. Cand2.Function->getPrimaryTemplate();
  7694. if (Cand1IsSpecialization != Cand2IsSpecialization)
  7695. return Cand2IsSpecialization;
  7696. // -- F1 and F2 are function template specializations, and the function
  7697. // template for F1 is more specialized than the template for F2
  7698. // according to the partial ordering rules described in 14.5.5.2, or,
  7699. // if not that,
  7700. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  7701. if (FunctionTemplateDecl *BetterTemplate
  7702. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  7703. Cand2.Function->getPrimaryTemplate(),
  7704. Loc,
  7705. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  7706. : TPOC_Call,
  7707. Cand1.ExplicitCallArguments,
  7708. Cand2.ExplicitCallArguments))
  7709. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  7710. }
  7711. // Check for enable_if value-based overload resolution.
  7712. if (Cand1.Function && Cand2.Function &&
  7713. (Cand1.Function->hasAttr<EnableIfAttr>() ||
  7714. Cand2.Function->hasAttr<EnableIfAttr>())) {
  7715. // FIXME: The next several lines are just
  7716. // specific_attr_iterator<EnableIfAttr> but going in declaration order,
  7717. // instead of reverse order which is how they're stored in the AST.
  7718. AttrVec Cand1Attrs;
  7719. if (Cand1.Function->hasAttrs()) {
  7720. Cand1Attrs = Cand1.Function->getAttrs();
  7721. Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
  7722. IsNotEnableIfAttr),
  7723. Cand1Attrs.end());
  7724. std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
  7725. }
  7726. AttrVec Cand2Attrs;
  7727. if (Cand2.Function->hasAttrs()) {
  7728. Cand2Attrs = Cand2.Function->getAttrs();
  7729. Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
  7730. IsNotEnableIfAttr),
  7731. Cand2Attrs.end());
  7732. std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
  7733. }
  7734. // Candidate 1 is better if it has strictly more attributes and
  7735. // the common sequence is identical.
  7736. if (Cand1Attrs.size() <= Cand2Attrs.size())
  7737. return false;
  7738. auto Cand1I = Cand1Attrs.begin();
  7739. for (auto &Cand2A : Cand2Attrs) {
  7740. auto &Cand1A = *Cand1I++;
  7741. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  7742. cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
  7743. S.getASTContext(), true);
  7744. cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
  7745. S.getASTContext(), true);
  7746. if (Cand1ID != Cand2ID)
  7747. return false;
  7748. }
  7749. return true;
  7750. }
  7751. return false;
  7752. }
  7753. /// \brief Computes the best viable function (C++ 13.3.3)
  7754. /// within an overload candidate set.
  7755. ///
  7756. /// \param Loc The location of the function name (or operator symbol) for
  7757. /// which overload resolution occurs.
  7758. ///
  7759. /// \param Best If overload resolution was successful or found a deleted
  7760. /// function, \p Best points to the candidate function found.
  7761. ///
  7762. /// \returns The result of overload resolution.
  7763. OverloadingResult
  7764. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  7765. iterator &Best,
  7766. bool UserDefinedConversion) {
  7767. // HLSL Change Starts
  7768. // Function calls should use HLSL-style overloading. operator[] overloads
  7769. // (used for const support) aren't supported by the defined rules, so
  7770. // use C++ overload resolution for those.
  7771. if (S.getLangOpts().HLSL && !empty() && begin()->Function != nullptr &&
  7772. (begin()->Function->getDeclName() !=
  7773. S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  7774. return ::hlsl::GetBestViableFunction(S, Loc, *this, Best);
  7775. }
  7776. // HLSL Change Ends
  7777. // Find the best viable function.
  7778. Best = end();
  7779. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7780. if (Cand->Viable)
  7781. if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
  7782. UserDefinedConversion))
  7783. Best = Cand;
  7784. }
  7785. // If we didn't find any viable functions, abort.
  7786. if (Best == end())
  7787. return OR_No_Viable_Function;
  7788. // Make sure that this function is better than every other viable
  7789. // function. If not, we have an ambiguity.
  7790. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7791. if (Cand->Viable &&
  7792. Cand != Best &&
  7793. !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
  7794. UserDefinedConversion)) {
  7795. Best = end();
  7796. return OR_Ambiguous;
  7797. }
  7798. }
  7799. // Best is the best viable function.
  7800. if (Best->Function &&
  7801. (Best->Function->isDeleted() ||
  7802. S.isFunctionConsideredUnavailable(Best->Function)))
  7803. return OR_Deleted;
  7804. return OR_Success;
  7805. }
  7806. namespace {
  7807. enum OverloadCandidateKind {
  7808. oc_function,
  7809. oc_method,
  7810. oc_constructor,
  7811. oc_function_template,
  7812. oc_method_template,
  7813. oc_constructor_template,
  7814. oc_implicit_default_constructor,
  7815. oc_implicit_copy_constructor,
  7816. oc_implicit_move_constructor,
  7817. oc_implicit_copy_assignment,
  7818. oc_implicit_move_assignment,
  7819. oc_implicit_inherited_constructor
  7820. };
  7821. OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
  7822. FunctionDecl *Fn,
  7823. std::string &Description) {
  7824. bool isTemplate = false;
  7825. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  7826. isTemplate = true;
  7827. Description = S.getTemplateArgumentBindingsText(
  7828. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  7829. }
  7830. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7831. if (!Ctor->isImplicit())
  7832. return isTemplate ? oc_constructor_template : oc_constructor;
  7833. if (Ctor->getInheritedConstructor())
  7834. return oc_implicit_inherited_constructor;
  7835. if (Ctor->isDefaultConstructor())
  7836. return oc_implicit_default_constructor;
  7837. if (Ctor->isMoveConstructor())
  7838. return oc_implicit_move_constructor;
  7839. assert(Ctor->isCopyConstructor() &&
  7840. "unexpected sort of implicit constructor");
  7841. return oc_implicit_copy_constructor;
  7842. }
  7843. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  7844. if (S.getLangOpts().HLSL) return isTemplate ? oc_method_template : oc_method; // HLSL Change - all intrinsics are implicit, doesn't imply conversion
  7845. // This actually gets spelled 'candidate function' for now, but
  7846. // it doesn't hurt to split it out.
  7847. if (!Meth->isImplicit())
  7848. return isTemplate ? oc_method_template : oc_method;
  7849. if (Meth->isMoveAssignmentOperator())
  7850. return oc_implicit_move_assignment;
  7851. if (Meth->isCopyAssignmentOperator())
  7852. return oc_implicit_copy_assignment;
  7853. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  7854. return oc_method;
  7855. }
  7856. return isTemplate ? oc_function_template : oc_function;
  7857. }
  7858. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
  7859. const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
  7860. if (!Ctor) return;
  7861. Ctor = Ctor->getInheritedConstructor();
  7862. if (!Ctor) return;
  7863. S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
  7864. }
  7865. } // end anonymous namespace
  7866. // Notes the location of an overload candidate.
  7867. void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
  7868. std::string FnDesc;
  7869. OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
  7870. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  7871. << (unsigned) K << FnDesc;
  7872. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  7873. Diag(Fn->getLocation(), PD);
  7874. MaybeEmitInheritedConstructorNote(*this, Fn);
  7875. }
  7876. // Notes the location of all overload candidates designated through
  7877. // OverloadedExpr
  7878. void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
  7879. assert(OverloadedExpr->getType() == Context.OverloadTy);
  7880. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  7881. OverloadExpr *OvlExpr = Ovl.Expression;
  7882. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  7883. IEnd = OvlExpr->decls_end();
  7884. I != IEnd; ++I) {
  7885. if (FunctionTemplateDecl *FunTmpl =
  7886. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  7887. NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
  7888. } else if (FunctionDecl *Fun
  7889. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  7890. NoteOverloadCandidate(Fun, DestType);
  7891. }
  7892. }
  7893. }
  7894. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  7895. /// "lead" diagnostic; it will be given two arguments, the source and
  7896. /// target types of the conversion.
  7897. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  7898. Sema &S,
  7899. SourceLocation CaretLoc,
  7900. const PartialDiagnostic &PDiag) const {
  7901. S.Diag(CaretLoc, PDiag)
  7902. << Ambiguous.getFromType() << Ambiguous.getToType();
  7903. // FIXME: The note limiting machinery is borrowed from
  7904. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  7905. // refactoring here.
  7906. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  7907. unsigned CandsShown = 0;
  7908. AmbiguousConversionSequence::const_iterator I, E;
  7909. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  7910. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  7911. break;
  7912. ++CandsShown;
  7913. S.NoteOverloadCandidate(*I);
  7914. }
  7915. if (I != E)
  7916. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  7917. }
  7918. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  7919. unsigned I, const ImplicitConversionSequence &Conv, SourceLocation OpLoc) { // HLSL Change: add OpLoc and Conv
  7920. // const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  7921. assert(Conv.isBad());
  7922. assert(Cand->Function && "for now, candidate must be a function");
  7923. FunctionDecl *Fn = Cand->Function;
  7924. // There's a conversion slot for the object argument if this is a
  7925. // non-constructor method. Note that 'I' corresponds the
  7926. // conversion-slot index.
  7927. bool isObjectArgument = false;
  7928. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  7929. if (I == 0)
  7930. isObjectArgument = true;
  7931. else
  7932. I--;
  7933. }
  7934. std::string FnDesc;
  7935. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  7936. Expr *FromExpr = Conv.Bad.FromExpr;
  7937. QualType FromTy = Conv.Bad.getFromType();
  7938. QualType ToTy = Conv.Bad.getToType();
  7939. // HLSL Change: replace Fn->getLocation() in diagnostics with FnDiagLocation
  7940. // and avoid notes that try to point to built-in targets
  7941. SourceLocation FnDiagLocation = Fn->getLocation().isValid() ? Fn->getLocation() : OpLoc;
  7942. if (FromTy == S.Context.OverloadTy) {
  7943. assert(FromExpr && "overload set argument came from implicit argument?");
  7944. Expr *E = FromExpr->IgnoreParens();
  7945. if (isa<UnaryOperator>(E))
  7946. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  7947. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  7948. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_overload) // HLSL Change - FnDiagLocation
  7949. << (unsigned) FnKind << FnDesc
  7950. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7951. << ToTy << Name << I+1;
  7952. MaybeEmitInheritedConstructorNote(S, Fn);
  7953. return;
  7954. }
  7955. // Do some hand-waving analysis to see if the non-viability is due
  7956. // to a qualifier mismatch.
  7957. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  7958. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  7959. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  7960. CToTy = RT->getPointeeType();
  7961. else {
  7962. // TODO: detect and diagnose the full richness of const mismatches.
  7963. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  7964. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
  7965. CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
  7966. }
  7967. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  7968. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  7969. Qualifiers FromQs = CFromTy.getQualifiers();
  7970. Qualifiers ToQs = CToTy.getQualifiers();
  7971. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  7972. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_addrspace)
  7973. << (unsigned) FnKind << FnDesc
  7974. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7975. << FromTy
  7976. << FromQs.getAddressSpace() << ToQs.getAddressSpace()
  7977. << (unsigned) isObjectArgument << I+1;
  7978. MaybeEmitInheritedConstructorNote(S, Fn);
  7979. return;
  7980. }
  7981. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  7982. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_ownership)
  7983. << (unsigned) FnKind << FnDesc
  7984. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7985. << FromTy
  7986. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  7987. << (unsigned) isObjectArgument << I+1;
  7988. MaybeEmitInheritedConstructorNote(S, Fn);
  7989. return;
  7990. }
  7991. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  7992. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_gc)
  7993. << (unsigned) FnKind << FnDesc
  7994. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7995. << FromTy
  7996. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  7997. << (unsigned) isObjectArgument << I+1;
  7998. MaybeEmitInheritedConstructorNote(S, Fn);
  7999. return;
  8000. }
  8001. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  8002. assert(CVR && "unexpected qualifiers mismatch");
  8003. if (isObjectArgument) {
  8004. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr_this)
  8005. << (unsigned) FnKind << FnDesc
  8006. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8007. << FromTy << (CVR - 1);
  8008. } else {
  8009. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr)
  8010. << (unsigned) FnKind << FnDesc
  8011. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8012. << FromTy << (CVR - 1) << I+1;
  8013. }
  8014. MaybeEmitInheritedConstructorNote(S, Fn);
  8015. return;
  8016. }
  8017. // Special diagnostic for failure to convert an initializer list, since
  8018. // telling the user that it has type void is not useful.
  8019. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8020. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_list_argument)
  8021. << (unsigned) FnKind << FnDesc
  8022. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8023. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8024. MaybeEmitInheritedConstructorNote(S, Fn);
  8025. return;
  8026. }
  8027. // Diagnose references or pointers to incomplete types differently,
  8028. // since it's far from impossible that the incompleteness triggered
  8029. // the failure.
  8030. QualType TempFromTy = FromTy.getNonReferenceType();
  8031. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8032. TempFromTy = PTy->getPointeeType();
  8033. if (TempFromTy->isIncompleteType()) {
  8034. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_conv_incomplete)
  8035. << (unsigned) FnKind << FnDesc
  8036. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8037. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8038. MaybeEmitInheritedConstructorNote(S, Fn);
  8039. return;
  8040. }
  8041. // Diagnose base -> derived pointer conversions.
  8042. unsigned BaseToDerivedConversion = 0;
  8043. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8044. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8045. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8046. FromPtrTy->getPointeeType()) &&
  8047. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8048. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8049. S.IsDerivedFrom(ToPtrTy->getPointeeType(),
  8050. FromPtrTy->getPointeeType()))
  8051. BaseToDerivedConversion = 1;
  8052. }
  8053. } else if (const ObjCObjectPointerType *FromPtrTy
  8054. = FromTy->getAs<ObjCObjectPointerType>()) {
  8055. if (const ObjCObjectPointerType *ToPtrTy
  8056. = ToTy->getAs<ObjCObjectPointerType>())
  8057. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8058. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8059. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8060. FromPtrTy->getPointeeType()) &&
  8061. FromIface->isSuperClassOf(ToIface))
  8062. BaseToDerivedConversion = 2;
  8063. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  8064. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  8065. !FromTy->isIncompleteType() &&
  8066. !ToRefTy->getPointeeType()->isIncompleteType() &&
  8067. S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
  8068. BaseToDerivedConversion = 3;
  8069. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  8070. ToTy.getNonReferenceType().getCanonicalType() ==
  8071. FromTy.getNonReferenceType().getCanonicalType()) {
  8072. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_lvalue)
  8073. << (unsigned) FnKind << FnDesc
  8074. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8075. << (unsigned) isObjectArgument << I + 1;
  8076. MaybeEmitInheritedConstructorNote(S, Fn);
  8077. return;
  8078. }
  8079. }
  8080. if (BaseToDerivedConversion) {
  8081. S.Diag(FnDiagLocation,
  8082. diag::note_ovl_candidate_bad_base_to_derived_conv)
  8083. << (unsigned) FnKind << FnDesc
  8084. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8085. << (BaseToDerivedConversion - 1)
  8086. << FromTy << ToTy << I+1;
  8087. MaybeEmitInheritedConstructorNote(S, Fn);
  8088. return;
  8089. }
  8090. if (isa<ObjCObjectPointerType>(CFromTy) &&
  8091. isa<PointerType>(CToTy)) {
  8092. Qualifiers FromQs = CFromTy.getQualifiers();
  8093. Qualifiers ToQs = CToTy.getQualifiers();
  8094. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8095. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_arc_conv)
  8096. << (unsigned) FnKind << FnDesc
  8097. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8098. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8099. MaybeEmitInheritedConstructorNote(S, Fn);
  8100. return;
  8101. }
  8102. }
  8103. // Emit the generic diagnostic and, optionally, add the hints to it.
  8104. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  8105. FDiag << (unsigned) FnKind << FnDesc
  8106. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8107. << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
  8108. << (unsigned) (Cand->Fix.Kind);
  8109. // If we can fix the conversion, suggest the FixIts.
  8110. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  8111. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  8112. FDiag << *HI;
  8113. S.Diag(FnDiagLocation, FDiag);
  8114. MaybeEmitInheritedConstructorNote(S, Fn);
  8115. }
  8116. /// Additional arity mismatch diagnosis specific to a function overload
  8117. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  8118. /// over a candidate in any candidate set.
  8119. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  8120. unsigned NumArgs) {
  8121. FunctionDecl *Fn = Cand->Function;
  8122. unsigned MinParams = Fn->getMinRequiredArguments();
  8123. // With invalid overloaded operators, it's possible that we think we
  8124. // have an arity mismatch when in fact it looks like we have the
  8125. // right number of arguments, because only overloaded operators have
  8126. // the weird behavior of overloading member and non-member functions.
  8127. // Just don't report anything.
  8128. if (Fn->isInvalidDecl() &&
  8129. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  8130. return true;
  8131. if (NumArgs < MinParams) {
  8132. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  8133. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8134. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  8135. } else {
  8136. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  8137. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8138. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  8139. }
  8140. return false;
  8141. }
  8142. /// General arity mismatch diagnosis over a candidate in a candidate set.
  8143. static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8144. assert(isa<FunctionDecl>(D) &&
  8145. "The templated declaration should at least be a function"
  8146. " when diagnosing bad template argument deduction due to too many"
  8147. " or too few arguments");
  8148. FunctionDecl *Fn = cast<FunctionDecl>(D);
  8149. // TODO: treat calls to a missing default constructor as a special case
  8150. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  8151. unsigned MinParams = Fn->getMinRequiredArguments();
  8152. // at least / at most / exactly
  8153. unsigned mode, modeCount;
  8154. if (NumFormalArgs < MinParams) {
  8155. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  8156. FnTy->isTemplateVariadic())
  8157. mode = 0; // "at least"
  8158. else
  8159. mode = 2; // "exactly"
  8160. modeCount = MinParams;
  8161. } else {
  8162. if (MinParams != FnTy->getNumParams())
  8163. mode = 1; // "at most"
  8164. else
  8165. mode = 2; // "exactly"
  8166. modeCount = FnTy->getNumParams();
  8167. }
  8168. std::string Description;
  8169. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
  8170. // HLSL Change Starts - fallback for built-ins
  8171. SourceLocation DiagLoc = Fn->getLocation();
  8172. if (DiagLoc.isInvalid()) DiagLoc = OpLoc;
  8173. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  8174. S.Diag(DiagLoc, diag::note_ovl_candidate_arity_one)
  8175. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8176. << mode << Fn->getParamDecl(0) << NumFormalArgs;
  8177. else
  8178. S.Diag(DiagLoc, diag::note_ovl_candidate_arity)
  8179. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8180. << mode << modeCount << NumFormalArgs;
  8181. // HLSL Change Ends
  8182. MaybeEmitInheritedConstructorNote(S, Fn);
  8183. }
  8184. /// Arity mismatch diagnosis specific to a function overload candidate.
  8185. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  8186. unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8187. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  8188. DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs, OpLoc);
  8189. }
  8190. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  8191. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
  8192. return FD->getDescribedFunctionTemplate();
  8193. else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
  8194. return RD->getDescribedClassTemplate();
  8195. llvm_unreachable("Unsupported: Getting the described template declaration"
  8196. " for bad deduction diagnosis");
  8197. }
  8198. /// Diagnose a failed template-argument deduction.
  8199. static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
  8200. DeductionFailureInfo &DeductionFailure,
  8201. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8202. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  8203. NamedDecl *ParamD;
  8204. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  8205. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  8206. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  8207. switch (DeductionFailure.Result) {
  8208. case Sema::TDK_Success:
  8209. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8210. case Sema::TDK_Incomplete: {
  8211. assert(ParamD && "no parameter found for incomplete deduction result");
  8212. S.Diag(Templated->getLocation(),
  8213. diag::note_ovl_candidate_incomplete_deduction)
  8214. << ParamD->getDeclName();
  8215. MaybeEmitInheritedConstructorNote(S, Templated);
  8216. return;
  8217. }
  8218. case Sema::TDK_Underqualified: {
  8219. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  8220. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  8221. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  8222. // Param will have been canonicalized, but it should just be a
  8223. // qualified version of ParamD, so move the qualifiers to that.
  8224. QualifierCollector Qs;
  8225. Qs.strip(Param);
  8226. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  8227. assert(S.Context.hasSameType(Param, NonCanonParam));
  8228. // Arg has also been canonicalized, but there's nothing we can do
  8229. // about that. It also doesn't matter as much, because it won't
  8230. // have any template parameters in it (because deduction isn't
  8231. // done on dependent types).
  8232. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  8233. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  8234. << ParamD->getDeclName() << Arg << NonCanonParam;
  8235. MaybeEmitInheritedConstructorNote(S, Templated);
  8236. return;
  8237. }
  8238. case Sema::TDK_Inconsistent: {
  8239. assert(ParamD && "no parameter found for inconsistent deduction result");
  8240. int which = 0;
  8241. if (isa<TemplateTypeParmDecl>(ParamD))
  8242. which = 0;
  8243. else if (isa<NonTypeTemplateParmDecl>(ParamD))
  8244. which = 1;
  8245. else {
  8246. which = 2;
  8247. }
  8248. S.Diag(Templated->getLocation(),
  8249. diag::note_ovl_candidate_inconsistent_deduction)
  8250. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  8251. << *DeductionFailure.getSecondArg();
  8252. MaybeEmitInheritedConstructorNote(S, Templated);
  8253. return;
  8254. }
  8255. case Sema::TDK_InvalidExplicitArguments:
  8256. assert(ParamD && "no parameter found for invalid explicit arguments");
  8257. if (ParamD->getDeclName())
  8258. S.Diag(Templated->getLocation(),
  8259. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  8260. << ParamD->getDeclName();
  8261. else {
  8262. int index = 0;
  8263. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  8264. index = TTP->getIndex();
  8265. else if (NonTypeTemplateParmDecl *NTTP
  8266. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  8267. index = NTTP->getIndex();
  8268. else
  8269. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  8270. S.Diag(Templated->getLocation(),
  8271. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  8272. << (index + 1);
  8273. }
  8274. MaybeEmitInheritedConstructorNote(S, Templated);
  8275. return;
  8276. case Sema::TDK_TooManyArguments:
  8277. case Sema::TDK_TooFewArguments:
  8278. DiagnoseArityMismatch(S, Templated, NumArgs, OpLoc);
  8279. return;
  8280. case Sema::TDK_InstantiationDepth:
  8281. S.Diag(Templated->getLocation(),
  8282. diag::note_ovl_candidate_instantiation_depth);
  8283. MaybeEmitInheritedConstructorNote(S, Templated);
  8284. return;
  8285. case Sema::TDK_SubstitutionFailure: {
  8286. // Format the template argument list into the argument string.
  8287. SmallString<128> TemplateArgString;
  8288. if (TemplateArgumentList *Args =
  8289. DeductionFailure.getTemplateArgumentList()) {
  8290. TemplateArgString = " ";
  8291. TemplateArgString += S.getTemplateArgumentBindingsText(
  8292. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  8293. }
  8294. // If this candidate was disabled by enable_if, say so.
  8295. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  8296. if (PDiag && PDiag->second.getDiagID() ==
  8297. diag::err_typename_nested_not_found_enable_if) {
  8298. // FIXME: Use the source range of the condition, and the fully-qualified
  8299. // name of the enable_if template. These are both present in PDiag.
  8300. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  8301. << "'enable_if'" << TemplateArgString;
  8302. return;
  8303. }
  8304. // Format the SFINAE diagnostic into the argument string.
  8305. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  8306. // formatted message in another diagnostic.
  8307. SmallString<128> SFINAEArgString;
  8308. SourceRange R;
  8309. if (PDiag) {
  8310. SFINAEArgString = ": ";
  8311. R = SourceRange(PDiag->first, PDiag->first);
  8312. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  8313. }
  8314. S.Diag(Templated->getLocation(),
  8315. diag::note_ovl_candidate_substitution_failure)
  8316. << TemplateArgString << SFINAEArgString << R;
  8317. MaybeEmitInheritedConstructorNote(S, Templated);
  8318. return;
  8319. }
  8320. case Sema::TDK_FailedOverloadResolution: {
  8321. OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
  8322. S.Diag(Templated->getLocation(),
  8323. diag::note_ovl_candidate_failed_overload_resolution)
  8324. << R.Expression->getName();
  8325. return;
  8326. }
  8327. case Sema::TDK_NonDeducedMismatch: {
  8328. // FIXME: Provide a source location to indicate what we couldn't match.
  8329. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  8330. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  8331. if (FirstTA.getKind() == TemplateArgument::Template &&
  8332. SecondTA.getKind() == TemplateArgument::Template) {
  8333. TemplateName FirstTN = FirstTA.getAsTemplate();
  8334. TemplateName SecondTN = SecondTA.getAsTemplate();
  8335. if (FirstTN.getKind() == TemplateName::Template &&
  8336. SecondTN.getKind() == TemplateName::Template) {
  8337. if (FirstTN.getAsTemplateDecl()->getName() ==
  8338. SecondTN.getAsTemplateDecl()->getName()) {
  8339. // FIXME: This fixes a bad diagnostic where both templates are named
  8340. // the same. This particular case is a bit difficult since:
  8341. // 1) It is passed as a string to the diagnostic printer.
  8342. // 2) The diagnostic printer only attempts to find a better
  8343. // name for types, not decls.
  8344. // Ideally, this should folded into the diagnostic printer.
  8345. S.Diag(Templated->getLocation(),
  8346. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  8347. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  8348. return;
  8349. }
  8350. }
  8351. }
  8352. // HLSL Change Starts
  8353. // The implementation for template argument deducation does not yet provide
  8354. // FirstArg and SecondArg information for failure cases; ellide the note in
  8355. // this case.
  8356. if (FirstTA.isNull() || SecondTA.isNull()) return;
  8357. // HLSL Change Ends
  8358. // FIXME: For generic lambda parameters, check if the function is a lambda
  8359. // call operator, and if so, emit a prettier and more informative
  8360. // diagnostic that mentions 'auto' and lambda in addition to
  8361. // (or instead of?) the canonical template type parameters.
  8362. S.Diag(Templated->getLocation(),
  8363. diag::note_ovl_candidate_non_deduced_mismatch)
  8364. << FirstTA << SecondTA;
  8365. return;
  8366. }
  8367. // TODO: diagnose these individually, then kill off
  8368. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  8369. case Sema::TDK_MiscellaneousDeductionFailure:
  8370. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  8371. MaybeEmitInheritedConstructorNote(S, Templated);
  8372. return;
  8373. }
  8374. }
  8375. /// Diagnose a failed template-argument deduction, for function calls.
  8376. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  8377. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8378. unsigned TDK = Cand->DeductionFailure.Result;
  8379. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  8380. if (CheckArityMismatch(S, Cand, NumArgs))
  8381. return;
  8382. }
  8383. DiagnoseBadDeduction(S, Cand->Function, // pattern
  8384. Cand->DeductionFailure, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8385. }
  8386. /// CUDA: diagnose an invalid call across targets.
  8387. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  8388. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  8389. FunctionDecl *Callee = Cand->Function;
  8390. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  8391. CalleeTarget = S.IdentifyCUDATarget(Callee);
  8392. std::string FnDesc;
  8393. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
  8394. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  8395. << (unsigned)FnKind << CalleeTarget << CallerTarget;
  8396. // This could be an implicit constructor for which we could not infer the
  8397. // target due to a collsion. Diagnose that case.
  8398. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  8399. if (Meth != nullptr && Meth->isImplicit()) {
  8400. CXXRecordDecl *ParentClass = Meth->getParent();
  8401. Sema::CXXSpecialMember CSM;
  8402. switch (FnKind) {
  8403. default:
  8404. return;
  8405. case oc_implicit_default_constructor:
  8406. CSM = Sema::CXXDefaultConstructor;
  8407. break;
  8408. case oc_implicit_copy_constructor:
  8409. CSM = Sema::CXXCopyConstructor;
  8410. break;
  8411. case oc_implicit_move_constructor:
  8412. CSM = Sema::CXXMoveConstructor;
  8413. break;
  8414. case oc_implicit_copy_assignment:
  8415. CSM = Sema::CXXCopyAssignment;
  8416. break;
  8417. case oc_implicit_move_assignment:
  8418. CSM = Sema::CXXMoveAssignment;
  8419. break;
  8420. };
  8421. bool ConstRHS = false;
  8422. if (Meth->getNumParams()) {
  8423. if (const ReferenceType *RT =
  8424. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  8425. ConstRHS = RT->getPointeeType().isConstQualified();
  8426. }
  8427. }
  8428. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  8429. /* ConstRHS */ ConstRHS,
  8430. /* Diagnose */ true);
  8431. }
  8432. }
  8433. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  8434. FunctionDecl *Callee = Cand->Function;
  8435. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  8436. S.Diag(Callee->getLocation(),
  8437. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  8438. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  8439. }
  8440. /// Generates a 'note' diagnostic for an overload candidate. We've
  8441. /// already generated a primary error at the call site.
  8442. ///
  8443. /// It really does need to be a single diagnostic with its caret
  8444. /// pointed at the candidate declaration. Yes, this creates some
  8445. /// major challenges of technical writing. Yes, this makes pointing
  8446. /// out problems with specific arguments quite awkward. It's still
  8447. /// better than generating twenty screens of text for every failed
  8448. /// overload.
  8449. ///
  8450. /// It would be great to be able to express per-candidate problems
  8451. /// more richly for those diagnostic clients that cared, but we'd
  8452. /// still have to be just as careful with the default diagnostics.
  8453. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  8454. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change: add OpLoc
  8455. FunctionDecl *Fn = Cand->Function;
  8456. // Note deleted candidates, but only if they're viable.
  8457. if (Cand->Viable && (Fn->isDeleted() ||
  8458. S.isFunctionConsideredUnavailable(Fn))) {
  8459. std::string FnDesc;
  8460. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  8461. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  8462. << FnKind << FnDesc
  8463. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  8464. MaybeEmitInheritedConstructorNote(S, Fn);
  8465. return;
  8466. }
  8467. // We don't really have anything else to say about viable candidates.
  8468. if (Cand->Viable) {
  8469. S.NoteOverloadCandidate(Fn);
  8470. return;
  8471. }
  8472. switch (Cand->FailureKind) {
  8473. case ovl_fail_too_many_arguments:
  8474. case ovl_fail_too_few_arguments:
  8475. return DiagnoseArityMismatch(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8476. case ovl_fail_bad_deduction:
  8477. return DiagnoseBadDeduction(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8478. case ovl_fail_illegal_constructor: {
  8479. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  8480. << (Fn->getPrimaryTemplate() ? 1 : 0);
  8481. MaybeEmitInheritedConstructorNote(S, Fn);
  8482. return;
  8483. }
  8484. case ovl_fail_trivial_conversion:
  8485. case ovl_fail_bad_final_conversion:
  8486. case ovl_fail_final_conversion_not_exact:
  8487. return S.NoteOverloadCandidate(Fn);
  8488. case ovl_fail_bad_conversion: {
  8489. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  8490. for (unsigned N = Cand->NumConversions; I != N; ++I)
  8491. if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8492. return DiagnoseBadConversion(S, Cand, I, Cand->Conversions[I], OpLoc); // HLSL Change: add OpLoc
  8493. if (Cand->OutConversions[I].isInitialized() && Cand->OutConversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8494. return DiagnoseBadConversion(S, Cand, I, Cand->OutConversions[I], OpLoc); // HLSL Change: add OpLoc
  8495. // FIXME: this currently happens when we're called from SemaInit
  8496. // when user-conversion overload fails. Figure out how to handle
  8497. // those conditions and diagnose them well.
  8498. return S.NoteOverloadCandidate(Fn);
  8499. }
  8500. case ovl_fail_bad_target:
  8501. return DiagnoseBadTarget(S, Cand);
  8502. case ovl_fail_enable_if:
  8503. return DiagnoseFailedEnableIfAttr(S, Cand);
  8504. }
  8505. }
  8506. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  8507. // Desugar the type of the surrogate down to a function type,
  8508. // retaining as many typedefs as possible while still showing
  8509. // the function type (and, therefore, its parameter types).
  8510. QualType FnType = Cand->Surrogate->getConversionType();
  8511. bool isLValueReference = false;
  8512. bool isRValueReference = false;
  8513. bool isPointer = false;
  8514. if (const LValueReferenceType *FnTypeRef =
  8515. FnType->getAs<LValueReferenceType>()) {
  8516. FnType = FnTypeRef->getPointeeType();
  8517. isLValueReference = true;
  8518. } else if (const RValueReferenceType *FnTypeRef =
  8519. FnType->getAs<RValueReferenceType>()) {
  8520. FnType = FnTypeRef->getPointeeType();
  8521. isRValueReference = true;
  8522. }
  8523. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  8524. FnType = FnTypePtr->getPointeeType();
  8525. isPointer = true;
  8526. }
  8527. // Desugar down to a function type.
  8528. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  8529. // Reconstruct the pointer/reference as appropriate.
  8530. if (isPointer) FnType = S.Context.getPointerType(FnType);
  8531. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  8532. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  8533. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  8534. << FnType;
  8535. MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
  8536. }
  8537. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  8538. SourceLocation OpLoc,
  8539. OverloadCandidate *Cand) {
  8540. assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
  8541. std::string TypeStr("operator");
  8542. TypeStr += Opc;
  8543. TypeStr += "(";
  8544. TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
  8545. if (Cand->NumConversions == 1) {
  8546. TypeStr += ")";
  8547. S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
  8548. } else {
  8549. TypeStr += ", ";
  8550. TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
  8551. TypeStr += ")";
  8552. S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
  8553. }
  8554. }
  8555. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  8556. OverloadCandidate *Cand) {
  8557. unsigned NoOperands = Cand->NumConversions;
  8558. for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
  8559. const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
  8560. if (ICS.isBad()) break; // all meaningless after first invalid
  8561. if (!ICS.isAmbiguous()) continue;
  8562. ICS.DiagnoseAmbiguousConversion(S, OpLoc,
  8563. S.PDiag(diag::note_ambiguous_type_conversion));
  8564. }
  8565. }
  8566. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  8567. if (Cand->Function)
  8568. return Cand->Function->getLocation();
  8569. if (Cand->IsSurrogate)
  8570. return Cand->Surrogate->getLocation();
  8571. return SourceLocation();
  8572. }
  8573. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  8574. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  8575. case Sema::TDK_Success:
  8576. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8577. case Sema::TDK_Invalid:
  8578. case Sema::TDK_Incomplete:
  8579. return 1;
  8580. case Sema::TDK_Underqualified:
  8581. case Sema::TDK_Inconsistent:
  8582. return 2;
  8583. case Sema::TDK_SubstitutionFailure:
  8584. case Sema::TDK_NonDeducedMismatch:
  8585. case Sema::TDK_MiscellaneousDeductionFailure:
  8586. return 3;
  8587. case Sema::TDK_InstantiationDepth:
  8588. case Sema::TDK_FailedOverloadResolution:
  8589. return 4;
  8590. case Sema::TDK_InvalidExplicitArguments:
  8591. return 5;
  8592. case Sema::TDK_TooManyArguments:
  8593. case Sema::TDK_TooFewArguments:
  8594. return 6;
  8595. }
  8596. llvm_unreachable("Unhandled deduction result");
  8597. }
  8598. namespace {
  8599. struct CompareOverloadCandidatesForDisplay {
  8600. Sema &S;
  8601. size_t NumArgs;
  8602. CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
  8603. : S(S), NumArgs(nArgs) {}
  8604. bool operator()(const OverloadCandidate *L,
  8605. const OverloadCandidate *R) {
  8606. // Fast-path this check.
  8607. if (L == R) return false;
  8608. // Order first by viability.
  8609. if (L->Viable) {
  8610. if (!R->Viable) return true;
  8611. // TODO: introduce a tri-valued comparison for overload
  8612. // candidates. Would be more worthwhile if we had a sort
  8613. // that could exploit it.
  8614. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
  8615. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
  8616. } else if (R->Viable)
  8617. return false;
  8618. assert(L->Viable == R->Viable);
  8619. // Criteria by which we can sort non-viable candidates:
  8620. if (!L->Viable) {
  8621. // 1. Arity mismatches come after other candidates.
  8622. if (L->FailureKind == ovl_fail_too_many_arguments ||
  8623. L->FailureKind == ovl_fail_too_few_arguments) {
  8624. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8625. R->FailureKind == ovl_fail_too_few_arguments) {
  8626. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  8627. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  8628. if (LDist == RDist) {
  8629. if (L->FailureKind == R->FailureKind)
  8630. // Sort non-surrogates before surrogates.
  8631. return !L->IsSurrogate && R->IsSurrogate;
  8632. // Sort candidates requiring fewer parameters than there were
  8633. // arguments given after candidates requiring more parameters
  8634. // than there were arguments given.
  8635. return L->FailureKind == ovl_fail_too_many_arguments;
  8636. }
  8637. return LDist < RDist;
  8638. }
  8639. return false;
  8640. }
  8641. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8642. R->FailureKind == ovl_fail_too_few_arguments)
  8643. return true;
  8644. // 2. Bad conversions come first and are ordered by the number
  8645. // of bad conversions and quality of good conversions.
  8646. if (L->FailureKind == ovl_fail_bad_conversion) {
  8647. if (R->FailureKind != ovl_fail_bad_conversion)
  8648. return true;
  8649. // The conversion that can be fixed with a smaller number of changes,
  8650. // comes first.
  8651. unsigned numLFixes = L->Fix.NumConversionsFixed;
  8652. unsigned numRFixes = R->Fix.NumConversionsFixed;
  8653. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  8654. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  8655. if (numLFixes != numRFixes) {
  8656. return numLFixes < numRFixes;
  8657. }
  8658. // If there's any ordering between the defined conversions...
  8659. // FIXME: this might not be transitive.
  8660. assert(L->NumConversions == R->NumConversions);
  8661. int leftBetter = 0;
  8662. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  8663. for (unsigned E = L->NumConversions; I != E; ++I) {
  8664. switch (CompareImplicitConversionSequences(S,
  8665. L->Conversions[I],
  8666. R->Conversions[I])) {
  8667. case ImplicitConversionSequence::Better:
  8668. leftBetter++;
  8669. break;
  8670. case ImplicitConversionSequence::Worse:
  8671. leftBetter--;
  8672. break;
  8673. case ImplicitConversionSequence::Indistinguishable:
  8674. break;
  8675. }
  8676. }
  8677. if (leftBetter > 0) return true;
  8678. if (leftBetter < 0) return false;
  8679. } else if (R->FailureKind == ovl_fail_bad_conversion)
  8680. return false;
  8681. if (L->FailureKind == ovl_fail_bad_deduction) {
  8682. if (R->FailureKind != ovl_fail_bad_deduction)
  8683. return true;
  8684. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8685. return RankDeductionFailure(L->DeductionFailure)
  8686. < RankDeductionFailure(R->DeductionFailure);
  8687. } else if (R->FailureKind == ovl_fail_bad_deduction)
  8688. return false;
  8689. // TODO: others?
  8690. }
  8691. // Sort everything else by location.
  8692. SourceLocation LLoc = GetLocationForCandidate(L);
  8693. SourceLocation RLoc = GetLocationForCandidate(R);
  8694. // Put candidates without locations (e.g. builtins) at the end.
  8695. if (LLoc.isInvalid()) return false;
  8696. if (RLoc.isInvalid()) return true;
  8697. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8698. }
  8699. };
  8700. }
  8701. /// CompleteNonViableCandidate - Normally, overload resolution only
  8702. /// computes up to the first. Produces the FixIt set if possible.
  8703. static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  8704. ArrayRef<Expr *> Args) {
  8705. assert(!Cand->Viable);
  8706. // Don't do anything on failures other than bad conversion.
  8707. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  8708. // We only want the FixIts if all the arguments can be corrected.
  8709. bool Unfixable = false;
  8710. // Use a implicit copy initialization to check conversion fixes.
  8711. Cand->Fix.setConversionChecker(TryCopyInitialization);
  8712. // Skip forward to the first bad conversion.
  8713. unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
  8714. unsigned ConvCount = Cand->NumConversions;
  8715. while (true) {
  8716. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  8717. ConvIdx++;
  8718. if (Cand->Conversions[ConvIdx - 1].isInitialized() && Cand->Conversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8719. Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
  8720. break;
  8721. }
  8722. // HLSL Change Starts - check out conversions
  8723. if (Cand->OutConversions[ConvIdx - 1].isInitialized() && Cand->OutConversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8724. // Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); - consider suggesting a fix
  8725. Unfixable = true;
  8726. break;
  8727. }
  8728. // HLSL Change End
  8729. }
  8730. if (ConvIdx == ConvCount)
  8731. return;
  8732. assert(!Cand->Conversions[ConvIdx].isInitialized() &&
  8733. "remaining conversion is initialized?");
  8734. // FIXME: this should probably be preserved from the overload
  8735. // operation somehow.
  8736. bool SuppressUserConversions = false;
  8737. const FunctionProtoType* Proto;
  8738. unsigned ArgIdx = ConvIdx;
  8739. if (Cand->IsSurrogate) {
  8740. QualType ConvType
  8741. = Cand->Surrogate->getConversionType().getNonReferenceType();
  8742. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  8743. ConvType = ConvPtrType->getPointeeType();
  8744. Proto = ConvType->getAs<FunctionProtoType>();
  8745. ArgIdx--;
  8746. } else if (Cand->Function) {
  8747. Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
  8748. if (isa<CXXMethodDecl>(Cand->Function) &&
  8749. !isa<CXXConstructorDecl>(Cand->Function))
  8750. ArgIdx--;
  8751. } else {
  8752. // Builtin binary operator with a bad first conversion.
  8753. assert(ConvCount <= 3);
  8754. for (; ConvIdx != ConvCount && ConvIdx < 3; ++ConvIdx) // HLSL Change: explicit about ConvIdx < 3
  8755. Cand->Conversions[ConvIdx]
  8756. = TryCopyInitialization(S, Args[ConvIdx],
  8757. Cand->BuiltinTypes.ParamTypes[ConvIdx],
  8758. SuppressUserConversions,
  8759. /*InOverloadResolution*/ true,
  8760. /*AllowObjCWritebackConversion=*/
  8761. S.getLangOpts().ObjCAutoRefCount);
  8762. return;
  8763. }
  8764. // Fill in the rest of the conversions.
  8765. unsigned NumParams = Proto->getNumParams();
  8766. for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
  8767. if (ArgIdx < NumParams) {
  8768. Cand->Conversions[ConvIdx] = TryCopyInitialization(
  8769. S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
  8770. /*InOverloadResolution=*/true,
  8771. /*AllowObjCWritebackConversion=*/
  8772. S.getLangOpts().ObjCAutoRefCount);
  8773. // Store the FixIt in the candidate if it exists.
  8774. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  8775. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  8776. }
  8777. else
  8778. Cand->Conversions[ConvIdx].setEllipsis();
  8779. }
  8780. }
  8781. /// PrintOverloadCandidates - When overload resolution fails, prints
  8782. /// diagnostic messages containing the candidates in the candidate
  8783. /// set.
  8784. void OverloadCandidateSet::NoteCandidates(Sema &S,
  8785. OverloadCandidateDisplayKind OCD,
  8786. ArrayRef<Expr *> Args,
  8787. StringRef Opc,
  8788. SourceLocation OpLoc) {
  8789. // Sort the candidates by viability and position. Sorting directly would
  8790. // be prohibitive, so we make a set of pointers and sort those.
  8791. SmallVector<OverloadCandidate*, 32> Cands;
  8792. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  8793. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8794. if (Cand->Viable)
  8795. Cands.push_back(Cand);
  8796. else if (OCD == OCD_AllCandidates) {
  8797. CompleteNonViableCandidate(S, Cand, Args);
  8798. if (Cand->Function || Cand->IsSurrogate)
  8799. Cands.push_back(Cand);
  8800. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  8801. // want to list every possible builtin candidate.
  8802. }
  8803. }
  8804. std::sort(Cands.begin(), Cands.end(),
  8805. CompareOverloadCandidatesForDisplay(S, Args.size()));
  8806. bool ReportedAmbiguousConversions = false;
  8807. SmallVectorImpl<OverloadCandidate*>::iterator I, E;
  8808. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8809. unsigned CandsShown = 0;
  8810. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8811. OverloadCandidate *Cand = *I;
  8812. // Set an arbitrary limit on the number of candidate functions we'll spam
  8813. // the user with. FIXME: This limit should depend on details of the
  8814. // candidate list.
  8815. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  8816. break;
  8817. }
  8818. ++CandsShown;
  8819. if (Cand->Function)
  8820. NoteFunctionCandidate(S, Cand, Args.size(), OpLoc); // HLSL Change: add OpLoc
  8821. else if (Cand->IsSurrogate)
  8822. NoteSurrogateCandidate(S, Cand);
  8823. else {
  8824. assert(Cand->Viable &&
  8825. "Non-viable built-in candidates are not added to Cands.");
  8826. // Generally we only see ambiguities including viable builtin
  8827. // operators if overload resolution got screwed up by an
  8828. // ambiguous user-defined conversion.
  8829. //
  8830. // FIXME: It's quite possible for different conversions to see
  8831. // different ambiguities, though.
  8832. if (!ReportedAmbiguousConversions) {
  8833. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  8834. ReportedAmbiguousConversions = true;
  8835. }
  8836. // If this is a viable builtin, print it.
  8837. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  8838. }
  8839. }
  8840. if (I != E)
  8841. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  8842. }
  8843. static SourceLocation
  8844. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  8845. return Cand->Specialization ? Cand->Specialization->getLocation()
  8846. : SourceLocation();
  8847. }
  8848. namespace {
  8849. struct CompareTemplateSpecCandidatesForDisplay {
  8850. Sema &S;
  8851. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  8852. bool operator()(const TemplateSpecCandidate *L,
  8853. const TemplateSpecCandidate *R) {
  8854. // Fast-path this check.
  8855. if (L == R)
  8856. return false;
  8857. // Assuming that both candidates are not matches...
  8858. // Sort by the ranking of deduction failures.
  8859. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8860. return RankDeductionFailure(L->DeductionFailure) <
  8861. RankDeductionFailure(R->DeductionFailure);
  8862. // Sort everything else by location.
  8863. SourceLocation LLoc = GetLocationForCandidate(L);
  8864. SourceLocation RLoc = GetLocationForCandidate(R);
  8865. // Put candidates without locations (e.g. builtins) at the end.
  8866. if (LLoc.isInvalid())
  8867. return false;
  8868. if (RLoc.isInvalid())
  8869. return true;
  8870. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8871. }
  8872. };
  8873. }
  8874. /// Diagnose a template argument deduction failure.
  8875. /// We are treating these failures as overload failures due to bad
  8876. /// deductions.
  8877. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
  8878. DiagnoseBadDeduction(S, Specialization, // pattern
  8879. DeductionFailure, /*NumArgs=*/0, SourceLocation()); // HLSL Change - add OpLoc
  8880. }
  8881. void TemplateSpecCandidateSet::destroyCandidates() {
  8882. for (iterator i = begin(), e = end(); i != e; ++i) {
  8883. i->DeductionFailure.Destroy();
  8884. }
  8885. }
  8886. void TemplateSpecCandidateSet::clear() {
  8887. destroyCandidates();
  8888. Candidates.clear();
  8889. }
  8890. /// NoteCandidates - When no template specialization match is found, prints
  8891. /// diagnostic messages containing the non-matching specializations that form
  8892. /// the candidate set.
  8893. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  8894. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  8895. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  8896. // Sort the candidates by position (assuming no candidate is a match).
  8897. // Sorting directly would be prohibitive, so we make a set of pointers
  8898. // and sort those.
  8899. SmallVector<TemplateSpecCandidate *, 32> Cands;
  8900. Cands.reserve(size());
  8901. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8902. if (Cand->Specialization)
  8903. Cands.push_back(Cand);
  8904. // Otherwise, this is a non-matching builtin candidate. We do not,
  8905. // in general, want to list every possible builtin candidate.
  8906. }
  8907. std::sort(Cands.begin(), Cands.end(),
  8908. CompareTemplateSpecCandidatesForDisplay(S));
  8909. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  8910. // for generalization purposes (?).
  8911. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8912. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  8913. unsigned CandsShown = 0;
  8914. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8915. TemplateSpecCandidate *Cand = *I;
  8916. // Set an arbitrary limit on the number of candidates we'll spam
  8917. // the user with. FIXME: This limit should depend on details of the
  8918. // candidate list.
  8919. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8920. break;
  8921. ++CandsShown;
  8922. assert(Cand->Specialization &&
  8923. "Non-matching built-in candidates are not added to Cands.");
  8924. Cand->NoteDeductionFailure(S);
  8925. }
  8926. if (I != E)
  8927. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  8928. }
  8929. // [PossiblyAFunctionType] --> [Return]
  8930. // NonFunctionType --> NonFunctionType
  8931. // R (A) --> R(A)
  8932. // R (*)(A) --> R (A)
  8933. // R (&)(A) --> R (A)
  8934. // R (S::*)(A) --> R (A)
  8935. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  8936. QualType Ret = PossiblyAFunctionType;
  8937. if (const PointerType *ToTypePtr =
  8938. PossiblyAFunctionType->getAs<PointerType>())
  8939. Ret = ToTypePtr->getPointeeType();
  8940. else if (const ReferenceType *ToTypeRef =
  8941. PossiblyAFunctionType->getAs<ReferenceType>())
  8942. Ret = ToTypeRef->getPointeeType();
  8943. else if (const MemberPointerType *MemTypePtr =
  8944. PossiblyAFunctionType->getAs<MemberPointerType>())
  8945. Ret = MemTypePtr->getPointeeType();
  8946. Ret =
  8947. Context.getCanonicalType(Ret).getUnqualifiedType();
  8948. return Ret;
  8949. }
  8950. namespace {
  8951. // A helper class to help with address of function resolution
  8952. // - allows us to avoid passing around all those ugly parameters
  8953. class AddressOfFunctionResolver {
  8954. Sema& S;
  8955. Expr* SourceExpr;
  8956. const QualType& TargetType;
  8957. QualType TargetFunctionType; // Extracted function type from target type
  8958. bool Complain;
  8959. //DeclAccessPair& ResultFunctionAccessPair;
  8960. ASTContext& Context;
  8961. bool TargetTypeIsNonStaticMemberFunction;
  8962. bool FoundNonTemplateFunction;
  8963. bool StaticMemberFunctionFromBoundPointer;
  8964. OverloadExpr::FindResult OvlExprInfo;
  8965. OverloadExpr *OvlExpr;
  8966. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  8967. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  8968. TemplateSpecCandidateSet FailedCandidates;
  8969. public:
  8970. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  8971. const QualType &TargetType, bool Complain)
  8972. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  8973. Complain(Complain), Context(S.getASTContext()),
  8974. TargetTypeIsNonStaticMemberFunction(
  8975. !!TargetType->getAs<MemberPointerType>()),
  8976. FoundNonTemplateFunction(false),
  8977. StaticMemberFunctionFromBoundPointer(false),
  8978. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  8979. OvlExpr(OvlExprInfo.Expression),
  8980. FailedCandidates(OvlExpr->getNameLoc()) {
  8981. ExtractUnqualifiedFunctionTypeFromTargetType();
  8982. if (TargetFunctionType->isFunctionType()) {
  8983. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  8984. if (!UME->isImplicitAccess() &&
  8985. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  8986. StaticMemberFunctionFromBoundPointer = true;
  8987. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  8988. DeclAccessPair dap;
  8989. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  8990. OvlExpr, false, &dap)) {
  8991. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  8992. if (!Method->isStatic()) {
  8993. // If the target type is a non-function type and the function found
  8994. // is a non-static member function, pretend as if that was the
  8995. // target, it's the only possible type to end up with.
  8996. TargetTypeIsNonStaticMemberFunction = true;
  8997. // And skip adding the function if its not in the proper form.
  8998. // We'll diagnose this due to an empty set of functions.
  8999. if (!OvlExprInfo.HasFormOfMemberPointer)
  9000. return;
  9001. }
  9002. Matches.push_back(std::make_pair(dap, Fn));
  9003. }
  9004. return;
  9005. }
  9006. if (OvlExpr->hasExplicitTemplateArgs())
  9007. OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
  9008. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  9009. // C++ [over.over]p4:
  9010. // If more than one function is selected, [...]
  9011. if (Matches.size() > 1) {
  9012. if (FoundNonTemplateFunction)
  9013. EliminateAllTemplateMatches();
  9014. else
  9015. EliminateAllExceptMostSpecializedTemplate();
  9016. }
  9017. }
  9018. }
  9019. private:
  9020. bool isTargetTypeAFunction() const {
  9021. return TargetFunctionType->isFunctionType();
  9022. }
  9023. // [ToType] [Return]
  9024. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  9025. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  9026. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  9027. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  9028. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  9029. }
  9030. // return true if any matching specializations were found
  9031. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  9032. const DeclAccessPair& CurAccessFunPair) {
  9033. if (CXXMethodDecl *Method
  9034. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  9035. // Skip non-static function templates when converting to pointer, and
  9036. // static when converting to member pointer.
  9037. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9038. return false;
  9039. }
  9040. else if (TargetTypeIsNonStaticMemberFunction)
  9041. return false;
  9042. // C++ [over.over]p2:
  9043. // If the name is a function template, template argument deduction is
  9044. // done (14.8.2.2), and if the argument deduction succeeds, the
  9045. // resulting template argument list is used to generate a single
  9046. // function template specialization, which is added to the set of
  9047. // overloaded functions considered.
  9048. FunctionDecl *Specialization = nullptr;
  9049. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9050. if (Sema::TemplateDeductionResult Result
  9051. = S.DeduceTemplateArguments(FunctionTemplate,
  9052. &OvlExplicitTemplateArgs,
  9053. TargetFunctionType, Specialization,
  9054. Info, /*InOverloadResolution=*/true)) {
  9055. // Make a note of the failed deduction for diagnostics.
  9056. FailedCandidates.addCandidate()
  9057. .set(FunctionTemplate->getTemplatedDecl(),
  9058. MakeDeductionFailureInfo(Context, Result, Info));
  9059. return false;
  9060. }
  9061. // Template argument deduction ensures that we have an exact match or
  9062. // compatible pointer-to-function arguments that would be adjusted by ICS.
  9063. // This function template specicalization works.
  9064. Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
  9065. assert(S.isSameOrCompatibleFunctionType(
  9066. Context.getCanonicalType(Specialization->getType()),
  9067. Context.getCanonicalType(TargetFunctionType)));
  9068. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  9069. return true;
  9070. }
  9071. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  9072. const DeclAccessPair& CurAccessFunPair) {
  9073. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  9074. // Skip non-static functions when converting to pointer, and static
  9075. // when converting to member pointer.
  9076. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9077. return false;
  9078. }
  9079. else if (TargetTypeIsNonStaticMemberFunction)
  9080. return false;
  9081. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  9082. if (S.getLangOpts().CUDA)
  9083. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  9084. if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
  9085. return false;
  9086. // If any candidate has a placeholder return type, trigger its deduction
  9087. // now.
  9088. if (S.getLangOpts().CPlusPlus14 &&
  9089. FunDecl->getReturnType()->isUndeducedType() &&
  9090. S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
  9091. return false;
  9092. QualType ResultTy;
  9093. if (Context.hasSameUnqualifiedType(TargetFunctionType,
  9094. FunDecl->getType()) ||
  9095. S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
  9096. ResultTy)) {
  9097. Matches.push_back(std::make_pair(CurAccessFunPair,
  9098. cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  9099. FoundNonTemplateFunction = true;
  9100. return true;
  9101. }
  9102. }
  9103. return false;
  9104. }
  9105. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  9106. bool Ret = false;
  9107. // If the overload expression doesn't have the form of a pointer to
  9108. // member, don't try to convert it to a pointer-to-member type.
  9109. if (IsInvalidFormOfPointerToMemberFunction())
  9110. return false;
  9111. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9112. E = OvlExpr->decls_end();
  9113. I != E; ++I) {
  9114. // Look through any using declarations to find the underlying function.
  9115. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  9116. // C++ [over.over]p3:
  9117. // Non-member functions and static member functions match
  9118. // targets of type "pointer-to-function" or "reference-to-function."
  9119. // Nonstatic member functions match targets of
  9120. // type "pointer-to-member-function."
  9121. // Note that according to DR 247, the containing class does not matter.
  9122. if (FunctionTemplateDecl *FunctionTemplate
  9123. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  9124. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  9125. Ret = true;
  9126. }
  9127. // If we have explicit template arguments supplied, skip non-templates.
  9128. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  9129. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  9130. Ret = true;
  9131. }
  9132. assert(Ret || Matches.empty());
  9133. return Ret;
  9134. }
  9135. void EliminateAllExceptMostSpecializedTemplate() {
  9136. // [...] and any given function template specialization F1 is
  9137. // eliminated if the set contains a second function template
  9138. // specialization whose function template is more specialized
  9139. // than the function template of F1 according to the partial
  9140. // ordering rules of 14.5.5.2.
  9141. // The algorithm specified above is quadratic. We instead use a
  9142. // two-pass algorithm (similar to the one used to identify the
  9143. // best viable function in an overload set) that identifies the
  9144. // best function template (if it exists).
  9145. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  9146. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  9147. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  9148. // TODO: It looks like FailedCandidates does not serve much purpose
  9149. // here, since the no_viable diagnostic has index 0.
  9150. UnresolvedSetIterator Result = S.getMostSpecialized(
  9151. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  9152. SourceExpr->getLocStart(), S.PDiag(),
  9153. S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
  9154. .second->getDeclName(),
  9155. S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
  9156. Complain, TargetFunctionType);
  9157. if (Result != MatchesCopy.end()) {
  9158. // Make it the first and only element
  9159. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  9160. Matches[0].second = cast<FunctionDecl>(*Result);
  9161. Matches.resize(1);
  9162. }
  9163. }
  9164. void EliminateAllTemplateMatches() {
  9165. // [...] any function template specializations in the set are
  9166. // eliminated if the set also contains a non-template function, [...]
  9167. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  9168. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  9169. ++I;
  9170. else {
  9171. Matches[I] = Matches[--N];
  9172. Matches.set_size(N);
  9173. }
  9174. }
  9175. }
  9176. public:
  9177. void ComplainNoMatchesFound() const {
  9178. assert(Matches.empty());
  9179. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
  9180. << OvlExpr->getName() << TargetFunctionType
  9181. << OvlExpr->getSourceRange();
  9182. if (FailedCandidates.empty())
  9183. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9184. else {
  9185. // We have some deduction failure messages. Use them to diagnose
  9186. // the function templates, and diagnose the non-template candidates
  9187. // normally.
  9188. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9189. IEnd = OvlExpr->decls_end();
  9190. I != IEnd; ++I)
  9191. if (FunctionDecl *Fun =
  9192. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  9193. S.NoteOverloadCandidate(Fun, TargetFunctionType);
  9194. FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
  9195. }
  9196. }
  9197. bool IsInvalidFormOfPointerToMemberFunction() const {
  9198. return TargetTypeIsNonStaticMemberFunction &&
  9199. !OvlExprInfo.HasFormOfMemberPointer;
  9200. }
  9201. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  9202. // TODO: Should we condition this on whether any functions might
  9203. // have matched, or is it more appropriate to do that in callers?
  9204. // TODO: a fixit wouldn't hurt.
  9205. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  9206. << TargetType << OvlExpr->getSourceRange();
  9207. }
  9208. bool IsStaticMemberFunctionFromBoundPointer() const {
  9209. return StaticMemberFunctionFromBoundPointer;
  9210. }
  9211. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  9212. S.Diag(OvlExpr->getLocStart(),
  9213. diag::err_invalid_form_pointer_member_function)
  9214. << OvlExpr->getSourceRange();
  9215. }
  9216. void ComplainOfInvalidConversion() const {
  9217. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
  9218. << OvlExpr->getName() << TargetType;
  9219. }
  9220. void ComplainMultipleMatchesFound() const {
  9221. assert(Matches.size() > 1);
  9222. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
  9223. << OvlExpr->getName()
  9224. << OvlExpr->getSourceRange();
  9225. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9226. }
  9227. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  9228. int getNumMatches() const { return Matches.size(); }
  9229. FunctionDecl* getMatchingFunctionDecl() const {
  9230. if (Matches.size() != 1) return nullptr;
  9231. return Matches[0].second;
  9232. }
  9233. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  9234. if (Matches.size() != 1) return nullptr;
  9235. return &Matches[0].first;
  9236. }
  9237. };
  9238. }
  9239. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  9240. /// an overloaded function (C++ [over.over]), where @p From is an
  9241. /// expression with overloaded function type and @p ToType is the type
  9242. /// we're trying to resolve to. For example:
  9243. ///
  9244. /// @code
  9245. /// int f(double);
  9246. /// int f(int);
  9247. ///
  9248. /// int (*pfd)(double) = f; // selects f(double)
  9249. /// @endcode
  9250. ///
  9251. /// This routine returns the resulting FunctionDecl if it could be
  9252. /// resolved, and NULL otherwise. When @p Complain is true, this
  9253. /// routine will emit diagnostics if there is an error.
  9254. FunctionDecl *
  9255. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  9256. QualType TargetType,
  9257. bool Complain,
  9258. DeclAccessPair &FoundResult,
  9259. bool *pHadMultipleCandidates) {
  9260. assert(AddressOfExpr->getType() == Context.OverloadTy);
  9261. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  9262. Complain);
  9263. int NumMatches = Resolver.getNumMatches();
  9264. FunctionDecl *Fn = nullptr;
  9265. if (NumMatches == 0 && Complain) {
  9266. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  9267. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  9268. else
  9269. Resolver.ComplainNoMatchesFound();
  9270. }
  9271. else if (NumMatches > 1 && Complain)
  9272. Resolver.ComplainMultipleMatchesFound();
  9273. else if (NumMatches == 1) {
  9274. Fn = Resolver.getMatchingFunctionDecl();
  9275. assert(Fn);
  9276. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  9277. if (Complain) {
  9278. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  9279. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  9280. else
  9281. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  9282. }
  9283. }
  9284. if (pHadMultipleCandidates)
  9285. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  9286. return Fn;
  9287. }
  9288. /// \brief Given an expression that refers to an overloaded function, try to
  9289. /// resolve that overloaded function expression down to a single function.
  9290. ///
  9291. /// This routine can only resolve template-ids that refer to a single function
  9292. /// template, where that template-id refers to a single template whose template
  9293. /// arguments are either provided by the template-id or have defaults,
  9294. /// as described in C++0x [temp.arg.explicit]p3.
  9295. ///
  9296. /// If no template-ids are found, no diagnostics are emitted and NULL is
  9297. /// returned.
  9298. FunctionDecl *
  9299. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  9300. bool Complain,
  9301. DeclAccessPair *FoundResult) {
  9302. // C++ [over.over]p1:
  9303. // [...] [Note: any redundant set of parentheses surrounding the
  9304. // overloaded function name is ignored (5.1). ]
  9305. // C++ [over.over]p1:
  9306. // [...] The overloaded function name can be preceded by the &
  9307. // operator.
  9308. // If we didn't actually find any template-ids, we're done.
  9309. if (!ovl->hasExplicitTemplateArgs())
  9310. return nullptr;
  9311. TemplateArgumentListInfo ExplicitTemplateArgs;
  9312. ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
  9313. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  9314. // Look through all of the overloaded functions, searching for one
  9315. // whose type matches exactly.
  9316. FunctionDecl *Matched = nullptr;
  9317. for (UnresolvedSetIterator I = ovl->decls_begin(),
  9318. E = ovl->decls_end(); I != E; ++I) {
  9319. // C++0x [temp.arg.explicit]p3:
  9320. // [...] In contexts where deduction is done and fails, or in contexts
  9321. // where deduction is not done, if a template argument list is
  9322. // specified and it, along with any default template arguments,
  9323. // identifies a single function template specialization, then the
  9324. // template-id is an lvalue for the function template specialization.
  9325. FunctionTemplateDecl *FunctionTemplate
  9326. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  9327. // C++ [over.over]p2:
  9328. // If the name is a function template, template argument deduction is
  9329. // done (14.8.2.2), and if the argument deduction succeeds, the
  9330. // resulting template argument list is used to generate a single
  9331. // function template specialization, which is added to the set of
  9332. // overloaded functions considered.
  9333. FunctionDecl *Specialization = nullptr;
  9334. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9335. if (TemplateDeductionResult Result
  9336. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  9337. Specialization, Info,
  9338. /*InOverloadResolution=*/true)) {
  9339. // Make a note of the failed deduction for diagnostics.
  9340. // TODO: Actually use the failed-deduction info?
  9341. FailedCandidates.addCandidate()
  9342. .set(FunctionTemplate->getTemplatedDecl(),
  9343. MakeDeductionFailureInfo(Context, Result, Info));
  9344. continue;
  9345. }
  9346. assert(Specialization && "no specialization and no error?");
  9347. // Multiple matches; we can't resolve to a single declaration.
  9348. if (Matched) {
  9349. if (Complain) {
  9350. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  9351. << ovl->getName();
  9352. NoteAllOverloadCandidates(ovl);
  9353. }
  9354. return nullptr;
  9355. }
  9356. Matched = Specialization;
  9357. if (FoundResult) *FoundResult = I.getPair();
  9358. }
  9359. if (Matched && getLangOpts().CPlusPlus14 &&
  9360. Matched->getReturnType()->isUndeducedType() &&
  9361. DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
  9362. return nullptr;
  9363. return Matched;
  9364. }
  9365. // Resolve and fix an overloaded expression that can be resolved
  9366. // because it identifies a single function template specialization.
  9367. //
  9368. // Last three arguments should only be supplied if Complain = true
  9369. //
  9370. // Return true if it was logically possible to so resolve the
  9371. // expression, regardless of whether or not it succeeded. Always
  9372. // returns true if 'complain' is set.
  9373. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  9374. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  9375. bool complain, const SourceRange& OpRangeForComplaining,
  9376. QualType DestTypeForComplaining,
  9377. unsigned DiagIDForComplaining) {
  9378. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  9379. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  9380. DeclAccessPair found;
  9381. ExprResult SingleFunctionExpression;
  9382. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  9383. ovl.Expression, /*complain*/ false, &found)) {
  9384. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
  9385. SrcExpr = ExprError();
  9386. return true;
  9387. }
  9388. // It is only correct to resolve to an instance method if we're
  9389. // resolving a form that's permitted to be a pointer to member.
  9390. // Otherwise we'll end up making a bound member expression, which
  9391. // is illegal in all the contexts we resolve like this.
  9392. if (!ovl.HasFormOfMemberPointer &&
  9393. isa<CXXMethodDecl>(fn) &&
  9394. cast<CXXMethodDecl>(fn)->isInstance()) {
  9395. if (!complain) return false;
  9396. Diag(ovl.Expression->getExprLoc(),
  9397. diag::err_bound_member_function)
  9398. << 0 << ovl.Expression->getSourceRange();
  9399. // TODO: I believe we only end up here if there's a mix of
  9400. // static and non-static candidates (otherwise the expression
  9401. // would have 'bound member' type, not 'overload' type).
  9402. // Ideally we would note which candidate was chosen and why
  9403. // the static candidates were rejected.
  9404. SrcExpr = ExprError();
  9405. return true;
  9406. }
  9407. // Fix the expression to refer to 'fn'.
  9408. SingleFunctionExpression =
  9409. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  9410. // If desired, do function-to-pointer decay.
  9411. if (doFunctionPointerConverion) {
  9412. SingleFunctionExpression =
  9413. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  9414. if (SingleFunctionExpression.isInvalid()) {
  9415. SrcExpr = ExprError();
  9416. return true;
  9417. }
  9418. }
  9419. }
  9420. if (!SingleFunctionExpression.isUsable()) {
  9421. if (complain) {
  9422. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  9423. << ovl.Expression->getName()
  9424. << DestTypeForComplaining
  9425. << OpRangeForComplaining
  9426. << ovl.Expression->getQualifierLoc().getSourceRange();
  9427. NoteAllOverloadCandidates(SrcExpr.get());
  9428. SrcExpr = ExprError();
  9429. return true;
  9430. }
  9431. return false;
  9432. }
  9433. SrcExpr = SingleFunctionExpression;
  9434. return true;
  9435. }
  9436. /// \brief Add a single candidate to the overload set.
  9437. static void AddOverloadedCallCandidate(Sema &S,
  9438. DeclAccessPair FoundDecl,
  9439. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9440. ArrayRef<Expr *> Args,
  9441. OverloadCandidateSet &CandidateSet,
  9442. bool PartialOverloading,
  9443. bool KnownValid) {
  9444. NamedDecl *Callee = FoundDecl.getDecl();
  9445. if (isa<UsingShadowDecl>(Callee))
  9446. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  9447. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  9448. if (ExplicitTemplateArgs) {
  9449. assert(!KnownValid && "Explicit template arguments?");
  9450. return;
  9451. }
  9452. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  9453. /*SuppressUsedConversions=*/false,
  9454. PartialOverloading);
  9455. return;
  9456. }
  9457. if (FunctionTemplateDecl *FuncTemplate
  9458. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  9459. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  9460. ExplicitTemplateArgs, Args, CandidateSet,
  9461. /*SuppressUsedConversions=*/false,
  9462. PartialOverloading);
  9463. return;
  9464. }
  9465. assert(!KnownValid && "unhandled case in overloaded call candidate");
  9466. }
  9467. /// \brief Add the overload candidates named by callee and/or found by argument
  9468. /// dependent lookup to the given overload set.
  9469. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  9470. ArrayRef<Expr *> Args,
  9471. OverloadCandidateSet &CandidateSet,
  9472. bool PartialOverloading) {
  9473. #ifndef NDEBUG
  9474. // Verify that ArgumentDependentLookup is consistent with the rules
  9475. // in C++0x [basic.lookup.argdep]p3:
  9476. //
  9477. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9478. // and let Y be the lookup set produced by argument dependent
  9479. // lookup (defined as follows). If X contains
  9480. //
  9481. // -- a declaration of a class member, or
  9482. //
  9483. // -- a block-scope function declaration that is not a
  9484. // using-declaration, or
  9485. //
  9486. // -- a declaration that is neither a function or a function
  9487. // template
  9488. //
  9489. // then Y is empty.
  9490. if (ULE->requiresADL()) {
  9491. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9492. E = ULE->decls_end(); I != E; ++I) {
  9493. assert(!(*I)->getDeclContext()->isRecord());
  9494. assert(isa<UsingShadowDecl>(*I) ||
  9495. !(*I)->getDeclContext()->isFunctionOrMethod());
  9496. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  9497. }
  9498. }
  9499. #endif
  9500. // HLSL Change - allow ExternalSource the ability to add the overloads for a call.
  9501. if (ExternalSource &&
  9502. ExternalSource->AddOverloadedCallCandidates(ULE, Args, CandidateSet, PartialOverloading)) {
  9503. return;
  9504. }
  9505. // It would be nice to avoid this copy.
  9506. TemplateArgumentListInfo TABuffer;
  9507. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9508. if (ULE->hasExplicitTemplateArgs()) {
  9509. ULE->copyTemplateArgumentsInto(TABuffer);
  9510. ExplicitTemplateArgs = &TABuffer;
  9511. }
  9512. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9513. E = ULE->decls_end(); I != E; ++I)
  9514. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  9515. CandidateSet, PartialOverloading,
  9516. /*KnownValid*/ true);
  9517. if (ULE->requiresADL())
  9518. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  9519. Args, ExplicitTemplateArgs,
  9520. CandidateSet, PartialOverloading);
  9521. }
  9522. /// Determine whether a declaration with the specified name could be moved into
  9523. /// a different namespace.
  9524. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  9525. switch (Name.getCXXOverloadedOperator()) {
  9526. case OO_New: case OO_Array_New:
  9527. case OO_Delete: case OO_Array_Delete:
  9528. return false;
  9529. default:
  9530. return true;
  9531. }
  9532. }
  9533. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  9534. /// template, where the non-dependent name was declared after the template
  9535. /// was defined. This is common in code written for a compilers which do not
  9536. /// correctly implement two-stage name lookup.
  9537. ///
  9538. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9539. static bool
  9540. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  9541. const CXXScopeSpec &SS, LookupResult &R,
  9542. OverloadCandidateSet::CandidateSetKind CSK,
  9543. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9544. ArrayRef<Expr *> Args,
  9545. bool *DoDiagnoseEmptyLookup = nullptr) {
  9546. if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
  9547. return false;
  9548. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  9549. if (DC->isTransparentContext())
  9550. continue;
  9551. SemaRef.LookupQualifiedName(R, DC);
  9552. if (!R.empty()) {
  9553. R.suppressDiagnostics();
  9554. if (isa<CXXRecordDecl>(DC)) {
  9555. // Don't diagnose names we find in classes; we get much better
  9556. // diagnostics for these from DiagnoseEmptyLookup.
  9557. R.clear();
  9558. if (DoDiagnoseEmptyLookup)
  9559. *DoDiagnoseEmptyLookup = true;
  9560. return false;
  9561. }
  9562. OverloadCandidateSet Candidates(FnLoc, CSK);
  9563. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  9564. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  9565. ExplicitTemplateArgs, Args,
  9566. Candidates, false, /*KnownValid*/ false);
  9567. OverloadCandidateSet::iterator Best;
  9568. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  9569. // No viable functions. Don't bother the user with notes for functions
  9570. // which don't work and shouldn't be found anyway.
  9571. R.clear();
  9572. return false;
  9573. }
  9574. // Find the namespaces where ADL would have looked, and suggest
  9575. // declaring the function there instead.
  9576. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9577. Sema::AssociatedClassSet AssociatedClasses;
  9578. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  9579. AssociatedNamespaces,
  9580. AssociatedClasses);
  9581. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  9582. if (canBeDeclaredInNamespace(R.getLookupName())) {
  9583. DeclContext *Std = SemaRef.getStdNamespace();
  9584. for (Sema::AssociatedNamespaceSet::iterator
  9585. it = AssociatedNamespaces.begin(),
  9586. end = AssociatedNamespaces.end(); it != end; ++it) {
  9587. // Never suggest declaring a function within namespace 'std'.
  9588. if (Std && Std->Encloses(*it))
  9589. continue;
  9590. // Never suggest declaring a function within a namespace with a
  9591. // reserved name, like __gnu_cxx.
  9592. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  9593. if (NS &&
  9594. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  9595. continue;
  9596. SuggestedNamespaces.insert(*it);
  9597. }
  9598. }
  9599. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  9600. << R.getLookupName();
  9601. if (SuggestedNamespaces.empty()) {
  9602. SemaRef.Diag(Best->Function->getLocation(),
  9603. diag::note_not_found_by_two_phase_lookup)
  9604. << R.getLookupName() << 0;
  9605. } else if (SuggestedNamespaces.size() == 1) {
  9606. SemaRef.Diag(Best->Function->getLocation(),
  9607. diag::note_not_found_by_two_phase_lookup)
  9608. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  9609. } else {
  9610. // FIXME: It would be useful to list the associated namespaces here,
  9611. // but the diagnostics infrastructure doesn't provide a way to produce
  9612. // a localized representation of a list of items.
  9613. SemaRef.Diag(Best->Function->getLocation(),
  9614. diag::note_not_found_by_two_phase_lookup)
  9615. << R.getLookupName() << 2;
  9616. }
  9617. // Try to recover by calling this function.
  9618. return true;
  9619. }
  9620. R.clear();
  9621. }
  9622. return false;
  9623. }
  9624. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  9625. /// template, where the non-dependent operator was declared after the template
  9626. /// was defined.
  9627. ///
  9628. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9629. static bool
  9630. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  9631. SourceLocation OpLoc,
  9632. ArrayRef<Expr *> Args) {
  9633. DeclarationName OpName =
  9634. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  9635. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  9636. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  9637. OverloadCandidateSet::CSK_Operator,
  9638. /*ExplicitTemplateArgs=*/nullptr, Args);
  9639. }
  9640. namespace {
  9641. class BuildRecoveryCallExprRAII {
  9642. Sema &SemaRef;
  9643. public:
  9644. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  9645. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  9646. SemaRef.IsBuildingRecoveryCallExpr = true;
  9647. }
  9648. ~BuildRecoveryCallExprRAII() {
  9649. SemaRef.IsBuildingRecoveryCallExpr = false;
  9650. }
  9651. };
  9652. }
  9653. static std::unique_ptr<CorrectionCandidateCallback>
  9654. MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
  9655. bool HasTemplateArgs, bool AllowTypoCorrection) {
  9656. if (!AllowTypoCorrection)
  9657. return llvm::make_unique<NoTypoCorrectionCCC>();
  9658. return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
  9659. HasTemplateArgs, ME);
  9660. }
  9661. /// Attempts to recover from a call where no functions were found.
  9662. ///
  9663. /// Returns true if new candidates were found.
  9664. static ExprResult
  9665. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9666. UnresolvedLookupExpr *ULE,
  9667. SourceLocation LParenLoc,
  9668. MutableArrayRef<Expr *> Args,
  9669. SourceLocation RParenLoc,
  9670. bool EmptyLookup, bool AllowTypoCorrection) {
  9671. // Do not try to recover if it is already building a recovery call.
  9672. // This stops infinite loops for template instantiations like
  9673. //
  9674. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  9675. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  9676. //
  9677. if (SemaRef.IsBuildingRecoveryCallExpr)
  9678. return ExprError();
  9679. BuildRecoveryCallExprRAII RCE(SemaRef);
  9680. CXXScopeSpec SS;
  9681. SS.Adopt(ULE->getQualifierLoc());
  9682. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  9683. TemplateArgumentListInfo TABuffer;
  9684. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9685. if (ULE->hasExplicitTemplateArgs()) {
  9686. ULE->copyTemplateArgumentsInto(TABuffer);
  9687. ExplicitTemplateArgs = &TABuffer;
  9688. }
  9689. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  9690. Sema::LookupOrdinaryName);
  9691. bool DoDiagnoseEmptyLookup = EmptyLookup;
  9692. if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
  9693. OverloadCandidateSet::CSK_Normal,
  9694. ExplicitTemplateArgs, Args,
  9695. &DoDiagnoseEmptyLookup) &&
  9696. (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
  9697. S, SS, R,
  9698. MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
  9699. ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
  9700. ExplicitTemplateArgs, Args)))
  9701. return ExprError();
  9702. assert(!R.empty() && "lookup results empty despite recovery");
  9703. // Build an implicit member call if appropriate. Just drop the
  9704. // casts and such from the call, we don't really care.
  9705. ExprResult NewFn = ExprError();
  9706. if ((*R.begin())->isCXXClassMember())
  9707. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  9708. R, ExplicitTemplateArgs);
  9709. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  9710. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  9711. ExplicitTemplateArgs);
  9712. else
  9713. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  9714. if (NewFn.isInvalid())
  9715. return ExprError();
  9716. // This shouldn't cause an infinite loop because we're giving it
  9717. // an expression with viable lookup results, which should never
  9718. // end up here.
  9719. return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  9720. MultiExprArg(Args.data(), Args.size()),
  9721. RParenLoc);
  9722. }
  9723. /// \brief Constructs and populates an OverloadedCandidateSet from
  9724. /// the given function.
  9725. /// \returns true when an the ExprResult output parameter has been set.
  9726. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  9727. UnresolvedLookupExpr *ULE,
  9728. MultiExprArg Args,
  9729. SourceLocation RParenLoc,
  9730. OverloadCandidateSet *CandidateSet,
  9731. ExprResult *Result) {
  9732. #ifndef NDEBUG
  9733. if (ULE->requiresADL()) {
  9734. // To do ADL, we must have found an unqualified name.
  9735. assert(!ULE->getQualifier() && "qualified name with ADL");
  9736. // We don't perform ADL for implicit declarations of builtins.
  9737. // Verify that this was correctly set up.
  9738. FunctionDecl *F;
  9739. if (ULE->decls_begin() + 1 == ULE->decls_end() &&
  9740. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  9741. F->getBuiltinID() && F->isImplicit())
  9742. llvm_unreachable("performing ADL for builtin");
  9743. // We don't perform ADL in C.
  9744. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  9745. }
  9746. #endif
  9747. UnbridgedCastsSet UnbridgedCasts;
  9748. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  9749. *Result = ExprError();
  9750. return true;
  9751. }
  9752. // Add the functions denoted by the callee to the set of candidate
  9753. // functions, including those from argument-dependent lookup.
  9754. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  9755. if (getLangOpts().MSVCCompat &&
  9756. CurContext->isDependentContext() && !isSFINAEContext() &&
  9757. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  9758. OverloadCandidateSet::iterator Best;
  9759. if (CandidateSet->empty() ||
  9760. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
  9761. OR_No_Viable_Function) {
  9762. // In Microsoft mode, if we are inside a template class member function then
  9763. // create a type dependent CallExpr. The goal is to postpone name lookup
  9764. // to instantiation time to be able to search into type dependent base
  9765. // classes.
  9766. CallExpr *CE = new (Context) CallExpr(
  9767. Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
  9768. CE->setTypeDependent(true);
  9769. *Result = CE;
  9770. return true;
  9771. }
  9772. }
  9773. if (CandidateSet->empty())
  9774. return false;
  9775. UnbridgedCasts.restore();
  9776. return false;
  9777. }
  9778. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  9779. /// the completed call expression. If overload resolution fails, emits
  9780. /// diagnostics and returns ExprError()
  9781. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9782. UnresolvedLookupExpr *ULE,
  9783. SourceLocation LParenLoc,
  9784. MultiExprArg Args,
  9785. SourceLocation RParenLoc,
  9786. Expr *ExecConfig,
  9787. OverloadCandidateSet *CandidateSet,
  9788. OverloadCandidateSet::iterator *Best,
  9789. OverloadingResult OverloadResult,
  9790. bool AllowTypoCorrection) {
  9791. if (CandidateSet->empty())
  9792. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  9793. RParenLoc, /*EmptyLookup=*/true,
  9794. AllowTypoCorrection);
  9795. switch (OverloadResult) {
  9796. case OR_Success: {
  9797. FunctionDecl *FDecl = (*Best)->Function;
  9798. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  9799. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  9800. return ExprError();
  9801. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9802. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9803. ExecConfig);
  9804. }
  9805. case OR_No_Viable_Function: {
  9806. // Try to recover by looking for viable functions which the user might
  9807. // have meant to call.
  9808. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  9809. Args, RParenLoc,
  9810. /*EmptyLookup=*/false,
  9811. AllowTypoCorrection);
  9812. if (!Recovery.isInvalid())
  9813. return Recovery;
  9814. SemaRef.Diag(Fn->getLocStart(),
  9815. diag::err_ovl_no_viable_function_in_call)
  9816. << ULE->getName() << Fn->getSourceRange();
  9817. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9818. break;
  9819. }
  9820. case OR_Ambiguous:
  9821. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
  9822. << ULE->getName() << Fn->getSourceRange();
  9823. CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
  9824. break;
  9825. case OR_Deleted: {
  9826. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
  9827. << (*Best)->Function->isDeleted()
  9828. << ULE->getName()
  9829. << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
  9830. << Fn->getSourceRange();
  9831. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9832. // We emitted an error for the unvailable/deleted function call but keep
  9833. // the call in the AST.
  9834. FunctionDecl *FDecl = (*Best)->Function;
  9835. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9836. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9837. ExecConfig);
  9838. }
  9839. }
  9840. // Overload resolution failed.
  9841. return ExprError();
  9842. }
  9843. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  9844. /// (which eventually refers to the declaration Func) and the call
  9845. /// arguments Args/NumArgs, attempt to resolve the function call down
  9846. /// to a specific function. If overload resolution succeeds, returns
  9847. /// the call expression produced by overload resolution.
  9848. /// Otherwise, emits diagnostics and returns ExprError.
  9849. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  9850. UnresolvedLookupExpr *ULE,
  9851. SourceLocation LParenLoc,
  9852. MultiExprArg Args,
  9853. SourceLocation RParenLoc,
  9854. Expr *ExecConfig,
  9855. bool AllowTypoCorrection) {
  9856. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  9857. OverloadCandidateSet::CSK_Normal);
  9858. ExprResult result;
  9859. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  9860. &result))
  9861. return result;
  9862. OverloadCandidateSet::iterator Best;
  9863. OverloadingResult OverloadResult =
  9864. CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
  9865. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
  9866. RParenLoc, ExecConfig, &CandidateSet,
  9867. &Best, OverloadResult,
  9868. AllowTypoCorrection);
  9869. }
  9870. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  9871. return Functions.size() > 1 ||
  9872. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  9873. }
  9874. /// \brief Create a unary operation that may resolve to an overloaded
  9875. /// operator.
  9876. ///
  9877. /// \param OpLoc The location of the operator itself (e.g., '*').
  9878. ///
  9879. /// \param OpcIn The UnaryOperator::Opcode that describes this
  9880. /// operator.
  9881. ///
  9882. /// \param Fns The set of non-member functions that will be
  9883. /// considered by overload resolution. The caller needs to build this
  9884. /// set based on the context using, e.g.,
  9885. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  9886. /// set should not contain any member functions; those will be added
  9887. /// by CreateOverloadedUnaryOp().
  9888. ///
  9889. /// \param Input The input argument.
  9890. ExprResult
  9891. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
  9892. const UnresolvedSetImpl &Fns,
  9893. Expr *Input) {
  9894. UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
  9895. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  9896. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  9897. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  9898. // TODO: provide better source location info.
  9899. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  9900. if (checkPlaceholderForOverload(*this, Input))
  9901. return ExprError();
  9902. Expr *Args[2] = { Input, nullptr };
  9903. unsigned NumArgs = 1;
  9904. // For post-increment and post-decrement, add the implicit '0' as
  9905. // the second argument, so that we know this is a post-increment or
  9906. // post-decrement.
  9907. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  9908. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  9909. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  9910. SourceLocation());
  9911. NumArgs = 2;
  9912. }
  9913. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  9914. if (Input->isTypeDependent()) {
  9915. if (Fns.empty())
  9916. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  9917. VK_RValue, OK_Ordinary, OpLoc);
  9918. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  9919. UnresolvedLookupExpr *Fn
  9920. = UnresolvedLookupExpr::Create(Context, NamingClass,
  9921. NestedNameSpecifierLoc(), OpNameInfo,
  9922. /*ADL*/ true, IsOverloaded(Fns),
  9923. Fns.begin(), Fns.end());
  9924. return new (Context)
  9925. CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
  9926. VK_RValue, OpLoc, false);
  9927. }
  9928. // Build an empty overload set.
  9929. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  9930. // Add the candidates from the given function set.
  9931. AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
  9932. // Add operator candidates that are member functions.
  9933. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9934. // Add candidates from ADL.
  9935. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  9936. /*ExplicitTemplateArgs*/nullptr,
  9937. CandidateSet);
  9938. // Add builtin operator candidates.
  9939. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9940. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9941. // Perform overload resolution.
  9942. OverloadCandidateSet::iterator Best;
  9943. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  9944. case OR_Success: {
  9945. // We found a built-in operator or an overloaded operator.
  9946. FunctionDecl *FnDecl = Best->Function;
  9947. if (FnDecl) {
  9948. // We matched an overloaded operator. Build a call to that
  9949. // operator.
  9950. // Convert the arguments.
  9951. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  9952. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  9953. ExprResult InputRes =
  9954. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  9955. Best->FoundDecl, Method);
  9956. if (InputRes.isInvalid())
  9957. return ExprError();
  9958. Input = InputRes.get();
  9959. } else {
  9960. // Convert the arguments.
  9961. ExprResult InputInit
  9962. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  9963. Context,
  9964. FnDecl->getParamDecl(0)),
  9965. SourceLocation(),
  9966. Input);
  9967. if (InputInit.isInvalid())
  9968. return ExprError();
  9969. Input = InputInit.get();
  9970. }
  9971. // Build the actual expression node.
  9972. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  9973. HadMultipleCandidates, OpLoc);
  9974. if (FnExpr.isInvalid())
  9975. return ExprError();
  9976. // Determine the result type.
  9977. QualType ResultTy = FnDecl->getReturnType();
  9978. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9979. ResultTy = ResultTy.getNonLValueExprType(Context);
  9980. Args[0] = Input;
  9981. CallExpr *TheCall =
  9982. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
  9983. ResultTy, VK, OpLoc, false);
  9984. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  9985. return ExprError();
  9986. return MaybeBindToTemporary(TheCall);
  9987. } else {
  9988. // We matched a built-in operator. Convert the arguments, then
  9989. // break out so that we will build the appropriate built-in
  9990. // operator node.
  9991. ExprResult InputRes =
  9992. PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
  9993. Best->Conversions[0], AA_Passing);
  9994. if (InputRes.isInvalid())
  9995. return ExprError();
  9996. Input = InputRes.get();
  9997. break;
  9998. }
  9999. }
  10000. case OR_No_Viable_Function:
  10001. // This is an erroneous use of an operator which can be overloaded by
  10002. // a non-member function. Check for non-member operators which were
  10003. // defined too late to be candidates.
  10004. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  10005. // FIXME: Recover by calling the found function.
  10006. return ExprError();
  10007. // No viable function; fall through to handling this as a
  10008. // built-in operator, which will produce an error message for us.
  10009. break;
  10010. case OR_Ambiguous:
  10011. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10012. << UnaryOperator::getOpcodeStr(Opc)
  10013. << Input->getType()
  10014. << Input->getSourceRange();
  10015. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
  10016. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10017. return ExprError();
  10018. case OR_Deleted:
  10019. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10020. << Best->Function->isDeleted()
  10021. << UnaryOperator::getOpcodeStr(Opc)
  10022. << getDeletedOrUnavailableSuffix(Best->Function)
  10023. << Input->getSourceRange();
  10024. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
  10025. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10026. return ExprError();
  10027. }
  10028. // Either we found no viable overloaded operator or we matched a
  10029. // built-in operator. In either case, fall through to trying to
  10030. // build a built-in operation.
  10031. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10032. }
  10033. /// \brief Create a binary operation that may resolve to an overloaded
  10034. /// operator.
  10035. ///
  10036. /// \param OpLoc The location of the operator itself (e.g., '+').
  10037. ///
  10038. /// \param OpcIn The BinaryOperator::Opcode that describes this
  10039. /// operator.
  10040. ///
  10041. /// \param Fns The set of non-member functions that will be
  10042. /// considered by overload resolution. The caller needs to build this
  10043. /// set based on the context using, e.g.,
  10044. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  10045. /// set should not contain any member functions; those will be added
  10046. /// by CreateOverloadedBinOp().
  10047. ///
  10048. /// \param LHS Left-hand argument.
  10049. /// \param RHS Right-hand argument.
  10050. ExprResult
  10051. Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  10052. unsigned OpcIn,
  10053. const UnresolvedSetImpl &Fns,
  10054. Expr *LHS, Expr *RHS) {
  10055. Expr *Args[2] = { LHS, RHS };
  10056. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  10057. BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
  10058. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  10059. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  10060. // If either side is type-dependent, create an appropriate dependent
  10061. // expression.
  10062. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10063. if (Fns.empty()) {
  10064. // If there are no functions to store, just build a dependent
  10065. // BinaryOperator or CompoundAssignment.
  10066. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  10067. return new (Context) BinaryOperator(
  10068. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  10069. OpLoc, FPFeatures.fp_contract);
  10070. return new (Context) CompoundAssignOperator(
  10071. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  10072. Context.DependentTy, Context.DependentTy, OpLoc,
  10073. FPFeatures.fp_contract);
  10074. }
  10075. // FIXME: save results of ADL from here?
  10076. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10077. // TODO: provide better source location info in DNLoc component.
  10078. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  10079. UnresolvedLookupExpr *Fn
  10080. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10081. NestedNameSpecifierLoc(), OpNameInfo,
  10082. /*ADL*/ true, IsOverloaded(Fns),
  10083. Fns.begin(), Fns.end());
  10084. return new (Context)
  10085. CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
  10086. VK_RValue, OpLoc, FPFeatures.fp_contract);
  10087. }
  10088. // Always do placeholder-like conversions on the RHS.
  10089. if (checkPlaceholderForOverload(*this, Args[1]))
  10090. return ExprError();
  10091. // Do placeholder-like conversion on the LHS; note that we should
  10092. // not get here with a PseudoObject LHS.
  10093. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  10094. if (checkPlaceholderForOverload(*this, Args[0]))
  10095. return ExprError();
  10096. // If this is the assignment operator, we only perform overload resolution
  10097. // if the left-hand side is a class or enumeration type. This is actually
  10098. // a hack. The standard requires that we do overload resolution between the
  10099. // various built-in candidates, but as DR507 points out, this can lead to
  10100. // problems. So we do it this way, which pretty much follows what GCC does.
  10101. // Note that we go the traditional code path for compound assignment forms.
  10102. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  10103. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10104. // If this is the .* operator, which is not overloadable, just
  10105. // create a built-in binary operator.
  10106. if (Opc == BO_PtrMemD)
  10107. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10108. // Build an empty overload set.
  10109. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  10110. // Add the candidates from the given function set.
  10111. AddFunctionCandidates(Fns, Args, CandidateSet);
  10112. // Add operator candidates that are member functions.
  10113. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10114. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  10115. // performed for an assignment operator (nor for operator[] nor operator->,
  10116. // which don't get here).
  10117. if (Opc != BO_Assign)
  10118. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  10119. /*ExplicitTemplateArgs*/ nullptr,
  10120. CandidateSet);
  10121. // Add builtin operator candidates.
  10122. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10123. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10124. // Perform overload resolution.
  10125. OverloadCandidateSet::iterator Best;
  10126. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10127. case OR_Success: {
  10128. // We found a built-in operator or an overloaded operator.
  10129. FunctionDecl *FnDecl = Best->Function;
  10130. if (FnDecl) {
  10131. // We matched an overloaded operator. Build a call to that
  10132. // operator.
  10133. // Convert the arguments.
  10134. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  10135. // Best->Access is only meaningful for class members.
  10136. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  10137. ExprResult Arg1 =
  10138. PerformCopyInitialization(
  10139. InitializedEntity::InitializeParameter(Context,
  10140. FnDecl->getParamDecl(0)),
  10141. SourceLocation(), Args[1]);
  10142. if (Arg1.isInvalid())
  10143. return ExprError();
  10144. ExprResult Arg0 =
  10145. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10146. Best->FoundDecl, Method);
  10147. if (Arg0.isInvalid())
  10148. return ExprError();
  10149. Args[0] = Arg0.getAs<Expr>();
  10150. Args[1] = RHS = Arg1.getAs<Expr>();
  10151. } else {
  10152. // Convert the arguments.
  10153. ExprResult Arg0 = PerformCopyInitialization(
  10154. InitializedEntity::InitializeParameter(Context,
  10155. FnDecl->getParamDecl(0)),
  10156. SourceLocation(), Args[0]);
  10157. if (Arg0.isInvalid())
  10158. return ExprError();
  10159. ExprResult Arg1 =
  10160. PerformCopyInitialization(
  10161. InitializedEntity::InitializeParameter(Context,
  10162. FnDecl->getParamDecl(1)),
  10163. SourceLocation(), Args[1]);
  10164. if (Arg1.isInvalid())
  10165. return ExprError();
  10166. Args[0] = LHS = Arg0.getAs<Expr>();
  10167. Args[1] = RHS = Arg1.getAs<Expr>();
  10168. }
  10169. // Build the actual expression node.
  10170. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10171. Best->FoundDecl,
  10172. HadMultipleCandidates, OpLoc);
  10173. if (FnExpr.isInvalid())
  10174. return ExprError();
  10175. // Determine the result type.
  10176. QualType ResultTy = FnDecl->getReturnType();
  10177. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10178. ResultTy = ResultTy.getNonLValueExprType(Context);
  10179. CXXOperatorCallExpr *TheCall =
  10180. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
  10181. Args, ResultTy, VK, OpLoc,
  10182. FPFeatures.fp_contract);
  10183. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  10184. FnDecl))
  10185. return ExprError();
  10186. ArrayRef<const Expr *> ArgsArray(Args, 2);
  10187. // Cut off the implicit 'this'.
  10188. if (isa<CXXMethodDecl>(FnDecl))
  10189. ArgsArray = ArgsArray.slice(1);
  10190. // Check for a self move.
  10191. if (Op == OO_Equal)
  10192. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  10193. checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
  10194. TheCall->getSourceRange(), VariadicDoesNotApply);
  10195. return MaybeBindToTemporary(TheCall);
  10196. } else {
  10197. // We matched a built-in operator. Convert the arguments, then
  10198. // break out so that we will build the appropriate built-in
  10199. // operator node.
  10200. ExprResult ArgsRes0 =
  10201. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10202. Best->Conversions[0], AA_Passing);
  10203. if (ArgsRes0.isInvalid())
  10204. return ExprError();
  10205. Args[0] = ArgsRes0.get();
  10206. ExprResult ArgsRes1 =
  10207. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10208. Best->Conversions[1], AA_Passing);
  10209. if (ArgsRes1.isInvalid())
  10210. return ExprError();
  10211. Args[1] = ArgsRes1.get();
  10212. break;
  10213. }
  10214. }
  10215. case OR_No_Viable_Function: {
  10216. // C++ [over.match.oper]p9:
  10217. // If the operator is the operator , [...] and there are no
  10218. // viable functions, then the operator is assumed to be the
  10219. // built-in operator and interpreted according to clause 5.
  10220. if (Opc == BO_Comma)
  10221. break;
  10222. // For class as left operand for assignment or compound assigment
  10223. // operator do not fall through to handling in built-in, but report that
  10224. // no overloaded assignment operator found
  10225. ExprResult Result = ExprError();
  10226. if (Args[0]->getType()->isRecordType() &&
  10227. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  10228. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10229. << BinaryOperator::getOpcodeStr(Opc)
  10230. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10231. if (Args[0]->getType()->isIncompleteType()) {
  10232. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  10233. << Args[0]->getType()
  10234. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10235. }
  10236. } else {
  10237. // This is an erroneous use of an operator which can be overloaded by
  10238. // a non-member function. Check for non-member operators which were
  10239. // defined too late to be candidates.
  10240. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  10241. // FIXME: Recover by calling the found function.
  10242. return ExprError();
  10243. // No viable function; try to create a built-in operation, which will
  10244. // produce an error. Then, show the non-viable candidates.
  10245. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10246. }
  10247. assert(Result.isInvalid() &&
  10248. "C++ binary operator overloading is missing candidates!");
  10249. if (Result.isInvalid())
  10250. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10251. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10252. return Result;
  10253. }
  10254. case OR_Ambiguous:
  10255. Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
  10256. << BinaryOperator::getOpcodeStr(Opc)
  10257. << Args[0]->getType() << Args[1]->getType()
  10258. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10259. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10260. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10261. return ExprError();
  10262. case OR_Deleted:
  10263. if (isImplicitlyDeleted(Best->Function)) {
  10264. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10265. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  10266. << Context.getRecordType(Method->getParent())
  10267. << getSpecialMember(Method);
  10268. // The user probably meant to call this special member. Just
  10269. // explain why it's deleted.
  10270. NoteDeletedFunction(Method);
  10271. return ExprError();
  10272. } else {
  10273. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10274. << Best->Function->isDeleted()
  10275. << BinaryOperator::getOpcodeStr(Opc)
  10276. << getDeletedOrUnavailableSuffix(Best->Function)
  10277. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10278. }
  10279. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10280. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10281. return ExprError();
  10282. }
  10283. // We matched a built-in operator; build it.
  10284. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10285. }
  10286. ExprResult
  10287. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  10288. SourceLocation RLoc,
  10289. Expr *Base, Expr *Idx) {
  10290. Expr *Args[2] = { Base, Idx };
  10291. DeclarationName OpName =
  10292. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  10293. // If either side is type-dependent, create an appropriate dependent
  10294. // expression.
  10295. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10296. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10297. // CHECKME: no 'operator' keyword?
  10298. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  10299. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10300. UnresolvedLookupExpr *Fn
  10301. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10302. NestedNameSpecifierLoc(), OpNameInfo,
  10303. /*ADL*/ true, /*Overloaded*/ false,
  10304. UnresolvedSetIterator(),
  10305. UnresolvedSetIterator());
  10306. // Can't add any actual overloads yet
  10307. return new (Context)
  10308. CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
  10309. Context.DependentTy, VK_RValue, RLoc, false);
  10310. }
  10311. // Handle placeholders on both operands.
  10312. if (checkPlaceholderForOverload(*this, Args[0]))
  10313. return ExprError();
  10314. if (checkPlaceholderForOverload(*this, Args[1]))
  10315. return ExprError();
  10316. // Build an empty overload set.
  10317. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  10318. // Subscript can only be overloaded as a member function.
  10319. // Add operator candidates that are member functions.
  10320. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10321. // Add builtin operator candidates.
  10322. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10323. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10324. // Perform overload resolution.
  10325. OverloadCandidateSet::iterator Best;
  10326. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  10327. case OR_Success: {
  10328. // We found a built-in operator or an overloaded operator.
  10329. FunctionDecl *FnDecl = Best->Function;
  10330. if (FnDecl) {
  10331. // We matched an overloaded operator. Build a call to that
  10332. // operator.
  10333. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  10334. // Convert the arguments.
  10335. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  10336. ExprResult Arg0 =
  10337. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10338. Best->FoundDecl, Method);
  10339. if (Arg0.isInvalid())
  10340. return ExprError();
  10341. Args[0] = Arg0.get();
  10342. // Convert the arguments.
  10343. ExprResult InputInit
  10344. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10345. Context,
  10346. FnDecl->getParamDecl(0)),
  10347. SourceLocation(),
  10348. Args[1]);
  10349. if (InputInit.isInvalid())
  10350. return ExprError();
  10351. Args[1] = InputInit.getAs<Expr>();
  10352. // Build the actual expression node.
  10353. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  10354. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10355. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10356. Best->FoundDecl,
  10357. HadMultipleCandidates,
  10358. OpLocInfo.getLoc(),
  10359. OpLocInfo.getInfo());
  10360. if (FnExpr.isInvalid())
  10361. return ExprError();
  10362. // Determine the result type
  10363. QualType ResultTy = FnDecl->getReturnType();
  10364. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10365. ResultTy = ResultTy.getNonLValueExprType(Context);
  10366. CXXOperatorCallExpr *TheCall =
  10367. new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
  10368. FnExpr.get(), Args,
  10369. ResultTy, VK, RLoc,
  10370. false);
  10371. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  10372. return ExprError();
  10373. return MaybeBindToTemporary(TheCall);
  10374. } else {
  10375. // We matched a built-in operator. Convert the arguments, then
  10376. // break out so that we will build the appropriate built-in
  10377. // operator node.
  10378. ExprResult ArgsRes0 =
  10379. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10380. Best->Conversions[0], AA_Passing);
  10381. if (ArgsRes0.isInvalid())
  10382. return ExprError();
  10383. Args[0] = ArgsRes0.get();
  10384. ExprResult ArgsRes1 =
  10385. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10386. Best->Conversions[1], AA_Passing);
  10387. if (ArgsRes1.isInvalid())
  10388. return ExprError();
  10389. Args[1] = ArgsRes1.get();
  10390. break;
  10391. }
  10392. }
  10393. case OR_No_Viable_Function: {
  10394. if (CandidateSet.empty())
  10395. Diag(LLoc, diag::err_ovl_no_oper)
  10396. << Args[0]->getType() << /*subscript*/ 0
  10397. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10398. else
  10399. Diag(LLoc, diag::err_ovl_no_viable_subscript)
  10400. << Args[0]->getType()
  10401. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10402. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10403. "[]", LLoc);
  10404. return ExprError();
  10405. }
  10406. case OR_Ambiguous:
  10407. Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
  10408. << "[]"
  10409. << Args[0]->getType() << Args[1]->getType()
  10410. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10411. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10412. "[]", LLoc);
  10413. return ExprError();
  10414. case OR_Deleted:
  10415. Diag(LLoc, diag::err_ovl_deleted_oper)
  10416. << Best->Function->isDeleted() << "[]"
  10417. << getDeletedOrUnavailableSuffix(Best->Function)
  10418. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10419. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10420. "[]", LLoc);
  10421. return ExprError();
  10422. }
  10423. // We matched a built-in operator; build it.
  10424. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  10425. }
  10426. /// BuildCallToMemberFunction - Build a call to a member
  10427. /// function. MemExpr is the expression that refers to the member
  10428. /// function (and includes the object parameter), Args/NumArgs are the
  10429. /// arguments to the function call (not including the object
  10430. /// parameter). The caller needs to validate that the member
  10431. /// expression refers to a non-static member function or an overloaded
  10432. /// member function.
  10433. ExprResult
  10434. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  10435. SourceLocation LParenLoc,
  10436. MultiExprArg Args,
  10437. SourceLocation RParenLoc) {
  10438. assert(MemExprE->getType() == Context.BoundMemberTy ||
  10439. MemExprE->getType() == Context.OverloadTy);
  10440. // Dig out the member expression. This holds both the object
  10441. // argument and the member function we're referring to.
  10442. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  10443. // Determine whether this is a call to a pointer-to-member function.
  10444. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  10445. assert(op->getType() == Context.BoundMemberTy);
  10446. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  10447. QualType fnType =
  10448. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  10449. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  10450. QualType resultType = proto->getCallResultType(Context);
  10451. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  10452. // Check that the object type isn't more qualified than the
  10453. // member function we're calling.
  10454. Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
  10455. QualType objectType = op->getLHS()->getType();
  10456. if (op->getOpcode() == BO_PtrMemI)
  10457. objectType = objectType->castAs<PointerType>()->getPointeeType();
  10458. Qualifiers objectQuals = objectType.getQualifiers();
  10459. Qualifiers difference = objectQuals - funcQuals;
  10460. difference.removeObjCGCAttr();
  10461. difference.removeAddressSpace();
  10462. if (difference) {
  10463. std::string qualsString = difference.getAsString();
  10464. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  10465. << fnType.getUnqualifiedType()
  10466. << qualsString
  10467. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  10468. }
  10469. if (resultType->isMemberPointerType())
  10470. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10471. RequireCompleteType(LParenLoc, resultType, 0);
  10472. CXXMemberCallExpr *call
  10473. = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10474. resultType, valueKind, RParenLoc);
  10475. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
  10476. call, nullptr))
  10477. return ExprError();
  10478. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  10479. return ExprError();
  10480. if (CheckOtherCall(call, proto))
  10481. return ExprError();
  10482. return MaybeBindToTemporary(call);
  10483. }
  10484. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  10485. return new (Context)
  10486. CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
  10487. UnbridgedCastsSet UnbridgedCasts;
  10488. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10489. return ExprError();
  10490. MemberExpr *MemExpr;
  10491. CXXMethodDecl *Method = nullptr;
  10492. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  10493. NestedNameSpecifier *Qualifier = nullptr;
  10494. if (isa<MemberExpr>(NakedMemExpr)) {
  10495. MemExpr = cast<MemberExpr>(NakedMemExpr);
  10496. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  10497. FoundDecl = MemExpr->getFoundDecl();
  10498. Qualifier = MemExpr->getQualifier();
  10499. UnbridgedCasts.restore();
  10500. } else {
  10501. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  10502. Qualifier = UnresExpr->getQualifier();
  10503. QualType ObjectType = UnresExpr->getBaseType();
  10504. Expr::Classification ObjectClassification
  10505. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  10506. : UnresExpr->getBase()->Classify(Context);
  10507. // Add overload candidates
  10508. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  10509. OverloadCandidateSet::CSK_Normal);
  10510. // FIXME: avoid copy.
  10511. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  10512. if (UnresExpr->hasExplicitTemplateArgs()) {
  10513. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  10514. TemplateArgs = &TemplateArgsBuffer;
  10515. }
  10516. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  10517. E = UnresExpr->decls_end(); I != E; ++I) {
  10518. NamedDecl *Func = *I;
  10519. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  10520. if (isa<UsingShadowDecl>(Func))
  10521. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  10522. // Microsoft supports direct constructor calls.
  10523. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  10524. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
  10525. Args, CandidateSet);
  10526. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  10527. // If explicit template arguments were provided, we can't call a
  10528. // non-template member function.
  10529. if (TemplateArgs)
  10530. continue;
  10531. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  10532. ObjectClassification, Args, CandidateSet,
  10533. /*SuppressUserConversions=*/false);
  10534. } else {
  10535. AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
  10536. I.getPair(), ActingDC, TemplateArgs,
  10537. ObjectType, ObjectClassification,
  10538. Args, CandidateSet,
  10539. /*SuppressUsedConversions=*/false);
  10540. }
  10541. }
  10542. DeclarationName DeclName = UnresExpr->getMemberName();
  10543. UnbridgedCasts.restore();
  10544. OverloadCandidateSet::iterator Best;
  10545. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
  10546. Best)) {
  10547. case OR_Success:
  10548. Method = cast<CXXMethodDecl>(Best->Function);
  10549. FoundDecl = Best->FoundDecl;
  10550. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  10551. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  10552. return ExprError();
  10553. // If FoundDecl is different from Method (such as if one is a template
  10554. // and the other a specialization), make sure DiagnoseUseOfDecl is
  10555. // called on both.
  10556. // FIXME: This would be more comprehensively addressed by modifying
  10557. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  10558. // being used.
  10559. if (Method != FoundDecl.getDecl() &&
  10560. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  10561. return ExprError();
  10562. break;
  10563. case OR_No_Viable_Function:
  10564. Diag(UnresExpr->getMemberLoc(),
  10565. diag::err_ovl_no_viable_member_function_in_call)
  10566. << DeclName << MemExprE->getSourceRange();
  10567. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, StringRef(), UnresExpr->getMemberLoc()); // HLSL Change - add member loc
  10568. // FIXME: Leaking incoming expressions!
  10569. return ExprError();
  10570. case OR_Ambiguous:
  10571. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
  10572. << DeclName << MemExprE->getSourceRange();
  10573. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10574. // FIXME: Leaking incoming expressions!
  10575. return ExprError();
  10576. case OR_Deleted:
  10577. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
  10578. << Best->Function->isDeleted()
  10579. << DeclName
  10580. << getDeletedOrUnavailableSuffix(Best->Function)
  10581. << MemExprE->getSourceRange();
  10582. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10583. // FIXME: Leaking incoming expressions!
  10584. return ExprError();
  10585. }
  10586. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  10587. // If overload resolution picked a static member, build a
  10588. // non-member call based on that function.
  10589. if (Method->isStatic()) {
  10590. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  10591. RParenLoc);
  10592. }
  10593. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  10594. }
  10595. QualType ResultType = Method->getReturnType();
  10596. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  10597. ResultType = ResultType.getNonLValueExprType(Context);
  10598. assert(Method && "Member call to something that isn't a method?");
  10599. CXXMemberCallExpr *TheCall =
  10600. new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10601. ResultType, VK, RParenLoc);
  10602. // (CUDA B.1): Check for invalid calls between targets.
  10603. if (getLangOpts().CUDA) {
  10604. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
  10605. if (CheckCUDATarget(Caller, Method)) {
  10606. Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
  10607. << IdentifyCUDATarget(Method) << Method->getIdentifier()
  10608. << IdentifyCUDATarget(Caller);
  10609. return ExprError();
  10610. }
  10611. }
  10612. }
  10613. // Check for a valid return type.
  10614. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  10615. TheCall, Method))
  10616. return ExprError();
  10617. // Convert the object argument (for a non-static member function call).
  10618. // We only need to do this if there was actually an overload; otherwise
  10619. // it was done at lookup.
  10620. if (!Method->isStatic()) {
  10621. ExprResult ObjectArg =
  10622. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  10623. FoundDecl, Method);
  10624. if (ObjectArg.isInvalid())
  10625. return ExprError();
  10626. MemExpr->setBase(ObjectArg.get());
  10627. }
  10628. // Convert the rest of the arguments
  10629. const FunctionProtoType *Proto =
  10630. Method->getType()->getAs<FunctionProtoType>();
  10631. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  10632. RParenLoc))
  10633. return ExprError();
  10634. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10635. if (CheckFunctionCall(Method, TheCall, Proto))
  10636. return ExprError();
  10637. if ((isa<CXXConstructorDecl>(CurContext) ||
  10638. isa<CXXDestructorDecl>(CurContext)) &&
  10639. TheCall->getMethodDecl()->isPure()) {
  10640. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  10641. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
  10642. Diag(MemExpr->getLocStart(),
  10643. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  10644. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  10645. << MD->getParent()->getDeclName();
  10646. Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
  10647. }
  10648. }
  10649. return MaybeBindToTemporary(TheCall);
  10650. }
  10651. /// BuildCallToObjectOfClassType - Build a call to an object of class
  10652. /// type (C++ [over.call.object]), which can end up invoking an
  10653. /// overloaded function call operator (@c operator()) or performing a
  10654. /// user-defined conversion on the object argument.
  10655. ExprResult
  10656. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  10657. SourceLocation LParenLoc,
  10658. MultiExprArg Args,
  10659. SourceLocation RParenLoc) {
  10660. if (checkPlaceholderForOverload(*this, Obj))
  10661. return ExprError();
  10662. ExprResult Object = Obj;
  10663. UnbridgedCastsSet UnbridgedCasts;
  10664. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10665. return ExprError();
  10666. assert(Object.get()->getType()->isRecordType() &&
  10667. "Requires object type argument");
  10668. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  10669. // C++ [over.call.object]p1:
  10670. // If the primary-expression E in the function call syntax
  10671. // evaluates to a class object of type "cv T", then the set of
  10672. // candidate functions includes at least the function call
  10673. // operators of T. The function call operators of T are obtained by
  10674. // ordinary lookup of the name operator() in the context of
  10675. // (E).operator().
  10676. OverloadCandidateSet CandidateSet(LParenLoc,
  10677. OverloadCandidateSet::CSK_Operator);
  10678. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  10679. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  10680. diag::err_incomplete_object_call, Object.get()))
  10681. return true;
  10682. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  10683. LookupQualifiedName(R, Record->getDecl());
  10684. R.suppressDiagnostics();
  10685. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10686. Oper != OperEnd; ++Oper) {
  10687. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  10688. Object.get()->Classify(Context),
  10689. Args, CandidateSet,
  10690. /*SuppressUserConversions=*/ false);
  10691. }
  10692. // C++ [over.call.object]p2:
  10693. // In addition, for each (non-explicit in C++0x) conversion function
  10694. // declared in T of the form
  10695. //
  10696. // operator conversion-type-id () cv-qualifier;
  10697. //
  10698. // where cv-qualifier is the same cv-qualification as, or a
  10699. // greater cv-qualification than, cv, and where conversion-type-id
  10700. // denotes the type "pointer to function of (P1,...,Pn) returning
  10701. // R", or the type "reference to pointer to function of
  10702. // (P1,...,Pn) returning R", or the type "reference to function
  10703. // of (P1,...,Pn) returning R", a surrogate call function [...]
  10704. // is also considered as a candidate function. Similarly,
  10705. // surrogate call functions are added to the set of candidate
  10706. // functions for each conversion function declared in an
  10707. // accessible base class provided the function is not hidden
  10708. // within T by another intervening declaration.
  10709. const auto &Conversions =
  10710. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  10711. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  10712. NamedDecl *D = *I;
  10713. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  10714. if (isa<UsingShadowDecl>(D))
  10715. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  10716. // Skip over templated conversion functions; they aren't
  10717. // surrogates.
  10718. if (isa<FunctionTemplateDecl>(D))
  10719. continue;
  10720. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  10721. if (!Conv->isExplicit()) {
  10722. // Strip the reference type (if any) and then the pointer type (if
  10723. // any) to get down to what might be a function type.
  10724. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  10725. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  10726. ConvType = ConvPtrType->getPointeeType();
  10727. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  10728. {
  10729. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  10730. Object.get(), Args, CandidateSet);
  10731. }
  10732. }
  10733. }
  10734. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10735. // Perform overload resolution.
  10736. OverloadCandidateSet::iterator Best;
  10737. switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
  10738. Best)) {
  10739. case OR_Success:
  10740. // Overload resolution succeeded; we'll build the appropriate call
  10741. // below.
  10742. break;
  10743. case OR_No_Viable_Function:
  10744. if (CandidateSet.empty())
  10745. Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
  10746. << Object.get()->getType() << /*call*/ 1
  10747. << Object.get()->getSourceRange();
  10748. else
  10749. Diag(Object.get()->getLocStart(),
  10750. diag::err_ovl_no_viable_object_call)
  10751. << Object.get()->getType() << Object.get()->getSourceRange();
  10752. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10753. break;
  10754. case OR_Ambiguous:
  10755. Diag(Object.get()->getLocStart(),
  10756. diag::err_ovl_ambiguous_object_call)
  10757. << Object.get()->getType() << Object.get()->getSourceRange();
  10758. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  10759. break;
  10760. case OR_Deleted:
  10761. Diag(Object.get()->getLocStart(),
  10762. diag::err_ovl_deleted_object_call)
  10763. << Best->Function->isDeleted()
  10764. << Object.get()->getType()
  10765. << getDeletedOrUnavailableSuffix(Best->Function)
  10766. << Object.get()->getSourceRange();
  10767. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10768. break;
  10769. }
  10770. if (Best == CandidateSet.end())
  10771. return true;
  10772. UnbridgedCasts.restore();
  10773. if (Best->Function == nullptr) {
  10774. // Since there is no function declaration, this is one of the
  10775. // surrogate candidates. Dig out the conversion function.
  10776. CXXConversionDecl *Conv
  10777. = cast<CXXConversionDecl>(
  10778. Best->Conversions[0].UserDefined.ConversionFunction);
  10779. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  10780. Best->FoundDecl);
  10781. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  10782. return ExprError();
  10783. assert(Conv == Best->FoundDecl.getDecl() &&
  10784. "Found Decl & conversion-to-functionptr should be same, right?!");
  10785. // We selected one of the surrogate functions that converts the
  10786. // object parameter to a function pointer. Perform the conversion
  10787. // on the object argument, then let ActOnCallExpr finish the job.
  10788. // Create an implicit member expr to refer to the conversion operator.
  10789. // and then call it.
  10790. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  10791. Conv, HadMultipleCandidates);
  10792. if (Call.isInvalid())
  10793. return ExprError();
  10794. // Record usage of conversion in an implicit cast.
  10795. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  10796. CK_UserDefinedConversion, Call.get(),
  10797. nullptr, VK_RValue);
  10798. return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  10799. }
  10800. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  10801. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  10802. // that calls this method, using Object for the implicit object
  10803. // parameter and passing along the remaining arguments.
  10804. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10805. // An error diagnostic has already been printed when parsing the declaration.
  10806. if (Method->isInvalidDecl())
  10807. return ExprError();
  10808. const FunctionProtoType *Proto =
  10809. Method->getType()->getAs<FunctionProtoType>();
  10810. unsigned NumParams = Proto->getNumParams();
  10811. DeclarationNameInfo OpLocInfo(
  10812. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  10813. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  10814. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10815. HadMultipleCandidates,
  10816. OpLocInfo.getLoc(),
  10817. OpLocInfo.getInfo());
  10818. if (NewFn.isInvalid())
  10819. return true;
  10820. // Build the full argument list for the method call (the implicit object
  10821. // parameter is placed at the beginning of the list).
  10822. std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
  10823. MethodArgs[0] = Object.get();
  10824. std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
  10825. // Once we've built TheCall, all of the expressions are properly
  10826. // owned.
  10827. QualType ResultTy = Method->getReturnType();
  10828. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10829. ResultTy = ResultTy.getNonLValueExprType(Context);
  10830. CXXOperatorCallExpr *TheCall = new (Context)
  10831. CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
  10832. llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
  10833. ResultTy, VK, RParenLoc, false);
  10834. MethodArgs.reset();
  10835. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  10836. return true;
  10837. // We may have default arguments. If so, we need to allocate more
  10838. // slots in the call for them.
  10839. if (Args.size() < NumParams)
  10840. TheCall->setNumArgs(Context, NumParams + 1);
  10841. bool IsError = false;
  10842. // Initialize the implicit object parameter.
  10843. ExprResult ObjRes =
  10844. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  10845. Best->FoundDecl, Method);
  10846. if (ObjRes.isInvalid())
  10847. IsError = true;
  10848. else
  10849. Object = ObjRes;
  10850. TheCall->setArg(0, Object.get());
  10851. // Check the argument types.
  10852. for (unsigned i = 0; i != NumParams; i++) {
  10853. Expr *Arg;
  10854. if (i < Args.size()) {
  10855. Arg = Args[i];
  10856. // Pass the argument.
  10857. ExprResult InputInit
  10858. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10859. Context,
  10860. Method->getParamDecl(i)),
  10861. SourceLocation(), Arg);
  10862. IsError |= InputInit.isInvalid();
  10863. Arg = InputInit.getAs<Expr>();
  10864. } else {
  10865. ExprResult DefArg
  10866. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  10867. if (DefArg.isInvalid()) {
  10868. IsError = true;
  10869. break;
  10870. }
  10871. Arg = DefArg.getAs<Expr>();
  10872. }
  10873. TheCall->setArg(i + 1, Arg);
  10874. }
  10875. // If this is a variadic call, handle args passed through "...".
  10876. if (Proto->isVariadic()) {
  10877. // Promote the arguments (C99 6.5.2.2p7).
  10878. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  10879. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  10880. nullptr);
  10881. IsError |= Arg.isInvalid();
  10882. TheCall->setArg(i + 1, Arg.get());
  10883. }
  10884. }
  10885. if (IsError) return true;
  10886. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10887. if (CheckFunctionCall(Method, TheCall, Proto))
  10888. return true;
  10889. return MaybeBindToTemporary(TheCall);
  10890. }
  10891. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  10892. /// (if one exists), where @c Base is an expression of class type and
  10893. /// @c Member is the name of the member we're trying to find.
  10894. ExprResult
  10895. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  10896. bool *NoArrowOperatorFound) {
  10897. assert(Base->getType()->isRecordType() &&
  10898. "left-hand side must have class type");
  10899. if (checkPlaceholderForOverload(*this, Base))
  10900. return ExprError();
  10901. SourceLocation Loc = Base->getExprLoc();
  10902. // C++ [over.ref]p1:
  10903. //
  10904. // [...] An expression x->m is interpreted as (x.operator->())->m
  10905. // for a class object x of type T if T::operator->() exists and if
  10906. // the operator is selected as the best match function by the
  10907. // overload resolution mechanism (13.3).
  10908. DeclarationName OpName =
  10909. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  10910. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  10911. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  10912. if (RequireCompleteType(Loc, Base->getType(),
  10913. diag::err_typecheck_incomplete_tag, Base))
  10914. return ExprError();
  10915. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  10916. LookupQualifiedName(R, BaseRecord->getDecl());
  10917. R.suppressDiagnostics();
  10918. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10919. Oper != OperEnd; ++Oper) {
  10920. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  10921. None, CandidateSet, /*SuppressUserConversions=*/false);
  10922. }
  10923. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10924. // Perform overload resolution.
  10925. OverloadCandidateSet::iterator Best;
  10926. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10927. case OR_Success:
  10928. // Overload resolution succeeded; we'll build the call below.
  10929. break;
  10930. case OR_No_Viable_Function:
  10931. if (CandidateSet.empty()) {
  10932. QualType BaseType = Base->getType();
  10933. if (NoArrowOperatorFound) {
  10934. // Report this specific error to the caller instead of emitting a
  10935. // diagnostic, as requested.
  10936. *NoArrowOperatorFound = true;
  10937. return ExprError();
  10938. }
  10939. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  10940. << BaseType << Base->getSourceRange();
  10941. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  10942. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  10943. << FixItHint::CreateReplacement(OpLoc, ".");
  10944. }
  10945. } else
  10946. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10947. << "operator->" << Base->getSourceRange();
  10948. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10949. return ExprError();
  10950. case OR_Ambiguous:
  10951. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10952. << "->" << Base->getType() << Base->getSourceRange();
  10953. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
  10954. return ExprError();
  10955. case OR_Deleted:
  10956. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10957. << Best->Function->isDeleted()
  10958. << "->"
  10959. << getDeletedOrUnavailableSuffix(Best->Function)
  10960. << Base->getSourceRange();
  10961. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10962. return ExprError();
  10963. }
  10964. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  10965. // Convert the object parameter.
  10966. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10967. ExprResult BaseResult =
  10968. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  10969. Best->FoundDecl, Method);
  10970. if (BaseResult.isInvalid())
  10971. return ExprError();
  10972. Base = BaseResult.get();
  10973. // Build the operator call.
  10974. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10975. HadMultipleCandidates, OpLoc);
  10976. if (FnExpr.isInvalid())
  10977. return ExprError();
  10978. QualType ResultTy = Method->getReturnType();
  10979. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10980. ResultTy = ResultTy.getNonLValueExprType(Context);
  10981. CXXOperatorCallExpr *TheCall =
  10982. new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
  10983. Base, ResultTy, VK, OpLoc, false);
  10984. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  10985. return ExprError();
  10986. return MaybeBindToTemporary(TheCall);
  10987. }
  10988. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  10989. /// a literal operator described by the provided lookup results.
  10990. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  10991. DeclarationNameInfo &SuffixInfo,
  10992. ArrayRef<Expr*> Args,
  10993. SourceLocation LitEndLoc,
  10994. TemplateArgumentListInfo *TemplateArgs) {
  10995. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  10996. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  10997. OverloadCandidateSet::CSK_Normal);
  10998. AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
  10999. /*SuppressUserConversions=*/true);
  11000. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11001. // Perform overload resolution. This will usually be trivial, but might need
  11002. // to perform substitutions for a literal operator template.
  11003. OverloadCandidateSet::iterator Best;
  11004. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  11005. case OR_Success:
  11006. case OR_Deleted:
  11007. break;
  11008. case OR_No_Viable_Function:
  11009. Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
  11010. << R.getLookupName();
  11011. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  11012. return ExprError();
  11013. case OR_Ambiguous:
  11014. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  11015. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  11016. return ExprError();
  11017. }
  11018. FunctionDecl *FD = Best->Function;
  11019. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  11020. HadMultipleCandidates,
  11021. SuffixInfo.getLoc(),
  11022. SuffixInfo.getInfo());
  11023. if (Fn.isInvalid())
  11024. return true;
  11025. // Check the argument types. This should almost always be a no-op, except
  11026. // that array-to-pointer decay is applied to string literals.
  11027. Expr *ConvArgs[2];
  11028. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  11029. ExprResult InputInit = PerformCopyInitialization(
  11030. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  11031. SourceLocation(), Args[ArgIdx]);
  11032. if (InputInit.isInvalid())
  11033. return true;
  11034. ConvArgs[ArgIdx] = InputInit.get();
  11035. }
  11036. QualType ResultTy = FD->getReturnType();
  11037. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11038. ResultTy = ResultTy.getNonLValueExprType(Context);
  11039. UserDefinedLiteral *UDL =
  11040. new (Context) UserDefinedLiteral(Context, Fn.get(),
  11041. llvm::makeArrayRef(ConvArgs, Args.size()),
  11042. ResultTy, VK, LitEndLoc, UDSuffixLoc);
  11043. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  11044. return ExprError();
  11045. if (CheckFunctionCall(FD, UDL, nullptr))
  11046. return ExprError();
  11047. return MaybeBindToTemporary(UDL);
  11048. }
  11049. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  11050. /// given LookupResult is non-empty, it is assumed to describe a member which
  11051. /// will be invoked. Otherwise, the function will be found via argument
  11052. /// dependent lookup.
  11053. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  11054. /// otherwise CallExpr is set to ExprError() and some non-success value
  11055. /// is returned.
  11056. Sema::ForRangeStatus
  11057. Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
  11058. SourceLocation RangeLoc, VarDecl *Decl,
  11059. BeginEndFunction BEF,
  11060. const DeclarationNameInfo &NameInfo,
  11061. LookupResult &MemberLookup,
  11062. OverloadCandidateSet *CandidateSet,
  11063. Expr *Range, ExprResult *CallExpr) {
  11064. CandidateSet->clear();
  11065. if (!MemberLookup.empty()) {
  11066. ExprResult MemberRef =
  11067. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  11068. /*IsPtr=*/false, CXXScopeSpec(),
  11069. /*TemplateKWLoc=*/SourceLocation(),
  11070. /*FirstQualifierInScope=*/nullptr,
  11071. MemberLookup,
  11072. /*TemplateArgs=*/nullptr);
  11073. if (MemberRef.isInvalid()) {
  11074. *CallExpr = ExprError();
  11075. Diag(Range->getLocStart(), diag::note_in_for_range)
  11076. << RangeLoc << BEF << Range->getType();
  11077. return FRS_DiagnosticIssued;
  11078. }
  11079. *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  11080. if (CallExpr->isInvalid()) {
  11081. *CallExpr = ExprError();
  11082. Diag(Range->getLocStart(), diag::note_in_for_range)
  11083. << RangeLoc << BEF << Range->getType();
  11084. return FRS_DiagnosticIssued;
  11085. }
  11086. } else {
  11087. UnresolvedSet<0> FoundNames;
  11088. UnresolvedLookupExpr *Fn =
  11089. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  11090. NestedNameSpecifierLoc(), NameInfo,
  11091. /*NeedsADL=*/true, /*Overloaded=*/false,
  11092. FoundNames.begin(), FoundNames.end());
  11093. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  11094. CandidateSet, CallExpr);
  11095. if (CandidateSet->empty() || CandidateSetError) {
  11096. *CallExpr = ExprError();
  11097. return FRS_NoViableFunction;
  11098. }
  11099. OverloadCandidateSet::iterator Best;
  11100. OverloadingResult OverloadResult =
  11101. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
  11102. if (OverloadResult == OR_No_Viable_Function) {
  11103. *CallExpr = ExprError();
  11104. return FRS_NoViableFunction;
  11105. }
  11106. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  11107. Loc, nullptr, CandidateSet, &Best,
  11108. OverloadResult,
  11109. /*AllowTypoCorrection=*/false);
  11110. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  11111. *CallExpr = ExprError();
  11112. Diag(Range->getLocStart(), diag::note_in_for_range)
  11113. << RangeLoc << BEF << Range->getType();
  11114. return FRS_DiagnosticIssued;
  11115. }
  11116. }
  11117. return FRS_Success;
  11118. }
  11119. /// FixOverloadedFunctionReference - E is an expression that refers to
  11120. /// a C++ overloaded function (possibly with some parentheses and
  11121. /// perhaps a '&' around it). We have resolved the overloaded function
  11122. /// to the function declaration Fn, so patch up the expression E to
  11123. /// refer (possibly indirectly) to Fn. Returns the new expr.
  11124. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  11125. FunctionDecl *Fn) {
  11126. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  11127. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  11128. Found, Fn);
  11129. if (SubExpr == PE->getSubExpr())
  11130. return PE;
  11131. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  11132. }
  11133. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  11134. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  11135. Found, Fn);
  11136. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  11137. SubExpr->getType()) &&
  11138. "Implicit cast type cannot be determined from overload");
  11139. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  11140. if (SubExpr == ICE->getSubExpr())
  11141. return ICE;
  11142. return ImplicitCastExpr::Create(Context, ICE->getType(),
  11143. ICE->getCastKind(),
  11144. SubExpr, nullptr,
  11145. ICE->getValueKind());
  11146. }
  11147. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  11148. assert(UnOp->getOpcode() == UO_AddrOf &&
  11149. "Can only take the address of an overloaded function");
  11150. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  11151. if (Method->isStatic()) {
  11152. // Do nothing: static member functions aren't any different
  11153. // from non-member functions.
  11154. } else {
  11155. // Fix the subexpression, which really has to be an
  11156. // UnresolvedLookupExpr holding an overloaded member function
  11157. // or template.
  11158. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11159. Found, Fn);
  11160. if (SubExpr == UnOp->getSubExpr())
  11161. return UnOp;
  11162. assert(isa<DeclRefExpr>(SubExpr)
  11163. && "fixed to something other than a decl ref");
  11164. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  11165. && "fixed to a member ref with no nested name qualifier");
  11166. // We have taken the address of a pointer to member
  11167. // function. Perform the computation here so that we get the
  11168. // appropriate pointer to member type.
  11169. QualType ClassType
  11170. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  11171. QualType MemPtrType
  11172. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  11173. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  11174. VK_RValue, OK_Ordinary,
  11175. UnOp->getOperatorLoc());
  11176. }
  11177. }
  11178. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11179. Found, Fn);
  11180. if (SubExpr == UnOp->getSubExpr())
  11181. return UnOp;
  11182. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  11183. Context.getPointerType(SubExpr->getType()),
  11184. VK_RValue, OK_Ordinary,
  11185. UnOp->getOperatorLoc());
  11186. }
  11187. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11188. // FIXME: avoid copy.
  11189. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11190. if (ULE->hasExplicitTemplateArgs()) {
  11191. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11192. TemplateArgs = &TemplateArgsBuffer;
  11193. }
  11194. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11195. ULE->getQualifierLoc(),
  11196. ULE->getTemplateKeywordLoc(),
  11197. Fn,
  11198. /*enclosing*/ false, // FIXME?
  11199. ULE->getNameLoc(),
  11200. Fn->getType(),
  11201. VK_LValue,
  11202. Found.getDecl(),
  11203. TemplateArgs);
  11204. MarkDeclRefReferenced(DRE);
  11205. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  11206. return DRE;
  11207. }
  11208. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  11209. // FIXME: avoid copy.
  11210. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11211. if (MemExpr->hasExplicitTemplateArgs()) {
  11212. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11213. TemplateArgs = &TemplateArgsBuffer;
  11214. }
  11215. Expr *Base;
  11216. // If we're filling in a static method where we used to have an
  11217. // implicit member access, rewrite to a simple decl ref.
  11218. if (MemExpr->isImplicitAccess()) {
  11219. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11220. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11221. MemExpr->getQualifierLoc(),
  11222. MemExpr->getTemplateKeywordLoc(),
  11223. Fn,
  11224. /*enclosing*/ false,
  11225. MemExpr->getMemberLoc(),
  11226. Fn->getType(),
  11227. VK_LValue,
  11228. Found.getDecl(),
  11229. TemplateArgs);
  11230. MarkDeclRefReferenced(DRE);
  11231. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  11232. return DRE;
  11233. } else {
  11234. SourceLocation Loc = MemExpr->getMemberLoc();
  11235. if (MemExpr->getQualifier())
  11236. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  11237. CheckCXXThisCapture(Loc);
  11238. Base = new (Context) CXXThisExpr(Loc,
  11239. MemExpr->getBaseType(),
  11240. /*isImplicit=*/true);
  11241. }
  11242. } else
  11243. Base = MemExpr->getBase();
  11244. ExprValueKind valueKind;
  11245. QualType type;
  11246. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11247. valueKind = VK_LValue;
  11248. type = Fn->getType();
  11249. } else {
  11250. valueKind = VK_RValue;
  11251. type = Context.BoundMemberTy;
  11252. }
  11253. MemberExpr *ME = MemberExpr::Create(
  11254. Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  11255. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  11256. MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
  11257. OK_Ordinary);
  11258. ME->setHadMultipleCandidates(true);
  11259. MarkMemberReferenced(ME);
  11260. return ME;
  11261. }
  11262. llvm_unreachable("Invalid reference to overloaded function");
  11263. }
  11264. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  11265. DeclAccessPair Found,
  11266. FunctionDecl *Fn) {
  11267. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  11268. }