SemaOverload.cpp 508 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718
  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 "clang/AST/HlslTypes.h" // HLSL Change
  32. #include "llvm/ADT/DenseSet.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/SmallPtrSet.h"
  35. #include "llvm/ADT/SmallString.h"
  36. #include <algorithm>
  37. #include <cstdlib>
  38. using namespace clang;
  39. using namespace sema;
  40. /// A convenience routine for creating a decayed reference to a function.
  41. static ExprResult
  42. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
  43. bool HadMultipleCandidates,
  44. SourceLocation Loc = SourceLocation(),
  45. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  46. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  47. return ExprError();
  48. // If FoundDecl is different from Fn (such as if one is a template
  49. // and the other a specialization), make sure DiagnoseUseOfDecl is
  50. // called on both.
  51. // FIXME: This would be more comprehensively addressed by modifying
  52. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  53. // being used.
  54. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  55. return ExprError();
  56. DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
  57. VK_LValue, Loc, LocInfo);
  58. if (HadMultipleCandidates)
  59. DRE->setHadMultipleCandidates(true);
  60. S.MarkDeclRefReferenced(DRE);
  61. ExprResult E = DRE;
  62. E = S.DefaultFunctionArrayConversion(E.get());
  63. if (E.isInvalid())
  64. return ExprError();
  65. return E;
  66. }
  67. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  68. bool InOverloadResolution,
  69. StandardConversionSequence &SCS,
  70. bool CStyle,
  71. bool AllowObjCWritebackConversion);
  72. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  73. QualType &ToType,
  74. bool InOverloadResolution,
  75. StandardConversionSequence &SCS,
  76. bool CStyle);
  77. static OverloadingResult
  78. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  79. UserDefinedConversionSequence& User,
  80. OverloadCandidateSet& Conversions,
  81. bool AllowExplicit,
  82. bool AllowObjCConversionOnExplicit);
  83. static ImplicitConversionSequence::CompareKind
  84. CompareStandardConversionSequences(Sema &S,
  85. const StandardConversionSequence& SCS1,
  86. const StandardConversionSequence& SCS2);
  87. static ImplicitConversionSequence::CompareKind
  88. CompareQualificationConversions(Sema &S,
  89. const StandardConversionSequence& SCS1,
  90. const StandardConversionSequence& SCS2);
  91. static ImplicitConversionSequence::CompareKind
  92. CompareDerivedToBaseConversions(Sema &S,
  93. const StandardConversionSequence& SCS1,
  94. const StandardConversionSequence& SCS2);
  95. /// GetConversionRank - Retrieve the implicit conversion rank
  96. /// corresponding to the given implicit conversion kind.
  97. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  98. static const ImplicitConversionRank
  99. Rank[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  100. ICR_Exact_Match,
  101. ICR_Exact_Match,
  102. ICR_Exact_Match,
  103. ICR_Exact_Match,
  104. ICR_Exact_Match,
  105. ICR_Exact_Match,
  106. ICR_Promotion,
  107. ICR_Promotion,
  108. ICR_Promotion,
  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_Conversion,
  120. ICR_Complex_Real_Conversion,
  121. ICR_Conversion,
  122. ICR_Conversion,
  123. ICR_Writeback_Conversion
  124. // HLSL Change Starts: missing from original
  125. ,ICR_Conversion,
  126. // HLSL Change: new entries
  127. ICR_Conversion,
  128. ICR_Conversion,
  129. ICR_Conversion,
  130. ICR_Conversion,
  131. ICR_Conversion,
  132. ICR_Conversion,
  133. // HLSL Change Ends
  134. };
  135. static_assert(_countof(Rank) == ICK_Num_Conversion_Kinds,
  136. "Otherwise, GetConversionRank is out of sync with ImplicitConversionKind"); // HLSL Change
  137. assert((int)Kind < (int)ICK_Num_Conversion_Kinds); // HLSL Change
  138. return Rank[(int)Kind];
  139. }
  140. /// GetImplicitConversionName - Return the name of this kind of
  141. /// implicit conversion.
  142. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  143. static const char* const Name[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  144. "No conversion",
  145. "Lvalue-to-rvalue",
  146. "Array-to-pointer",
  147. "Function-to-pointer",
  148. "Noreturn adjustment",
  149. "Qualification",
  150. "Integral promotion",
  151. "Floating point promotion",
  152. "Complex promotion",
  153. "Integral conversion",
  154. "Floating conversion",
  155. "Complex conversion",
  156. "Floating-integral conversion",
  157. "Pointer conversion",
  158. "Pointer-to-member conversion",
  159. "Boolean conversion",
  160. "Compatible-types conversion",
  161. "Derived-to-base conversion",
  162. "Vector conversion",
  163. "Vector splat",
  164. "Complex-real conversion",
  165. "Block Pointer conversion",
  166. "Transparent Union Conversion",
  167. "Writeback conversion"
  168. // HLSL Change Starts
  169. ,"Zero constant to event conversion", // HLSL Change: missing value
  170. // HLSL Change: new values
  171. "HLSLVector/Matrix to scalar",
  172. "HLSLVector/Matrix conversion",
  173. "Flat assignment conversion",
  174. "HLSLVector/Matrix splat",
  175. "HLSLVector/Matrix truncation",
  176. "HLSL derived to base",
  177. // HLSL Change Ends
  178. };
  179. static_assert(_countof(Name) == ICK_Num_Conversion_Kinds,
  180. "Otherwise, GetImplicitConversionName is out of sync with ImplicitConversionKind"); // HLSL Change
  181. return Name[Kind];
  182. }
  183. /// StandardConversionSequence - Set the standard conversion
  184. /// sequence to the identity conversion.
  185. void StandardConversionSequence::setAsIdentityConversion() {
  186. First = ICK_Identity;
  187. Second = ICK_Identity;
  188. Third = ICK_Identity;
  189. DeprecatedStringLiteralToCharPtr = false;
  190. QualificationIncludesObjCLifetime = false;
  191. ReferenceBinding = false;
  192. DirectBinding = false;
  193. IsLvalueReference = true;
  194. BindsToFunctionLvalue = false;
  195. BindsToRvalue = false;
  196. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  197. ObjCLifetimeConversionBinding = false;
  198. CopyConstructor = nullptr;
  199. }
  200. /// getRank - Retrieve the rank of this standard conversion sequence
  201. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  202. /// implicit conversions.
  203. ImplicitConversionRank StandardConversionSequence::getRank() const {
  204. ImplicitConversionRank Rank = ICR_Exact_Match;
  205. if (GetConversionRank(First) > Rank)
  206. Rank = GetConversionRank(First);
  207. if (GetConversionRank(Second) > Rank)
  208. Rank = GetConversionRank(Second);
  209. if (GetConversionRank(ComponentConversion) > Rank) // HLSL Change
  210. Rank = GetConversionRank(ComponentConversion);
  211. if (GetConversionRank(Third) > Rank)
  212. Rank = GetConversionRank(Third);
  213. return Rank;
  214. }
  215. /// isPointerConversionToBool - Determines whether this conversion is
  216. /// a conversion of a pointer or pointer-to-member to bool. This is
  217. /// used as part of the ranking of standard conversion sequences
  218. /// (C++ 13.3.3.2p4).
  219. bool StandardConversionSequence::isPointerConversionToBool() const {
  220. // Note that FromType has not necessarily been transformed by the
  221. // array-to-pointer or function-to-pointer implicit conversions, so
  222. // check for their presence as well as checking whether FromType is
  223. // a pointer.
  224. if (getToType(1)->isBooleanType() &&
  225. (getFromType()->isPointerType() ||
  226. getFromType()->isObjCObjectPointerType() ||
  227. getFromType()->isBlockPointerType() ||
  228. getFromType()->isNullPtrType() ||
  229. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  230. return true;
  231. return false;
  232. }
  233. /// isPointerConversionToVoidPointer - Determines whether this
  234. /// conversion is a conversion of a pointer to a void pointer. This is
  235. /// used as part of the ranking of standard conversion sequences (C++
  236. /// 13.3.3.2p4).
  237. bool
  238. StandardConversionSequence::
  239. isPointerConversionToVoidPointer(ASTContext& Context) const {
  240. QualType FromType = getFromType();
  241. QualType ToType = getToType(1);
  242. // Note that FromType has not necessarily been transformed by the
  243. // array-to-pointer implicit conversion, so check for its presence
  244. // and redo the conversion to get a pointer.
  245. if (First == ICK_Array_To_Pointer)
  246. FromType = Context.getArrayDecayedType(FromType);
  247. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  248. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  249. return ToPtrType->getPointeeType()->isVoidType();
  250. return false;
  251. }
  252. /// Skip any implicit casts which could be either part of a narrowing conversion
  253. /// or after one in an implicit conversion.
  254. static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
  255. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  256. switch (ICE->getCastKind()) {
  257. case CK_NoOp:
  258. case CK_IntegralCast:
  259. case CK_IntegralToBoolean:
  260. case CK_IntegralToFloating:
  261. case CK_FloatingToIntegral:
  262. case CK_FloatingToBoolean:
  263. case CK_FloatingCast:
  264. Converted = ICE->getSubExpr();
  265. continue;
  266. default:
  267. return Converted;
  268. }
  269. }
  270. return Converted;
  271. }
  272. /// Check if this standard conversion sequence represents a narrowing
  273. /// conversion, according to C++11 [dcl.init.list]p7.
  274. ///
  275. /// \param Ctx The AST context.
  276. /// \param Converted The result of applying this standard conversion sequence.
  277. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  278. /// value of the expression prior to the narrowing conversion.
  279. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  280. /// type of the expression prior to the narrowing conversion.
  281. NarrowingKind
  282. StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
  283. const Expr *Converted,
  284. APValue &ConstantValue,
  285. QualType &ConstantType) const {
  286. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  287. // C++11 [dcl.init.list]p7:
  288. // A narrowing conversion is an implicit conversion ...
  289. QualType FromType = getToType(0);
  290. QualType ToType = getToType(1);
  291. switch (Second) {
  292. // 'bool' is an integral type; dispatch to the right place to handle it.
  293. case ICK_Boolean_Conversion:
  294. if (FromType->isRealFloatingType())
  295. goto FloatingIntegralConversion;
  296. if (FromType->isIntegralOrUnscopedEnumerationType())
  297. goto IntegralConversion;
  298. // Boolean conversions can be from pointers and pointers to members
  299. // [conv.bool], and those aren't considered narrowing conversions.
  300. return NK_Not_Narrowing;
  301. // -- from a floating-point type to an integer type, or
  302. //
  303. // -- from an integer type or unscoped enumeration type to a floating-point
  304. // type, except where the source is a constant expression and the actual
  305. // value after conversion will fit into the target type and will produce
  306. // the original value when converted back to the original type, or
  307. case ICK_Floating_Integral:
  308. FloatingIntegralConversion:
  309. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  310. return NK_Type_Narrowing;
  311. } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
  312. llvm::APSInt IntConstantValue;
  313. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  314. if (Initializer &&
  315. Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  316. // Convert the integer to the floating type.
  317. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  318. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  319. llvm::APFloat::rmNearestTiesToEven);
  320. // And back.
  321. llvm::APSInt ConvertedValue = IntConstantValue;
  322. bool ignored;
  323. Result.convertToInteger(ConvertedValue,
  324. llvm::APFloat::rmTowardZero, &ignored);
  325. // If the resulting value is different, this was a narrowing conversion.
  326. if (IntConstantValue != ConvertedValue) {
  327. ConstantValue = APValue(IntConstantValue);
  328. ConstantType = Initializer->getType();
  329. return NK_Constant_Narrowing;
  330. }
  331. } else {
  332. // Variables are always narrowings.
  333. return NK_Variable_Narrowing;
  334. }
  335. }
  336. return NK_Not_Narrowing;
  337. // -- from long double to double or float, or from double to float, except
  338. // where the source is a constant expression and the actual value after
  339. // conversion is within the range of values that can be represented (even
  340. // if it cannot be represented exactly), or
  341. case ICK_Floating_Conversion:
  342. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  343. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  344. // FromType is larger than ToType.
  345. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  346. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  347. // Constant!
  348. assert(ConstantValue.isFloat());
  349. llvm::APFloat FloatVal = ConstantValue.getFloat();
  350. // Convert the source value into the target type.
  351. bool ignored;
  352. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  353. Ctx.getFloatTypeSemantics(ToType),
  354. llvm::APFloat::rmNearestTiesToEven, &ignored);
  355. // If there was no overflow, the source value is within the range of
  356. // values that can be represented.
  357. if (ConvertStatus & llvm::APFloat::opOverflow) {
  358. ConstantType = Initializer->getType();
  359. return NK_Constant_Narrowing;
  360. }
  361. } else {
  362. return NK_Variable_Narrowing;
  363. }
  364. }
  365. return NK_Not_Narrowing;
  366. // -- from an integer type or unscoped enumeration type to an integer type
  367. // that cannot represent all the values of the original type, except where
  368. // the source is a constant expression and the actual value after
  369. // conversion will fit into the target type and will produce the original
  370. // value when converted back to the original type.
  371. case ICK_Integral_Conversion:
  372. IntegralConversion: {
  373. assert(FromType->isIntegralOrUnscopedEnumerationType());
  374. assert(ToType->isIntegralOrUnscopedEnumerationType());
  375. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  376. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  377. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  378. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  379. if (FromWidth > ToWidth ||
  380. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  381. (FromSigned && !ToSigned)) {
  382. // Not all values of FromType can be represented in ToType.
  383. llvm::APSInt InitializerValue;
  384. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  385. if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  386. // Such conversions on variables are always narrowing.
  387. return NK_Variable_Narrowing;
  388. }
  389. bool Narrowing = false;
  390. if (FromWidth < ToWidth) {
  391. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  392. // narrowing.
  393. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  394. Narrowing = true;
  395. } else {
  396. // Add a bit to the InitializerValue so we don't have to worry about
  397. // signed vs. unsigned comparisons.
  398. InitializerValue = InitializerValue.extend(
  399. InitializerValue.getBitWidth() + 1);
  400. // Convert the initializer to and from the target width and signed-ness.
  401. llvm::APSInt ConvertedValue = InitializerValue;
  402. ConvertedValue = ConvertedValue.trunc(ToWidth);
  403. ConvertedValue.setIsSigned(ToSigned);
  404. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  405. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  406. // If the result is different, this was a narrowing conversion.
  407. if (ConvertedValue != InitializerValue)
  408. Narrowing = true;
  409. }
  410. if (Narrowing) {
  411. ConstantType = Initializer->getType();
  412. ConstantValue = APValue(InitializerValue);
  413. return NK_Constant_Narrowing;
  414. }
  415. }
  416. return NK_Not_Narrowing;
  417. }
  418. default:
  419. // Other kinds of conversions are not narrowings.
  420. return NK_Not_Narrowing;
  421. }
  422. }
  423. /// dump - Print this standard conversion sequence to standard
  424. /// error. Useful for debugging overloading issues.
  425. void StandardConversionSequence::dump() const {
  426. raw_ostream &OS = llvm::errs();
  427. bool PrintedSomething = false;
  428. if (First != ICK_Identity) {
  429. OS << GetImplicitConversionName(First);
  430. PrintedSomething = true;
  431. }
  432. if (Second != ICK_Identity) {
  433. if (PrintedSomething) {
  434. OS << " -> ";
  435. }
  436. OS << GetImplicitConversionName(Second);
  437. if (CopyConstructor) {
  438. OS << " (by copy constructor)";
  439. } else if (DirectBinding) {
  440. OS << " (direct reference binding)";
  441. } else if (ReferenceBinding) {
  442. OS << " (reference binding)";
  443. }
  444. PrintedSomething = true;
  445. }
  446. // HLSL Change Starts
  447. if (ComponentConversion != ICK_Identity) {
  448. if (PrintedSomething) {
  449. OS << " -> ";
  450. }
  451. OS << GetImplicitConversionName(ComponentConversion);
  452. PrintedSomething = true;
  453. }
  454. // HLSL Change Ends
  455. if (Third != ICK_Identity) {
  456. if (PrintedSomething) {
  457. OS << " -> ";
  458. }
  459. OS << GetImplicitConversionName(Third);
  460. PrintedSomething = true;
  461. }
  462. if (!PrintedSomething) {
  463. OS << "No conversions required";
  464. }
  465. }
  466. /// dump - Print this user-defined conversion sequence to standard
  467. /// error. Useful for debugging overloading issues.
  468. void UserDefinedConversionSequence::dump() const {
  469. raw_ostream &OS = llvm::errs();
  470. if (Before.First || Before.Second || Before.Third) {
  471. Before.dump();
  472. OS << " -> ";
  473. }
  474. if (ConversionFunction)
  475. OS << '\'' << *ConversionFunction << '\'';
  476. else
  477. OS << "aggregate initialization";
  478. if (After.First || After.Second || After.Third) {
  479. OS << " -> ";
  480. After.dump();
  481. }
  482. }
  483. /// dump - Print this implicit conversion sequence to standard
  484. /// error. Useful for debugging overloading issues.
  485. void ImplicitConversionSequence::dump() const {
  486. raw_ostream &OS = llvm::errs();
  487. if (isStdInitializerListElement())
  488. OS << "Worst std::initializer_list element conversion: ";
  489. switch (ConversionKind) {
  490. case StandardConversion:
  491. OS << "Standard conversion: ";
  492. Standard.dump();
  493. break;
  494. case UserDefinedConversion:
  495. OS << "User-defined conversion: ";
  496. UserDefined.dump();
  497. break;
  498. case EllipsisConversion:
  499. OS << "Ellipsis conversion";
  500. break;
  501. case AmbiguousConversion:
  502. OS << "Ambiguous conversion";
  503. break;
  504. case BadConversion:
  505. OS << "Bad conversion";
  506. break;
  507. }
  508. OS << "\n";
  509. }
  510. void AmbiguousConversionSequence::construct() {
  511. new (&conversions()) ConversionSet();
  512. }
  513. void AmbiguousConversionSequence::destruct() {
  514. conversions().~ConversionSet();
  515. }
  516. void
  517. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  518. FromTypePtr = O.FromTypePtr;
  519. ToTypePtr = O.ToTypePtr;
  520. new (&conversions()) ConversionSet(O.conversions());
  521. }
  522. namespace {
  523. // Structure used by DeductionFailureInfo to store
  524. // template argument information.
  525. struct DFIArguments {
  526. TemplateArgument FirstArg;
  527. TemplateArgument SecondArg;
  528. };
  529. // Structure used by DeductionFailureInfo to store
  530. // template parameter and template argument information.
  531. struct DFIParamWithArguments : DFIArguments {
  532. TemplateParameter Param;
  533. };
  534. }
  535. /// \brief Convert from Sema's representation of template deduction information
  536. /// to the form used in overload-candidate information.
  537. DeductionFailureInfo
  538. clang::MakeDeductionFailureInfo(ASTContext &Context,
  539. Sema::TemplateDeductionResult TDK,
  540. TemplateDeductionInfo &Info) {
  541. DeductionFailureInfo Result;
  542. Result.Result = static_cast<unsigned>(TDK);
  543. Result.HasDiagnostic = false;
  544. Result.Data = nullptr;
  545. switch (TDK) {
  546. case Sema::TDK_Success:
  547. case Sema::TDK_Invalid:
  548. case Sema::TDK_InstantiationDepth:
  549. case Sema::TDK_TooManyArguments:
  550. case Sema::TDK_TooFewArguments:
  551. break;
  552. case Sema::TDK_Incomplete:
  553. case Sema::TDK_InvalidExplicitArguments:
  554. Result.Data = Info.Param.getOpaqueValue();
  555. break;
  556. case Sema::TDK_NonDeducedMismatch: {
  557. // FIXME: Should allocate from normal heap so that we can free this later.
  558. DFIArguments *Saved = new (Context) DFIArguments;
  559. Saved->FirstArg = Info.FirstArg;
  560. Saved->SecondArg = Info.SecondArg;
  561. Result.Data = Saved;
  562. break;
  563. }
  564. case Sema::TDK_Inconsistent:
  565. case Sema::TDK_Underqualified: {
  566. // FIXME: Should allocate from normal heap so that we can free this later.
  567. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  568. Saved->Param = Info.Param;
  569. Saved->FirstArg = Info.FirstArg;
  570. Saved->SecondArg = Info.SecondArg;
  571. Result.Data = Saved;
  572. break;
  573. }
  574. case Sema::TDK_SubstitutionFailure:
  575. Result.Data = Info.take();
  576. if (Info.hasSFINAEDiagnostic()) {
  577. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  578. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  579. Info.takeSFINAEDiagnostic(*Diag);
  580. Result.HasDiagnostic = true;
  581. }
  582. break;
  583. case Sema::TDK_FailedOverloadResolution:
  584. Result.Data = Info.Expression;
  585. break;
  586. case Sema::TDK_MiscellaneousDeductionFailure:
  587. break;
  588. }
  589. return Result;
  590. }
  591. void DeductionFailureInfo::Destroy() {
  592. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  593. case Sema::TDK_Success:
  594. case Sema::TDK_Invalid:
  595. case Sema::TDK_InstantiationDepth:
  596. case Sema::TDK_Incomplete:
  597. case Sema::TDK_TooManyArguments:
  598. case Sema::TDK_TooFewArguments:
  599. case Sema::TDK_InvalidExplicitArguments:
  600. case Sema::TDK_FailedOverloadResolution:
  601. break;
  602. case Sema::TDK_Inconsistent:
  603. case Sema::TDK_Underqualified:
  604. case Sema::TDK_NonDeducedMismatch:
  605. // FIXME: Destroy the data?
  606. Data = nullptr;
  607. break;
  608. case Sema::TDK_SubstitutionFailure:
  609. // FIXME: Destroy the template argument list?
  610. Data = nullptr;
  611. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  612. Diag->~PartialDiagnosticAt();
  613. HasDiagnostic = false;
  614. }
  615. break;
  616. // Unhandled
  617. case Sema::TDK_MiscellaneousDeductionFailure:
  618. break;
  619. }
  620. }
  621. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  622. if (HasDiagnostic)
  623. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  624. return nullptr;
  625. }
  626. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  627. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  628. case Sema::TDK_Success:
  629. case Sema::TDK_Invalid:
  630. case Sema::TDK_InstantiationDepth:
  631. case Sema::TDK_TooManyArguments:
  632. case Sema::TDK_TooFewArguments:
  633. case Sema::TDK_SubstitutionFailure:
  634. case Sema::TDK_NonDeducedMismatch:
  635. case Sema::TDK_FailedOverloadResolution:
  636. return TemplateParameter();
  637. case Sema::TDK_Incomplete:
  638. case Sema::TDK_InvalidExplicitArguments:
  639. return TemplateParameter::getFromOpaqueValue(Data);
  640. case Sema::TDK_Inconsistent:
  641. case Sema::TDK_Underqualified:
  642. return static_cast<DFIParamWithArguments*>(Data)->Param;
  643. // Unhandled
  644. case Sema::TDK_MiscellaneousDeductionFailure:
  645. break;
  646. }
  647. return TemplateParameter();
  648. }
  649. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  650. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  651. case Sema::TDK_Success:
  652. case Sema::TDK_Invalid:
  653. case Sema::TDK_InstantiationDepth:
  654. case Sema::TDK_TooManyArguments:
  655. case Sema::TDK_TooFewArguments:
  656. case Sema::TDK_Incomplete:
  657. case Sema::TDK_InvalidExplicitArguments:
  658. case Sema::TDK_Inconsistent:
  659. case Sema::TDK_Underqualified:
  660. case Sema::TDK_NonDeducedMismatch:
  661. case Sema::TDK_FailedOverloadResolution:
  662. return nullptr;
  663. case Sema::TDK_SubstitutionFailure:
  664. return static_cast<TemplateArgumentList*>(Data);
  665. // Unhandled
  666. case Sema::TDK_MiscellaneousDeductionFailure:
  667. break;
  668. }
  669. return nullptr;
  670. }
  671. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  672. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  673. case Sema::TDK_Success:
  674. case Sema::TDK_Invalid:
  675. case Sema::TDK_InstantiationDepth:
  676. case Sema::TDK_Incomplete:
  677. case Sema::TDK_TooManyArguments:
  678. case Sema::TDK_TooFewArguments:
  679. case Sema::TDK_InvalidExplicitArguments:
  680. case Sema::TDK_SubstitutionFailure:
  681. case Sema::TDK_FailedOverloadResolution:
  682. return nullptr;
  683. case Sema::TDK_Inconsistent:
  684. case Sema::TDK_Underqualified:
  685. case Sema::TDK_NonDeducedMismatch:
  686. return &static_cast<DFIArguments*>(Data)->FirstArg;
  687. // Unhandled
  688. case Sema::TDK_MiscellaneousDeductionFailure:
  689. break;
  690. }
  691. return nullptr;
  692. }
  693. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  694. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  695. case Sema::TDK_Success:
  696. case Sema::TDK_Invalid:
  697. case Sema::TDK_InstantiationDepth:
  698. case Sema::TDK_Incomplete:
  699. case Sema::TDK_TooManyArguments:
  700. case Sema::TDK_TooFewArguments:
  701. case Sema::TDK_InvalidExplicitArguments:
  702. case Sema::TDK_SubstitutionFailure:
  703. case Sema::TDK_FailedOverloadResolution:
  704. return nullptr;
  705. case Sema::TDK_Inconsistent:
  706. case Sema::TDK_Underqualified:
  707. case Sema::TDK_NonDeducedMismatch:
  708. return &static_cast<DFIArguments*>(Data)->SecondArg;
  709. // Unhandled
  710. case Sema::TDK_MiscellaneousDeductionFailure:
  711. break;
  712. }
  713. return nullptr;
  714. }
  715. Expr *DeductionFailureInfo::getExpr() {
  716. if (static_cast<Sema::TemplateDeductionResult>(Result) ==
  717. Sema::TDK_FailedOverloadResolution)
  718. return static_cast<Expr*>(Data);
  719. return nullptr;
  720. }
  721. void OverloadCandidateSet::destroyCandidates() {
  722. for (iterator i = begin(), e = end(); i != e; ++i) {
  723. for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
  724. i->Conversions[ii].~ImplicitConversionSequence();
  725. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  726. i->DeductionFailure.Destroy();
  727. }
  728. }
  729. void OverloadCandidateSet::clear() {
  730. destroyCandidates();
  731. NumInlineSequences = 0;
  732. Candidates.clear();
  733. Functions.clear();
  734. }
  735. namespace {
  736. class UnbridgedCastsSet {
  737. struct Entry {
  738. Expr **Addr;
  739. Expr *Saved;
  740. };
  741. SmallVector<Entry, 2> Entries;
  742. public:
  743. void save(Sema &S, Expr *&E) {
  744. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  745. Entry entry = { &E, E };
  746. Entries.push_back(entry);
  747. E = S.stripARCUnbridgedCast(E);
  748. }
  749. void restore() {
  750. for (SmallVectorImpl<Entry>::iterator
  751. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  752. *i->Addr = i->Saved;
  753. }
  754. };
  755. }
  756. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  757. /// preprocessing on the given expression.
  758. ///
  759. /// \param unbridgedCasts a collection to which to add unbridged casts;
  760. /// without this, they will be immediately diagnosed as errors
  761. ///
  762. /// Return true on unrecoverable error.
  763. static bool
  764. checkPlaceholderForOverload(Sema &S, Expr *&E,
  765. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  766. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  767. // We can't handle overloaded expressions here because overload
  768. // resolution might reasonably tweak them.
  769. if (placeholder->getKind() == BuiltinType::Overload) return false;
  770. // If the context potentially accepts unbridged ARC casts, strip
  771. // the unbridged cast and add it to the collection for later restoration.
  772. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  773. unbridgedCasts) {
  774. unbridgedCasts->save(S, E);
  775. return false;
  776. }
  777. // Go ahead and check everything else.
  778. ExprResult result = S.CheckPlaceholderExpr(E);
  779. if (result.isInvalid())
  780. return true;
  781. E = result.get();
  782. return false;
  783. }
  784. // Nothing to do.
  785. return false;
  786. }
  787. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  788. /// placeholders.
  789. static bool checkArgPlaceholdersForOverload(Sema &S,
  790. MultiExprArg Args,
  791. UnbridgedCastsSet &unbridged) {
  792. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  793. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  794. return true;
  795. return false;
  796. }
  797. // IsOverload - Determine whether the given New declaration is an
  798. // overload of the declarations in Old. This routine returns false if
  799. // New and Old cannot be overloaded, e.g., if New has the same
  800. // signature as some function in Old (C++ 1.3.10) or if the Old
  801. // declarations aren't functions (or function templates) at all. When
  802. // it does return false, MatchedDecl will point to the decl that New
  803. // cannot be overloaded with. This decl may be a UsingShadowDecl on
  804. // top of the underlying declaration.
  805. //
  806. // Example: Given the following input:
  807. //
  808. // void f(int, float); // #1
  809. // void f(int, int); // #2
  810. // int f(int, int); // #3
  811. //
  812. // When we process #1, there is no previous declaration of "f",
  813. // so IsOverload will not be used.
  814. //
  815. // When we process #2, Old contains only the FunctionDecl for #1. By
  816. // comparing the parameter types, we see that #1 and #2 are overloaded
  817. // (since they have different signatures), so this routine returns
  818. // false; MatchedDecl is unchanged.
  819. //
  820. // When we process #3, Old is an overload set containing #1 and #2. We
  821. // compare the signatures of #3 to #1 (they're overloaded, so we do
  822. // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
  823. // identical (return types of functions are not part of the
  824. // signature), IsOverload returns false and MatchedDecl will be set to
  825. // point to the FunctionDecl for #2.
  826. //
  827. // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
  828. // into a class by a using declaration. The rules for whether to hide
  829. // shadow declarations ignore some properties which otherwise figure
  830. // into a function template's signature.
  831. Sema::OverloadKind
  832. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  833. NamedDecl *&Match, bool NewIsUsingDecl) {
  834. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  835. I != E; ++I) {
  836. NamedDecl *OldD = *I;
  837. bool OldIsUsingDecl = false;
  838. if (isa<UsingShadowDecl>(OldD)) {
  839. OldIsUsingDecl = true;
  840. // We can always introduce two using declarations into the same
  841. // context, even if they have identical signatures.
  842. if (NewIsUsingDecl) continue;
  843. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  844. }
  845. // If either declaration was introduced by a using declaration,
  846. // we'll need to use slightly different rules for matching.
  847. // Essentially, these rules are the normal rules, except that
  848. // function templates hide function templates with different
  849. // return types or template parameter lists.
  850. bool UseMemberUsingDeclRules =
  851. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  852. !New->getFriendObjectKind();
  853. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  854. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  855. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  856. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  857. continue;
  858. }
  859. if (!isa<FunctionTemplateDecl>(OldD) &&
  860. !shouldLinkPossiblyHiddenDecl(*I, New))
  861. continue;
  862. Match = *I;
  863. return Ovl_Match;
  864. }
  865. } else if (isa<UsingDecl>(OldD)) {
  866. // We can overload with these, which can show up when doing
  867. // redeclaration checks for UsingDecls.
  868. assert(Old.getLookupKind() == LookupUsingDeclName);
  869. } else if (isa<TagDecl>(OldD)) {
  870. // We can always overload with tags by hiding them.
  871. } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
  872. // Optimistically assume that an unresolved using decl will
  873. // overload; if it doesn't, we'll have to diagnose during
  874. // template instantiation.
  875. } else {
  876. // (C++ 13p1):
  877. // Only function declarations can be overloaded; object and type
  878. // declarations cannot be overloaded.
  879. Match = *I;
  880. return Ovl_NonFunction;
  881. }
  882. }
  883. return Ovl_Overload;
  884. }
  885. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  886. bool UseUsingDeclRules) {
  887. // C++ [basic.start.main]p2: This function shall not be overloaded.
  888. if (New->isMain())
  889. return false;
  890. // MSVCRT user defined entry points cannot be overloaded.
  891. if (New->isMSVCRTEntryPoint())
  892. return false;
  893. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  894. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  895. // C++ [temp.fct]p2:
  896. // A function template can be overloaded with other function templates
  897. // and with normal (non-template) functions.
  898. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  899. return true;
  900. // Is the function New an overload of the function Old?
  901. QualType OldQType = Context.getCanonicalType(Old->getType());
  902. QualType NewQType = Context.getCanonicalType(New->getType());
  903. // Compare the signatures (C++ 1.3.10) of the two functions to
  904. // determine whether they are overloads. If we find any mismatch
  905. // in the signature, they are overloads.
  906. // If either of these functions is a K&R-style function (no
  907. // prototype), then we consider them to have matching signatures.
  908. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  909. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  910. return false;
  911. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  912. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  913. // The signature of a function includes the types of its
  914. // parameters (C++ 1.3.10), which includes the presence or absence
  915. // of the ellipsis; see C++ DR 357).
  916. if (OldQType != NewQType &&
  917. (OldType->getNumParams() != NewType->getNumParams() ||
  918. OldType->isVariadic() != NewType->isVariadic() ||
  919. !FunctionParamTypesAreEqual(OldType, NewType)))
  920. return true;
  921. // C++ [temp.over.link]p4:
  922. // The signature of a function template consists of its function
  923. // signature, its return type and its template parameter list. The names
  924. // of the template parameters are significant only for establishing the
  925. // relationship between the template parameters and the rest of the
  926. // signature.
  927. //
  928. // We check the return type and template parameter lists for function
  929. // templates first; the remaining checks follow.
  930. //
  931. // However, we don't consider either of these when deciding whether
  932. // a member introduced by a shadow declaration is hidden.
  933. if (!UseUsingDeclRules && NewTemplate &&
  934. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  935. OldTemplate->getTemplateParameters(),
  936. false, TPL_TemplateMatch) ||
  937. OldType->getReturnType() != NewType->getReturnType()))
  938. return true;
  939. // If the function is a class member, its signature includes the
  940. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  941. //
  942. // As part of this, also check whether one of the member functions
  943. // is static, in which case they are not overloads (C++
  944. // 13.1p2). While not part of the definition of the signature,
  945. // this check is important to determine whether these functions
  946. // can be overloaded.
  947. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  948. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  949. if (OldMethod && NewMethod &&
  950. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  951. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  952. if (!UseUsingDeclRules &&
  953. (OldMethod->getRefQualifier() == RQ_None ||
  954. NewMethod->getRefQualifier() == RQ_None)) {
  955. // C++0x [over.load]p2:
  956. // - Member function declarations with the same name and the same
  957. // parameter-type-list as well as member function template
  958. // declarations with the same name, the same parameter-type-list, and
  959. // the same template parameter lists cannot be overloaded if any of
  960. // them, but not all, have a ref-qualifier (8.3.5).
  961. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  962. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  963. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  964. }
  965. return true;
  966. }
  967. // We may not have applied the implicit const for a constexpr member
  968. // function yet (because we haven't yet resolved whether this is a static
  969. // or non-static member function). Add it now, on the assumption that this
  970. // is a redeclaration of OldMethod.
  971. unsigned OldQuals = OldMethod->getTypeQualifiers();
  972. unsigned NewQuals = NewMethod->getTypeQualifiers();
  973. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  974. !isa<CXXConstructorDecl>(NewMethod))
  975. NewQuals |= Qualifiers::Const;
  976. // We do not allow overloading based off of '__restrict'.
  977. OldQuals &= ~Qualifiers::Restrict;
  978. NewQuals &= ~Qualifiers::Restrict;
  979. if (OldQuals != NewQuals)
  980. return true;
  981. }
  982. // enable_if attributes are an order-sensitive part of the signature.
  983. for (specific_attr_iterator<EnableIfAttr>
  984. NewI = New->specific_attr_begin<EnableIfAttr>(),
  985. NewE = New->specific_attr_end<EnableIfAttr>(),
  986. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  987. OldE = Old->specific_attr_end<EnableIfAttr>();
  988. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  989. if (NewI == NewE || OldI == OldE)
  990. return true;
  991. llvm::FoldingSetNodeID NewID, OldID;
  992. NewI->getCond()->Profile(NewID, Context, true);
  993. OldI->getCond()->Profile(OldID, Context, true);
  994. if (NewID != OldID)
  995. return true;
  996. }
  997. // The signatures match; this is not an overload.
  998. return false;
  999. }
  1000. /// \brief Checks availability of the function depending on the current
  1001. /// function context. Inside an unavailable function, unavailability is ignored.
  1002. ///
  1003. /// \returns true if \arg FD is unavailable and current context is inside
  1004. /// an available function, false otherwise.
  1005. bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
  1006. return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
  1007. }
  1008. /// \brief Tries a user-defined conversion from From to ToType.
  1009. ///
  1010. /// Produces an implicit conversion sequence for when a standard conversion
  1011. /// is not an option. See TryImplicitConversion for more information.
  1012. static ImplicitConversionSequence
  1013. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1014. bool SuppressUserConversions,
  1015. bool AllowExplicit,
  1016. bool InOverloadResolution,
  1017. bool CStyle,
  1018. bool AllowObjCWritebackConversion,
  1019. bool AllowObjCConversionOnExplicit) {
  1020. ImplicitConversionSequence ICS;
  1021. if (SuppressUserConversions || S.getLangOpts().HLSL) { // HLSL Change - no user conversions
  1022. // We're not in the case above, so there is no conversion that
  1023. // we can perform.
  1024. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1025. return ICS;
  1026. }
  1027. // Attempt user-defined conversion.
  1028. OverloadCandidateSet Conversions(From->getExprLoc(),
  1029. OverloadCandidateSet::CSK_Normal);
  1030. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1031. Conversions, AllowExplicit,
  1032. AllowObjCConversionOnExplicit)) {
  1033. case OR_Success:
  1034. case OR_Deleted:
  1035. ICS.setUserDefined();
  1036. ICS.UserDefined.Before.setAsIdentityConversion();
  1037. // C++ [over.ics.user]p4:
  1038. // A conversion of an expression of class type to the same class
  1039. // type is given Exact Match rank, and a conversion of an
  1040. // expression of class type to a base class of that type is
  1041. // given Conversion rank, in spite of the fact that a copy
  1042. // constructor (i.e., a user-defined conversion function) is
  1043. // called for those cases.
  1044. if (CXXConstructorDecl *Constructor
  1045. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1046. QualType FromCanon
  1047. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1048. QualType ToCanon
  1049. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1050. if (Constructor->isCopyConstructor() &&
  1051. (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
  1052. // Turn this into a "standard" conversion sequence, so that it
  1053. // gets ranked with standard conversion sequences.
  1054. ICS.setStandard();
  1055. ICS.Standard.setAsIdentityConversion();
  1056. ICS.Standard.setFromType(From->getType());
  1057. ICS.Standard.setAllToTypes(ToType);
  1058. ICS.Standard.CopyConstructor = Constructor;
  1059. if (ToCanon != FromCanon)
  1060. ICS.Standard.Second = ICK_Derived_To_Base;
  1061. }
  1062. }
  1063. break;
  1064. case OR_Ambiguous:
  1065. ICS.setAmbiguous();
  1066. ICS.Ambiguous.setFromType(From->getType());
  1067. ICS.Ambiguous.setToType(ToType);
  1068. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1069. Cand != Conversions.end(); ++Cand)
  1070. if (Cand->Viable)
  1071. ICS.Ambiguous.addConversion(Cand->Function);
  1072. break;
  1073. // Fall through.
  1074. case OR_No_Viable_Function:
  1075. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1076. break;
  1077. }
  1078. return ICS;
  1079. }
  1080. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1081. /// from the given expression (Expr) to the given type (ToType). This
  1082. /// function returns an implicit conversion sequence that can be used
  1083. /// to perform the initialization. Given
  1084. ///
  1085. /// void f(float f);
  1086. /// void g(int i) { f(i); }
  1087. ///
  1088. /// this routine would produce an implicit conversion sequence to
  1089. /// describe the initialization of f from i, which will be a standard
  1090. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1091. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1092. //
  1093. /// Note that this routine only determines how the conversion can be
  1094. /// performed; it does not actually perform the conversion. As such,
  1095. /// it will not produce any diagnostics if no conversion is available,
  1096. /// but will instead return an implicit conversion sequence of kind
  1097. /// "BadConversion".
  1098. ///
  1099. /// If @p SuppressUserConversions, then user-defined conversions are
  1100. /// not permitted.
  1101. /// If @p AllowExplicit, then explicit user-defined conversions are
  1102. /// permitted.
  1103. ///
  1104. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1105. /// writeback conversion, which allows __autoreleasing id* parameters to
  1106. /// be initialized with __strong id* or __weak id* arguments.
  1107. static ImplicitConversionSequence
  1108. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1109. bool SuppressUserConversions,
  1110. bool AllowExplicit,
  1111. bool InOverloadResolution,
  1112. bool CStyle,
  1113. bool AllowObjCWritebackConversion,
  1114. bool AllowObjCConversionOnExplicit) {
  1115. ImplicitConversionSequence ICS;
  1116. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1117. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1118. ICS.setStandard();
  1119. return ICS;
  1120. }
  1121. if (!S.getLangOpts().CPlusPlus) {
  1122. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1123. return ICS;
  1124. }
  1125. // C++ [over.ics.user]p4:
  1126. // A conversion of an expression of class type to the same class
  1127. // type is given Exact Match rank, and a conversion of an
  1128. // expression of class type to a base class of that type is
  1129. // given Conversion rank, in spite of the fact that a copy/move
  1130. // constructor (i.e., a user-defined conversion function) is
  1131. // called for those cases.
  1132. QualType FromType = From->getType();
  1133. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1134. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1135. S.IsDerivedFrom(FromType, ToType))) {
  1136. ICS.setStandard();
  1137. ICS.Standard.setAsIdentityConversion();
  1138. ICS.Standard.setFromType(FromType);
  1139. ICS.Standard.setAllToTypes(ToType);
  1140. // We don't actually check at this point whether there is a valid
  1141. // copy/move constructor, since overloading just assumes that it
  1142. // exists. When we actually perform initialization, we'll find the
  1143. // appropriate constructor to copy the returned object, if needed.
  1144. ICS.Standard.CopyConstructor = nullptr;
  1145. // Determine whether this is considered a derived-to-base conversion.
  1146. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1147. ICS.Standard.Second = ICK_Derived_To_Base;
  1148. return ICS;
  1149. }
  1150. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1151. AllowExplicit, InOverloadResolution, CStyle,
  1152. AllowObjCWritebackConversion,
  1153. AllowObjCConversionOnExplicit);
  1154. }
  1155. ImplicitConversionSequence
  1156. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1157. bool SuppressUserConversions,
  1158. bool AllowExplicit,
  1159. bool InOverloadResolution,
  1160. bool CStyle,
  1161. bool AllowObjCWritebackConversion) {
  1162. return ::TryImplicitConversion(*this, From, ToType,
  1163. SuppressUserConversions, AllowExplicit,
  1164. InOverloadResolution, CStyle,
  1165. AllowObjCWritebackConversion,
  1166. /*AllowObjCConversionOnExplicit=*/false);
  1167. }
  1168. /// PerformImplicitConversion - Perform an implicit conversion of the
  1169. /// expression From to the type ToType. Returns the
  1170. /// converted expression. Flavor is the kind of conversion we're
  1171. /// performing, used in the error message. If @p AllowExplicit,
  1172. /// explicit user-defined conversions are permitted.
  1173. ExprResult
  1174. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1175. AssignmentAction Action, bool AllowExplicit) {
  1176. ImplicitConversionSequence ICS;
  1177. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1178. }
  1179. ExprResult
  1180. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1181. AssignmentAction Action, bool AllowExplicit,
  1182. ImplicitConversionSequence& ICS) {
  1183. if (checkPlaceholderForOverload(*this, From))
  1184. return ExprError();
  1185. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1186. bool AllowObjCWritebackConversion
  1187. = getLangOpts().ObjCAutoRefCount &&
  1188. (Action == AA_Passing || Action == AA_Sending);
  1189. if (getLangOpts().ObjC1)
  1190. CheckObjCBridgeRelatedConversions(From->getLocStart(),
  1191. ToType, From->getType(), From);
  1192. ICS = ::TryImplicitConversion(*this, From, ToType,
  1193. /*SuppressUserConversions=*/false,
  1194. AllowExplicit,
  1195. /*InOverloadResolution=*/false,
  1196. /*CStyle=*/false,
  1197. AllowObjCWritebackConversion,
  1198. /*AllowObjCConversionOnExplicit=*/false);
  1199. return PerformImplicitConversion(From, ToType, ICS, Action);
  1200. }
  1201. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1202. /// conversion that strips "noreturn" off the nested function type.
  1203. bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
  1204. QualType &ResultTy) {
  1205. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1206. return false;
  1207. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1208. // where F adds one of the following at most once:
  1209. // - a pointer
  1210. // - a member pointer
  1211. // - a block pointer
  1212. CanQualType CanTo = Context.getCanonicalType(ToType);
  1213. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1214. Type::TypeClass TyClass = CanTo->getTypeClass();
  1215. if (TyClass != CanFrom->getTypeClass()) return false;
  1216. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1217. if (TyClass == Type::Pointer) {
  1218. CanTo = CanTo.getAs<PointerType>()->getPointeeType();
  1219. CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
  1220. } else if (TyClass == Type::BlockPointer) {
  1221. CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
  1222. CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
  1223. } else if (TyClass == Type::MemberPointer) {
  1224. CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
  1225. CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
  1226. } else {
  1227. return false;
  1228. }
  1229. TyClass = CanTo->getTypeClass();
  1230. if (TyClass != CanFrom->getTypeClass()) return false;
  1231. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1232. return false;
  1233. }
  1234. const FunctionType *FromFn = cast<FunctionType>(CanFrom);
  1235. FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
  1236. if (!EInfo.getNoReturn()) return false;
  1237. FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
  1238. assert(QualType(FromFn, 0).isCanonical());
  1239. if (QualType(FromFn, 0) != CanTo) return false;
  1240. ResultTy = ToType;
  1241. return true;
  1242. }
  1243. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1244. /// vector conversion.
  1245. ///
  1246. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1247. /// conversion.
  1248. static bool IsVectorConversion(Sema &S, QualType FromType,
  1249. QualType ToType, ImplicitConversionKind &ICK) {
  1250. // We need at least one of these types to be a vector type to have a vector
  1251. // conversion.
  1252. if (!ToType->isVectorType() && !FromType->isVectorType())
  1253. return false;
  1254. // Identical types require no conversions.
  1255. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1256. return false;
  1257. // There are no conversions between extended vector types, only identity.
  1258. if (ToType->isExtVectorType()) {
  1259. // There are no conversions between extended vector types other than the
  1260. // identity conversion.
  1261. if (FromType->isExtVectorType())
  1262. return false;
  1263. // Vector splat from any arithmetic type to a vector.
  1264. if (FromType->isArithmeticType()) {
  1265. ICK = ICK_Vector_Splat;
  1266. return true;
  1267. }
  1268. }
  1269. // We can perform the conversion between vector types in the following cases:
  1270. // 1)vector types are equivalent AltiVec and GCC vector types
  1271. // 2)lax vector conversions are permitted and the vector types are of the
  1272. // same size
  1273. if (ToType->isVectorType() && FromType->isVectorType()) {
  1274. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1275. S.isLaxVectorConversion(FromType, ToType)) {
  1276. ICK = ICK_Vector_Conversion;
  1277. return true;
  1278. }
  1279. }
  1280. return false;
  1281. }
  1282. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1283. bool InOverloadResolution,
  1284. StandardConversionSequence &SCS,
  1285. bool CStyle);
  1286. /// IsStandardConversion - Determines whether there is a standard
  1287. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1288. /// expression From to the type ToType. Standard conversion sequences
  1289. /// only consider non-class types; for conversions that involve class
  1290. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1291. /// contain the standard conversion sequence required to perform this
  1292. /// conversion and this routine will return true. Otherwise, this
  1293. /// routine will return false and the value of SCS is unspecified.
  1294. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1295. bool InOverloadResolution,
  1296. StandardConversionSequence &SCS,
  1297. bool CStyle,
  1298. bool AllowObjCWritebackConversion) {
  1299. QualType FromType = From->getType();
  1300. // Standard conversions (C++ [conv])
  1301. SCS.setAsIdentityConversion();
  1302. SCS.IncompatibleObjC = false;
  1303. SCS.setFromType(FromType);
  1304. SCS.CopyConstructor = nullptr;
  1305. // HLSL Change Begins
  1306. if (S.getLangOpts().HLSL) {
  1307. return hlsl::CanConvert(&S, SourceLocation(), From, ToType, /*explicitConversion=*/false, &SCS);
  1308. }
  1309. // HLSL Change Ends
  1310. // There are no standard conversions for class types in C++, so
  1311. // abort early. When overloading in C, however, we do permit
  1312. if (FromType->isRecordType() || ToType->isRecordType()) {
  1313. if (S.getLangOpts().CPlusPlus)
  1314. return false;
  1315. // When we're overloading in C, we allow, as standard conversions,
  1316. }
  1317. // The first conversion can be an lvalue-to-rvalue conversion,
  1318. // array-to-pointer conversion, or function-to-pointer conversion
  1319. // (C++ 4p1).
  1320. if (FromType == S.Context.OverloadTy) {
  1321. DeclAccessPair AccessPair;
  1322. if (FunctionDecl *Fn
  1323. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1324. AccessPair)) {
  1325. // We were able to resolve the address of the overloaded function,
  1326. // so we can convert to the type of that function.
  1327. FromType = Fn->getType();
  1328. SCS.setFromType(FromType);
  1329. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1330. // if the type matches (identity) or we are converting to bool
  1331. if (!S.Context.hasSameUnqualifiedType(
  1332. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1333. QualType resultTy;
  1334. // if the function type matches except for [[noreturn]], it's ok
  1335. if (!S.IsNoReturnConversion(FromType,
  1336. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1337. // otherwise, only a boolean conversion is standard
  1338. if (!ToType->isBooleanType())
  1339. return false;
  1340. }
  1341. // Check if the "from" expression is taking the address of an overloaded
  1342. // function and recompute the FromType accordingly. Take advantage of the
  1343. // fact that non-static member functions *must* have such an address-of
  1344. // expression.
  1345. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1346. if (Method && !Method->isStatic()) {
  1347. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1348. "Non-unary operator on non-static member address");
  1349. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1350. == UO_AddrOf &&
  1351. "Non-address-of operator on non-static member address");
  1352. const Type *ClassType
  1353. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1354. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1355. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1356. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1357. UO_AddrOf &&
  1358. "Non-address-of operator for overloaded function expression");
  1359. FromType = S.Context.getPointerType(FromType);
  1360. }
  1361. // Check that we've computed the proper type after overload resolution.
  1362. assert(S.Context.hasSameType(
  1363. FromType,
  1364. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1365. } else {
  1366. return false;
  1367. }
  1368. }
  1369. // Lvalue-to-rvalue conversion (C++11 4.1):
  1370. // A glvalue (3.10) of a non-function, non-array type T can
  1371. // be converted to a prvalue.
  1372. bool argIsLValue = From->isGLValue();
  1373. if (argIsLValue &&
  1374. !FromType->isFunctionType() && (!FromType->isArrayType() || S.getLangOpts().HLSL) && // HLSL Change - HLSL allows arrays
  1375. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1376. SCS.First = ICK_Lvalue_To_Rvalue;
  1377. // C11 6.3.2.1p2:
  1378. // ... if the lvalue has atomic type, the value has the non-atomic version
  1379. // of the type of the lvalue ...
  1380. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1381. FromType = Atomic->getValueType();
  1382. // If T is a non-class type, the type of the rvalue is the
  1383. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1384. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1385. // just strip the qualifiers because they don't matter.
  1386. FromType = FromType.getUnqualifiedType();
  1387. } else if (FromType->isArrayType()) {
  1388. // Array-to-pointer conversion (C++ 4.2)
  1389. SCS.First = ICK_Array_To_Pointer;
  1390. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1391. // bound of T" can be converted to an rvalue of type "pointer to
  1392. // T" (C++ 4.2p1).
  1393. FromType = S.Context.getArrayDecayedType(FromType);
  1394. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1395. // This conversion is deprecated in C++03 (D.4)
  1396. SCS.DeprecatedStringLiteralToCharPtr = true;
  1397. // For the purpose of ranking in overload resolution
  1398. // (13.3.3.1.1), this conversion is considered an
  1399. // array-to-pointer conversion followed by a qualification
  1400. // conversion (4.4). (C++ 4.2p2)
  1401. SCS.Second = ICK_Identity;
  1402. SCS.Third = ICK_Qualification;
  1403. SCS.QualificationIncludesObjCLifetime = false;
  1404. SCS.setAllToTypes(FromType);
  1405. return true;
  1406. }
  1407. } else if (FromType->isFunctionType() && argIsLValue) {
  1408. // Function-to-pointer conversion (C++ 4.3).
  1409. SCS.First = ICK_Function_To_Pointer;
  1410. // An lvalue of function type T can be converted to an rvalue of
  1411. // type "pointer to T." The result is a pointer to the
  1412. // function. (C++ 4.3p1).
  1413. FromType = S.Context.getPointerType(FromType);
  1414. } else {
  1415. // We don't require any conversions for the first step.
  1416. SCS.First = ICK_Identity;
  1417. }
  1418. SCS.setToType(0, FromType);
  1419. // The second conversion can be an integral promotion, floating
  1420. // point promotion, integral conversion, floating point conversion,
  1421. // floating-integral conversion, pointer conversion,
  1422. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1423. // For overloading in C, this can also be a "compatible-type"
  1424. // conversion.
  1425. bool IncompatibleObjC = false;
  1426. ImplicitConversionKind SecondICK = ICK_Identity;
  1427. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1428. // The unqualified versions of the types are the same: there's no
  1429. // conversion to do.
  1430. SCS.Second = ICK_Identity;
  1431. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1432. // Integral promotion (C++ 4.5).
  1433. SCS.Second = ICK_Integral_Promotion;
  1434. FromType = ToType.getUnqualifiedType();
  1435. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1436. // Floating point promotion (C++ 4.6).
  1437. SCS.Second = ICK_Floating_Promotion;
  1438. FromType = ToType.getUnqualifiedType();
  1439. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1440. // Complex promotion (Clang extension)
  1441. SCS.Second = ICK_Complex_Promotion;
  1442. FromType = ToType.getUnqualifiedType();
  1443. } else if (ToType->isBooleanType() &&
  1444. (FromType->isArithmeticType() ||
  1445. FromType->isAnyPointerType() ||
  1446. FromType->isBlockPointerType() ||
  1447. FromType->isMemberPointerType() ||
  1448. FromType->isNullPtrType())) {
  1449. // Boolean conversions (C++ 4.12).
  1450. SCS.Second = ICK_Boolean_Conversion;
  1451. FromType = S.Context.BoolTy;
  1452. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1453. ToType->isIntegralType(S.Context)) {
  1454. // Integral conversions (C++ 4.7).
  1455. SCS.Second = ICK_Integral_Conversion;
  1456. FromType = ToType.getUnqualifiedType();
  1457. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1458. // Complex conversions (C99 6.3.1.6)
  1459. SCS.Second = ICK_Complex_Conversion;
  1460. FromType = ToType.getUnqualifiedType();
  1461. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1462. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1463. // Complex-real conversions (C99 6.3.1.7)
  1464. SCS.Second = ICK_Complex_Real;
  1465. FromType = ToType.getUnqualifiedType();
  1466. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1467. // Floating point conversions (C++ 4.8).
  1468. SCS.Second = ICK_Floating_Conversion;
  1469. FromType = ToType.getUnqualifiedType();
  1470. } else if ((FromType->isRealFloatingType() &&
  1471. ToType->isIntegralType(S.Context)) ||
  1472. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1473. ToType->isRealFloatingType())) {
  1474. // Floating-integral conversions (C++ 4.9).
  1475. SCS.Second = ICK_Floating_Integral;
  1476. FromType = ToType.getUnqualifiedType();
  1477. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1478. SCS.Second = ICK_Block_Pointer_Conversion;
  1479. } else if (AllowObjCWritebackConversion &&
  1480. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1481. SCS.Second = ICK_Writeback_Conversion;
  1482. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1483. FromType, IncompatibleObjC)) {
  1484. // Pointer conversions (C++ 4.10).
  1485. SCS.Second = ICK_Pointer_Conversion;
  1486. SCS.IncompatibleObjC = IncompatibleObjC;
  1487. FromType = FromType.getUnqualifiedType();
  1488. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1489. InOverloadResolution, FromType)) {
  1490. // Pointer to member conversions (4.11).
  1491. SCS.Second = ICK_Pointer_Member;
  1492. } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
  1493. SCS.Second = SecondICK;
  1494. FromType = ToType.getUnqualifiedType();
  1495. } else if (!S.getLangOpts().CPlusPlus &&
  1496. S.Context.typesAreCompatible(ToType, FromType)) {
  1497. // Compatible conversions (Clang extension for C function overloading)
  1498. SCS.Second = ICK_Compatible_Conversion;
  1499. FromType = ToType.getUnqualifiedType();
  1500. } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
  1501. // Treat a conversion that strips "noreturn" as an identity conversion.
  1502. SCS.Second = ICK_NoReturn_Adjustment;
  1503. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1504. InOverloadResolution,
  1505. SCS, CStyle)) {
  1506. SCS.Second = ICK_TransparentUnionConversion;
  1507. FromType = ToType;
  1508. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1509. CStyle)) {
  1510. // tryAtomicConversion has updated the standard conversion sequence
  1511. // appropriately.
  1512. return true;
  1513. } else if (ToType->isEventT() &&
  1514. From->isIntegerConstantExpr(S.getASTContext()) &&
  1515. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1516. SCS.Second = ICK_Zero_Event_Conversion;
  1517. FromType = ToType;
  1518. } else {
  1519. // No second conversion required.
  1520. SCS.Second = ICK_Identity;
  1521. }
  1522. SCS.setToType(1, FromType);
  1523. QualType CanonFrom;
  1524. QualType CanonTo;
  1525. // The third conversion can be a qualification conversion (C++ 4p1).
  1526. bool ObjCLifetimeConversion;
  1527. if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1528. ObjCLifetimeConversion)) {
  1529. SCS.Third = ICK_Qualification;
  1530. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1531. FromType = ToType;
  1532. CanonFrom = S.Context.getCanonicalType(FromType);
  1533. CanonTo = S.Context.getCanonicalType(ToType);
  1534. } else {
  1535. // No conversion required
  1536. SCS.Third = ICK_Identity;
  1537. // C++ [over.best.ics]p6:
  1538. // [...] Any difference in top-level cv-qualification is
  1539. // subsumed by the initialization itself and does not constitute
  1540. // a conversion. [...]
  1541. CanonFrom = S.Context.getCanonicalType(FromType);
  1542. CanonTo = S.Context.getCanonicalType(ToType);
  1543. if (CanonFrom.getLocalUnqualifiedType()
  1544. == CanonTo.getLocalUnqualifiedType() &&
  1545. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1546. FromType = ToType;
  1547. CanonFrom = CanonTo;
  1548. }
  1549. }
  1550. SCS.setToType(2, FromType);
  1551. // If we have not converted the argument type to the parameter type,
  1552. // this is a bad conversion sequence.
  1553. if (CanonFrom != CanonTo)
  1554. return false;
  1555. return true;
  1556. }
  1557. static bool
  1558. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1559. QualType &ToType,
  1560. bool InOverloadResolution,
  1561. StandardConversionSequence &SCS,
  1562. bool CStyle) {
  1563. const RecordType *UT = ToType->getAsUnionType();
  1564. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1565. return false;
  1566. // The field to initialize within the transparent union.
  1567. RecordDecl *UD = UT->getDecl();
  1568. // It's compatible if the expression matches any of the fields.
  1569. for (const auto *it : UD->fields()) {
  1570. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1571. CStyle, /*ObjCWritebackConversion=*/false)) {
  1572. ToType = it->getType();
  1573. return true;
  1574. }
  1575. }
  1576. return false;
  1577. }
  1578. /// IsIntegralPromotion - Determines whether the conversion from the
  1579. /// expression From (whose potentially-adjusted type is FromType) to
  1580. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1581. /// sets PromotedType to the promoted type.
  1582. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1583. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1584. // All integers are built-in.
  1585. if (!To) {
  1586. return false;
  1587. }
  1588. // An rvalue of type char, signed char, unsigned char, short int, or
  1589. // unsigned short int can be converted to an rvalue of type int if
  1590. // int can represent all the values of the source type; otherwise,
  1591. // the source rvalue can be converted to an rvalue of type unsigned
  1592. // int (C++ 4.5p1).
  1593. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1594. !FromType->isEnumeralType()) {
  1595. if (// We can promote any signed, promotable integer type to an int
  1596. (FromType->isSignedIntegerType() ||
  1597. // We can promote any unsigned integer type whose size is
  1598. // less than int to an int.
  1599. (!FromType->isSignedIntegerType() &&
  1600. Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
  1601. return To->getKind() == BuiltinType::Int;
  1602. }
  1603. return To->getKind() == BuiltinType::UInt;
  1604. }
  1605. // C++11 [conv.prom]p3:
  1606. // A prvalue of an unscoped enumeration type whose underlying type is not
  1607. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1608. // following types that can represent all the values of the enumeration
  1609. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1610. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1611. // long long int. If none of the types in that list can represent all the
  1612. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1613. // type can be converted to an rvalue a prvalue of the extended integer type
  1614. // with lowest integer conversion rank (4.13) greater than the rank of long
  1615. // long in which all the values of the enumeration can be represented. If
  1616. // there are two such extended types, the signed one is chosen.
  1617. // C++11 [conv.prom]p4:
  1618. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  1619. // can be converted to a prvalue of its underlying type. Moreover, if
  1620. // integral promotion can be applied to its underlying type, a prvalue of an
  1621. // unscoped enumeration type whose underlying type is fixed can also be
  1622. // converted to a prvalue of the promoted underlying type.
  1623. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1624. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1625. // provided for a scoped enumeration.
  1626. if (FromEnumType->getDecl()->isScoped())
  1627. return false;
  1628. // We can perform an integral promotion to the underlying type of the enum,
  1629. // even if that's not the promoted type. Note that the check for promoting
  1630. // the underlying type is based on the type alone, and does not consider
  1631. // the bitfield-ness of the actual source expression.
  1632. if (FromEnumType->getDecl()->isFixed()) {
  1633. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  1634. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  1635. IsIntegralPromotion(nullptr, Underlying, ToType);
  1636. }
  1637. // We have already pre-calculated the promotion type, so this is trivial.
  1638. if (ToType->isIntegerType() &&
  1639. !RequireCompleteType(From->getLocStart(), FromType, 0))
  1640. return Context.hasSameUnqualifiedType(
  1641. ToType, FromEnumType->getDecl()->getPromotionType());
  1642. }
  1643. // C++0x [conv.prom]p2:
  1644. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1645. // to an rvalue a prvalue of the first of the following types that can
  1646. // represent all the values of its underlying type: int, unsigned int,
  1647. // long int, unsigned long int, long long int, or unsigned long long int.
  1648. // If none of the types in that list can represent all the values of its
  1649. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1650. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1651. // type.
  1652. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1653. ToType->isIntegerType()) {
  1654. // Determine whether the type we're converting from is signed or
  1655. // unsigned.
  1656. bool FromIsSigned = FromType->isSignedIntegerType();
  1657. uint64_t FromSize = Context.getTypeSize(FromType);
  1658. // The types we'll try to promote to, in the appropriate
  1659. // order. Try each of these types.
  1660. QualType PromoteTypes[6] = {
  1661. Context.IntTy, Context.UnsignedIntTy,
  1662. Context.LongTy, Context.UnsignedLongTy ,
  1663. Context.LongLongTy, Context.UnsignedLongLongTy
  1664. };
  1665. for (int Idx = 0; Idx < 6; ++Idx) {
  1666. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1667. if (FromSize < ToSize ||
  1668. (FromSize == ToSize &&
  1669. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1670. // We found the type that we can promote to. If this is the
  1671. // type we wanted, we have a promotion. Otherwise, no
  1672. // promotion.
  1673. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1674. }
  1675. }
  1676. }
  1677. // An rvalue for an integral bit-field (9.6) can be converted to an
  1678. // rvalue of type int if int can represent all the values of the
  1679. // bit-field; otherwise, it can be converted to unsigned int if
  1680. // unsigned int can represent all the values of the bit-field. If
  1681. // the bit-field is larger yet, no integral promotion applies to
  1682. // it. If the bit-field has an enumerated type, it is treated as any
  1683. // other value of that type for promotion purposes (C++ 4.5p3).
  1684. // FIXME: We should delay checking of bit-fields until we actually perform the
  1685. // conversion.
  1686. if (From) {
  1687. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  1688. llvm::APSInt BitWidth;
  1689. if (FromType->isIntegralType(Context) &&
  1690. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1691. llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1692. ToSize = Context.getTypeSize(ToType);
  1693. // Are we promoting to an int from a bitfield that fits in an int?
  1694. if (BitWidth < ToSize ||
  1695. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1696. return To->getKind() == BuiltinType::Int;
  1697. }
  1698. // Are we promoting to an unsigned int from an unsigned bitfield
  1699. // that fits into an unsigned int?
  1700. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1701. return To->getKind() == BuiltinType::UInt;
  1702. }
  1703. return false;
  1704. }
  1705. }
  1706. }
  1707. // An rvalue of type bool can be converted to an rvalue of type int,
  1708. // with false becoming zero and true becoming one (C++ 4.5p4).
  1709. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1710. return true;
  1711. }
  1712. return false;
  1713. }
  1714. /// IsFloatingPointPromotion - Determines whether the conversion from
  1715. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1716. /// returns true and sets PromotedType to the promoted type.
  1717. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1718. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1719. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1720. /// An rvalue of type float can be converted to an rvalue of type
  1721. /// double. (C++ 4.6p1).
  1722. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1723. ToBuiltin->getKind() == BuiltinType::Double)
  1724. return true;
  1725. // C99 6.3.1.5p1:
  1726. // When a float is promoted to double or long double, or a
  1727. // double is promoted to long double [...].
  1728. if (!getLangOpts().CPlusPlus &&
  1729. (FromBuiltin->getKind() == BuiltinType::Float ||
  1730. FromBuiltin->getKind() == BuiltinType::Double) &&
  1731. (ToBuiltin->getKind() == BuiltinType::LongDouble))
  1732. return true;
  1733. // Half can be promoted to float.
  1734. if (!getLangOpts().NativeHalfType &&
  1735. FromBuiltin->getKind() == BuiltinType::Half &&
  1736. ToBuiltin->getKind() == BuiltinType::Float)
  1737. return true;
  1738. // HLSL Change Starts
  1739. // TODO: Update this for new builtin types min16float, min16int, min16uint.
  1740. if (getLangOpts().HLSL) {
  1741. if (FromBuiltin->getKind() == BuiltinType::LitFloat &&
  1742. (ToBuiltin->getKind() == BuiltinType::Min10Float ||
  1743. ToBuiltin->getKind() == BuiltinType::HalfFloat ||
  1744. ToBuiltin->getKind() == BuiltinType::Float ||
  1745. ToBuiltin->getKind() == BuiltinType::Half ||
  1746. ToBuiltin->getKind() == BuiltinType::Double))
  1747. return true;
  1748. if (FromBuiltin->getKind() == BuiltinType::Min10Float &&
  1749. (ToBuiltin->getKind() == BuiltinType::Float ||
  1750. ToBuiltin->getKind() == BuiltinType::HalfFloat ||
  1751. ToBuiltin->getKind() == BuiltinType::Half ||
  1752. ToBuiltin->getKind() == BuiltinType::Double))
  1753. return true;
  1754. }
  1755. // HLSL Change Ends
  1756. }
  1757. return false;
  1758. }
  1759. /// \brief Determine if a conversion is a complex promotion.
  1760. ///
  1761. /// A complex promotion is defined as a complex -> complex conversion
  1762. /// where the conversion between the underlying real types is a
  1763. /// floating-point or integral promotion.
  1764. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1765. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1766. if (!FromComplex)
  1767. return false;
  1768. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1769. if (!ToComplex)
  1770. return false;
  1771. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1772. ToComplex->getElementType()) ||
  1773. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  1774. ToComplex->getElementType());
  1775. }
  1776. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1777. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1778. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1779. /// if non-empty, will be a pointer to ToType that may or may not have
  1780. /// the right set of qualifiers on its pointee.
  1781. ///
  1782. static QualType
  1783. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  1784. QualType ToPointee, QualType ToType,
  1785. ASTContext &Context,
  1786. bool StripObjCLifetime = false) {
  1787. assert((FromPtr->getTypeClass() == Type::Pointer ||
  1788. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  1789. "Invalid similarly-qualified pointer type");
  1790. /// Conversions to 'id' subsume cv-qualifier conversions.
  1791. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  1792. return ToType.getUnqualifiedType();
  1793. QualType CanonFromPointee
  1794. = Context.getCanonicalType(FromPtr->getPointeeType());
  1795. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  1796. Qualifiers Quals = CanonFromPointee.getQualifiers();
  1797. if (StripObjCLifetime)
  1798. Quals.removeObjCLifetime();
  1799. // Exact qualifier match -> return the pointer type we're converting to.
  1800. if (CanonToPointee.getLocalQualifiers() == Quals) {
  1801. // ToType is exactly what we need. Return it.
  1802. if (!ToType.isNull())
  1803. return ToType.getUnqualifiedType();
  1804. // Build a pointer to ToPointee. It has the right qualifiers
  1805. // already.
  1806. if (isa<ObjCObjectPointerType>(ToType))
  1807. return Context.getObjCObjectPointerType(ToPointee);
  1808. return Context.getPointerType(ToPointee);
  1809. }
  1810. // Just build a canonical type that has the right qualifiers.
  1811. QualType QualifiedCanonToPointee
  1812. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  1813. if (isa<ObjCObjectPointerType>(ToType))
  1814. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  1815. return Context.getPointerType(QualifiedCanonToPointee);
  1816. }
  1817. static bool isNullPointerConstantForConversion(Expr *Expr,
  1818. bool InOverloadResolution,
  1819. ASTContext &Context) {
  1820. // Handle value-dependent integral null pointer constants correctly.
  1821. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  1822. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  1823. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  1824. return !InOverloadResolution;
  1825. return Expr->isNullPointerConstant(Context,
  1826. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  1827. : Expr::NPC_ValueDependentIsNull);
  1828. }
  1829. /// IsPointerConversion - Determines whether the conversion of the
  1830. /// expression From, which has the (possibly adjusted) type FromType,
  1831. /// can be converted to the type ToType via a pointer conversion (C++
  1832. /// 4.10). If so, returns true and places the converted type (that
  1833. /// might differ from ToType in its cv-qualifiers at some level) into
  1834. /// ConvertedType.
  1835. ///
  1836. /// This routine also supports conversions to and from block pointers
  1837. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  1838. /// pointers to interfaces. FIXME: Once we've determined the
  1839. /// appropriate overloading rules for Objective-C, we may want to
  1840. /// split the Objective-C checks into a different routine; however,
  1841. /// GCC seems to consider all of these conversions to be pointer
  1842. /// conversions, so for now they live here. IncompatibleObjC will be
  1843. /// set if the conversion is an allowed Objective-C conversion that
  1844. /// should result in a warning.
  1845. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  1846. bool InOverloadResolution,
  1847. QualType& ConvertedType,
  1848. bool &IncompatibleObjC) {
  1849. IncompatibleObjC = false;
  1850. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  1851. IncompatibleObjC))
  1852. return true;
  1853. // Conversion from a null pointer constant to any Objective-C pointer type.
  1854. if (ToType->isObjCObjectPointerType() &&
  1855. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1856. ConvertedType = ToType;
  1857. return true;
  1858. }
  1859. // Blocks: Block pointers can be converted to void*.
  1860. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  1861. ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
  1862. ConvertedType = ToType;
  1863. return true;
  1864. }
  1865. // Blocks: A null pointer constant can be converted to a block
  1866. // pointer type.
  1867. if (ToType->isBlockPointerType() &&
  1868. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1869. ConvertedType = ToType;
  1870. return true;
  1871. }
  1872. // If the left-hand-side is nullptr_t, the right side can be a null
  1873. // pointer constant.
  1874. if (ToType->isNullPtrType() &&
  1875. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1876. ConvertedType = ToType;
  1877. return true;
  1878. }
  1879. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  1880. if (!ToTypePtr)
  1881. return false;
  1882. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  1883. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1884. ConvertedType = ToType;
  1885. return true;
  1886. }
  1887. // Beyond this point, both types need to be pointers
  1888. // , including objective-c pointers.
  1889. QualType ToPointeeType = ToTypePtr->getPointeeType();
  1890. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  1891. !getLangOpts().ObjCAutoRefCount) {
  1892. ConvertedType = BuildSimilarlyQualifiedPointerType(
  1893. FromType->getAs<ObjCObjectPointerType>(),
  1894. ToPointeeType,
  1895. ToType, Context);
  1896. return true;
  1897. }
  1898. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  1899. if (!FromTypePtr)
  1900. return false;
  1901. QualType FromPointeeType = FromTypePtr->getPointeeType();
  1902. // If the unqualified pointee types are the same, this can't be a
  1903. // pointer conversion, so don't do all of the work below.
  1904. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  1905. return false;
  1906. // An rvalue of type "pointer to cv T," where T is an object type,
  1907. // can be converted to an rvalue of type "pointer to cv void" (C++
  1908. // 4.10p2).
  1909. if (FromPointeeType->isIncompleteOrObjectType() &&
  1910. ToPointeeType->isVoidType()) {
  1911. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1912. ToPointeeType,
  1913. ToType, Context,
  1914. /*StripObjCLifetime=*/true);
  1915. return true;
  1916. }
  1917. // MSVC allows implicit function to void* type conversion.
  1918. if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
  1919. ToPointeeType->isVoidType()) {
  1920. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1921. ToPointeeType,
  1922. ToType, Context);
  1923. return true;
  1924. }
  1925. // When we're overloading in C, we allow a special kind of pointer
  1926. // conversion for compatible-but-not-identical pointee types.
  1927. if (!getLangOpts().CPlusPlus &&
  1928. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  1929. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1930. ToPointeeType,
  1931. ToType, Context);
  1932. return true;
  1933. }
  1934. // C++ [conv.ptr]p3:
  1935. //
  1936. // An rvalue of type "pointer to cv D," where D is a class type,
  1937. // can be converted to an rvalue of type "pointer to cv B," where
  1938. // B is a base class (clause 10) of D. If B is an inaccessible
  1939. // (clause 11) or ambiguous (10.2) base class of D, a program that
  1940. // necessitates this conversion is ill-formed. The result of the
  1941. // conversion is a pointer to the base class sub-object of the
  1942. // derived class object. The null pointer value is converted to
  1943. // the null pointer value of the destination type.
  1944. //
  1945. // Note that we do not check for ambiguity or inaccessibility
  1946. // here. That is handled by CheckPointerConversion.
  1947. if (getLangOpts().CPlusPlus &&
  1948. FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  1949. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  1950. !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
  1951. IsDerivedFrom(FromPointeeType, ToPointeeType)) {
  1952. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1953. ToPointeeType,
  1954. ToType, Context);
  1955. return true;
  1956. }
  1957. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  1958. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  1959. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1960. ToPointeeType,
  1961. ToType, Context);
  1962. return true;
  1963. }
  1964. return false;
  1965. }
  1966. /// \brief Adopt the given qualifiers for the given type.
  1967. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  1968. Qualifiers TQs = T.getQualifiers();
  1969. // Check whether qualifiers already match.
  1970. if (TQs == Qs)
  1971. return T;
  1972. if (Qs.compatiblyIncludes(TQs))
  1973. return Context.getQualifiedType(T, Qs);
  1974. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  1975. }
  1976. /// isObjCPointerConversion - Determines whether this is an
  1977. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  1978. /// with the same arguments and return values.
  1979. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  1980. QualType& ConvertedType,
  1981. bool &IncompatibleObjC) {
  1982. if (!getLangOpts().ObjC1)
  1983. return false;
  1984. // The set of qualifiers on the type we're converting from.
  1985. Qualifiers FromQualifiers = FromType.getQualifiers();
  1986. // First, we handle all conversions on ObjC object pointer types.
  1987. const ObjCObjectPointerType* ToObjCPtr =
  1988. ToType->getAs<ObjCObjectPointerType>();
  1989. const ObjCObjectPointerType *FromObjCPtr =
  1990. FromType->getAs<ObjCObjectPointerType>();
  1991. if (ToObjCPtr && FromObjCPtr) {
  1992. // If the pointee types are the same (ignoring qualifications),
  1993. // then this is not a pointer conversion.
  1994. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  1995. FromObjCPtr->getPointeeType()))
  1996. return false;
  1997. // Conversion between Objective-C pointers.
  1998. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  1999. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  2000. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  2001. if (getLangOpts().CPlusPlus && LHS && RHS &&
  2002. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  2003. FromObjCPtr->getPointeeType()))
  2004. return false;
  2005. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2006. ToObjCPtr->getPointeeType(),
  2007. ToType, Context);
  2008. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2009. return true;
  2010. }
  2011. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2012. // Okay: this is some kind of implicit downcast of Objective-C
  2013. // interfaces, which is permitted. However, we're going to
  2014. // complain about it.
  2015. IncompatibleObjC = true;
  2016. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2017. ToObjCPtr->getPointeeType(),
  2018. ToType, Context);
  2019. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2020. return true;
  2021. }
  2022. }
  2023. // Beyond this point, both types need to be C pointers or block pointers.
  2024. QualType ToPointeeType;
  2025. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2026. ToPointeeType = ToCPtr->getPointeeType();
  2027. else if (const BlockPointerType *ToBlockPtr =
  2028. ToType->getAs<BlockPointerType>()) {
  2029. // Objective C++: We're able to convert from a pointer to any object
  2030. // to a block pointer type.
  2031. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2032. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2033. return true;
  2034. }
  2035. ToPointeeType = ToBlockPtr->getPointeeType();
  2036. }
  2037. else if (FromType->getAs<BlockPointerType>() &&
  2038. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2039. // Objective C++: We're able to convert from a block pointer type to a
  2040. // pointer to any object.
  2041. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2042. return true;
  2043. }
  2044. else
  2045. return false;
  2046. QualType FromPointeeType;
  2047. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2048. FromPointeeType = FromCPtr->getPointeeType();
  2049. else if (const BlockPointerType *FromBlockPtr =
  2050. FromType->getAs<BlockPointerType>())
  2051. FromPointeeType = FromBlockPtr->getPointeeType();
  2052. else
  2053. return false;
  2054. // If we have pointers to pointers, recursively check whether this
  2055. // is an Objective-C conversion.
  2056. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2057. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2058. IncompatibleObjC)) {
  2059. // We always complain about this conversion.
  2060. IncompatibleObjC = true;
  2061. ConvertedType = Context.getPointerType(ConvertedType);
  2062. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2063. return true;
  2064. }
  2065. // Allow conversion of pointee being objective-c pointer to another one;
  2066. // as in I* to id.
  2067. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2068. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2069. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2070. IncompatibleObjC)) {
  2071. ConvertedType = Context.getPointerType(ConvertedType);
  2072. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2073. return true;
  2074. }
  2075. // If we have pointers to functions or blocks, check whether the only
  2076. // differences in the argument and result types are in Objective-C
  2077. // pointer conversions. If so, we permit the conversion (but
  2078. // complain about it).
  2079. const FunctionProtoType *FromFunctionType
  2080. = FromPointeeType->getAs<FunctionProtoType>();
  2081. const FunctionProtoType *ToFunctionType
  2082. = ToPointeeType->getAs<FunctionProtoType>();
  2083. if (FromFunctionType && ToFunctionType) {
  2084. // If the function types are exactly the same, this isn't an
  2085. // Objective-C pointer conversion.
  2086. if (Context.getCanonicalType(FromPointeeType)
  2087. == Context.getCanonicalType(ToPointeeType))
  2088. return false;
  2089. // Perform the quick checks that will tell us whether these
  2090. // function types are obviously different.
  2091. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2092. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2093. FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
  2094. return false;
  2095. bool HasObjCConversion = false;
  2096. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2097. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2098. // Okay, the types match exactly. Nothing to do.
  2099. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2100. ToFunctionType->getReturnType(),
  2101. ConvertedType, IncompatibleObjC)) {
  2102. // Okay, we have an Objective-C pointer conversion.
  2103. HasObjCConversion = true;
  2104. } else {
  2105. // Function types are too different. Abort.
  2106. return false;
  2107. }
  2108. // Check argument types.
  2109. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2110. ArgIdx != NumArgs; ++ArgIdx) {
  2111. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2112. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2113. if (Context.getCanonicalType(FromArgType)
  2114. == Context.getCanonicalType(ToArgType)) {
  2115. // Okay, the types match exactly. Nothing to do.
  2116. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2117. ConvertedType, IncompatibleObjC)) {
  2118. // Okay, we have an Objective-C pointer conversion.
  2119. HasObjCConversion = true;
  2120. } else {
  2121. // Argument types are too different. Abort.
  2122. return false;
  2123. }
  2124. }
  2125. if (HasObjCConversion) {
  2126. // We had an Objective-C conversion. Allow this pointer
  2127. // conversion, but complain about it.
  2128. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2129. IncompatibleObjC = true;
  2130. return true;
  2131. }
  2132. }
  2133. return false;
  2134. }
  2135. /// \brief Determine whether this is an Objective-C writeback conversion,
  2136. /// used for parameter passing when performing automatic reference counting.
  2137. ///
  2138. /// \param FromType The type we're converting form.
  2139. ///
  2140. /// \param ToType The type we're converting to.
  2141. ///
  2142. /// \param ConvertedType The type that will be produced after applying
  2143. /// this conversion.
  2144. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2145. QualType &ConvertedType) {
  2146. if (!getLangOpts().ObjCAutoRefCount ||
  2147. Context.hasSameUnqualifiedType(FromType, ToType))
  2148. return false;
  2149. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2150. QualType ToPointee;
  2151. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2152. ToPointee = ToPointer->getPointeeType();
  2153. else
  2154. return false;
  2155. Qualifiers ToQuals = ToPointee.getQualifiers();
  2156. if (!ToPointee->isObjCLifetimeType() ||
  2157. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2158. !ToQuals.withoutObjCLifetime().empty())
  2159. return false;
  2160. // Argument must be a pointer to __strong to __weak.
  2161. QualType FromPointee;
  2162. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2163. FromPointee = FromPointer->getPointeeType();
  2164. else
  2165. return false;
  2166. Qualifiers FromQuals = FromPointee.getQualifiers();
  2167. if (!FromPointee->isObjCLifetimeType() ||
  2168. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2169. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2170. return false;
  2171. // Make sure that we have compatible qualifiers.
  2172. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2173. if (!ToQuals.compatiblyIncludes(FromQuals))
  2174. return false;
  2175. // Remove qualifiers from the pointee type we're converting from; they
  2176. // aren't used in the compatibility check belong, and we'll be adding back
  2177. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2178. FromPointee = FromPointee.getUnqualifiedType();
  2179. // The unqualified form of the pointee types must be compatible.
  2180. ToPointee = ToPointee.getUnqualifiedType();
  2181. bool IncompatibleObjC;
  2182. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2183. FromPointee = ToPointee;
  2184. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2185. IncompatibleObjC))
  2186. return false;
  2187. /// \brief Construct the type we're converting to, which is a pointer to
  2188. /// __autoreleasing pointee.
  2189. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2190. ConvertedType = Context.getPointerType(FromPointee);
  2191. return true;
  2192. }
  2193. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2194. QualType& ConvertedType) {
  2195. QualType ToPointeeType;
  2196. if (const BlockPointerType *ToBlockPtr =
  2197. ToType->getAs<BlockPointerType>())
  2198. ToPointeeType = ToBlockPtr->getPointeeType();
  2199. else
  2200. return false;
  2201. QualType FromPointeeType;
  2202. if (const BlockPointerType *FromBlockPtr =
  2203. FromType->getAs<BlockPointerType>())
  2204. FromPointeeType = FromBlockPtr->getPointeeType();
  2205. else
  2206. return false;
  2207. // We have pointer to blocks, check whether the only
  2208. // differences in the argument and result types are in Objective-C
  2209. // pointer conversions. If so, we permit the conversion.
  2210. const FunctionProtoType *FromFunctionType
  2211. = FromPointeeType->getAs<FunctionProtoType>();
  2212. const FunctionProtoType *ToFunctionType
  2213. = ToPointeeType->getAs<FunctionProtoType>();
  2214. if (!FromFunctionType || !ToFunctionType)
  2215. return false;
  2216. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2217. return true;
  2218. // Perform the quick checks that will tell us whether these
  2219. // function types are obviously different.
  2220. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2221. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2222. return false;
  2223. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2224. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2225. if (FromEInfo != ToEInfo)
  2226. return false;
  2227. bool IncompatibleObjC = false;
  2228. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2229. ToFunctionType->getReturnType())) {
  2230. // Okay, the types match exactly. Nothing to do.
  2231. } else {
  2232. QualType RHS = FromFunctionType->getReturnType();
  2233. QualType LHS = ToFunctionType->getReturnType();
  2234. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2235. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2236. LHS = LHS.getUnqualifiedType();
  2237. if (Context.hasSameType(RHS,LHS)) {
  2238. // OK exact match.
  2239. } else if (isObjCPointerConversion(RHS, LHS,
  2240. ConvertedType, IncompatibleObjC)) {
  2241. if (IncompatibleObjC)
  2242. return false;
  2243. // Okay, we have an Objective-C pointer conversion.
  2244. }
  2245. else
  2246. return false;
  2247. }
  2248. // Check argument types.
  2249. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2250. ArgIdx != NumArgs; ++ArgIdx) {
  2251. IncompatibleObjC = false;
  2252. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2253. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2254. if (Context.hasSameType(FromArgType, ToArgType)) {
  2255. // Okay, the types match exactly. Nothing to do.
  2256. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2257. ConvertedType, IncompatibleObjC)) {
  2258. if (IncompatibleObjC)
  2259. return false;
  2260. // Okay, we have an Objective-C pointer conversion.
  2261. } else
  2262. // Argument types are too different. Abort.
  2263. return false;
  2264. }
  2265. if (LangOpts.ObjCAutoRefCount &&
  2266. !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
  2267. ToFunctionType))
  2268. return false;
  2269. ConvertedType = ToType;
  2270. return true;
  2271. }
  2272. enum {
  2273. ft_default,
  2274. ft_different_class,
  2275. ft_parameter_arity,
  2276. ft_parameter_mismatch,
  2277. ft_return_type,
  2278. ft_qualifer_mismatch
  2279. };
  2280. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2281. /// function types. Catches different number of parameter, mismatch in
  2282. /// parameter types, and different return types.
  2283. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2284. QualType FromType, QualType ToType) {
  2285. // If either type is not valid, include no extra info.
  2286. if (FromType.isNull() || ToType.isNull()) {
  2287. PDiag << ft_default;
  2288. return;
  2289. }
  2290. // Get the function type from the pointers.
  2291. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2292. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2293. *ToMember = ToType->getAs<MemberPointerType>();
  2294. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2295. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2296. << QualType(FromMember->getClass(), 0);
  2297. return;
  2298. }
  2299. FromType = FromMember->getPointeeType();
  2300. ToType = ToMember->getPointeeType();
  2301. }
  2302. if (FromType->isPointerType())
  2303. FromType = FromType->getPointeeType();
  2304. if (ToType->isPointerType())
  2305. ToType = ToType->getPointeeType();
  2306. // Remove references.
  2307. FromType = FromType.getNonReferenceType();
  2308. ToType = ToType.getNonReferenceType();
  2309. // Don't print extra info for non-specialized template functions.
  2310. if (FromType->isInstantiationDependentType() &&
  2311. !FromType->getAs<TemplateSpecializationType>()) {
  2312. PDiag << ft_default;
  2313. return;
  2314. }
  2315. // No extra info for same types.
  2316. if (Context.hasSameType(FromType, ToType)) {
  2317. PDiag << ft_default;
  2318. return;
  2319. }
  2320. const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
  2321. *ToFunction = ToType->getAs<FunctionProtoType>();
  2322. // Both types need to be function types.
  2323. if (!FromFunction || !ToFunction) {
  2324. PDiag << ft_default;
  2325. return;
  2326. }
  2327. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2328. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2329. << FromFunction->getNumParams();
  2330. return;
  2331. }
  2332. // Handle different parameter types.
  2333. unsigned ArgPos;
  2334. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2335. PDiag << ft_parameter_mismatch << ArgPos + 1
  2336. << ToFunction->getParamType(ArgPos)
  2337. << FromFunction->getParamType(ArgPos);
  2338. return;
  2339. }
  2340. // Handle different return type.
  2341. if (!Context.hasSameType(FromFunction->getReturnType(),
  2342. ToFunction->getReturnType())) {
  2343. PDiag << ft_return_type << ToFunction->getReturnType()
  2344. << FromFunction->getReturnType();
  2345. return;
  2346. }
  2347. unsigned FromQuals = FromFunction->getTypeQuals(),
  2348. ToQuals = ToFunction->getTypeQuals();
  2349. if (FromQuals != ToQuals) {
  2350. PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
  2351. return;
  2352. }
  2353. // Unable to find a difference, so add no extra info.
  2354. PDiag << ft_default;
  2355. }
  2356. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2357. /// for equality of their argument types. Caller has already checked that
  2358. /// they have same number of arguments. If the parameters are different,
  2359. /// ArgPos will have the parameter index of the first different parameter.
  2360. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2361. const FunctionProtoType *NewType,
  2362. unsigned *ArgPos) {
  2363. int index = 0;
  2364. for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
  2365. N = NewType->param_type_begin(),
  2366. E = OldType->param_type_end();
  2367. O && (O != E); ++O, ++N) {
  2368. if (!Context.hasSameType(O->getUnqualifiedType(),
  2369. N->getUnqualifiedType())
  2370. || OldType->getParamMods()[index] != NewType->getParamMods()[index]) { // HLSL Change - check param mods
  2371. index++;
  2372. if (ArgPos)
  2373. *ArgPos = O - OldType->param_type_begin();
  2374. return false;
  2375. }
  2376. }
  2377. return true;
  2378. }
  2379. /// CheckPointerConversion - Check the pointer conversion from the
  2380. /// expression From to the type ToType. This routine checks for
  2381. /// ambiguous or inaccessible derived-to-base pointer
  2382. /// conversions for which IsPointerConversion has already returned
  2383. /// true. It returns true and produces a diagnostic if there was an
  2384. /// error, or returns false otherwise.
  2385. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2386. CastKind &Kind,
  2387. CXXCastPath& BasePath,
  2388. bool IgnoreBaseAccess) {
  2389. QualType FromType = From->getType();
  2390. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2391. Kind = CK_BitCast;
  2392. if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2393. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2394. Expr::NPCK_ZeroExpression) {
  2395. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2396. DiagRuntimeBehavior(From->getExprLoc(), From,
  2397. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2398. << ToType << From->getSourceRange());
  2399. else if (!isUnevaluatedContext())
  2400. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2401. << ToType << From->getSourceRange();
  2402. }
  2403. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2404. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2405. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2406. ToPointeeType = ToPtrType->getPointeeType();
  2407. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2408. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2409. // We must have a derived-to-base conversion. Check an
  2410. // ambiguous or inaccessible conversion.
  2411. if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
  2412. From->getExprLoc(),
  2413. From->getSourceRange(), &BasePath,
  2414. IgnoreBaseAccess))
  2415. return true;
  2416. // The conversion was successful.
  2417. Kind = CK_DerivedToBase;
  2418. }
  2419. }
  2420. } else if (const ObjCObjectPointerType *ToPtrType =
  2421. ToType->getAs<ObjCObjectPointerType>()) {
  2422. if (const ObjCObjectPointerType *FromPtrType =
  2423. FromType->getAs<ObjCObjectPointerType>()) {
  2424. // Objective-C++ conversions are always okay.
  2425. // FIXME: We should have a different class of conversions for the
  2426. // Objective-C++ implicit conversions.
  2427. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2428. return false;
  2429. } else if (FromType->isBlockPointerType()) {
  2430. Kind = CK_BlockPointerToObjCPointerCast;
  2431. } else {
  2432. Kind = CK_CPointerToObjCPointerCast;
  2433. }
  2434. } else if (ToType->isBlockPointerType()) {
  2435. if (!FromType->isBlockPointerType())
  2436. Kind = CK_AnyPointerToBlockPointerCast;
  2437. }
  2438. // We shouldn't fall into this case unless it's valid for other
  2439. // reasons.
  2440. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2441. Kind = CK_NullToPointer;
  2442. return false;
  2443. }
  2444. /// IsMemberPointerConversion - Determines whether the conversion of the
  2445. /// expression From, which has the (possibly adjusted) type FromType, can be
  2446. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2447. /// If so, returns true and places the converted type (that might differ from
  2448. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2449. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2450. QualType ToType,
  2451. bool InOverloadResolution,
  2452. QualType &ConvertedType) {
  2453. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2454. if (!ToTypePtr)
  2455. return false;
  2456. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2457. if (From->isNullPointerConstant(Context,
  2458. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2459. : Expr::NPC_ValueDependentIsNull)) {
  2460. ConvertedType = ToType;
  2461. return true;
  2462. }
  2463. // Otherwise, both types have to be member pointers.
  2464. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2465. if (!FromTypePtr)
  2466. return false;
  2467. // A pointer to member of B can be converted to a pointer to member of D,
  2468. // where D is derived from B (C++ 4.11p2).
  2469. QualType FromClass(FromTypePtr->getClass(), 0);
  2470. QualType ToClass(ToTypePtr->getClass(), 0);
  2471. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2472. !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
  2473. IsDerivedFrom(ToClass, FromClass)) {
  2474. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2475. ToClass.getTypePtr());
  2476. return true;
  2477. }
  2478. return false;
  2479. }
  2480. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2481. /// expression From to the type ToType. This routine checks for ambiguous or
  2482. /// virtual or inaccessible base-to-derived member pointer conversions
  2483. /// for which IsMemberPointerConversion has already returned true. It returns
  2484. /// true and produces a diagnostic if there was an error, or returns false
  2485. /// otherwise.
  2486. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2487. CastKind &Kind,
  2488. CXXCastPath &BasePath,
  2489. bool IgnoreBaseAccess) {
  2490. QualType FromType = From->getType();
  2491. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2492. if (!FromPtrType) {
  2493. // This must be a null pointer to member pointer conversion
  2494. assert(From->isNullPointerConstant(Context,
  2495. Expr::NPC_ValueDependentIsNull) &&
  2496. "Expr must be null pointer constant!");
  2497. Kind = CK_NullToMemberPointer;
  2498. return false;
  2499. }
  2500. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2501. assert(ToPtrType && "No member pointer cast has a target type "
  2502. "that is not a member pointer.");
  2503. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2504. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2505. // FIXME: What about dependent types?
  2506. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2507. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2508. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2509. /*DetectVirtual=*/true);
  2510. bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
  2511. assert(DerivationOkay &&
  2512. "Should not have been called if derivation isn't OK.");
  2513. (void)DerivationOkay;
  2514. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2515. getUnqualifiedType())) {
  2516. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2517. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2518. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2519. return true;
  2520. }
  2521. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2522. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2523. << FromClass << ToClass << QualType(VBase, 0)
  2524. << From->getSourceRange();
  2525. return true;
  2526. }
  2527. if (!IgnoreBaseAccess)
  2528. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2529. Paths.front(),
  2530. diag::err_downcast_from_inaccessible_base);
  2531. // Must be a base to derived member conversion.
  2532. BuildBasePathArray(Paths, BasePath);
  2533. Kind = CK_BaseToDerivedMemberPointer;
  2534. return false;
  2535. }
  2536. /// Determine whether the lifetime conversion between the two given
  2537. /// qualifiers sets is nontrivial.
  2538. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2539. Qualifiers ToQuals) {
  2540. // Converting anything to const __unsafe_unretained is trivial.
  2541. if (ToQuals.hasConst() &&
  2542. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2543. return false;
  2544. return true;
  2545. }
  2546. /// IsQualificationConversion - Determines whether the conversion from
  2547. /// an rvalue of type FromType to ToType is a qualification conversion
  2548. /// (C++ 4.4).
  2549. ///
  2550. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2551. /// when the qualification conversion involves a change in the Objective-C
  2552. /// object lifetime.
  2553. bool
  2554. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2555. bool CStyle, bool &ObjCLifetimeConversion) {
  2556. FromType = Context.getCanonicalType(FromType);
  2557. ToType = Context.getCanonicalType(ToType);
  2558. ObjCLifetimeConversion = false;
  2559. // If FromType and ToType are the same type, this is not a
  2560. // qualification conversion.
  2561. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2562. return false;
  2563. // (C++ 4.4p4):
  2564. // A conversion can add cv-qualifiers at levels other than the first
  2565. // in multi-level pointers, subject to the following rules: [...]
  2566. bool PreviousToQualsIncludeConst = true;
  2567. bool UnwrappedAnyPointer = false;
  2568. while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
  2569. // Within each iteration of the loop, we check the qualifiers to
  2570. // determine if this still looks like a qualification
  2571. // conversion. Then, if all is well, we unwrap one more level of
  2572. // pointers or pointers-to-members and do it all again
  2573. // until there are no more pointers or pointers-to-members left to
  2574. // unwrap.
  2575. UnwrappedAnyPointer = true;
  2576. Qualifiers FromQuals = FromType.getQualifiers();
  2577. Qualifiers ToQuals = ToType.getQualifiers();
  2578. // Objective-C ARC:
  2579. // Check Objective-C lifetime conversions.
  2580. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2581. UnwrappedAnyPointer) {
  2582. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2583. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2584. ObjCLifetimeConversion = true;
  2585. FromQuals.removeObjCLifetime();
  2586. ToQuals.removeObjCLifetime();
  2587. } else {
  2588. // Qualification conversions cannot cast between different
  2589. // Objective-C lifetime qualifiers.
  2590. return false;
  2591. }
  2592. }
  2593. // Allow addition/removal of GC attributes but not changing GC attributes.
  2594. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2595. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2596. FromQuals.removeObjCGCAttr();
  2597. ToQuals.removeObjCGCAttr();
  2598. }
  2599. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2600. // 2,j, and similarly for volatile.
  2601. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2602. return false;
  2603. // -- if the cv 1,j and cv 2,j are different, then const is in
  2604. // every cv for 0 < k < j.
  2605. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2606. && !PreviousToQualsIncludeConst)
  2607. return false;
  2608. // Keep track of whether all prior cv-qualifiers in the "to" type
  2609. // include const.
  2610. PreviousToQualsIncludeConst
  2611. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2612. }
  2613. // We are left with FromType and ToType being the pointee types
  2614. // after unwrapping the original FromType and ToType the same number
  2615. // of types. If we unwrapped any pointers, and if FromType and
  2616. // ToType have the same unqualified type (since we checked
  2617. // qualifiers above), then this is a qualification conversion.
  2618. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2619. }
  2620. /// \brief - Determine whether this is a conversion from a scalar type to an
  2621. /// atomic type.
  2622. ///
  2623. /// If successful, updates \c SCS's second and third steps in the conversion
  2624. /// sequence to finish the conversion.
  2625. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2626. bool InOverloadResolution,
  2627. StandardConversionSequence &SCS,
  2628. bool CStyle) {
  2629. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2630. if (!ToAtomic)
  2631. return false;
  2632. StandardConversionSequence InnerSCS;
  2633. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2634. InOverloadResolution, InnerSCS,
  2635. CStyle, /*AllowObjCWritebackConversion=*/false))
  2636. return false;
  2637. SCS.Second = InnerSCS.Second;
  2638. SCS.setToType(1, InnerSCS.getToType(1));
  2639. SCS.Third = InnerSCS.Third;
  2640. SCS.QualificationIncludesObjCLifetime
  2641. = InnerSCS.QualificationIncludesObjCLifetime;
  2642. SCS.setToType(2, InnerSCS.getToType(2));
  2643. return true;
  2644. }
  2645. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2646. CXXConstructorDecl *Constructor,
  2647. QualType Type) {
  2648. const FunctionProtoType *CtorType =
  2649. Constructor->getType()->getAs<FunctionProtoType>();
  2650. if (CtorType->getNumParams() > 0) {
  2651. QualType FirstArg = CtorType->getParamType(0);
  2652. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2653. return true;
  2654. }
  2655. return false;
  2656. }
  2657. static OverloadingResult
  2658. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2659. CXXRecordDecl *To,
  2660. UserDefinedConversionSequence &User,
  2661. OverloadCandidateSet &CandidateSet,
  2662. bool AllowExplicit) {
  2663. DeclContext::lookup_result R = S.LookupConstructors(To);
  2664. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2665. Con != ConEnd; ++Con) {
  2666. NamedDecl *D = *Con;
  2667. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2668. // Find the constructor (which may be a template).
  2669. CXXConstructorDecl *Constructor = nullptr;
  2670. FunctionTemplateDecl *ConstructorTmpl
  2671. = dyn_cast<FunctionTemplateDecl>(D);
  2672. if (ConstructorTmpl)
  2673. Constructor
  2674. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2675. else
  2676. Constructor = cast<CXXConstructorDecl>(D);
  2677. bool Usable = !Constructor->isInvalidDecl() &&
  2678. S.isInitListConstructor(Constructor) &&
  2679. (AllowExplicit || !Constructor->isExplicit());
  2680. if (Usable) {
  2681. // If the first argument is (a reference to) the target type,
  2682. // suppress conversions.
  2683. bool SuppressUserConversions =
  2684. isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
  2685. if (ConstructorTmpl)
  2686. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2687. /*ExplicitArgs*/ nullptr,
  2688. From, CandidateSet,
  2689. SuppressUserConversions);
  2690. else
  2691. S.AddOverloadCandidate(Constructor, FoundDecl,
  2692. From, CandidateSet,
  2693. SuppressUserConversions);
  2694. }
  2695. }
  2696. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2697. OverloadCandidateSet::iterator Best;
  2698. switch (auto Result =
  2699. CandidateSet.BestViableFunction(S, From->getLocStart(),
  2700. Best, true)) {
  2701. case OR_Deleted:
  2702. case OR_Success: {
  2703. // Record the standard conversion we used and the conversion function.
  2704. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2705. QualType ThisType = Constructor->getThisType(S.Context);
  2706. // Initializer lists don't have conversions as such.
  2707. User.Before.setAsIdentityConversion();
  2708. User.HadMultipleCandidates = HadMultipleCandidates;
  2709. User.ConversionFunction = Constructor;
  2710. User.FoundConversionFunction = Best->FoundDecl;
  2711. User.After.setAsIdentityConversion();
  2712. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2713. User.After.setAllToTypes(ToType);
  2714. return Result;
  2715. }
  2716. case OR_No_Viable_Function:
  2717. return OR_No_Viable_Function;
  2718. case OR_Ambiguous:
  2719. return OR_Ambiguous;
  2720. }
  2721. llvm_unreachable("Invalid OverloadResult!");
  2722. }
  2723. /// Determines whether there is a user-defined conversion sequence
  2724. /// (C++ [over.ics.user]) that converts expression From to the type
  2725. /// ToType. If such a conversion exists, User will contain the
  2726. /// user-defined conversion sequence that performs such a conversion
  2727. /// and this routine will return true. Otherwise, this routine returns
  2728. /// false and User is unspecified.
  2729. ///
  2730. /// \param AllowExplicit true if the conversion should consider C++0x
  2731. /// "explicit" conversion functions as well as non-explicit conversion
  2732. /// functions (C++0x [class.conv.fct]p2).
  2733. ///
  2734. /// \param AllowObjCConversionOnExplicit true if the conversion should
  2735. /// allow an extra Objective-C pointer conversion on uses of explicit
  2736. /// constructors. Requires \c AllowExplicit to also be set.
  2737. static OverloadingResult
  2738. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2739. UserDefinedConversionSequence &User,
  2740. OverloadCandidateSet &CandidateSet,
  2741. bool AllowExplicit,
  2742. bool AllowObjCConversionOnExplicit) {
  2743. assert(AllowExplicit || !AllowObjCConversionOnExplicit);
  2744. // Whether we will only visit constructors.
  2745. bool ConstructorsOnly = false;
  2746. // If the type we are conversion to is a class type, enumerate its
  2747. // constructors.
  2748. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2749. // C++ [over.match.ctor]p1:
  2750. // When objects of class type are direct-initialized (8.5), or
  2751. // copy-initialized from an expression of the same or a
  2752. // derived class type (8.5), overload resolution selects the
  2753. // constructor. [...] For copy-initialization, the candidate
  2754. // functions are all the converting constructors (12.3.1) of
  2755. // that class. The argument list is the expression-list within
  2756. // the parentheses of the initializer.
  2757. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  2758. (From->getType()->getAs<RecordType>() &&
  2759. S.IsDerivedFrom(From->getType(), ToType)))
  2760. ConstructorsOnly = true;
  2761. S.RequireCompleteType(From->getExprLoc(), ToType, 0);
  2762. // RequireCompleteType may have returned true due to some invalid decl
  2763. // during template instantiation, but ToType may be complete enough now
  2764. // to try to recover.
  2765. if (ToType->isIncompleteType()) {
  2766. // We're not going to find any constructors.
  2767. } else if (CXXRecordDecl *ToRecordDecl
  2768. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  2769. Expr **Args = &From;
  2770. unsigned NumArgs = 1;
  2771. bool ListInitializing = false;
  2772. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  2773. // But first, see if there is an init-list-constructor that will work.
  2774. OverloadingResult Result = IsInitializerListConstructorConversion(
  2775. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  2776. if (Result != OR_No_Viable_Function)
  2777. return Result;
  2778. // Never mind.
  2779. CandidateSet.clear();
  2780. // If we're list-initializing, we pass the individual elements as
  2781. // arguments, not the entire list.
  2782. Args = InitList->getInits();
  2783. NumArgs = InitList->getNumInits();
  2784. ListInitializing = true;
  2785. }
  2786. DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
  2787. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2788. Con != ConEnd; ++Con) {
  2789. NamedDecl *D = *Con;
  2790. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2791. // Find the constructor (which may be a template).
  2792. CXXConstructorDecl *Constructor = nullptr;
  2793. FunctionTemplateDecl *ConstructorTmpl
  2794. = dyn_cast<FunctionTemplateDecl>(D);
  2795. if (ConstructorTmpl)
  2796. Constructor
  2797. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2798. else
  2799. Constructor = cast<CXXConstructorDecl>(D);
  2800. bool Usable = !Constructor->isInvalidDecl();
  2801. if (ListInitializing)
  2802. Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
  2803. else
  2804. Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
  2805. if (Usable) {
  2806. bool SuppressUserConversions = !ConstructorsOnly;
  2807. if (SuppressUserConversions && ListInitializing) {
  2808. SuppressUserConversions = false;
  2809. if (NumArgs == 1) {
  2810. // If the first argument is (a reference to) the target type,
  2811. // suppress conversions.
  2812. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2813. S.Context, Constructor, ToType);
  2814. }
  2815. }
  2816. if (ConstructorTmpl)
  2817. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2818. /*ExplicitArgs*/ nullptr,
  2819. llvm::makeArrayRef(Args, NumArgs),
  2820. CandidateSet, SuppressUserConversions);
  2821. else
  2822. // Allow one user-defined conversion when user specifies a
  2823. // From->ToType conversion via an static cast (c-style, etc).
  2824. S.AddOverloadCandidate(Constructor, FoundDecl,
  2825. llvm::makeArrayRef(Args, NumArgs),
  2826. CandidateSet, SuppressUserConversions);
  2827. }
  2828. }
  2829. }
  2830. }
  2831. // Enumerate conversion functions, if we're allowed to.
  2832. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  2833. } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
  2834. // No conversion functions from incomplete types.
  2835. } else if (const RecordType *FromRecordType
  2836. = From->getType()->getAs<RecordType>()) {
  2837. if (CXXRecordDecl *FromRecordDecl
  2838. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  2839. // Add all of the conversion functions as candidates.
  2840. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  2841. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  2842. DeclAccessPair FoundDecl = I.getPair();
  2843. NamedDecl *D = FoundDecl.getDecl();
  2844. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  2845. if (isa<UsingShadowDecl>(D))
  2846. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2847. CXXConversionDecl *Conv;
  2848. FunctionTemplateDecl *ConvTemplate;
  2849. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  2850. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  2851. else
  2852. Conv = cast<CXXConversionDecl>(D);
  2853. if (AllowExplicit || !Conv->isExplicit()) {
  2854. if (ConvTemplate)
  2855. S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
  2856. ActingContext, From, ToType,
  2857. CandidateSet,
  2858. AllowObjCConversionOnExplicit);
  2859. else
  2860. S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
  2861. From, ToType, CandidateSet,
  2862. AllowObjCConversionOnExplicit);
  2863. }
  2864. }
  2865. }
  2866. }
  2867. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2868. OverloadCandidateSet::iterator Best;
  2869. switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
  2870. Best, true)) {
  2871. case OR_Success:
  2872. case OR_Deleted:
  2873. // Record the standard conversion we used and the conversion function.
  2874. if (CXXConstructorDecl *Constructor
  2875. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  2876. // C++ [over.ics.user]p1:
  2877. // If the user-defined conversion is specified by a
  2878. // constructor (12.3.1), the initial standard conversion
  2879. // sequence converts the source type to the type required by
  2880. // the argument of the constructor.
  2881. //
  2882. QualType ThisType = Constructor->getThisType(S.Context);
  2883. if (isa<InitListExpr>(From)) {
  2884. // Initializer lists don't have conversions as such.
  2885. User.Before.setAsIdentityConversion();
  2886. } else {
  2887. if (Best->Conversions[0].isEllipsis())
  2888. User.EllipsisConversion = true;
  2889. else {
  2890. User.Before = Best->Conversions[0].Standard;
  2891. User.EllipsisConversion = false;
  2892. }
  2893. }
  2894. User.HadMultipleCandidates = HadMultipleCandidates;
  2895. User.ConversionFunction = Constructor;
  2896. User.FoundConversionFunction = Best->FoundDecl;
  2897. User.After.setAsIdentityConversion();
  2898. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2899. User.After.setAllToTypes(ToType);
  2900. return Result;
  2901. }
  2902. if (CXXConversionDecl *Conversion
  2903. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  2904. // C++ [over.ics.user]p1:
  2905. //
  2906. // [...] If the user-defined conversion is specified by a
  2907. // conversion function (12.3.2), the initial standard
  2908. // conversion sequence converts the source type to the
  2909. // implicit object parameter of the conversion function.
  2910. User.Before = Best->Conversions[0].Standard;
  2911. User.HadMultipleCandidates = HadMultipleCandidates;
  2912. User.ConversionFunction = Conversion;
  2913. User.FoundConversionFunction = Best->FoundDecl;
  2914. User.EllipsisConversion = false;
  2915. // C++ [over.ics.user]p2:
  2916. // The second standard conversion sequence converts the
  2917. // result of the user-defined conversion to the target type
  2918. // for the sequence. Since an implicit conversion sequence
  2919. // is an initialization, the special rules for
  2920. // initialization by user-defined conversion apply when
  2921. // selecting the best user-defined conversion for a
  2922. // user-defined conversion sequence (see 13.3.3 and
  2923. // 13.3.3.1).
  2924. User.After = Best->FinalConversion;
  2925. return Result;
  2926. }
  2927. llvm_unreachable("Not a constructor or conversion function?");
  2928. case OR_No_Viable_Function:
  2929. return OR_No_Viable_Function;
  2930. case OR_Ambiguous:
  2931. return OR_Ambiguous;
  2932. }
  2933. llvm_unreachable("Invalid OverloadResult!");
  2934. }
  2935. bool
  2936. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  2937. ImplicitConversionSequence ICS;
  2938. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  2939. OverloadCandidateSet::CSK_Normal);
  2940. OverloadingResult OvResult =
  2941. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  2942. CandidateSet, false, false);
  2943. if (OvResult == OR_Ambiguous)
  2944. Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
  2945. << From->getType() << ToType << From->getSourceRange();
  2946. else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
  2947. if (!RequireCompleteType(From->getLocStart(), ToType,
  2948. diag::err_typecheck_nonviable_condition_incomplete,
  2949. From->getType(), From->getSourceRange()))
  2950. Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
  2951. << From->getType() << From->getSourceRange() << ToType;
  2952. } else
  2953. return false;
  2954. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
  2955. return true;
  2956. }
  2957. /// \brief Compare the user-defined conversion functions or constructors
  2958. /// of two user-defined conversion sequences to determine whether any ordering
  2959. /// is possible.
  2960. static ImplicitConversionSequence::CompareKind
  2961. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  2962. FunctionDecl *Function2) {
  2963. if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
  2964. return ImplicitConversionSequence::Indistinguishable;
  2965. // Objective-C++:
  2966. // If both conversion functions are implicitly-declared conversions from
  2967. // a lambda closure type to a function pointer and a block pointer,
  2968. // respectively, always prefer the conversion to a function pointer,
  2969. // because the function pointer is more lightweight and is more likely
  2970. // to keep code working.
  2971. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  2972. if (!Conv1)
  2973. return ImplicitConversionSequence::Indistinguishable;
  2974. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  2975. if (!Conv2)
  2976. return ImplicitConversionSequence::Indistinguishable;
  2977. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  2978. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  2979. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  2980. if (Block1 != Block2)
  2981. return Block1 ? ImplicitConversionSequence::Worse
  2982. : ImplicitConversionSequence::Better;
  2983. }
  2984. return ImplicitConversionSequence::Indistinguishable;
  2985. }
  2986. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  2987. const ImplicitConversionSequence &ICS) {
  2988. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  2989. (ICS.isUserDefined() &&
  2990. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  2991. }
  2992. /// CompareImplicitConversionSequences - Compare two implicit
  2993. /// conversion sequences to determine whether one is better than the
  2994. /// other or if they are indistinguishable (C++ 13.3.3.2).
  2995. static ImplicitConversionSequence::CompareKind
  2996. CompareImplicitConversionSequences(Sema &S,
  2997. const ImplicitConversionSequence& ICS1,
  2998. const ImplicitConversionSequence& ICS2)
  2999. {
  3000. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  3001. // conversion sequences (as defined in 13.3.3.1)
  3002. // -- a standard conversion sequence (13.3.3.1.1) is a better
  3003. // conversion sequence than a user-defined conversion sequence or
  3004. // an ellipsis conversion sequence, and
  3005. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3006. // conversion sequence than an ellipsis conversion sequence
  3007. // (13.3.3.1.3).
  3008. //
  3009. // C++0x [over.best.ics]p10:
  3010. // For the purpose of ranking implicit conversion sequences as
  3011. // described in 13.3.3.2, the ambiguous conversion sequence is
  3012. // treated as a user-defined sequence that is indistinguishable
  3013. // from any other user-defined conversion sequence.
  3014. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3015. // been removed from C++11. We still accept this conversion, if it happens at
  3016. // the best viable function. Otherwise, this conversion is considered worse
  3017. // than ellipsis conversion. Consider this as an extension; this is not in the
  3018. // standard. For example:
  3019. //
  3020. // int &f(...); // #1
  3021. // void f(char*); // #2
  3022. // void g() { int &r = f("foo"); }
  3023. //
  3024. // In C++03, we pick #2 as the best viable function.
  3025. // In C++11, we pick #1 as the best viable function, because ellipsis
  3026. // conversion is better than string-literal to char* conversion (since there
  3027. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3028. // convert arguments, #2 would be the best viable function in C++11.
  3029. // If the best viable function has this conversion, a warning will be issued
  3030. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3031. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3032. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3033. hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
  3034. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3035. ? ImplicitConversionSequence::Worse
  3036. : ImplicitConversionSequence::Better;
  3037. // HLSL Change Starts
  3038. // This ranking happens in HLSL as part of diagnostics; otherwise the specific ranking is used.
  3039. if (S.getLangOpts().HLSL) {
  3040. if (!ICS1.isInitialized() || !ICS2.isInitialized())
  3041. return ImplicitConversionSequence::Indistinguishable;
  3042. }
  3043. // HLSL Change Ends
  3044. if (ICS1.getKindRank() < ICS2.getKindRank())
  3045. return ImplicitConversionSequence::Better;
  3046. if (ICS2.getKindRank() < ICS1.getKindRank())
  3047. return ImplicitConversionSequence::Worse;
  3048. // The following checks require both conversion sequences to be of
  3049. // the same kind.
  3050. if (ICS1.getKind() != ICS2.getKind())
  3051. return ImplicitConversionSequence::Indistinguishable;
  3052. ImplicitConversionSequence::CompareKind Result =
  3053. ImplicitConversionSequence::Indistinguishable;
  3054. // Two implicit conversion sequences of the same form are
  3055. // indistinguishable conversion sequences unless one of the
  3056. // following rules apply: (C++ 13.3.3.2p3):
  3057. // List-initialization sequence L1 is a better conversion sequence than
  3058. // list-initialization sequence L2 if:
  3059. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3060. // if not that,
  3061. // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
  3062. // and N1 is smaller than N2.,
  3063. // even if one of the other rules in this paragraph would otherwise apply.
  3064. if (!ICS1.isBad()) {
  3065. if (ICS1.isStdInitializerListElement() &&
  3066. !ICS2.isStdInitializerListElement())
  3067. return ImplicitConversionSequence::Better;
  3068. if (!ICS1.isStdInitializerListElement() &&
  3069. ICS2.isStdInitializerListElement())
  3070. return ImplicitConversionSequence::Worse;
  3071. }
  3072. if (ICS1.isStandard())
  3073. // Standard conversion sequence S1 is a better conversion sequence than
  3074. // standard conversion sequence S2 if [...]
  3075. Result = CompareStandardConversionSequences(S,
  3076. ICS1.Standard, ICS2.Standard);
  3077. else if (ICS1.isUserDefined()) {
  3078. // User-defined conversion sequence U1 is a better conversion
  3079. // sequence than another user-defined conversion sequence U2 if
  3080. // they contain the same user-defined conversion function or
  3081. // constructor and if the second standard conversion sequence of
  3082. // U1 is better than the second standard conversion sequence of
  3083. // U2 (C++ 13.3.3.2p3).
  3084. if (ICS1.UserDefined.ConversionFunction ==
  3085. ICS2.UserDefined.ConversionFunction)
  3086. Result = CompareStandardConversionSequences(S,
  3087. ICS1.UserDefined.After,
  3088. ICS2.UserDefined.After);
  3089. else
  3090. Result = compareConversionFunctions(S,
  3091. ICS1.UserDefined.ConversionFunction,
  3092. ICS2.UserDefined.ConversionFunction);
  3093. }
  3094. return Result;
  3095. }
  3096. static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
  3097. while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3098. Qualifiers Quals;
  3099. T1 = Context.getUnqualifiedArrayType(T1, Quals);
  3100. T2 = Context.getUnqualifiedArrayType(T2, Quals);
  3101. }
  3102. return Context.hasSameUnqualifiedType(T1, T2);
  3103. }
  3104. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3105. // determine if one is a proper subset of the other.
  3106. static ImplicitConversionSequence::CompareKind
  3107. compareStandardConversionSubsets(ASTContext &Context,
  3108. const StandardConversionSequence& SCS1,
  3109. const StandardConversionSequence& SCS2) {
  3110. ImplicitConversionSequence::CompareKind Result
  3111. = ImplicitConversionSequence::Indistinguishable;
  3112. // the identity conversion sequence is considered to be a subsequence of
  3113. // any non-identity conversion sequence
  3114. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3115. return ImplicitConversionSequence::Better;
  3116. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3117. return ImplicitConversionSequence::Worse;
  3118. if (SCS1.Second != SCS2.Second) {
  3119. if (SCS1.Second == ICK_Identity)
  3120. Result = ImplicitConversionSequence::Better;
  3121. else if (SCS2.Second == ICK_Identity)
  3122. Result = ImplicitConversionSequence::Worse;
  3123. else
  3124. return ImplicitConversionSequence::Indistinguishable;
  3125. } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
  3126. return ImplicitConversionSequence::Indistinguishable;
  3127. if (SCS1.Third == SCS2.Third) {
  3128. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3129. : ImplicitConversionSequence::Indistinguishable;
  3130. }
  3131. if (SCS1.Third == ICK_Identity)
  3132. return Result == ImplicitConversionSequence::Worse
  3133. ? ImplicitConversionSequence::Indistinguishable
  3134. : ImplicitConversionSequence::Better;
  3135. if (SCS2.Third == ICK_Identity)
  3136. return Result == ImplicitConversionSequence::Better
  3137. ? ImplicitConversionSequence::Indistinguishable
  3138. : ImplicitConversionSequence::Worse;
  3139. return ImplicitConversionSequence::Indistinguishable;
  3140. }
  3141. /// \brief Determine whether one of the given reference bindings is better
  3142. /// than the other based on what kind of bindings they are.
  3143. static bool
  3144. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3145. const StandardConversionSequence &SCS2) {
  3146. // C++0x [over.ics.rank]p3b4:
  3147. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3148. // implicit object parameter of a non-static member function declared
  3149. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3150. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3151. // lvalue reference to a function lvalue and S2 binds an rvalue
  3152. // reference*.
  3153. //
  3154. // FIXME: Rvalue references. We're going rogue with the above edits,
  3155. // because the semantics in the current C++0x working paper (N3225 at the
  3156. // time of this writing) break the standard definition of std::forward
  3157. // and std::reference_wrapper when dealing with references to functions.
  3158. // Proposed wording changes submitted to CWG for consideration.
  3159. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3160. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3161. return false;
  3162. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3163. SCS2.IsLvalueReference) ||
  3164. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3165. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3166. }
  3167. /// CompareStandardConversionSequences - Compare two standard
  3168. /// conversion sequences to determine whether one is better than the
  3169. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3170. static ImplicitConversionSequence::CompareKind
  3171. CompareStandardConversionSequences(Sema &S,
  3172. const StandardConversionSequence& SCS1,
  3173. const StandardConversionSequence& SCS2)
  3174. {
  3175. // Standard conversion sequence S1 is a better conversion sequence
  3176. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3177. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3178. // sequences in the canonical form defined by 13.3.3.1.1,
  3179. // excluding any Lvalue Transformation; the identity conversion
  3180. // sequence is considered to be a subsequence of any
  3181. // non-identity conversion sequence) or, if not that,
  3182. if (ImplicitConversionSequence::CompareKind CK
  3183. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3184. return CK;
  3185. // -- the rank of S1 is better than the rank of S2 (by the rules
  3186. // defined below), or, if not that,
  3187. ImplicitConversionRank Rank1 = SCS1.getRank();
  3188. ImplicitConversionRank Rank2 = SCS2.getRank();
  3189. if (Rank1 < Rank2)
  3190. return ImplicitConversionSequence::Better;
  3191. else if (Rank2 < Rank1)
  3192. return ImplicitConversionSequence::Worse;
  3193. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3194. // are indistinguishable unless one of the following rules
  3195. // applies:
  3196. // A conversion that is not a conversion of a pointer, or
  3197. // pointer to member, to bool is better than another conversion
  3198. // that is such a conversion.
  3199. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3200. return SCS2.isPointerConversionToBool()
  3201. ? ImplicitConversionSequence::Better
  3202. : ImplicitConversionSequence::Worse;
  3203. // C++ [over.ics.rank]p4b2:
  3204. //
  3205. // If class B is derived directly or indirectly from class A,
  3206. // conversion of B* to A* is better than conversion of B* to
  3207. // void*, and conversion of A* to void* is better than conversion
  3208. // of B* to void*.
  3209. bool SCS1ConvertsToVoid
  3210. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3211. bool SCS2ConvertsToVoid
  3212. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3213. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3214. // Exactly one of the conversion sequences is a conversion to
  3215. // a void pointer; it's the worse conversion.
  3216. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3217. : ImplicitConversionSequence::Worse;
  3218. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3219. // Neither conversion sequence converts to a void pointer; compare
  3220. // their derived-to-base conversions.
  3221. if (ImplicitConversionSequence::CompareKind DerivedCK
  3222. = CompareDerivedToBaseConversions(S, SCS1, SCS2))
  3223. return DerivedCK;
  3224. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3225. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3226. // Both conversion sequences are conversions to void
  3227. // pointers. Compare the source types to determine if there's an
  3228. // inheritance relationship in their sources.
  3229. QualType FromType1 = SCS1.getFromType();
  3230. QualType FromType2 = SCS2.getFromType();
  3231. // Adjust the types we're converting from via the array-to-pointer
  3232. // conversion, if we need to.
  3233. if (SCS1.First == ICK_Array_To_Pointer)
  3234. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3235. if (SCS2.First == ICK_Array_To_Pointer)
  3236. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3237. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3238. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3239. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3240. return ImplicitConversionSequence::Better;
  3241. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3242. return ImplicitConversionSequence::Worse;
  3243. // Objective-C++: If one interface is more specific than the
  3244. // other, it is the better one.
  3245. const ObjCObjectPointerType* FromObjCPtr1
  3246. = FromType1->getAs<ObjCObjectPointerType>();
  3247. const ObjCObjectPointerType* FromObjCPtr2
  3248. = FromType2->getAs<ObjCObjectPointerType>();
  3249. if (FromObjCPtr1 && FromObjCPtr2) {
  3250. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3251. FromObjCPtr2);
  3252. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3253. FromObjCPtr1);
  3254. if (AssignLeft != AssignRight) {
  3255. return AssignLeft? ImplicitConversionSequence::Better
  3256. : ImplicitConversionSequence::Worse;
  3257. }
  3258. }
  3259. }
  3260. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3261. // bullet 3).
  3262. if (ImplicitConversionSequence::CompareKind QualCK
  3263. = CompareQualificationConversions(S, SCS1, SCS2))
  3264. return QualCK;
  3265. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3266. // Check for a better reference binding based on the kind of bindings.
  3267. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3268. return ImplicitConversionSequence::Better;
  3269. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3270. return ImplicitConversionSequence::Worse;
  3271. // C++ [over.ics.rank]p3b4:
  3272. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3273. // which the references refer are the same type except for
  3274. // top-level cv-qualifiers, and the type to which the reference
  3275. // initialized by S2 refers is more cv-qualified than the type
  3276. // to which the reference initialized by S1 refers.
  3277. QualType T1 = SCS1.getToType(2);
  3278. QualType T2 = SCS2.getToType(2);
  3279. T1 = S.Context.getCanonicalType(T1);
  3280. T2 = S.Context.getCanonicalType(T2);
  3281. Qualifiers T1Quals, T2Quals;
  3282. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3283. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3284. if (UnqualT1 == UnqualT2) {
  3285. // Objective-C++ ARC: If the references refer to objects with different
  3286. // lifetimes, prefer bindings that don't change lifetime.
  3287. if (SCS1.ObjCLifetimeConversionBinding !=
  3288. SCS2.ObjCLifetimeConversionBinding) {
  3289. return SCS1.ObjCLifetimeConversionBinding
  3290. ? ImplicitConversionSequence::Worse
  3291. : ImplicitConversionSequence::Better;
  3292. }
  3293. // If the type is an array type, promote the element qualifiers to the
  3294. // type for comparison.
  3295. if (isa<ArrayType>(T1) && T1Quals)
  3296. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3297. if (isa<ArrayType>(T2) && T2Quals)
  3298. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3299. if (T2.isMoreQualifiedThan(T1))
  3300. return ImplicitConversionSequence::Better;
  3301. else if (T1.isMoreQualifiedThan(T2))
  3302. return ImplicitConversionSequence::Worse;
  3303. }
  3304. }
  3305. // In Microsoft mode, prefer an integral conversion to a
  3306. // floating-to-integral conversion if the integral conversion
  3307. // is between types of the same size.
  3308. // For example:
  3309. // void f(float);
  3310. // void f(int);
  3311. // int main {
  3312. // long a;
  3313. // f(a);
  3314. // }
  3315. // Here, MSVC will call f(int) instead of generating a compile error
  3316. // as clang will do in standard mode.
  3317. if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
  3318. SCS2.Second == ICK_Floating_Integral &&
  3319. S.Context.getTypeSize(SCS1.getFromType()) ==
  3320. S.Context.getTypeSize(SCS1.getToType(2)))
  3321. return ImplicitConversionSequence::Better;
  3322. return ImplicitConversionSequence::Indistinguishable;
  3323. }
  3324. /// CompareQualificationConversions - Compares two standard conversion
  3325. /// sequences to determine whether they can be ranked based on their
  3326. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3327. static ImplicitConversionSequence::CompareKind
  3328. CompareQualificationConversions(Sema &S,
  3329. const StandardConversionSequence& SCS1,
  3330. const StandardConversionSequence& SCS2) {
  3331. // C++ 13.3.3.2p3:
  3332. // -- S1 and S2 differ only in their qualification conversion and
  3333. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3334. // cv-qualification signature of type T1 is a proper subset of
  3335. // the cv-qualification signature of type T2, and S1 is not the
  3336. // deprecated string literal array-to-pointer conversion (4.2).
  3337. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3338. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3339. return ImplicitConversionSequence::Indistinguishable;
  3340. // FIXME: the example in the standard doesn't use a qualification
  3341. // conversion (!)
  3342. QualType T1 = SCS1.getToType(2);
  3343. QualType T2 = SCS2.getToType(2);
  3344. T1 = S.Context.getCanonicalType(T1);
  3345. T2 = S.Context.getCanonicalType(T2);
  3346. Qualifiers T1Quals, T2Quals;
  3347. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3348. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3349. // If the types are the same, we won't learn anything by unwrapped
  3350. // them.
  3351. if (UnqualT1 == UnqualT2)
  3352. return ImplicitConversionSequence::Indistinguishable;
  3353. // If the type is an array type, promote the element qualifiers to the type
  3354. // for comparison.
  3355. if (isa<ArrayType>(T1) && T1Quals)
  3356. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3357. if (isa<ArrayType>(T2) && T2Quals)
  3358. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3359. ImplicitConversionSequence::CompareKind Result
  3360. = ImplicitConversionSequence::Indistinguishable;
  3361. // Objective-C++ ARC:
  3362. // Prefer qualification conversions not involving a change in lifetime
  3363. // to qualification conversions that do not change lifetime.
  3364. if (SCS1.QualificationIncludesObjCLifetime !=
  3365. SCS2.QualificationIncludesObjCLifetime) {
  3366. Result = SCS1.QualificationIncludesObjCLifetime
  3367. ? ImplicitConversionSequence::Worse
  3368. : ImplicitConversionSequence::Better;
  3369. }
  3370. while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3371. // Within each iteration of the loop, we check the qualifiers to
  3372. // determine if this still looks like a qualification
  3373. // conversion. Then, if all is well, we unwrap one more level of
  3374. // pointers or pointers-to-members and do it all again
  3375. // until there are no more pointers or pointers-to-members left
  3376. // to unwrap. This essentially mimics what
  3377. // IsQualificationConversion does, but here we're checking for a
  3378. // strict subset of qualifiers.
  3379. if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
  3380. // The qualifiers are the same, so this doesn't tell us anything
  3381. // about how the sequences rank.
  3382. ;
  3383. else if (T2.isMoreQualifiedThan(T1)) {
  3384. // T1 has fewer qualifiers, so it could be the better sequence.
  3385. if (Result == ImplicitConversionSequence::Worse)
  3386. // Neither has qualifiers that are a subset of the other's
  3387. // qualifiers.
  3388. return ImplicitConversionSequence::Indistinguishable;
  3389. Result = ImplicitConversionSequence::Better;
  3390. } else if (T1.isMoreQualifiedThan(T2)) {
  3391. // T2 has fewer qualifiers, so it could be the better sequence.
  3392. if (Result == ImplicitConversionSequence::Better)
  3393. // Neither has qualifiers that are a subset of the other's
  3394. // qualifiers.
  3395. return ImplicitConversionSequence::Indistinguishable;
  3396. Result = ImplicitConversionSequence::Worse;
  3397. } else {
  3398. // Qualifiers are disjoint.
  3399. return ImplicitConversionSequence::Indistinguishable;
  3400. }
  3401. // If the types after this point are equivalent, we're done.
  3402. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3403. break;
  3404. }
  3405. // Check that the winning standard conversion sequence isn't using
  3406. // the deprecated string literal array to pointer conversion.
  3407. switch (Result) {
  3408. case ImplicitConversionSequence::Better:
  3409. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3410. Result = ImplicitConversionSequence::Indistinguishable;
  3411. break;
  3412. case ImplicitConversionSequence::Indistinguishable:
  3413. break;
  3414. case ImplicitConversionSequence::Worse:
  3415. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3416. Result = ImplicitConversionSequence::Indistinguishable;
  3417. break;
  3418. }
  3419. return Result;
  3420. }
  3421. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3422. /// sequences to determine whether they can be ranked based on their
  3423. /// various kinds of derived-to-base conversions (C++
  3424. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3425. /// conversions between Objective-C interface types.
  3426. static ImplicitConversionSequence::CompareKind
  3427. CompareDerivedToBaseConversions(Sema &S,
  3428. const StandardConversionSequence& SCS1,
  3429. const StandardConversionSequence& SCS2) {
  3430. QualType FromType1 = SCS1.getFromType();
  3431. QualType ToType1 = SCS1.getToType(1);
  3432. QualType FromType2 = SCS2.getFromType();
  3433. QualType ToType2 = SCS2.getToType(1);
  3434. // Adjust the types we're converting from via the array-to-pointer
  3435. // conversion, if we need to.
  3436. if (SCS1.First == ICK_Array_To_Pointer)
  3437. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3438. if (SCS2.First == ICK_Array_To_Pointer)
  3439. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3440. // Canonicalize all of the types.
  3441. FromType1 = S.Context.getCanonicalType(FromType1);
  3442. ToType1 = S.Context.getCanonicalType(ToType1);
  3443. FromType2 = S.Context.getCanonicalType(FromType2);
  3444. ToType2 = S.Context.getCanonicalType(ToType2);
  3445. // C++ [over.ics.rank]p4b3:
  3446. //
  3447. // If class B is derived directly or indirectly from class A and
  3448. // class C is derived directly or indirectly from B,
  3449. //
  3450. // Compare based on pointer conversions.
  3451. if (SCS1.Second == ICK_Pointer_Conversion &&
  3452. SCS2.Second == ICK_Pointer_Conversion &&
  3453. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3454. FromType1->isPointerType() && FromType2->isPointerType() &&
  3455. ToType1->isPointerType() && ToType2->isPointerType()) {
  3456. QualType FromPointee1
  3457. = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3458. QualType ToPointee1
  3459. = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3460. QualType FromPointee2
  3461. = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3462. QualType ToPointee2
  3463. = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3464. // -- conversion of C* to B* is better than conversion of C* to A*,
  3465. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3466. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3467. return ImplicitConversionSequence::Better;
  3468. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3469. return ImplicitConversionSequence::Worse;
  3470. }
  3471. // -- conversion of B* to A* is better than conversion of C* to A*,
  3472. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3473. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3474. return ImplicitConversionSequence::Better;
  3475. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3476. return ImplicitConversionSequence::Worse;
  3477. }
  3478. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3479. SCS2.Second == ICK_Pointer_Conversion) {
  3480. const ObjCObjectPointerType *FromPtr1
  3481. = FromType1->getAs<ObjCObjectPointerType>();
  3482. const ObjCObjectPointerType *FromPtr2
  3483. = FromType2->getAs<ObjCObjectPointerType>();
  3484. const ObjCObjectPointerType *ToPtr1
  3485. = ToType1->getAs<ObjCObjectPointerType>();
  3486. const ObjCObjectPointerType *ToPtr2
  3487. = ToType2->getAs<ObjCObjectPointerType>();
  3488. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3489. // Apply the same conversion ranking rules for Objective-C pointer types
  3490. // that we do for C++ pointers to class types. However, we employ the
  3491. // Objective-C pseudo-subtyping relationship used for assignment of
  3492. // Objective-C pointer types.
  3493. bool FromAssignLeft
  3494. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3495. bool FromAssignRight
  3496. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3497. bool ToAssignLeft
  3498. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3499. bool ToAssignRight
  3500. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3501. // A conversion to an a non-id object pointer type or qualified 'id'
  3502. // type is better than a conversion to 'id'.
  3503. if (ToPtr1->isObjCIdType() &&
  3504. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3505. return ImplicitConversionSequence::Worse;
  3506. if (ToPtr2->isObjCIdType() &&
  3507. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3508. return ImplicitConversionSequence::Better;
  3509. // A conversion to a non-id object pointer type is better than a
  3510. // conversion to a qualified 'id' type
  3511. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3512. return ImplicitConversionSequence::Worse;
  3513. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3514. return ImplicitConversionSequence::Better;
  3515. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3516. // type is better than a conversion to 'Class'.
  3517. if (ToPtr1->isObjCClassType() &&
  3518. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3519. return ImplicitConversionSequence::Worse;
  3520. if (ToPtr2->isObjCClassType() &&
  3521. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3522. return ImplicitConversionSequence::Better;
  3523. // A conversion to a non-Class object pointer type is better than a
  3524. // conversion to a qualified 'Class' type.
  3525. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3526. return ImplicitConversionSequence::Worse;
  3527. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3528. return ImplicitConversionSequence::Better;
  3529. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3530. if (S.Context.hasSameType(FromType1, FromType2) &&
  3531. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3532. (ToAssignLeft != ToAssignRight))
  3533. return ToAssignLeft? ImplicitConversionSequence::Worse
  3534. : ImplicitConversionSequence::Better;
  3535. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3536. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3537. (FromAssignLeft != FromAssignRight))
  3538. return FromAssignLeft? ImplicitConversionSequence::Better
  3539. : ImplicitConversionSequence::Worse;
  3540. }
  3541. }
  3542. // Ranking of member-pointer types.
  3543. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3544. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3545. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3546. const MemberPointerType * FromMemPointer1 =
  3547. FromType1->getAs<MemberPointerType>();
  3548. const MemberPointerType * ToMemPointer1 =
  3549. ToType1->getAs<MemberPointerType>();
  3550. const MemberPointerType * FromMemPointer2 =
  3551. FromType2->getAs<MemberPointerType>();
  3552. const MemberPointerType * ToMemPointer2 =
  3553. ToType2->getAs<MemberPointerType>();
  3554. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3555. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3556. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3557. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3558. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3559. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3560. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3561. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3562. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3563. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3564. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3565. return ImplicitConversionSequence::Worse;
  3566. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3567. return ImplicitConversionSequence::Better;
  3568. }
  3569. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3570. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3571. if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3572. return ImplicitConversionSequence::Better;
  3573. else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3574. return ImplicitConversionSequence::Worse;
  3575. }
  3576. }
  3577. if (SCS1.Second == ICK_Derived_To_Base) {
  3578. // -- conversion of C to B is better than conversion of C to A,
  3579. // -- binding of an expression of type C to a reference of type
  3580. // B& is better than binding an expression of type C to a
  3581. // reference of type A&,
  3582. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3583. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3584. if (S.IsDerivedFrom(ToType1, ToType2))
  3585. return ImplicitConversionSequence::Better;
  3586. else if (S.IsDerivedFrom(ToType2, ToType1))
  3587. return ImplicitConversionSequence::Worse;
  3588. }
  3589. // -- conversion of B to A is better than conversion of C to A.
  3590. // -- binding of an expression of type B to a reference of type
  3591. // A& is better than binding an expression of type C to a
  3592. // reference of type A&,
  3593. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3594. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3595. if (S.IsDerivedFrom(FromType2, FromType1))
  3596. return ImplicitConversionSequence::Better;
  3597. else if (S.IsDerivedFrom(FromType1, FromType2))
  3598. return ImplicitConversionSequence::Worse;
  3599. }
  3600. }
  3601. return ImplicitConversionSequence::Indistinguishable;
  3602. }
  3603. /// \brief Determine whether the given type is valid, e.g., it is not an invalid
  3604. /// C++ class.
  3605. static bool isTypeValid(QualType T) {
  3606. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3607. return !Record->isInvalidDecl();
  3608. return true;
  3609. }
  3610. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3611. /// determine whether they are reference-related,
  3612. /// reference-compatible, reference-compatible with added
  3613. /// qualification, or incompatible, for use in C++ initialization by
  3614. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3615. /// type, and the first type (T1) is the pointee type of the reference
  3616. /// type being initialized.
  3617. Sema::ReferenceCompareResult
  3618. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3619. QualType OrigT1, QualType OrigT2,
  3620. bool &DerivedToBase,
  3621. bool &ObjCConversion,
  3622. bool &ObjCLifetimeConversion) {
  3623. assert(!OrigT1->isReferenceType() &&
  3624. "T1 must be the pointee type of the reference type");
  3625. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3626. QualType T1 = Context.getCanonicalType(OrigT1);
  3627. QualType T2 = Context.getCanonicalType(OrigT2);
  3628. Qualifiers T1Quals, T2Quals;
  3629. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3630. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3631. // C++ [dcl.init.ref]p4:
  3632. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3633. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3634. // T1 is a base class of T2.
  3635. DerivedToBase = false;
  3636. ObjCConversion = false;
  3637. ObjCLifetimeConversion = false;
  3638. if (UnqualT1 == UnqualT2) {
  3639. // Nothing to do.
  3640. } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
  3641. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3642. IsDerivedFrom(UnqualT2, UnqualT1))
  3643. DerivedToBase = true;
  3644. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3645. UnqualT2->isObjCObjectOrInterfaceType() &&
  3646. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3647. ObjCConversion = true;
  3648. else
  3649. return Ref_Incompatible;
  3650. // At this point, we know that T1 and T2 are reference-related (at
  3651. // least).
  3652. // If the type is an array type, promote the element qualifiers to the type
  3653. // for comparison.
  3654. if (isa<ArrayType>(T1) && T1Quals)
  3655. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3656. if (isa<ArrayType>(T2) && T2Quals)
  3657. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3658. // C++ [dcl.init.ref]p4:
  3659. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3660. // reference-related to T2 and cv1 is the same cv-qualification
  3661. // as, or greater cv-qualification than, cv2. For purposes of
  3662. // overload resolution, cases for which cv1 is greater
  3663. // cv-qualification than cv2 are identified as
  3664. // reference-compatible with added qualification (see 13.3.3.2).
  3665. //
  3666. // Note that we also require equivalence of Objective-C GC and address-space
  3667. // qualifiers when performing these computations, so that e.g., an int in
  3668. // address space 1 is not reference-compatible with an int in address
  3669. // space 2.
  3670. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3671. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3672. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3673. ObjCLifetimeConversion = true;
  3674. T1Quals.removeObjCLifetime();
  3675. T2Quals.removeObjCLifetime();
  3676. }
  3677. if (T1Quals == T2Quals)
  3678. return Ref_Compatible;
  3679. else if (T1Quals.compatiblyIncludes(T2Quals))
  3680. return Ref_Compatible_With_Added_Qualification;
  3681. else
  3682. return Ref_Related;
  3683. }
  3684. /// \brief Look for a user-defined conversion to an value reference-compatible
  3685. /// with DeclType. Return true if something definite is found.
  3686. static bool
  3687. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  3688. QualType DeclType, SourceLocation DeclLoc,
  3689. Expr *Init, QualType T2, bool AllowRvalues,
  3690. bool AllowExplicit) {
  3691. assert(T2->isRecordType() && "Can only find conversions of record types.");
  3692. CXXRecordDecl *T2RecordDecl
  3693. = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
  3694. OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
  3695. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3696. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3697. NamedDecl *D = *I;
  3698. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3699. if (isa<UsingShadowDecl>(D))
  3700. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3701. FunctionTemplateDecl *ConvTemplate
  3702. = dyn_cast<FunctionTemplateDecl>(D);
  3703. CXXConversionDecl *Conv;
  3704. if (ConvTemplate)
  3705. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3706. else
  3707. Conv = cast<CXXConversionDecl>(D);
  3708. // If this is an explicit conversion, and we're not allowed to consider
  3709. // explicit conversions, skip it.
  3710. if (!AllowExplicit && Conv->isExplicit())
  3711. continue;
  3712. if (AllowRvalues) {
  3713. bool DerivedToBase = false;
  3714. bool ObjCConversion = false;
  3715. bool ObjCLifetimeConversion = false;
  3716. // If we are initializing an rvalue reference, don't permit conversion
  3717. // functions that return lvalues.
  3718. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  3719. const ReferenceType *RefType
  3720. = Conv->getConversionType()->getAs<LValueReferenceType>();
  3721. if (RefType && !RefType->getPointeeType()->isFunctionType())
  3722. continue;
  3723. }
  3724. if (!ConvTemplate &&
  3725. S.CompareReferenceRelationship(
  3726. DeclLoc,
  3727. Conv->getConversionType().getNonReferenceType()
  3728. .getUnqualifiedType(),
  3729. DeclType.getNonReferenceType().getUnqualifiedType(),
  3730. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  3731. Sema::Ref_Incompatible)
  3732. continue;
  3733. } else {
  3734. // If the conversion function doesn't return a reference type,
  3735. // it can't be considered for this conversion. An rvalue reference
  3736. // is only acceptable if its referencee is a function type.
  3737. const ReferenceType *RefType =
  3738. Conv->getConversionType()->getAs<ReferenceType>();
  3739. if (!RefType ||
  3740. (!RefType->isLValueReferenceType() &&
  3741. !RefType->getPointeeType()->isFunctionType()))
  3742. continue;
  3743. }
  3744. if (ConvTemplate)
  3745. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
  3746. Init, DeclType, CandidateSet,
  3747. /*AllowObjCConversionOnExplicit=*/false);
  3748. else
  3749. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
  3750. DeclType, CandidateSet,
  3751. /*AllowObjCConversionOnExplicit=*/false);
  3752. }
  3753. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3754. OverloadCandidateSet::iterator Best;
  3755. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  3756. case OR_Success:
  3757. // C++ [over.ics.ref]p1:
  3758. //
  3759. // [...] If the parameter binds directly to the result of
  3760. // applying a conversion function to the argument
  3761. // expression, the implicit conversion sequence is a
  3762. // user-defined conversion sequence (13.3.3.1.2), with the
  3763. // second standard conversion sequence either an identity
  3764. // conversion or, if the conversion function returns an
  3765. // entity of a type that is a derived class of the parameter
  3766. // type, a derived-to-base Conversion.
  3767. if (!Best->FinalConversion.DirectBinding)
  3768. return false;
  3769. ICS.setUserDefined();
  3770. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  3771. ICS.UserDefined.After = Best->FinalConversion;
  3772. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  3773. ICS.UserDefined.ConversionFunction = Best->Function;
  3774. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  3775. ICS.UserDefined.EllipsisConversion = false;
  3776. assert(ICS.UserDefined.After.ReferenceBinding &&
  3777. ICS.UserDefined.After.DirectBinding &&
  3778. "Expected a direct reference binding!");
  3779. return true;
  3780. case OR_Ambiguous:
  3781. ICS.setAmbiguous();
  3782. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  3783. Cand != CandidateSet.end(); ++Cand)
  3784. if (Cand->Viable)
  3785. ICS.Ambiguous.addConversion(Cand->Function);
  3786. return true;
  3787. case OR_No_Viable_Function:
  3788. case OR_Deleted:
  3789. // There was no suitable conversion, or we found a deleted
  3790. // conversion; continue with other checks.
  3791. return false;
  3792. }
  3793. llvm_unreachable("Invalid OverloadResult!");
  3794. }
  3795. /// \brief Compute an implicit conversion sequence for reference
  3796. /// initialization.
  3797. static ImplicitConversionSequence
  3798. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  3799. SourceLocation DeclLoc,
  3800. bool SuppressUserConversions,
  3801. bool AllowExplicit) {
  3802. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  3803. // Most paths end in a failed conversion.
  3804. ImplicitConversionSequence ICS;
  3805. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3806. QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
  3807. QualType T2 = Init->getType();
  3808. // If the initializer is the address of an overloaded function, try
  3809. // to resolve the overloaded function. If all goes well, T2 is the
  3810. // type of the resulting function.
  3811. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  3812. DeclAccessPair Found;
  3813. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  3814. false, Found))
  3815. T2 = Fn->getType();
  3816. }
  3817. // Compute some basic properties of the types and the initializer.
  3818. bool isRValRef = DeclType->isRValueReferenceType();
  3819. bool DerivedToBase = false;
  3820. bool ObjCConversion = false;
  3821. bool ObjCLifetimeConversion = false;
  3822. Expr::Classification InitCategory = Init->Classify(S.Context);
  3823. Sema::ReferenceCompareResult RefRelationship
  3824. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  3825. ObjCConversion, ObjCLifetimeConversion);
  3826. // C++0x [dcl.init.ref]p5:
  3827. // A reference to type "cv1 T1" is initialized by an expression
  3828. // of type "cv2 T2" as follows:
  3829. // -- If reference is an lvalue reference and the initializer expression
  3830. if (!isRValRef) {
  3831. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  3832. // reference-compatible with "cv2 T2," or
  3833. //
  3834. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  3835. if (InitCategory.isLValue() &&
  3836. RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
  3837. // C++ [over.ics.ref]p1:
  3838. // When a parameter of reference type binds directly (8.5.3)
  3839. // to an argument expression, the implicit conversion sequence
  3840. // is the identity conversion, unless the argument expression
  3841. // has a type that is a derived class of the parameter type,
  3842. // in which case the implicit conversion sequence is a
  3843. // derived-to-base Conversion (13.3.3.1).
  3844. ICS.setStandard();
  3845. ICS.Standard.First = ICK_Identity;
  3846. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3847. : ObjCConversion? ICK_Compatible_Conversion
  3848. : ICK_Identity;
  3849. ICS.Standard.Third = ICK_Identity;
  3850. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3851. ICS.Standard.setToType(0, T2);
  3852. ICS.Standard.setToType(1, T1);
  3853. ICS.Standard.setToType(2, T1);
  3854. ICS.Standard.ReferenceBinding = true;
  3855. ICS.Standard.DirectBinding = true;
  3856. ICS.Standard.IsLvalueReference = !isRValRef;
  3857. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3858. ICS.Standard.BindsToRvalue = false;
  3859. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3860. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3861. ICS.Standard.CopyConstructor = nullptr;
  3862. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3863. // Nothing more to do: the inaccessibility/ambiguity check for
  3864. // derived-to-base conversions is suppressed when we're
  3865. // computing the implicit conversion sequence (C++
  3866. // [over.best.ics]p2).
  3867. return ICS;
  3868. }
  3869. // -- has a class type (i.e., T2 is a class type), where T1 is
  3870. // not reference-related to T2, and can be implicitly
  3871. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  3872. // is reference-compatible with "cv3 T3" 92) (this
  3873. // conversion is selected by enumerating the applicable
  3874. // conversion functions (13.3.1.6) and choosing the best
  3875. // one through overload resolution (13.3)),
  3876. if (!SuppressUserConversions && T2->isRecordType() &&
  3877. !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3878. RefRelationship == Sema::Ref_Incompatible) {
  3879. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3880. Init, T2, /*AllowRvalues=*/false,
  3881. AllowExplicit))
  3882. return ICS;
  3883. }
  3884. }
  3885. // -- Otherwise, the reference shall be an lvalue reference to a
  3886. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3887. // shall be an rvalue reference.
  3888. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  3889. return ICS;
  3890. // -- If the initializer expression
  3891. //
  3892. // -- is an xvalue, class prvalue, array prvalue or function
  3893. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  3894. if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
  3895. (InitCategory.isXValue() ||
  3896. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  3897. (InitCategory.isLValue() && T2->isFunctionType()))) {
  3898. ICS.setStandard();
  3899. ICS.Standard.First = ICK_Identity;
  3900. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3901. : ObjCConversion? ICK_Compatible_Conversion
  3902. : ICK_Identity;
  3903. ICS.Standard.Third = ICK_Identity;
  3904. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3905. ICS.Standard.setToType(0, T2);
  3906. ICS.Standard.setToType(1, T1);
  3907. ICS.Standard.setToType(2, T1);
  3908. ICS.Standard.ReferenceBinding = true;
  3909. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  3910. // binding unless we're binding to a class prvalue.
  3911. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  3912. // allow the use of rvalue references in C++98/03 for the benefit of
  3913. // standard library implementors; therefore, we need the xvalue check here.
  3914. ICS.Standard.DirectBinding =
  3915. S.getLangOpts().CPlusPlus11 ||
  3916. !(InitCategory.isPRValue() || T2->isRecordType());
  3917. ICS.Standard.IsLvalueReference = !isRValRef;
  3918. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3919. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  3920. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3921. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3922. ICS.Standard.CopyConstructor = nullptr;
  3923. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3924. return ICS;
  3925. }
  3926. // -- has a class type (i.e., T2 is a class type), where T1 is not
  3927. // reference-related to T2, and can be implicitly converted to
  3928. // an xvalue, class prvalue, or function lvalue of type
  3929. // "cv3 T3", where "cv1 T1" is reference-compatible with
  3930. // "cv3 T3",
  3931. //
  3932. // then the reference is bound to the value of the initializer
  3933. // expression in the first case and to the result of the conversion
  3934. // in the second case (or, in either case, to an appropriate base
  3935. // class subobject).
  3936. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3937. T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3938. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3939. Init, T2, /*AllowRvalues=*/true,
  3940. AllowExplicit)) {
  3941. // In the second case, if the reference is an rvalue reference
  3942. // and the second standard conversion sequence of the
  3943. // user-defined conversion sequence includes an lvalue-to-rvalue
  3944. // conversion, the program is ill-formed.
  3945. if (ICS.isUserDefined() && isRValRef &&
  3946. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  3947. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3948. return ICS;
  3949. }
  3950. // A temporary of function type cannot be created; don't even try.
  3951. if (T1->isFunctionType())
  3952. return ICS;
  3953. // -- Otherwise, a temporary of type "cv1 T1" is created and
  3954. // initialized from the initializer expression using the
  3955. // rules for a non-reference copy initialization (8.5). The
  3956. // reference is then bound to the temporary. If T1 is
  3957. // reference-related to T2, cv1 must be the same
  3958. // cv-qualification as, or greater cv-qualification than,
  3959. // cv2; otherwise, the program is ill-formed.
  3960. if (RefRelationship == Sema::Ref_Related) {
  3961. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  3962. // we would be reference-compatible or reference-compatible with
  3963. // added qualification. But that wasn't the case, so the reference
  3964. // initialization fails.
  3965. //
  3966. // Note that we only want to check address spaces and cvr-qualifiers here.
  3967. // ObjC GC and lifetime qualifiers aren't important.
  3968. Qualifiers T1Quals = T1.getQualifiers();
  3969. Qualifiers T2Quals = T2.getQualifiers();
  3970. T1Quals.removeObjCGCAttr();
  3971. T1Quals.removeObjCLifetime();
  3972. T2Quals.removeObjCGCAttr();
  3973. T2Quals.removeObjCLifetime();
  3974. if (!T1Quals.compatiblyIncludes(T2Quals))
  3975. return ICS;
  3976. }
  3977. // If at least one of the types is a class type, the types are not
  3978. // related, and we aren't allowed any user conversions, the
  3979. // reference binding fails. This case is important for breaking
  3980. // recursion, since TryImplicitConversion below will attempt to
  3981. // create a temporary through the use of a copy constructor.
  3982. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3983. (T1->isRecordType() || T2->isRecordType()))
  3984. return ICS;
  3985. // If T1 is reference-related to T2 and the reference is an rvalue
  3986. // reference, the initializer expression shall not be an lvalue.
  3987. if (RefRelationship >= Sema::Ref_Related &&
  3988. isRValRef && Init->Classify(S.Context).isLValue())
  3989. return ICS;
  3990. // C++ [over.ics.ref]p2:
  3991. // When a parameter of reference type is not bound directly to
  3992. // an argument expression, the conversion sequence is the one
  3993. // required to convert the argument expression to the
  3994. // underlying type of the reference according to
  3995. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  3996. // to copy-initializing a temporary of the underlying type with
  3997. // the argument expression. Any difference in top-level
  3998. // cv-qualification is subsumed by the initialization itself
  3999. // and does not constitute a conversion.
  4000. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4001. /*AllowExplicit=*/false,
  4002. /*InOverloadResolution=*/false,
  4003. /*CStyle=*/false,
  4004. /*AllowObjCWritebackConversion=*/false,
  4005. /*AllowObjCConversionOnExplicit=*/false);
  4006. // Of course, that's still a reference binding.
  4007. if (ICS.isStandard()) {
  4008. ICS.Standard.ReferenceBinding = true;
  4009. ICS.Standard.IsLvalueReference = !isRValRef;
  4010. ICS.Standard.BindsToFunctionLvalue = false;
  4011. ICS.Standard.BindsToRvalue = true;
  4012. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4013. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4014. } else if (ICS.isUserDefined()) {
  4015. const ReferenceType *LValRefType =
  4016. ICS.UserDefined.ConversionFunction->getReturnType()
  4017. ->getAs<LValueReferenceType>();
  4018. // C++ [over.ics.ref]p3:
  4019. // Except for an implicit object parameter, for which see 13.3.1, a
  4020. // standard conversion sequence cannot be formed if it requires [...]
  4021. // binding an rvalue reference to an lvalue other than a function
  4022. // lvalue.
  4023. // Note that the function case is not possible here.
  4024. if (DeclType->isRValueReferenceType() && LValRefType) {
  4025. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4026. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4027. // reference to an rvalue!
  4028. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4029. return ICS;
  4030. }
  4031. ICS.UserDefined.Before.setAsIdentityConversion();
  4032. ICS.UserDefined.After.ReferenceBinding = true;
  4033. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4034. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4035. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4036. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4037. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4038. }
  4039. return ICS;
  4040. }
  4041. static ImplicitConversionSequence
  4042. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4043. bool SuppressUserConversions,
  4044. bool InOverloadResolution,
  4045. bool AllowObjCWritebackConversion,
  4046. bool AllowExplicit = false);
  4047. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4048. /// initializer list From.
  4049. static ImplicitConversionSequence
  4050. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4051. bool SuppressUserConversions,
  4052. bool InOverloadResolution,
  4053. bool AllowObjCWritebackConversion) {
  4054. // C++11 [over.ics.list]p1:
  4055. // When an argument is an initializer list, it is not an expression and
  4056. // special rules apply for converting it to a parameter type.
  4057. ImplicitConversionSequence Result;
  4058. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4059. // We need a complete type for what follows. Incomplete types can never be
  4060. // initialized from init lists.
  4061. if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
  4062. return Result;
  4063. // Per DR1467:
  4064. // If the parameter type is a class X and the initializer list has a single
  4065. // element of type cv U, where U is X or a class derived from X, the
  4066. // implicit conversion sequence is the one required to convert the element
  4067. // to the parameter type.
  4068. //
  4069. // Otherwise, if the parameter type is a character array [... ]
  4070. // and the initializer list has a single element that is an
  4071. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4072. // implicit conversion sequence is the identity conversion.
  4073. if (From->getNumInits() == 1) {
  4074. if (ToType->isRecordType()) {
  4075. QualType InitType = From->getInit(0)->getType();
  4076. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4077. S.IsDerivedFrom(InitType, ToType))
  4078. return TryCopyInitialization(S, From->getInit(0), ToType,
  4079. SuppressUserConversions,
  4080. InOverloadResolution,
  4081. AllowObjCWritebackConversion);
  4082. }
  4083. // FIXME: Check the other conditions here: array of character type,
  4084. // initializer is a string literal.
  4085. if (ToType->isArrayType()) {
  4086. InitializedEntity Entity =
  4087. InitializedEntity::InitializeParameter(S.Context, ToType,
  4088. /*Consumed=*/false);
  4089. if (S.CanPerformCopyInitialization(Entity, From)) {
  4090. Result.setStandard();
  4091. Result.Standard.setAsIdentityConversion();
  4092. Result.Standard.setFromType(ToType);
  4093. Result.Standard.setAllToTypes(ToType);
  4094. return Result;
  4095. }
  4096. }
  4097. }
  4098. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4099. // C++11 [over.ics.list]p2:
  4100. // If the parameter type is std::initializer_list<X> or "array of X" and
  4101. // all the elements can be implicitly converted to X, the implicit
  4102. // conversion sequence is the worst conversion necessary to convert an
  4103. // element of the list to X.
  4104. //
  4105. // C++14 [over.ics.list]p3:
  4106. // Otherwise, if the parameter type is "array of N X", if the initializer
  4107. // list has exactly N elements or if it has fewer than N elements and X is
  4108. // default-constructible, and if all the elements of the initializer list
  4109. // can be implicitly converted to X, the implicit conversion sequence is
  4110. // the worst conversion necessary to convert an element of the list to X.
  4111. //
  4112. // FIXME: We're missing a lot of these checks.
  4113. bool toStdInitializerList = false;
  4114. QualType X;
  4115. if (ToType->isArrayType())
  4116. X = S.Context.getAsArrayType(ToType)->getElementType();
  4117. else
  4118. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4119. if (!X.isNull()) {
  4120. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4121. Expr *Init = From->getInit(i);
  4122. ImplicitConversionSequence ICS =
  4123. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4124. InOverloadResolution,
  4125. AllowObjCWritebackConversion);
  4126. // If a single element isn't convertible, fail.
  4127. if (ICS.isBad()) {
  4128. Result = ICS;
  4129. break;
  4130. }
  4131. // Otherwise, look for the worst conversion.
  4132. if (Result.isBad() ||
  4133. CompareImplicitConversionSequences(S, ICS, Result) ==
  4134. ImplicitConversionSequence::Worse)
  4135. Result = ICS;
  4136. }
  4137. // For an empty list, we won't have computed any conversion sequence.
  4138. // Introduce the identity conversion sequence.
  4139. if (From->getNumInits() == 0) {
  4140. Result.setStandard();
  4141. Result.Standard.setAsIdentityConversion();
  4142. Result.Standard.setFromType(ToType);
  4143. Result.Standard.setAllToTypes(ToType);
  4144. }
  4145. Result.setStdInitializerListElement(toStdInitializerList);
  4146. return Result;
  4147. }
  4148. // C++14 [over.ics.list]p4:
  4149. // C++11 [over.ics.list]p3:
  4150. // Otherwise, if the parameter is a non-aggregate class X and overload
  4151. // resolution chooses a single best constructor [...] the implicit
  4152. // conversion sequence is a user-defined conversion sequence. If multiple
  4153. // constructors are viable but none is better than the others, the
  4154. // implicit conversion sequence is a user-defined conversion sequence.
  4155. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4156. // This function can deal with initializer lists.
  4157. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4158. /*AllowExplicit=*/false,
  4159. InOverloadResolution, /*CStyle=*/false,
  4160. AllowObjCWritebackConversion,
  4161. /*AllowObjCConversionOnExplicit=*/false);
  4162. }
  4163. // C++14 [over.ics.list]p5:
  4164. // C++11 [over.ics.list]p4:
  4165. // Otherwise, if the parameter has an aggregate type which can be
  4166. // initialized from the initializer list [...] the implicit conversion
  4167. // sequence is a user-defined conversion sequence.
  4168. if (ToType->isAggregateType()) {
  4169. // Type is an aggregate, argument is an init list. At this point it comes
  4170. // down to checking whether the initialization works.
  4171. // FIXME: Find out whether this parameter is consumed or not.
  4172. InitializedEntity Entity =
  4173. InitializedEntity::InitializeParameter(S.Context, ToType,
  4174. /*Consumed=*/false);
  4175. if (S.CanPerformCopyInitialization(Entity, From)) {
  4176. Result.setUserDefined();
  4177. Result.UserDefined.Before.setAsIdentityConversion();
  4178. // Initializer lists don't have a type.
  4179. Result.UserDefined.Before.setFromType(QualType());
  4180. Result.UserDefined.Before.setAllToTypes(QualType());
  4181. Result.UserDefined.After.setAsIdentityConversion();
  4182. Result.UserDefined.After.setFromType(ToType);
  4183. Result.UserDefined.After.setAllToTypes(ToType);
  4184. Result.UserDefined.ConversionFunction = nullptr;
  4185. }
  4186. return Result;
  4187. }
  4188. // C++14 [over.ics.list]p6:
  4189. // C++11 [over.ics.list]p5:
  4190. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4191. if (ToType->isReferenceType()) {
  4192. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4193. // mention initializer lists in any way. So we go by what list-
  4194. // initialization would do and try to extrapolate from that.
  4195. QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
  4196. // If the initializer list has a single element that is reference-related
  4197. // to the parameter type, we initialize the reference from that.
  4198. if (From->getNumInits() == 1) {
  4199. Expr *Init = From->getInit(0);
  4200. QualType T2 = Init->getType();
  4201. // If the initializer is the address of an overloaded function, try
  4202. // to resolve the overloaded function. If all goes well, T2 is the
  4203. // type of the resulting function.
  4204. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4205. DeclAccessPair Found;
  4206. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4207. Init, ToType, false, Found))
  4208. T2 = Fn->getType();
  4209. }
  4210. // Compute some basic properties of the types and the initializer.
  4211. bool dummy1 = false;
  4212. bool dummy2 = false;
  4213. bool dummy3 = false;
  4214. Sema::ReferenceCompareResult RefRelationship
  4215. = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
  4216. dummy2, dummy3);
  4217. if (RefRelationship >= Sema::Ref_Related) {
  4218. return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
  4219. SuppressUserConversions,
  4220. /*AllowExplicit=*/false);
  4221. }
  4222. }
  4223. // Otherwise, we bind the reference to a temporary created from the
  4224. // initializer list.
  4225. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4226. InOverloadResolution,
  4227. AllowObjCWritebackConversion);
  4228. if (Result.isFailure())
  4229. return Result;
  4230. assert(!Result.isEllipsis() &&
  4231. "Sub-initialization cannot result in ellipsis conversion.");
  4232. // Can we even bind to a temporary?
  4233. if (ToType->isRValueReferenceType() ||
  4234. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4235. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4236. Result.UserDefined.After;
  4237. SCS.ReferenceBinding = true;
  4238. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4239. SCS.BindsToRvalue = true;
  4240. SCS.BindsToFunctionLvalue = false;
  4241. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4242. SCS.ObjCLifetimeConversionBinding = false;
  4243. } else
  4244. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4245. From, ToType);
  4246. return Result;
  4247. }
  4248. // C++14 [over.ics.list]p7:
  4249. // C++11 [over.ics.list]p6:
  4250. // Otherwise, if the parameter type is not a class:
  4251. if (!ToType->isRecordType()) {
  4252. // - if the initializer list has one element that is not itself an
  4253. // initializer list, the implicit conversion sequence is the one
  4254. // required to convert the element to the parameter type.
  4255. unsigned NumInits = From->getNumInits();
  4256. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4257. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4258. SuppressUserConversions,
  4259. InOverloadResolution,
  4260. AllowObjCWritebackConversion);
  4261. // - if the initializer list has no elements, the implicit conversion
  4262. // sequence is the identity conversion.
  4263. else if (NumInits == 0) {
  4264. Result.setStandard();
  4265. Result.Standard.setAsIdentityConversion();
  4266. Result.Standard.setFromType(ToType);
  4267. Result.Standard.setAllToTypes(ToType);
  4268. }
  4269. return Result;
  4270. }
  4271. // C++14 [over.ics.list]p8:
  4272. // C++11 [over.ics.list]p7:
  4273. // In all cases other than those enumerated above, no conversion is possible
  4274. return Result;
  4275. }
  4276. /// TryCopyInitialization - Try to copy-initialize a value of type
  4277. /// ToType from the expression From. Return the implicit conversion
  4278. /// sequence required to pass this argument, which may be a bad
  4279. /// conversion sequence (meaning that the argument cannot be passed to
  4280. /// a parameter of this type). If @p SuppressUserConversions, then we
  4281. /// do not permit any user-defined conversion sequences.
  4282. static ImplicitConversionSequence
  4283. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4284. bool SuppressUserConversions,
  4285. bool InOverloadResolution,
  4286. bool AllowObjCWritebackConversion,
  4287. bool AllowExplicit) {
  4288. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4289. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4290. InOverloadResolution,AllowObjCWritebackConversion);
  4291. // HLSL Change Starts
  4292. if (S.getLangOpts().HLSL) {
  4293. // Note that this is incorrect. Copy initialization isn't syntactically
  4294. // allowed in HLSL, but C++ uses it to perform matching for argments to
  4295. // parameters.
  4296. //
  4297. // The correct fix should go to implicit conversions, but because the type
  4298. // system isn't currently up to spec, it's easier to isolate the behavior by
  4299. // putting this only on this path.
  4300. const bool ListInitFalse = false;
  4301. const bool SuppressDiagTrue = true;
  4302. const Sema::CheckedConversionKind kind = Sema::CCK_ImplicitConversion;
  4303. ImplicitConversionSequence ICS;
  4304. ICS.setStandard();
  4305. unsigned msg;
  4306. CastKind castKind;
  4307. CXXCastPath castPath;
  4308. ExprResult E(From);
  4309. if (::hlsl::TryStaticCastForHLSL(
  4310. &S, E, ToType, kind, From->getSourceRange(), msg, castKind,
  4311. castPath, ListInitFalse, SuppressDiagTrue, &ICS.Standard)) {
  4312. return ICS;
  4313. }
  4314. }
  4315. // HLSL Change Ends
  4316. if (ToType->isReferenceType())
  4317. return TryReferenceInit(S, From, ToType,
  4318. /*FIXME:*/From->getLocStart(),
  4319. SuppressUserConversions,
  4320. AllowExplicit);
  4321. return TryImplicitConversion(S, From, ToType,
  4322. SuppressUserConversions,
  4323. /*AllowExplicit=*/false,
  4324. InOverloadResolution,
  4325. /*CStyle=*/false,
  4326. AllowObjCWritebackConversion,
  4327. /*AllowObjCConversionOnExplicit=*/false);
  4328. }
  4329. static bool TryCopyInitialization(const CanQualType FromQTy,
  4330. const CanQualType ToQTy,
  4331. Sema &S,
  4332. SourceLocation Loc,
  4333. ExprValueKind FromVK) {
  4334. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4335. ImplicitConversionSequence ICS =
  4336. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4337. return !ICS.isBad();
  4338. }
  4339. /// TryObjectArgumentInitialization - Try to initialize the object
  4340. /// parameter of the given member function (@c Method) from the
  4341. /// expression @p From.
  4342. static ImplicitConversionSequence
  4343. TryObjectArgumentInitialization(Sema &S, QualType FromType,
  4344. Expr::Classification FromClassification,
  4345. CXXMethodDecl *Method,
  4346. CXXRecordDecl *ActingContext) {
  4347. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4348. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4349. // const volatile object.
  4350. unsigned Quals = isa<CXXDestructorDecl>(Method) ?
  4351. Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
  4352. QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
  4353. // Set up the conversion sequence as a "bad" conversion, to allow us
  4354. // to exit early.
  4355. ImplicitConversionSequence ICS;
  4356. // We need to have an object of class type.
  4357. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4358. FromType = PT->getPointeeType();
  4359. // When we had a pointer, it's implicitly dereferenced, so we
  4360. // better have an lvalue.
  4361. assert(FromClassification.isLValue());
  4362. }
  4363. assert(FromType->isRecordType());
  4364. // C++0x [over.match.funcs]p4:
  4365. // For non-static member functions, the type of the implicit object
  4366. // parameter is
  4367. //
  4368. // - "lvalue reference to cv X" for functions declared without a
  4369. // ref-qualifier or with the & ref-qualifier
  4370. // - "rvalue reference to cv X" for functions declared with the &&
  4371. // ref-qualifier
  4372. //
  4373. // where X is the class of which the function is a member and cv is the
  4374. // cv-qualification on the member function declaration.
  4375. //
  4376. // However, when finding an implicit conversion sequence for the argument, we
  4377. // are not allowed to create temporaries or perform user-defined conversions
  4378. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4379. // reference binding here, that allows class rvalues to bind to
  4380. // non-constant references.
  4381. // First check the qualifiers.
  4382. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4383. // HLSL Change Starts - for calls other than subscript overloads, disregard const
  4384. FromTypeCanon.removeLocalRestrict(); // HLSL Change - disregard restrict.
  4385. if (!S.getLangOpts().HLSL ||
  4386. (Method != nullptr && Method->getDeclName() == S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  4387. // HLSL Change Ends
  4388. if (ImplicitParamType.getCVRQualifiers()
  4389. != FromTypeCanon.getLocalCVRQualifiers() &&
  4390. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4391. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4392. FromType, ImplicitParamType);
  4393. return ICS;
  4394. }
  4395. } // HLSL Change - end branch
  4396. // Check that we have either the same type or a derived type. It
  4397. // affects the conversion rank.
  4398. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4399. ImplicitConversionKind SecondKind;
  4400. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4401. SecondKind = ICK_Identity;
  4402. } else if (S.IsDerivedFrom(FromType, ClassType))
  4403. SecondKind = ICK_Derived_To_Base;
  4404. else {
  4405. ICS.setBad(BadConversionSequence::unrelated_class,
  4406. FromType, ImplicitParamType);
  4407. return ICS;
  4408. }
  4409. // Check the ref-qualifier.
  4410. switch (Method->getRefQualifier()) {
  4411. case RQ_None:
  4412. // Do nothing; we don't care about lvalueness or rvalueness.
  4413. break;
  4414. case RQ_LValue:
  4415. if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
  4416. // non-const lvalue reference cannot bind to an rvalue
  4417. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4418. ImplicitParamType);
  4419. return ICS;
  4420. }
  4421. break;
  4422. case RQ_RValue:
  4423. if (!FromClassification.isRValue()) {
  4424. // rvalue reference cannot bind to an lvalue
  4425. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4426. ImplicitParamType);
  4427. return ICS;
  4428. }
  4429. break;
  4430. }
  4431. // Success. Mark this as a reference binding.
  4432. ICS.setStandard();
  4433. ICS.Standard.setAsIdentityConversion();
  4434. ICS.Standard.Second = SecondKind;
  4435. ICS.Standard.setFromType(FromType);
  4436. ICS.Standard.setAllToTypes(ImplicitParamType);
  4437. ICS.Standard.ReferenceBinding = true;
  4438. ICS.Standard.DirectBinding = true;
  4439. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4440. ICS.Standard.BindsToFunctionLvalue = false;
  4441. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4442. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4443. = (Method->getRefQualifier() == RQ_None);
  4444. ICS.Standard.ComponentConversion = ICK_Identity;
  4445. return ICS;
  4446. }
  4447. // HLSL Change Starts
  4448. static void
  4449. InitCallParamConversions(Sema &S, const FunctionProtoType *Proto,
  4450. ParmVarDecl *Param, unsigned ArgIdx, Expr *Arg,
  4451. bool SuppressUserConversions,
  4452. bool InOverloadResolution, bool AllowExplicit,
  4453. ImplicitConversionSequence &InConversion,
  4454. ImplicitConversionSequence &OutConversion) {
  4455. hlsl::ParameterModifier paramMods = Proto->getParamMods()[ArgIdx];
  4456. QualType ParamType = Proto->getParamType(ArgIdx);
  4457. if (paramMods.isAnyIn()) {
  4458. InConversion =
  4459. TryCopyInitialization(S, Arg, ParamType, SuppressUserConversions,
  4460. InOverloadResolution, false, AllowExplicit);
  4461. }
  4462. if (paramMods.isAnyOut()) {
  4463. // TryCopyInitialization takes an expression but there isn't one at this
  4464. // point - we're just trying to figure out whether the result value can be
  4465. // converted back into the argument.
  4466. if (Arg->getType().isConstant(S.getASTContext()) || !Arg->isLValue()) {
  4467. OutConversion.setBad(
  4468. BadConversionSequence::FailureKind::rvalue_ref_to_lvalue, ParamType,
  4469. Arg->getType());
  4470. return;
  4471. }
  4472. Expr *OutFrom = DeclRefExpr::Create(
  4473. S.getASTContext(), NestedNameSpecifierLoc(), SourceLocation(), Param,
  4474. true, Param->getLocation(), ParamType.getNonReferenceType(), VK_RValue, nullptr);
  4475. OutConversion = TryCopyInitialization(
  4476. S, OutFrom, Arg->getType(), SuppressUserConversions,
  4477. InOverloadResolution, false, AllowExplicit);
  4478. }
  4479. }
  4480. // HLSL Change Ends
  4481. /// PerformObjectArgumentInitialization - Perform initialization of
  4482. /// the implicit object parameter for the given Method with the given
  4483. /// expression.
  4484. ExprResult
  4485. Sema::PerformObjectArgumentInitialization(Expr *From,
  4486. NestedNameSpecifier *Qualifier,
  4487. NamedDecl *FoundDecl,
  4488. CXXMethodDecl *Method) {
  4489. QualType FromRecordType, DestType;
  4490. QualType ImplicitParamRecordType =
  4491. Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
  4492. Expr::Classification FromClassification;
  4493. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4494. FromRecordType = PT->getPointeeType();
  4495. DestType = Method->getThisType(Context);
  4496. FromClassification = Expr::Classification::makeSimpleLValue();
  4497. } else {
  4498. FromRecordType = From->getType();
  4499. DestType = ImplicitParamRecordType;
  4500. FromClassification = From->Classify(Context);
  4501. }
  4502. // Note that we always use the true parent context when performing
  4503. // the actual argument initialization.
  4504. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4505. *this, From->getType(), FromClassification, Method, Method->getParent());
  4506. if (ICS.isBad()) {
  4507. if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
  4508. Qualifiers FromQs = FromRecordType.getQualifiers();
  4509. Qualifiers ToQs = DestType.getQualifiers();
  4510. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4511. if (CVR) {
  4512. Diag(From->getLocStart(),
  4513. diag::err_member_function_call_bad_cvr)
  4514. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4515. << From->getSourceRange();
  4516. Diag(Method->getLocation(), diag::note_previous_decl)
  4517. << Method->getDeclName();
  4518. return ExprError();
  4519. }
  4520. }
  4521. return Diag(From->getLocStart(),
  4522. diag::err_implicit_object_parameter_init)
  4523. << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
  4524. }
  4525. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4526. ExprResult FromRes =
  4527. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4528. if (FromRes.isInvalid())
  4529. return ExprError();
  4530. From = FromRes.get();
  4531. }
  4532. if (!Context.hasSameType(From->getType(), DestType))
  4533. From = ImpCastExprToType(From, DestType, CK_NoOp,
  4534. From->getValueKind()).get();
  4535. return From;
  4536. }
  4537. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4538. /// expression From to bool (C++0x [conv]p3).
  4539. static ImplicitConversionSequence
  4540. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4541. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4542. /*SuppressUserConversions=*/false,
  4543. /*AllowExplicit=*/true,
  4544. /*InOverloadResolution=*/false,
  4545. /*CStyle=*/false,
  4546. /*AllowObjCWritebackConversion=*/false,
  4547. /*AllowObjCConversionOnExplicit=*/false);
  4548. }
  4549. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4550. /// of the expression From to bool (C++0x [conv]p3).
  4551. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4552. if (checkPlaceholderForOverload(*this, From))
  4553. return ExprError();
  4554. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4555. if (!ICS.isBad())
  4556. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4557. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4558. return Diag(From->getLocStart(),
  4559. diag::err_typecheck_bool_condition)
  4560. << From->getType() << From->getSourceRange();
  4561. return ExprError();
  4562. }
  4563. /// Check that the specified conversion is permitted in a converted constant
  4564. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4565. /// is acceptable.
  4566. static bool CheckConvertedConstantConversions(Sema &S,
  4567. StandardConversionSequence &SCS) {
  4568. // Since we know that the target type is an integral or unscoped enumeration
  4569. // type, most conversion kinds are impossible. All possible First and Third
  4570. // conversions are fine.
  4571. switch (SCS.Second) {
  4572. case ICK_Identity:
  4573. case ICK_NoReturn_Adjustment:
  4574. case ICK_Integral_Promotion:
  4575. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4576. return true;
  4577. case ICK_Boolean_Conversion:
  4578. // Conversion from an integral or unscoped enumeration type to bool is
  4579. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4580. // conversion, so we allow it in a converted constant expression.
  4581. //
  4582. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4583. // a lot of popular code. We should at least add a warning for this
  4584. // (non-conforming) extension.
  4585. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4586. SCS.getToType(2)->isBooleanType();
  4587. case ICK_Pointer_Conversion:
  4588. case ICK_Pointer_Member:
  4589. // C++1z: null pointer conversions and null member pointer conversions are
  4590. // only permitted if the source type is std::nullptr_t.
  4591. return SCS.getFromType()->isNullPtrType();
  4592. case ICK_Floating_Promotion:
  4593. case ICK_Complex_Promotion:
  4594. case ICK_Floating_Conversion:
  4595. case ICK_Complex_Conversion:
  4596. case ICK_Floating_Integral:
  4597. case ICK_Compatible_Conversion:
  4598. case ICK_Derived_To_Base:
  4599. case ICK_Vector_Conversion:
  4600. case ICK_Vector_Splat:
  4601. case ICK_Complex_Real:
  4602. case ICK_Block_Pointer_Conversion:
  4603. case ICK_TransparentUnionConversion:
  4604. case ICK_Writeback_Conversion:
  4605. case ICK_Zero_Event_Conversion:
  4606. case ICK_Flat_Conversion: // HLSL Change
  4607. return false;
  4608. case ICK_Lvalue_To_Rvalue:
  4609. case ICK_Array_To_Pointer:
  4610. case ICK_Function_To_Pointer:
  4611. llvm_unreachable("found a first conversion kind in Second");
  4612. case ICK_Qualification:
  4613. llvm_unreachable("found a third conversion kind in Second");
  4614. case ICK_Num_Conversion_Kinds:
  4615. break;
  4616. }
  4617. llvm_unreachable("unknown conversion kind");
  4618. }
  4619. /// CheckConvertedConstantExpression - Check that the expression From is a
  4620. /// converted constant expression of type T, perform the conversion and produce
  4621. /// the converted expression, per C++11 [expr.const]p3.
  4622. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4623. QualType T, APValue &Value,
  4624. Sema::CCEKind CCE,
  4625. bool RequireInt) {
  4626. assert((S.getLangOpts().CPlusPlus11 || S.getLangOpts().HLSLVersion >= 2017) &&
  4627. "converted constant expression outside C++11");
  4628. if (checkPlaceholderForOverload(S, From))
  4629. return ExprError();
  4630. // C++1z [expr.const]p3:
  4631. // A converted constant expression of type T is an expression,
  4632. // implicitly converted to type T, where the converted
  4633. // expression is a constant expression and the implicit conversion
  4634. // sequence contains only [... list of conversions ...].
  4635. ImplicitConversionSequence ICS =
  4636. TryCopyInitialization(S, From, T,
  4637. /*SuppressUserConversions=*/false,
  4638. /*InOverloadResolution=*/false,
  4639. /*AllowObjcWritebackConversion=*/false,
  4640. /*AllowExplicit=*/false);
  4641. StandardConversionSequence *SCS = nullptr;
  4642. switch (ICS.getKind()) {
  4643. case ImplicitConversionSequence::StandardConversion:
  4644. SCS = &ICS.Standard;
  4645. break;
  4646. case ImplicitConversionSequence::UserDefinedConversion:
  4647. // We are converting to a non-class type, so the Before sequence
  4648. // must be trivial.
  4649. SCS = &ICS.UserDefined.After;
  4650. break;
  4651. case ImplicitConversionSequence::AmbiguousConversion:
  4652. case ImplicitConversionSequence::BadConversion:
  4653. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4654. return S.Diag(From->getLocStart(),
  4655. diag::err_typecheck_converted_constant_expression)
  4656. << From->getType() << From->getSourceRange() << T;
  4657. return ExprError();
  4658. case ImplicitConversionSequence::EllipsisConversion:
  4659. llvm_unreachable("ellipsis conversion in converted constant expression");
  4660. }
  4661. // Check that we would only use permitted conversions.
  4662. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4663. return S.Diag(From->getLocStart(),
  4664. diag::err_typecheck_converted_constant_expression_disallowed)
  4665. << From->getType() << From->getSourceRange() << T;
  4666. }
  4667. // [...] and where the reference binding (if any) binds directly.
  4668. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4669. return S.Diag(From->getLocStart(),
  4670. diag::err_typecheck_converted_constant_expression_indirect)
  4671. << From->getType() << From->getSourceRange() << T;
  4672. }
  4673. ExprResult Result =
  4674. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4675. if (Result.isInvalid())
  4676. return Result;
  4677. // Check for a narrowing implicit conversion.
  4678. APValue PreNarrowingValue;
  4679. QualType PreNarrowingType;
  4680. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4681. PreNarrowingType)) {
  4682. case NK_Variable_Narrowing:
  4683. // Implicit conversion to a narrower type, and the value is not a constant
  4684. // expression. We'll diagnose this in a moment.
  4685. case NK_Not_Narrowing:
  4686. break;
  4687. case NK_Constant_Narrowing:
  4688. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4689. << CCE << /*Constant*/1
  4690. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  4691. break;
  4692. case NK_Type_Narrowing:
  4693. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4694. << CCE << /*Constant*/0 << From->getType() << T;
  4695. break;
  4696. }
  4697. // Check the expression is a constant expression.
  4698. SmallVector<PartialDiagnosticAt, 8> Notes;
  4699. Expr::EvalResult Eval;
  4700. Eval.Diag = &Notes;
  4701. if ((T->isReferenceType()
  4702. ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
  4703. : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
  4704. (RequireInt && !Eval.Val.isInt())) {
  4705. // The expression can't be folded, so we can't keep it at this position in
  4706. // the AST.
  4707. Result = ExprError();
  4708. } else {
  4709. Value = Eval.Val;
  4710. if (Notes.empty()) {
  4711. // It's a constant expression.
  4712. return Result;
  4713. }
  4714. }
  4715. // It's not a constant expression. Produce an appropriate diagnostic.
  4716. if (Notes.size() == 1 &&
  4717. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  4718. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  4719. else {
  4720. S.Diag(From->getLocStart(), diag::err_expr_not_cce)
  4721. << CCE << From->getSourceRange();
  4722. for (unsigned I = 0; I < Notes.size(); ++I)
  4723. S.Diag(Notes[I].first, Notes[I].second);
  4724. }
  4725. return ExprError();
  4726. }
  4727. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4728. APValue &Value, CCEKind CCE) {
  4729. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  4730. }
  4731. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4732. llvm::APSInt &Value,
  4733. CCEKind CCE) {
  4734. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  4735. APValue V;
  4736. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  4737. if (!R.isInvalid())
  4738. Value = V.getInt();
  4739. return R;
  4740. }
  4741. /// dropPointerConversions - If the given standard conversion sequence
  4742. /// involves any pointer conversions, remove them. This may change
  4743. /// the result type of the conversion sequence.
  4744. static void dropPointerConversion(StandardConversionSequence &SCS) {
  4745. if (SCS.Second == ICK_Pointer_Conversion) {
  4746. SCS.Second = ICK_Identity;
  4747. SCS.Third = ICK_Identity;
  4748. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  4749. }
  4750. }
  4751. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  4752. /// convert the expression From to an Objective-C pointer type.
  4753. static ImplicitConversionSequence
  4754. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  4755. // Do an implicit conversion to 'id'.
  4756. QualType Ty = S.Context.getObjCIdType();
  4757. ImplicitConversionSequence ICS
  4758. = TryImplicitConversion(S, From, Ty,
  4759. // FIXME: Are these flags correct?
  4760. /*SuppressUserConversions=*/false,
  4761. /*AllowExplicit=*/true,
  4762. /*InOverloadResolution=*/false,
  4763. /*CStyle=*/false,
  4764. /*AllowObjCWritebackConversion=*/false,
  4765. /*AllowObjCConversionOnExplicit=*/true);
  4766. // Strip off any final conversions to 'id'.
  4767. switch (ICS.getKind()) {
  4768. case ImplicitConversionSequence::BadConversion:
  4769. case ImplicitConversionSequence::AmbiguousConversion:
  4770. case ImplicitConversionSequence::EllipsisConversion:
  4771. break;
  4772. case ImplicitConversionSequence::UserDefinedConversion:
  4773. dropPointerConversion(ICS.UserDefined.After);
  4774. break;
  4775. case ImplicitConversionSequence::StandardConversion:
  4776. dropPointerConversion(ICS.Standard);
  4777. break;
  4778. }
  4779. return ICS;
  4780. }
  4781. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  4782. /// conversion of the expression From to an Objective-C pointer type.
  4783. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  4784. if (checkPlaceholderForOverload(*this, From))
  4785. return ExprError();
  4786. QualType Ty = Context.getObjCIdType();
  4787. ImplicitConversionSequence ICS =
  4788. TryContextuallyConvertToObjCPointer(*this, From);
  4789. if (!ICS.isBad())
  4790. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  4791. return ExprError();
  4792. }
  4793. /// Determine whether the provided type is an integral type, or an enumeration
  4794. /// type of a permitted flavor.
  4795. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  4796. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  4797. : T->isIntegralOrUnscopedEnumerationType();
  4798. }
  4799. static ExprResult
  4800. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  4801. Sema::ContextualImplicitConverter &Converter,
  4802. QualType T, UnresolvedSetImpl &ViableConversions) {
  4803. if (Converter.Suppress)
  4804. return ExprError();
  4805. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  4806. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4807. CXXConversionDecl *Conv =
  4808. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  4809. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  4810. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  4811. }
  4812. return From;
  4813. }
  4814. static bool
  4815. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4816. Sema::ContextualImplicitConverter &Converter,
  4817. QualType T, bool HadMultipleCandidates,
  4818. UnresolvedSetImpl &ExplicitConversions) {
  4819. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  4820. DeclAccessPair Found = ExplicitConversions[0];
  4821. CXXConversionDecl *Conversion =
  4822. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4823. // The user probably meant to invoke the given explicit
  4824. // conversion; use it.
  4825. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  4826. std::string TypeStr;
  4827. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  4828. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  4829. << FixItHint::CreateInsertion(From->getLocStart(),
  4830. "static_cast<" + TypeStr + ">(")
  4831. << FixItHint::CreateInsertion(
  4832. SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
  4833. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  4834. // If we aren't in a SFINAE context, build a call to the
  4835. // explicit conversion function.
  4836. if (SemaRef.isSFINAEContext())
  4837. return true;
  4838. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4839. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4840. HadMultipleCandidates);
  4841. if (Result.isInvalid())
  4842. return true;
  4843. // Record usage of conversion in an implicit cast.
  4844. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4845. CK_UserDefinedConversion, Result.get(),
  4846. nullptr, Result.get()->getValueKind());
  4847. }
  4848. return false;
  4849. }
  4850. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4851. Sema::ContextualImplicitConverter &Converter,
  4852. QualType T, bool HadMultipleCandidates,
  4853. DeclAccessPair &Found) {
  4854. CXXConversionDecl *Conversion =
  4855. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4856. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4857. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  4858. if (!Converter.SuppressConversion) {
  4859. if (SemaRef.isSFINAEContext())
  4860. return true;
  4861. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  4862. << From->getSourceRange();
  4863. }
  4864. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4865. HadMultipleCandidates);
  4866. if (Result.isInvalid())
  4867. return true;
  4868. // Record usage of conversion in an implicit cast.
  4869. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4870. CK_UserDefinedConversion, Result.get(),
  4871. nullptr, Result.get()->getValueKind());
  4872. return false;
  4873. }
  4874. static ExprResult finishContextualImplicitConversion(
  4875. Sema &SemaRef, SourceLocation Loc, Expr *From,
  4876. Sema::ContextualImplicitConverter &Converter) {
  4877. if (!Converter.match(From->getType()) && !Converter.Suppress)
  4878. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  4879. << From->getSourceRange();
  4880. return SemaRef.DefaultLvalueConversion(From);
  4881. }
  4882. static void
  4883. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  4884. UnresolvedSetImpl &ViableConversions,
  4885. OverloadCandidateSet &CandidateSet) {
  4886. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4887. DeclAccessPair FoundDecl = ViableConversions[I];
  4888. NamedDecl *D = FoundDecl.getDecl();
  4889. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  4890. if (isa<UsingShadowDecl>(D))
  4891. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4892. CXXConversionDecl *Conv;
  4893. FunctionTemplateDecl *ConvTemplate;
  4894. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  4895. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4896. else
  4897. Conv = cast<CXXConversionDecl>(D);
  4898. if (ConvTemplate)
  4899. SemaRef.AddTemplateConversionCandidate(
  4900. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  4901. /*AllowObjCConversionOnExplicit=*/false);
  4902. else
  4903. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  4904. ToType, CandidateSet,
  4905. /*AllowObjCConversionOnExplicit=*/false);
  4906. }
  4907. }
  4908. /// \brief Attempt to convert the given expression to a type which is accepted
  4909. /// by the given converter.
  4910. ///
  4911. /// This routine will attempt to convert an expression of class type to a
  4912. /// type accepted by the specified converter. In C++11 and before, the class
  4913. /// must have a single non-explicit conversion function converting to a matching
  4914. /// type. In C++1y, there can be multiple such conversion functions, but only
  4915. /// one target type.
  4916. ///
  4917. /// \param Loc The source location of the construct that requires the
  4918. /// conversion.
  4919. ///
  4920. /// \param From The expression we're converting from.
  4921. ///
  4922. /// \param Converter Used to control and diagnose the conversion process.
  4923. ///
  4924. /// \returns The expression, converted to an integral or enumeration type if
  4925. /// successful.
  4926. ExprResult Sema::PerformContextualImplicitConversion(
  4927. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  4928. // We can't perform any more checking for type-dependent expressions.
  4929. if (From->isTypeDependent())
  4930. return From;
  4931. // Process placeholders immediately.
  4932. if (From->hasPlaceholderType()) {
  4933. ExprResult result = CheckPlaceholderExpr(From);
  4934. if (result.isInvalid())
  4935. return result;
  4936. From = result.get();
  4937. }
  4938. // If the expression already has a matching type, we're golden.
  4939. QualType T = From->getType();
  4940. if (Converter.match(T))
  4941. return DefaultLvalueConversion(From);
  4942. // FIXME: Check for missing '()' if T is a function type?
  4943. // We can only perform contextual implicit conversions on objects of class
  4944. // type.
  4945. const RecordType *RecordTy = T->getAs<RecordType>();
  4946. if (!RecordTy || !getLangOpts().CPlusPlus) {
  4947. if (!Converter.Suppress)
  4948. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  4949. return From;
  4950. }
  4951. // We must have a complete class type.
  4952. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  4953. ContextualImplicitConverter &Converter;
  4954. Expr *From;
  4955. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  4956. : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
  4957. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  4958. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  4959. }
  4960. } IncompleteDiagnoser(Converter, From);
  4961. if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
  4962. return From;
  4963. // Look for a conversion to an integral or enumeration type.
  4964. UnresolvedSet<4>
  4965. ViableConversions; // These are *potentially* viable in C++1y.
  4966. UnresolvedSet<4> ExplicitConversions;
  4967. const auto &Conversions =
  4968. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  4969. bool HadMultipleCandidates =
  4970. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  4971. // To check that there is only one target type, in C++1y:
  4972. QualType ToType;
  4973. bool HasUniqueTargetType = true;
  4974. // Collect explicit or viable (potentially in C++1y) conversions.
  4975. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4976. NamedDecl *D = (*I)->getUnderlyingDecl();
  4977. CXXConversionDecl *Conversion;
  4978. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4979. if (ConvTemplate) {
  4980. if (getLangOpts().CPlusPlus14)
  4981. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4982. else
  4983. continue; // C++11 does not consider conversion operator templates(?).
  4984. } else
  4985. Conversion = cast<CXXConversionDecl>(D);
  4986. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  4987. "Conversion operator templates are considered potentially "
  4988. "viable in C++1y");
  4989. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  4990. if (Converter.match(CurToType) || ConvTemplate) {
  4991. if (Conversion->isExplicit()) {
  4992. // FIXME: For C++1y, do we need this restriction?
  4993. // cf. diagnoseNoViableConversion()
  4994. if (!ConvTemplate)
  4995. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  4996. } else {
  4997. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  4998. if (ToType.isNull())
  4999. ToType = CurToType.getUnqualifiedType();
  5000. else if (HasUniqueTargetType &&
  5001. (CurToType.getUnqualifiedType() != ToType))
  5002. HasUniqueTargetType = false;
  5003. }
  5004. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5005. }
  5006. }
  5007. }
  5008. if (getLangOpts().CPlusPlus14) {
  5009. // C++1y [conv]p6:
  5010. // ... An expression e of class type E appearing in such a context
  5011. // is said to be contextually implicitly converted to a specified
  5012. // type T and is well-formed if and only if e can be implicitly
  5013. // converted to a type T that is determined as follows: E is searched
  5014. // for conversion functions whose return type is cv T or reference to
  5015. // cv T such that T is allowed by the context. There shall be
  5016. // exactly one such T.
  5017. // If no unique T is found:
  5018. if (ToType.isNull()) {
  5019. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5020. HadMultipleCandidates,
  5021. ExplicitConversions))
  5022. return ExprError();
  5023. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5024. }
  5025. // If more than one unique Ts are found:
  5026. if (!HasUniqueTargetType)
  5027. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5028. ViableConversions);
  5029. // If one unique T is found:
  5030. // First, build a candidate set from the previously recorded
  5031. // potentially viable conversions.
  5032. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5033. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5034. CandidateSet);
  5035. // Then, perform overload resolution over the candidate set.
  5036. OverloadCandidateSet::iterator Best;
  5037. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5038. case OR_Success: {
  5039. // Apply this conversion.
  5040. DeclAccessPair Found =
  5041. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5042. if (recordConversion(*this, Loc, From, Converter, T,
  5043. HadMultipleCandidates, Found))
  5044. return ExprError();
  5045. break;
  5046. }
  5047. case OR_Ambiguous:
  5048. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5049. ViableConversions);
  5050. case OR_No_Viable_Function:
  5051. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5052. HadMultipleCandidates,
  5053. ExplicitConversions))
  5054. return ExprError();
  5055. // fall through 'OR_Deleted' case.
  5056. case OR_Deleted:
  5057. // We'll complain below about a non-integral condition type.
  5058. break;
  5059. }
  5060. } else {
  5061. switch (ViableConversions.size()) {
  5062. case 0: {
  5063. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5064. HadMultipleCandidates,
  5065. ExplicitConversions))
  5066. return ExprError();
  5067. // We'll complain below about a non-integral condition type.
  5068. break;
  5069. }
  5070. case 1: {
  5071. // Apply this conversion.
  5072. DeclAccessPair Found = ViableConversions[0];
  5073. if (recordConversion(*this, Loc, From, Converter, T,
  5074. HadMultipleCandidates, Found))
  5075. return ExprError();
  5076. break;
  5077. }
  5078. default:
  5079. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5080. ViableConversions);
  5081. }
  5082. }
  5083. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5084. }
  5085. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5086. /// an acceptable non-member overloaded operator for a call whose
  5087. /// arguments have types T1 (and, if non-empty, T2). This routine
  5088. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5089. /// enumeration types.
  5090. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5091. FunctionDecl *Fn,
  5092. ArrayRef<Expr *> Args) {
  5093. QualType T1 = Args[0]->getType();
  5094. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5095. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5096. return true;
  5097. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5098. return true;
  5099. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5100. if (Proto->getNumParams() < 1)
  5101. return false;
  5102. if (T1->isEnumeralType()) {
  5103. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5104. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5105. return true;
  5106. }
  5107. if (Proto->getNumParams() < 2)
  5108. return false;
  5109. if (!T2.isNull() && T2->isEnumeralType()) {
  5110. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5111. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5112. return true;
  5113. }
  5114. return false;
  5115. }
  5116. /// AddOverloadCandidate - Adds the given function to the set of
  5117. /// candidate functions, using the given function call arguments. If
  5118. /// @p SuppressUserConversions, then don't allow user-defined
  5119. /// conversions via constructors or conversion operators.
  5120. ///
  5121. /// \param PartialOverloading true if we are performing "partial" overloading
  5122. /// based on an incomplete set of function arguments. This feature is used by
  5123. /// code completion.
  5124. void
  5125. Sema::AddOverloadCandidate(FunctionDecl *Function,
  5126. DeclAccessPair FoundDecl,
  5127. ArrayRef<Expr *> Args,
  5128. OverloadCandidateSet &CandidateSet,
  5129. bool SuppressUserConversions,
  5130. bool PartialOverloading,
  5131. bool AllowExplicit) {
  5132. const FunctionProtoType *Proto
  5133. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5134. assert(Proto && "Functions without a prototype cannot be overloaded");
  5135. assert(!Function->getDescribedFunctionTemplate() &&
  5136. "Use AddTemplateOverloadCandidate for function templates");
  5137. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5138. if (!isa<CXXConstructorDecl>(Method)) {
  5139. // If we get here, it's because we're calling a member function
  5140. // that is named without a member access expression (e.g.,
  5141. // "this->f") that was either written explicitly or created
  5142. // implicitly. This can happen with a qualified call to a member
  5143. // function, e.g., X::f(). We use an empty type for the implied
  5144. // object argument (C++ [over.call.func]p3), and the acting context
  5145. // is irrelevant.
  5146. AddMethodCandidate(Method, FoundDecl, Method->getParent(),
  5147. QualType(), Expr::Classification::makeSimpleLValue(),
  5148. Args, CandidateSet, SuppressUserConversions,
  5149. PartialOverloading);
  5150. return;
  5151. }
  5152. // We treat a constructor like a non-member function, since its object
  5153. // argument doesn't participate in overload resolution.
  5154. }
  5155. if (!CandidateSet.isNewCandidate(Function) || hlsl::IsIntrinsicOp(Function))
  5156. return;
  5157. // C++ [over.match.oper]p3:
  5158. // if no operand has a class type, only those non-member functions in the
  5159. // lookup set that have a first parameter of type T1 or "reference to
  5160. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5161. // is a right operand) a second parameter of type T2 or "reference to
  5162. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5163. // candidate functions.
  5164. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5165. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5166. return;
  5167. // C++11 [class.copy]p11: [DR1402]
  5168. // A defaulted move constructor that is defined as deleted is ignored by
  5169. // overload resolution.
  5170. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5171. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5172. Constructor->isMoveConstructor())
  5173. return;
  5174. // Overload resolution is always an unevaluated context.
  5175. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5176. // Add this candidate
  5177. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  5178. Candidate.FoundDecl = FoundDecl;
  5179. Candidate.Function = Function;
  5180. Candidate.Viable = true;
  5181. Candidate.IsSurrogate = false;
  5182. Candidate.IgnoreObjectArgument = false;
  5183. Candidate.ExplicitCallArguments = Args.size();
  5184. if (Constructor) {
  5185. // C++ [class.copy]p3:
  5186. // A member function template is never instantiated to perform the copy
  5187. // of a class object to an object of its class type.
  5188. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5189. if (Args.size() == 1 &&
  5190. Constructor->isSpecializationCopyingObject() &&
  5191. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5192. IsDerivedFrom(Args[0]->getType(), ClassType))) {
  5193. Candidate.Viable = false;
  5194. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5195. return;
  5196. }
  5197. }
  5198. unsigned NumParams = Proto->getNumParams();
  5199. // (C++ 13.3.2p2): A candidate function having fewer than m
  5200. // parameters is viable only if it has an ellipsis in its parameter
  5201. // list (8.3.5).
  5202. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5203. !Proto->isVariadic()) {
  5204. Candidate.Viable = false;
  5205. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5206. return;
  5207. }
  5208. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5209. // is viable only if the (m+1)st parameter has a default argument
  5210. // (8.3.6). For the purposes of overload resolution, the
  5211. // parameter list is truncated on the right, so that there are
  5212. // exactly m parameters.
  5213. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5214. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5215. // Not enough arguments.
  5216. Candidate.Viable = false;
  5217. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5218. return;
  5219. }
  5220. // (CUDA B.1): Check for invalid calls between targets.
  5221. if (getLangOpts().CUDA)
  5222. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5223. // Skip the check for callers that are implicit members, because in this
  5224. // case we may not yet know what the member's target is; the target is
  5225. // inferred for the member automatically, based on the bases and fields of
  5226. // the class.
  5227. if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
  5228. Candidate.Viable = false;
  5229. Candidate.FailureKind = ovl_fail_bad_target;
  5230. return;
  5231. }
  5232. // Determine the implicit conversion sequences for each of the
  5233. // arguments.
  5234. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5235. if (ArgIdx < NumParams) {
  5236. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5237. // exist for each argument an implicit conversion sequence
  5238. // (13.3.3.1) that converts that argument to the corresponding
  5239. // parameter of F.
  5240. // HLSL Change Starts
  5241. if (getLangOpts().HLSL) {
  5242. InitCallParamConversions(
  5243. *this, Proto, Function->getParamDecl(ArgIdx), ArgIdx, Args[ArgIdx],
  5244. SuppressUserConversions, true, AllowExplicit,
  5245. Candidate.Conversions[ArgIdx], Candidate.OutConversions[ArgIdx]);
  5246. } else {
  5247. QualType ParamType = Proto->getParamType(ArgIdx);
  5248. Candidate.Conversions[ArgIdx]
  5249. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5250. SuppressUserConversions,
  5251. /*InOverloadResolution=*/true,
  5252. /*AllowObjCWritebackConversion=*/
  5253. getLangOpts().ObjCAutoRefCount,
  5254. AllowExplicit);
  5255. }
  5256. // HLSL Change Ends
  5257. if ((Candidate.Conversions[ArgIdx].isInitialized() && Candidate.Conversions[ArgIdx].isBad())
  5258. || (Candidate.OutConversions[ArgIdx].isInitialized() && Candidate.OutConversions[ArgIdx].isBad())) { // HLSL Change - add out conversion, check initialized
  5259. Candidate.Viable = false;
  5260. Candidate.FailureKind = ovl_fail_bad_conversion;
  5261. return;
  5262. }
  5263. } else {
  5264. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5265. // argument for which there is no corresponding parameter is
  5266. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5267. Candidate.Conversions[ArgIdx].setEllipsis();
  5268. }
  5269. }
  5270. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5271. Candidate.Viable = false;
  5272. Candidate.FailureKind = ovl_fail_enable_if;
  5273. Candidate.DeductionFailure.Data = FailedAttr;
  5274. return;
  5275. }
  5276. }
  5277. ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
  5278. bool IsInstance) {
  5279. SmallVector<ObjCMethodDecl*, 4> Methods;
  5280. if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
  5281. return nullptr;
  5282. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5283. bool Match = true;
  5284. ObjCMethodDecl *Method = Methods[b];
  5285. unsigned NumNamedArgs = Sel.getNumArgs();
  5286. // Method might have more arguments than selector indicates. This is due
  5287. // to addition of c-style arguments in method.
  5288. if (Method->param_size() > NumNamedArgs)
  5289. NumNamedArgs = Method->param_size();
  5290. if (Args.size() < NumNamedArgs)
  5291. continue;
  5292. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5293. // We can't do any type-checking on a type-dependent argument.
  5294. if (Args[i]->isTypeDependent()) {
  5295. Match = false;
  5296. break;
  5297. }
  5298. ParmVarDecl *param = Method->parameters()[i];
  5299. Expr *argExpr = Args[i];
  5300. assert(argExpr && "SelectBestMethod(): missing expression");
  5301. // Strip the unbridged-cast placeholder expression off unless it's
  5302. // a consumed argument.
  5303. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5304. !param->hasAttr<CFConsumedAttr>())
  5305. argExpr = stripARCUnbridgedCast(argExpr);
  5306. // If the parameter is __unknown_anytype, move on to the next method.
  5307. if (param->getType() == Context.UnknownAnyTy) {
  5308. Match = false;
  5309. break;
  5310. }
  5311. ImplicitConversionSequence ConversionState
  5312. = TryCopyInitialization(*this, argExpr, param->getType(),
  5313. /*SuppressUserConversions*/false,
  5314. /*InOverloadResolution=*/true,
  5315. /*AllowObjCWritebackConversion=*/
  5316. getLangOpts().ObjCAutoRefCount,
  5317. /*AllowExplicit*/false);
  5318. if (ConversionState.isBad()) {
  5319. Match = false;
  5320. break;
  5321. }
  5322. }
  5323. // Promote additional arguments to variadic methods.
  5324. if (Match && Method->isVariadic()) {
  5325. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5326. if (Args[i]->isTypeDependent()) {
  5327. Match = false;
  5328. break;
  5329. }
  5330. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5331. nullptr);
  5332. if (Arg.isInvalid()) {
  5333. Match = false;
  5334. break;
  5335. }
  5336. }
  5337. } else {
  5338. // Check for extra arguments to non-variadic methods.
  5339. if (Args.size() != NumNamedArgs)
  5340. Match = false;
  5341. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5342. // Special case when selectors have no argument. In this case, select
  5343. // one with the most general result type of 'id'.
  5344. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5345. QualType ReturnT = Methods[b]->getReturnType();
  5346. if (ReturnT->isObjCIdType())
  5347. return Methods[b];
  5348. }
  5349. }
  5350. }
  5351. if (Match)
  5352. return Method;
  5353. }
  5354. return nullptr;
  5355. }
  5356. static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
  5357. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5358. bool MissingImplicitThis) {
  5359. // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
  5360. // we need to find the first failing one.
  5361. if (!Function->hasAttrs())
  5362. return nullptr;
  5363. AttrVec Attrs = Function->getAttrs();
  5364. AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
  5365. IsNotEnableIfAttr);
  5366. if (Attrs.begin() == E)
  5367. return nullptr;
  5368. std::reverse(Attrs.begin(), E);
  5369. SFINAETrap Trap(*this);
  5370. // Convert the arguments.
  5371. SmallVector<Expr *, 16> ConvertedArgs;
  5372. bool InitializationFailed = false;
  5373. bool ContainsValueDependentExpr = false;
  5374. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5375. if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
  5376. !cast<CXXMethodDecl>(Function)->isStatic() &&
  5377. !isa<CXXConstructorDecl>(Function)) {
  5378. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5379. ExprResult R =
  5380. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  5381. Method, Method);
  5382. if (R.isInvalid()) {
  5383. InitializationFailed = true;
  5384. break;
  5385. }
  5386. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5387. ConvertedArgs.push_back(R.get());
  5388. } else {
  5389. ExprResult R =
  5390. PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5391. Context,
  5392. Function->getParamDecl(i)),
  5393. SourceLocation(),
  5394. Args[i]);
  5395. if (R.isInvalid()) {
  5396. InitializationFailed = true;
  5397. break;
  5398. }
  5399. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5400. ConvertedArgs.push_back(R.get());
  5401. }
  5402. }
  5403. if (InitializationFailed || Trap.hasErrorOccurred())
  5404. return cast<EnableIfAttr>(Attrs[0]);
  5405. for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
  5406. APValue Result;
  5407. EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
  5408. if (EIA->getCond()->isValueDependent()) {
  5409. // Don't even try now, we'll examine it after instantiation.
  5410. continue;
  5411. }
  5412. if (!EIA->getCond()->EvaluateWithSubstitution(
  5413. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
  5414. if (!ContainsValueDependentExpr)
  5415. return EIA;
  5416. } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
  5417. return EIA;
  5418. }
  5419. }
  5420. return nullptr;
  5421. }
  5422. /// \brief Add all of the function declarations in the given function set to
  5423. /// the overload candidate set.
  5424. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5425. ArrayRef<Expr *> Args,
  5426. OverloadCandidateSet& CandidateSet,
  5427. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5428. bool SuppressUserConversions,
  5429. bool PartialOverloading) {
  5430. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5431. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5432. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  5433. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  5434. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5435. cast<CXXMethodDecl>(FD)->getParent(),
  5436. Args[0]->getType(), Args[0]->Classify(Context),
  5437. Args.slice(1), CandidateSet,
  5438. SuppressUserConversions, PartialOverloading);
  5439. else
  5440. AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
  5441. SuppressUserConversions, PartialOverloading);
  5442. } else {
  5443. FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
  5444. if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
  5445. !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
  5446. AddMethodTemplateCandidate(FunTmpl, F.getPair(),
  5447. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5448. ExplicitTemplateArgs,
  5449. Args[0]->getType(),
  5450. Args[0]->Classify(Context), Args.slice(1),
  5451. CandidateSet, SuppressUserConversions,
  5452. PartialOverloading);
  5453. else
  5454. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  5455. ExplicitTemplateArgs, Args,
  5456. CandidateSet, SuppressUserConversions,
  5457. PartialOverloading);
  5458. }
  5459. }
  5460. }
  5461. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5462. /// method) as a method candidate to the given overload set.
  5463. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
  5464. QualType ObjectType,
  5465. Expr::Classification ObjectClassification,
  5466. ArrayRef<Expr *> Args,
  5467. OverloadCandidateSet& CandidateSet,
  5468. bool SuppressUserConversions) {
  5469. NamedDecl *Decl = FoundDecl.getDecl();
  5470. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5471. if (isa<UsingShadowDecl>(Decl))
  5472. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5473. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5474. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5475. "Expected a member function template");
  5476. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5477. /*ExplicitArgs*/ nullptr,
  5478. ObjectType, ObjectClassification,
  5479. Args, CandidateSet,
  5480. SuppressUserConversions);
  5481. } else {
  5482. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5483. ObjectType, ObjectClassification,
  5484. Args,
  5485. CandidateSet, SuppressUserConversions);
  5486. }
  5487. }
  5488. /// AddMethodCandidate - Adds the given C++ member function to the set
  5489. /// of candidate functions, using the given function call arguments
  5490. /// and the object argument (@c Object). For example, in a call
  5491. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5492. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5493. /// allow user-defined conversions via constructors or conversion
  5494. /// operators.
  5495. void
  5496. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5497. CXXRecordDecl *ActingContext, QualType ObjectType,
  5498. Expr::Classification ObjectClassification,
  5499. ArrayRef<Expr *> Args,
  5500. OverloadCandidateSet &CandidateSet,
  5501. bool SuppressUserConversions,
  5502. bool PartialOverloading) {
  5503. const FunctionProtoType *Proto
  5504. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5505. assert(Proto && "Methods without a prototype cannot be overloaded");
  5506. assert(!isa<CXXConstructorDecl>(Method) &&
  5507. "Use AddOverloadCandidate for constructors");
  5508. if (!CandidateSet.isNewCandidate(Method))
  5509. return;
  5510. // C++11 [class.copy]p23: [DR1402]
  5511. // A defaulted move assignment operator that is defined as deleted is
  5512. // ignored by overload resolution.
  5513. if (Method->isDefaulted() && Method->isDeleted() &&
  5514. Method->isMoveAssignmentOperator())
  5515. return;
  5516. // Overload resolution is always an unevaluated context.
  5517. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5518. // Add this candidate
  5519. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5520. Candidate.FoundDecl = FoundDecl;
  5521. Candidate.Function = Method;
  5522. Candidate.IsSurrogate = false;
  5523. Candidate.IgnoreObjectArgument = false;
  5524. Candidate.ExplicitCallArguments = Args.size();
  5525. unsigned NumParams = Proto->getNumParams();
  5526. // (C++ 13.3.2p2): A candidate function having fewer than m
  5527. // parameters is viable only if it has an ellipsis in its parameter
  5528. // list (8.3.5).
  5529. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5530. !Proto->isVariadic()) {
  5531. Candidate.Viable = false;
  5532. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5533. return;
  5534. }
  5535. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5536. // is viable only if the (m+1)st parameter has a default argument
  5537. // (8.3.6). For the purposes of overload resolution, the
  5538. // parameter list is truncated on the right, so that there are
  5539. // exactly m parameters.
  5540. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  5541. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5542. // Not enough arguments.
  5543. Candidate.Viable = false;
  5544. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5545. return;
  5546. }
  5547. Candidate.Viable = true;
  5548. if (Method->isStatic() || ObjectType.isNull())
  5549. // The implicit object argument is ignored.
  5550. Candidate.IgnoreObjectArgument = true;
  5551. else {
  5552. // Determine the implicit conversion sequence for the object
  5553. // parameter.
  5554. Candidate.Conversions[0]
  5555. = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
  5556. Method, ActingContext);
  5557. if (Candidate.Conversions[0].isBad()) {
  5558. Candidate.Viable = false;
  5559. Candidate.FailureKind = ovl_fail_bad_conversion;
  5560. return;
  5561. }
  5562. }
  5563. // (CUDA B.1): Check for invalid calls between targets.
  5564. if (getLangOpts().CUDA)
  5565. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5566. if (CheckCUDATarget(Caller, Method)) {
  5567. Candidate.Viable = false;
  5568. Candidate.FailureKind = ovl_fail_bad_target;
  5569. return;
  5570. }
  5571. // Determine the implicit conversion sequences for each of the
  5572. // arguments.
  5573. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5574. if (ArgIdx < NumParams) {
  5575. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5576. // exist for each argument an implicit conversion sequence
  5577. // (13.3.3.1) that converts that argument to the corresponding
  5578. // parameter of F.
  5579. QualType ParamType = Proto->getParamType(ArgIdx);
  5580. // HLSL Change Starts
  5581. if (getLangOpts().HLSL && Method->getDeclName() == Context.DeclarationNames.getCXXOperatorName(OO_Subscript)) {
  5582. Candidate.Conversions[ArgIdx + 1] = hlsl::TrySubscriptIndexInitialization(
  5583. this, Args[ArgIdx], ParamType);
  5584. goto EvaluateCandidate;
  5585. }
  5586. // HLSL Change Ends
  5587. Candidate.Conversions[ArgIdx + 1]
  5588. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5589. SuppressUserConversions,
  5590. /*InOverloadResolution=*/true,
  5591. /*AllowObjCWritebackConversion=*/
  5592. getLangOpts().ObjCAutoRefCount);
  5593. EvaluateCandidate:// HLSL Change - present alterantive to TryCopyInitialization
  5594. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  5595. Candidate.Viable = false;
  5596. Candidate.FailureKind = ovl_fail_bad_conversion;
  5597. return;
  5598. }
  5599. } else {
  5600. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5601. // argument for which there is no corresponding parameter is
  5602. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  5603. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  5604. }
  5605. }
  5606. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  5607. Candidate.Viable = false;
  5608. Candidate.FailureKind = ovl_fail_enable_if;
  5609. Candidate.DeductionFailure.Data = FailedAttr;
  5610. return;
  5611. }
  5612. }
  5613. /// \brief Add a C++ member function template as a candidate to the candidate
  5614. /// set, using template argument deduction to produce an appropriate member
  5615. /// function template specialization.
  5616. void
  5617. Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
  5618. DeclAccessPair FoundDecl,
  5619. CXXRecordDecl *ActingContext,
  5620. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5621. QualType ObjectType,
  5622. Expr::Classification ObjectClassification,
  5623. ArrayRef<Expr *> Args,
  5624. OverloadCandidateSet& CandidateSet,
  5625. bool SuppressUserConversions,
  5626. bool PartialOverloading) {
  5627. if (!CandidateSet.isNewCandidate(MethodTmpl))
  5628. return;
  5629. // C++ [over.match.funcs]p7:
  5630. // In each case where a candidate is a function template, candidate
  5631. // function template specializations are generated using template argument
  5632. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5633. // candidate functions in the usual way.113) A given name can refer to one
  5634. // or more function templates and also to a set of overloaded non-template
  5635. // functions. In such a case, the candidate functions generated from each
  5636. // function template are combined with the set of non-template candidate
  5637. // functions.
  5638. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5639. FunctionDecl *Specialization = nullptr;
  5640. if (TemplateDeductionResult Result
  5641. = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
  5642. Specialization, Info, PartialOverloading)) {
  5643. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5644. Candidate.FoundDecl = FoundDecl;
  5645. Candidate.Function = MethodTmpl->getTemplatedDecl();
  5646. Candidate.Viable = false;
  5647. Candidate.FailureKind = ovl_fail_bad_deduction;
  5648. Candidate.IsSurrogate = false;
  5649. Candidate.IgnoreObjectArgument = false;
  5650. Candidate.ExplicitCallArguments = Args.size();
  5651. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5652. Info);
  5653. return;
  5654. }
  5655. // Add the function template specialization produced by template argument
  5656. // deduction as a candidate.
  5657. assert(Specialization && "Missing member function template specialization?");
  5658. assert(isa<CXXMethodDecl>(Specialization) &&
  5659. "Specialization is not a member function?");
  5660. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  5661. ActingContext, ObjectType, ObjectClassification, Args,
  5662. CandidateSet, SuppressUserConversions, PartialOverloading);
  5663. }
  5664. /// \brief Add a C++ function template specialization as a candidate
  5665. /// in the candidate set, using template argument deduction to produce
  5666. /// an appropriate function template specialization.
  5667. void
  5668. Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
  5669. DeclAccessPair FoundDecl,
  5670. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5671. ArrayRef<Expr *> Args,
  5672. OverloadCandidateSet& CandidateSet,
  5673. bool SuppressUserConversions,
  5674. bool PartialOverloading) {
  5675. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5676. return;
  5677. // C++ [over.match.funcs]p7:
  5678. // In each case where a candidate is a function template, candidate
  5679. // function template specializations are generated using template argument
  5680. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5681. // candidate functions in the usual way.113) A given name can refer to one
  5682. // or more function templates and also to a set of overloaded non-template
  5683. // functions. In such a case, the candidate functions generated from each
  5684. // function template are combined with the set of non-template candidate
  5685. // functions.
  5686. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5687. FunctionDecl *Specialization = nullptr;
  5688. if (TemplateDeductionResult Result
  5689. = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
  5690. Specialization, Info, PartialOverloading)) {
  5691. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5692. Candidate.FoundDecl = FoundDecl;
  5693. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5694. Candidate.Viable = false;
  5695. Candidate.FailureKind = ovl_fail_bad_deduction;
  5696. Candidate.IsSurrogate = false;
  5697. Candidate.IgnoreObjectArgument = false;
  5698. Candidate.ExplicitCallArguments = Args.size();
  5699. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5700. Info);
  5701. return;
  5702. }
  5703. // Add the function template specialization produced by template argument
  5704. // deduction as a candidate.
  5705. assert(Specialization && "Missing function template specialization?");
  5706. AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
  5707. SuppressUserConversions, PartialOverloading);
  5708. }
  5709. /// Determine whether this is an allowable conversion from the result
  5710. /// of an explicit conversion operator to the expected type, per C++
  5711. /// [over.match.conv]p1 and [over.match.ref]p1.
  5712. ///
  5713. /// \param ConvType The return type of the conversion function.
  5714. ///
  5715. /// \param ToType The type we are converting to.
  5716. ///
  5717. /// \param AllowObjCPointerConversion Allow a conversion from one
  5718. /// Objective-C pointer to another.
  5719. ///
  5720. /// \returns true if the conversion is allowable, false otherwise.
  5721. static bool isAllowableExplicitConversion(Sema &S,
  5722. QualType ConvType, QualType ToType,
  5723. bool AllowObjCPointerConversion) {
  5724. QualType ToNonRefType = ToType.getNonReferenceType();
  5725. // Easy case: the types are the same.
  5726. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  5727. return true;
  5728. // Allow qualification conversions.
  5729. bool ObjCLifetimeConversion;
  5730. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  5731. ObjCLifetimeConversion))
  5732. return true;
  5733. // If we're not allowed to consider Objective-C pointer conversions,
  5734. // we're done.
  5735. if (!AllowObjCPointerConversion)
  5736. return false;
  5737. // Is this an Objective-C pointer conversion?
  5738. bool IncompatibleObjC = false;
  5739. QualType ConvertedType;
  5740. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  5741. IncompatibleObjC);
  5742. }
  5743. /// AddConversionCandidate - Add a C++ conversion function as a
  5744. /// candidate in the candidate set (C++ [over.match.conv],
  5745. /// C++ [over.match.copy]). From is the expression we're converting from,
  5746. /// and ToType is the type that we're eventually trying to convert to
  5747. /// (which may or may not be the same type as the type that the
  5748. /// conversion function produces).
  5749. void
  5750. Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
  5751. DeclAccessPair FoundDecl,
  5752. CXXRecordDecl *ActingContext,
  5753. Expr *From, QualType ToType,
  5754. OverloadCandidateSet& CandidateSet,
  5755. bool AllowObjCConversionOnExplicit) {
  5756. assert(!Conversion->getDescribedFunctionTemplate() &&
  5757. "Conversion function templates use AddTemplateConversionCandidate");
  5758. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  5759. if (!CandidateSet.isNewCandidate(Conversion))
  5760. return;
  5761. // If the conversion function has an undeduced return type, trigger its
  5762. // deduction now.
  5763. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  5764. if (DeduceReturnType(Conversion, From->getExprLoc()))
  5765. return;
  5766. ConvType = Conversion->getConversionType().getNonReferenceType();
  5767. }
  5768. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  5769. // operator is only a candidate if its return type is the target type or
  5770. // can be converted to the target type with a qualification conversion.
  5771. if (Conversion->isExplicit() &&
  5772. !isAllowableExplicitConversion(*this, ConvType, ToType,
  5773. AllowObjCConversionOnExplicit))
  5774. return;
  5775. // Overload resolution is always an unevaluated context.
  5776. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5777. // Add this candidate
  5778. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  5779. Candidate.FoundDecl = FoundDecl;
  5780. Candidate.Function = Conversion;
  5781. Candidate.IsSurrogate = false;
  5782. Candidate.IgnoreObjectArgument = false;
  5783. Candidate.FinalConversion.setAsIdentityConversion();
  5784. Candidate.FinalConversion.setFromType(ConvType);
  5785. Candidate.FinalConversion.setAllToTypes(ToType);
  5786. Candidate.Viable = true;
  5787. Candidate.ExplicitCallArguments = 1;
  5788. // C++ [over.match.funcs]p4:
  5789. // For conversion functions, the function is considered to be a member of
  5790. // the class of the implicit implied object argument for the purpose of
  5791. // defining the type of the implicit object parameter.
  5792. //
  5793. // Determine the implicit conversion sequence for the implicit
  5794. // object parameter.
  5795. QualType ImplicitParamType = From->getType();
  5796. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  5797. ImplicitParamType = FromPtrType->getPointeeType();
  5798. CXXRecordDecl *ConversionContext
  5799. = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
  5800. Candidate.Conversions[0]
  5801. = TryObjectArgumentInitialization(*this, From->getType(),
  5802. From->Classify(Context),
  5803. Conversion, ConversionContext);
  5804. if (Candidate.Conversions[0].isBad()) {
  5805. Candidate.Viable = false;
  5806. Candidate.FailureKind = ovl_fail_bad_conversion;
  5807. return;
  5808. }
  5809. // We won't go through a user-defined type conversion function to convert a
  5810. // derived to base as such conversions are given Conversion Rank. They only
  5811. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  5812. QualType FromCanon
  5813. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  5814. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  5815. if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
  5816. Candidate.Viable = false;
  5817. Candidate.FailureKind = ovl_fail_trivial_conversion;
  5818. return;
  5819. }
  5820. // To determine what the conversion from the result of calling the
  5821. // conversion function to the type we're eventually trying to
  5822. // convert to (ToType), we need to synthesize a call to the
  5823. // conversion function and attempt copy initialization from it. This
  5824. // makes sure that we get the right semantics with respect to
  5825. // lvalues/rvalues and the type. Fortunately, we can allocate this
  5826. // call on the stack and we don't need its arguments to be
  5827. // well-formed.
  5828. DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
  5829. VK_LValue, From->getLocStart());
  5830. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  5831. Context.getPointerType(Conversion->getType()),
  5832. CK_FunctionToPointerDecay,
  5833. &ConversionRef, VK_RValue);
  5834. QualType ConversionType = Conversion->getConversionType();
  5835. if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
  5836. Candidate.Viable = false;
  5837. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5838. return;
  5839. }
  5840. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  5841. // Note that it is safe to allocate CallExpr on the stack here because
  5842. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  5843. // allocator).
  5844. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  5845. CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
  5846. From->getLocStart());
  5847. ImplicitConversionSequence ICS =
  5848. TryCopyInitialization(*this, &Call, ToType,
  5849. /*SuppressUserConversions=*/true,
  5850. /*InOverloadResolution=*/false,
  5851. /*AllowObjCWritebackConversion=*/false);
  5852. switch (ICS.getKind()) {
  5853. case ImplicitConversionSequence::StandardConversion:
  5854. Candidate.FinalConversion = ICS.Standard;
  5855. // C++ [over.ics.user]p3:
  5856. // If the user-defined conversion is specified by a specialization of a
  5857. // conversion function template, the second standard conversion sequence
  5858. // shall have exact match rank.
  5859. if (Conversion->getPrimaryTemplate() &&
  5860. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  5861. Candidate.Viable = false;
  5862. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  5863. return;
  5864. }
  5865. // C++0x [dcl.init.ref]p5:
  5866. // In the second case, if the reference is an rvalue reference and
  5867. // the second standard conversion sequence of the user-defined
  5868. // conversion sequence includes an lvalue-to-rvalue conversion, the
  5869. // program is ill-formed.
  5870. if (ToType->isRValueReferenceType() &&
  5871. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5872. Candidate.Viable = false;
  5873. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5874. return;
  5875. }
  5876. break;
  5877. case ImplicitConversionSequence::BadConversion:
  5878. Candidate.Viable = false;
  5879. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5880. return;
  5881. default:
  5882. llvm_unreachable(
  5883. "Can only end up with a standard conversion sequence or failure");
  5884. }
  5885. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  5886. Candidate.Viable = false;
  5887. Candidate.FailureKind = ovl_fail_enable_if;
  5888. Candidate.DeductionFailure.Data = FailedAttr;
  5889. return;
  5890. }
  5891. }
  5892. /// \brief Adds a conversion function template specialization
  5893. /// candidate to the overload set, using template argument deduction
  5894. /// to deduce the template arguments of the conversion function
  5895. /// template from the type that we are converting to (C++
  5896. /// [temp.deduct.conv]).
  5897. void
  5898. Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
  5899. DeclAccessPair FoundDecl,
  5900. CXXRecordDecl *ActingDC,
  5901. Expr *From, QualType ToType,
  5902. OverloadCandidateSet &CandidateSet,
  5903. bool AllowObjCConversionOnExplicit) {
  5904. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  5905. "Only conversion function templates permitted here");
  5906. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5907. return;
  5908. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5909. CXXConversionDecl *Specialization = nullptr;
  5910. if (TemplateDeductionResult Result
  5911. = DeduceTemplateArguments(FunctionTemplate, ToType,
  5912. Specialization, Info)) {
  5913. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5914. Candidate.FoundDecl = FoundDecl;
  5915. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5916. Candidate.Viable = false;
  5917. Candidate.FailureKind = ovl_fail_bad_deduction;
  5918. Candidate.IsSurrogate = false;
  5919. Candidate.IgnoreObjectArgument = false;
  5920. Candidate.ExplicitCallArguments = 1;
  5921. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5922. Info);
  5923. return;
  5924. }
  5925. // Add the conversion function template specialization produced by
  5926. // template argument deduction as a candidate.
  5927. assert(Specialization && "Missing function template specialization?");
  5928. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  5929. CandidateSet, AllowObjCConversionOnExplicit);
  5930. }
  5931. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  5932. /// converts the given @c Object to a function pointer via the
  5933. /// conversion function @c Conversion, and then attempts to call it
  5934. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  5935. /// the type of function that we'll eventually be calling.
  5936. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  5937. DeclAccessPair FoundDecl,
  5938. CXXRecordDecl *ActingContext,
  5939. const FunctionProtoType *Proto,
  5940. Expr *Object,
  5941. ArrayRef<Expr *> Args,
  5942. OverloadCandidateSet& CandidateSet) {
  5943. if (!CandidateSet.isNewCandidate(Conversion))
  5944. return;
  5945. // Overload resolution is always an unevaluated context.
  5946. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5947. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5948. Candidate.FoundDecl = FoundDecl;
  5949. Candidate.Function = nullptr;
  5950. Candidate.Surrogate = Conversion;
  5951. Candidate.Viable = true;
  5952. Candidate.IsSurrogate = true;
  5953. Candidate.IgnoreObjectArgument = false;
  5954. Candidate.ExplicitCallArguments = Args.size();
  5955. // Determine the implicit conversion sequence for the implicit
  5956. // object parameter.
  5957. ImplicitConversionSequence ObjectInit
  5958. = TryObjectArgumentInitialization(*this, Object->getType(),
  5959. Object->Classify(Context),
  5960. Conversion, ActingContext);
  5961. if (ObjectInit.isBad()) {
  5962. Candidate.Viable = false;
  5963. Candidate.FailureKind = ovl_fail_bad_conversion;
  5964. Candidate.Conversions[0] = ObjectInit;
  5965. return;
  5966. }
  5967. // The first conversion is actually a user-defined conversion whose
  5968. // first conversion is ObjectInit's standard conversion (which is
  5969. // effectively a reference binding). Record it as such.
  5970. Candidate.Conversions[0].setUserDefined();
  5971. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  5972. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  5973. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  5974. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  5975. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  5976. Candidate.Conversions[0].UserDefined.After
  5977. = Candidate.Conversions[0].UserDefined.Before;
  5978. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  5979. // Find the
  5980. unsigned NumParams = Proto->getNumParams();
  5981. // (C++ 13.3.2p2): A candidate function having fewer than m
  5982. // parameters is viable only if it has an ellipsis in its parameter
  5983. // list (8.3.5).
  5984. if (Args.size() > NumParams && !Proto->isVariadic()) {
  5985. Candidate.Viable = false;
  5986. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5987. return;
  5988. }
  5989. // Function types don't have any default arguments, so just check if
  5990. // we have enough arguments.
  5991. if (Args.size() < NumParams) {
  5992. // Not enough arguments.
  5993. Candidate.Viable = false;
  5994. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5995. return;
  5996. }
  5997. // Determine the implicit conversion sequences for each of the
  5998. // arguments.
  5999. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6000. if (ArgIdx < NumParams) {
  6001. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6002. // exist for each argument an implicit conversion sequence
  6003. // (13.3.3.1) that converts that argument to the corresponding
  6004. // parameter of F.
  6005. QualType ParamType = Proto->getParamType(ArgIdx);
  6006. Candidate.Conversions[ArgIdx + 1]
  6007. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6008. /*SuppressUserConversions=*/false,
  6009. /*InOverloadResolution=*/false,
  6010. /*AllowObjCWritebackConversion=*/
  6011. getLangOpts().ObjCAutoRefCount);
  6012. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6013. Candidate.Viable = false;
  6014. Candidate.FailureKind = ovl_fail_bad_conversion;
  6015. return;
  6016. }
  6017. } else {
  6018. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6019. // argument for which there is no corresponding parameter is
  6020. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6021. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6022. }
  6023. }
  6024. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6025. Candidate.Viable = false;
  6026. Candidate.FailureKind = ovl_fail_enable_if;
  6027. Candidate.DeductionFailure.Data = FailedAttr;
  6028. return;
  6029. }
  6030. }
  6031. /// \brief Add overload candidates for overloaded operators that are
  6032. /// member functions.
  6033. ///
  6034. /// Add the overloaded operator candidates that are member functions
  6035. /// for the operator Op that was used in an operator expression such
  6036. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6037. /// CandidateSet will store the added overload candidates. (C++
  6038. /// [over.match.oper]).
  6039. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6040. SourceLocation OpLoc,
  6041. ArrayRef<Expr *> Args,
  6042. OverloadCandidateSet& CandidateSet,
  6043. SourceRange OpRange) {
  6044. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6045. // C++ [over.match.oper]p3:
  6046. // For a unary operator @ with an operand of a type whose
  6047. // cv-unqualified version is T1, and for a binary operator @ with
  6048. // a left operand of a type whose cv-unqualified version is T1 and
  6049. // a right operand of a type whose cv-unqualified version is T2,
  6050. // three sets of candidate functions, designated member
  6051. // candidates, non-member candidates and built-in candidates, are
  6052. // constructed as follows:
  6053. QualType T1 = Args[0]->getType();
  6054. // -- If T1 is a complete class type or a class currently being
  6055. // defined, the set of member candidates is the result of the
  6056. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6057. // the set of member candidates is empty.
  6058. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6059. // Complete the type if it can be completed.
  6060. RequireCompleteType(OpLoc, T1, 0);
  6061. // If the type is neither complete nor being defined, bail out now.
  6062. if (!T1Rec->getDecl()->getDefinition())
  6063. return;
  6064. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6065. LookupQualifiedName(Operators, T1Rec->getDecl());
  6066. Operators.suppressDiagnostics();
  6067. for (LookupResult::iterator Oper = Operators.begin(),
  6068. OperEnd = Operators.end();
  6069. Oper != OperEnd;
  6070. ++Oper)
  6071. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6072. Args[0]->Classify(Context),
  6073. Args.slice(1),
  6074. CandidateSet,
  6075. /* SuppressUserConversions = */ false);
  6076. }
  6077. }
  6078. /// AddBuiltinCandidate - Add a candidate for a built-in
  6079. /// operator. ResultTy and ParamTys are the result and parameter types
  6080. /// of the built-in candidate, respectively. Args and NumArgs are the
  6081. /// arguments being passed to the candidate. IsAssignmentOperator
  6082. /// should be true when this built-in candidate is an assignment
  6083. /// operator. NumContextualBoolArguments is the number of arguments
  6084. /// (at the beginning of the argument list) that will be contextually
  6085. /// converted to bool.
  6086. void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
  6087. ArrayRef<Expr *> Args,
  6088. OverloadCandidateSet& CandidateSet,
  6089. bool IsAssignmentOperator,
  6090. unsigned NumContextualBoolArguments) {
  6091. // Overload resolution is always an unevaluated context.
  6092. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  6093. // Add this candidate
  6094. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6095. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6096. Candidate.Function = nullptr;
  6097. Candidate.IsSurrogate = false;
  6098. Candidate.IgnoreObjectArgument = false;
  6099. Candidate.BuiltinTypes.ResultTy = ResultTy;
  6100. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  6101. Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
  6102. // Determine the implicit conversion sequences for each of the
  6103. // arguments.
  6104. Candidate.Viable = true;
  6105. Candidate.ExplicitCallArguments = Args.size();
  6106. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6107. // C++ [over.match.oper]p4:
  6108. // For the built-in assignment operators, conversions of the
  6109. // left operand are restricted as follows:
  6110. // -- no temporaries are introduced to hold the left operand, and
  6111. // -- no user-defined conversions are applied to the left
  6112. // operand to achieve a type match with the left-most
  6113. // parameter of a built-in candidate.
  6114. //
  6115. // We block these conversions by turning off user-defined
  6116. // conversions, since that is the only way that initialization of
  6117. // a reference to a non-class type can occur from something that
  6118. // is not of the same type.
  6119. if (ArgIdx < NumContextualBoolArguments) {
  6120. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6121. "Contextual conversion to bool requires bool type");
  6122. Candidate.Conversions[ArgIdx]
  6123. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6124. } else {
  6125. Candidate.Conversions[ArgIdx]
  6126. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6127. ArgIdx == 0 && IsAssignmentOperator,
  6128. /*InOverloadResolution=*/false,
  6129. /*AllowObjCWritebackConversion=*/
  6130. getLangOpts().ObjCAutoRefCount);
  6131. }
  6132. if (Candidate.Conversions[ArgIdx].isBad()) {
  6133. Candidate.Viable = false;
  6134. Candidate.FailureKind = ovl_fail_bad_conversion;
  6135. break;
  6136. }
  6137. }
  6138. }
  6139. namespace {
  6140. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6141. /// candidate operator functions for built-in operators (C++
  6142. /// [over.built]). The types are separated into pointer types and
  6143. /// enumeration types.
  6144. class BuiltinCandidateTypeSet {
  6145. /// TypeSet - A set of types.
  6146. typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
  6147. /// PointerTypes - The set of pointer types that will be used in the
  6148. /// built-in candidates.
  6149. TypeSet PointerTypes;
  6150. /// MemberPointerTypes - The set of member pointer types that will be
  6151. /// used in the built-in candidates.
  6152. TypeSet MemberPointerTypes;
  6153. /// EnumerationTypes - The set of enumeration types that will be
  6154. /// used in the built-in candidates.
  6155. TypeSet EnumerationTypes;
  6156. /// \brief The set of vector types that will be used in the built-in
  6157. /// candidates.
  6158. TypeSet VectorTypes;
  6159. /// \brief A flag indicating non-record types are viable candidates
  6160. bool HasNonRecordTypes;
  6161. /// \brief A flag indicating whether either arithmetic or enumeration types
  6162. /// were present in the candidate set.
  6163. bool HasArithmeticOrEnumeralTypes;
  6164. /// \brief A flag indicating whether the nullptr type was present in the
  6165. /// candidate set.
  6166. bool HasNullPtrType;
  6167. /// Sema - The semantic analysis instance where we are building the
  6168. /// candidate type set.
  6169. Sema &SemaRef;
  6170. /// Context - The AST context in which we will build the type sets.
  6171. ASTContext &Context;
  6172. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6173. const Qualifiers &VisibleQuals);
  6174. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6175. public:
  6176. /// iterator - Iterates through the types that are part of the set.
  6177. typedef TypeSet::iterator iterator;
  6178. BuiltinCandidateTypeSet(Sema &SemaRef)
  6179. : HasNonRecordTypes(false),
  6180. HasArithmeticOrEnumeralTypes(false),
  6181. HasNullPtrType(false),
  6182. SemaRef(SemaRef),
  6183. Context(SemaRef.Context) { }
  6184. void AddTypesConvertedFrom(QualType Ty,
  6185. SourceLocation Loc,
  6186. bool AllowUserConversions,
  6187. bool AllowExplicitConversions,
  6188. const Qualifiers &VisibleTypeConversionsQuals);
  6189. /// pointer_begin - First pointer type found;
  6190. iterator pointer_begin() { return PointerTypes.begin(); }
  6191. /// pointer_end - Past the last pointer type found;
  6192. iterator pointer_end() { return PointerTypes.end(); }
  6193. /// member_pointer_begin - First member pointer type found;
  6194. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6195. /// member_pointer_end - Past the last member pointer type found;
  6196. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6197. /// enumeration_begin - First enumeration type found;
  6198. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6199. /// enumeration_end - Past the last enumeration type found;
  6200. iterator enumeration_end() { return EnumerationTypes.end(); }
  6201. iterator vector_begin() { return VectorTypes.begin(); }
  6202. iterator vector_end() { return VectorTypes.end(); }
  6203. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6204. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6205. bool hasNullPtrType() const { return HasNullPtrType; }
  6206. };
  6207. } // end anonymous namespace
  6208. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6209. /// the set of pointer types along with any more-qualified variants of
  6210. /// that type. For example, if @p Ty is "int const *", this routine
  6211. /// will add "int const *", "int const volatile *", "int const
  6212. /// restrict *", and "int const volatile restrict *" to the set of
  6213. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6214. /// false otherwise.
  6215. ///
  6216. /// FIXME: what to do about extended qualifiers?
  6217. bool
  6218. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6219. const Qualifiers &VisibleQuals) {
  6220. // Insert this type.
  6221. if (!PointerTypes.insert(Ty).second)
  6222. return false;
  6223. QualType PointeeTy;
  6224. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6225. bool buildObjCPtr = false;
  6226. if (!PointerTy) {
  6227. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6228. PointeeTy = PTy->getPointeeType();
  6229. buildObjCPtr = true;
  6230. } else {
  6231. PointeeTy = PointerTy->getPointeeType();
  6232. }
  6233. // Don't add qualified variants of arrays. For one, they're not allowed
  6234. // (the qualifier would sink to the element type), and for another, the
  6235. // only overload situation where it matters is subscript or pointer +- int,
  6236. // and those shouldn't have qualifier variants anyway.
  6237. if (PointeeTy->isArrayType())
  6238. return true;
  6239. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6240. bool hasVolatile = VisibleQuals.hasVolatile();
  6241. bool hasRestrict = VisibleQuals.hasRestrict();
  6242. // Iterate through all strict supersets of BaseCVR.
  6243. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6244. if ((CVR | BaseCVR) != CVR) continue;
  6245. // Skip over volatile if no volatile found anywhere in the types.
  6246. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6247. // Skip over restrict if no restrict found anywhere in the types, or if
  6248. // the type cannot be restrict-qualified.
  6249. if ((CVR & Qualifiers::Restrict) &&
  6250. (!hasRestrict ||
  6251. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6252. continue;
  6253. // Build qualified pointee type.
  6254. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6255. // Build qualified pointer type.
  6256. QualType QPointerTy;
  6257. if (!buildObjCPtr)
  6258. QPointerTy = Context.getPointerType(QPointeeTy);
  6259. else
  6260. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6261. // Insert qualified pointer type.
  6262. PointerTypes.insert(QPointerTy);
  6263. }
  6264. return true;
  6265. }
  6266. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6267. /// to the set of pointer types along with any more-qualified variants of
  6268. /// that type. For example, if @p Ty is "int const *", this routine
  6269. /// will add "int const *", "int const volatile *", "int const
  6270. /// restrict *", and "int const volatile restrict *" to the set of
  6271. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6272. /// false otherwise.
  6273. ///
  6274. /// FIXME: what to do about extended qualifiers?
  6275. bool
  6276. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6277. QualType Ty) {
  6278. // Insert this type.
  6279. if (!MemberPointerTypes.insert(Ty).second)
  6280. return false;
  6281. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6282. assert(PointerTy && "type was not a member pointer type!");
  6283. QualType PointeeTy = PointerTy->getPointeeType();
  6284. // Don't add qualified variants of arrays. For one, they're not allowed
  6285. // (the qualifier would sink to the element type), and for another, the
  6286. // only overload situation where it matters is subscript or pointer +- int,
  6287. // and those shouldn't have qualifier variants anyway.
  6288. if (PointeeTy->isArrayType())
  6289. return true;
  6290. const Type *ClassTy = PointerTy->getClass();
  6291. // Iterate through all strict supersets of the pointee type's CVR
  6292. // qualifiers.
  6293. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6294. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6295. if ((CVR | BaseCVR) != CVR) continue;
  6296. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6297. MemberPointerTypes.insert(
  6298. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6299. }
  6300. return true;
  6301. }
  6302. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6303. /// Ty can be implicit converted to the given set of @p Types. We're
  6304. /// primarily interested in pointer types and enumeration types. We also
  6305. /// take member pointer types, for the conditional operator.
  6306. /// AllowUserConversions is true if we should look at the conversion
  6307. /// functions of a class type, and AllowExplicitConversions if we
  6308. /// should also include the explicit conversion functions of a class
  6309. /// type.
  6310. void
  6311. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6312. SourceLocation Loc,
  6313. bool AllowUserConversions,
  6314. bool AllowExplicitConversions,
  6315. const Qualifiers &VisibleQuals) {
  6316. // Only deal with canonical types.
  6317. Ty = Context.getCanonicalType(Ty);
  6318. // Look through reference types; they aren't part of the type of an
  6319. // expression for the purposes of conversions.
  6320. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6321. Ty = RefTy->getPointeeType();
  6322. // If we're dealing with an array type, decay to the pointer.
  6323. if (Ty->isArrayType())
  6324. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6325. // Otherwise, we don't care about qualifiers on the type.
  6326. Ty = Ty.getLocalUnqualifiedType();
  6327. // Flag if we ever add a non-record type.
  6328. const RecordType *TyRec = Ty->getAs<RecordType>();
  6329. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6330. // Flag if we encounter an arithmetic type.
  6331. HasArithmeticOrEnumeralTypes =
  6332. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6333. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6334. PointerTypes.insert(Ty);
  6335. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6336. // Insert our type, and its more-qualified variants, into the set
  6337. // of types.
  6338. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6339. return;
  6340. } else if (Ty->isMemberPointerType()) {
  6341. // Member pointers are far easier, since the pointee can't be converted.
  6342. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6343. return;
  6344. } else if (Ty->isEnumeralType()) {
  6345. HasArithmeticOrEnumeralTypes = true;
  6346. EnumerationTypes.insert(Ty);
  6347. } else if (Ty->isVectorType()) {
  6348. // We treat vector types as arithmetic types in many contexts as an
  6349. // extension.
  6350. HasArithmeticOrEnumeralTypes = true;
  6351. VectorTypes.insert(Ty);
  6352. } else if (Ty->isNullPtrType()) {
  6353. HasNullPtrType = true;
  6354. } else if (AllowUserConversions && TyRec) {
  6355. // No conversion functions in incomplete types.
  6356. if (SemaRef.RequireCompleteType(Loc, Ty, 0))
  6357. return;
  6358. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6359. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6360. if (isa<UsingShadowDecl>(D))
  6361. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6362. // Skip conversion function templates; they don't tell us anything
  6363. // about which builtin types we can convert to.
  6364. if (isa<FunctionTemplateDecl>(D))
  6365. continue;
  6366. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6367. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6368. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6369. VisibleQuals);
  6370. }
  6371. }
  6372. }
  6373. }
  6374. /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
  6375. /// the volatile- and non-volatile-qualified assignment operators for the
  6376. /// given type to the candidate set.
  6377. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  6378. QualType T,
  6379. ArrayRef<Expr *> Args,
  6380. OverloadCandidateSet &CandidateSet) {
  6381. QualType ParamTypes[2];
  6382. // T& operator=(T&, T)
  6383. ParamTypes[0] = S.Context.getLValueReferenceType(T);
  6384. ParamTypes[1] = T;
  6385. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6386. /*IsAssignmentOperator=*/true);
  6387. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  6388. // volatile T& operator=(volatile T&, T)
  6389. ParamTypes[0]
  6390. = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
  6391. ParamTypes[1] = T;
  6392. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6393. /*IsAssignmentOperator=*/true);
  6394. }
  6395. }
  6396. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  6397. /// if any, found in visible type conversion functions found in ArgExpr's type.
  6398. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  6399. Qualifiers VRQuals;
  6400. const RecordType *TyRec;
  6401. if (const MemberPointerType *RHSMPType =
  6402. ArgExpr->getType()->getAs<MemberPointerType>())
  6403. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  6404. else
  6405. TyRec = ArgExpr->getType()->getAs<RecordType>();
  6406. if (!TyRec) {
  6407. // Just to be safe, assume the worst case.
  6408. VRQuals.addVolatile();
  6409. VRQuals.addRestrict();
  6410. return VRQuals;
  6411. }
  6412. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6413. if (!ClassDecl->hasDefinition())
  6414. return VRQuals;
  6415. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6416. if (isa<UsingShadowDecl>(D))
  6417. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6418. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  6419. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  6420. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  6421. CanTy = ResTypeRef->getPointeeType();
  6422. // Need to go down the pointer/mempointer chain and add qualifiers
  6423. // as see them.
  6424. bool done = false;
  6425. while (!done) {
  6426. if (CanTy.isRestrictQualified())
  6427. VRQuals.addRestrict();
  6428. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  6429. CanTy = ResTypePtr->getPointeeType();
  6430. else if (const MemberPointerType *ResTypeMPtr =
  6431. CanTy->getAs<MemberPointerType>())
  6432. CanTy = ResTypeMPtr->getPointeeType();
  6433. else
  6434. done = true;
  6435. if (CanTy.isVolatileQualified())
  6436. VRQuals.addVolatile();
  6437. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  6438. return VRQuals;
  6439. }
  6440. }
  6441. }
  6442. return VRQuals;
  6443. }
  6444. namespace {
  6445. /// \brief Helper class to manage the addition of builtin operator overload
  6446. /// candidates. It provides shared state and utility methods used throughout
  6447. /// the process, as well as a helper method to add each group of builtin
  6448. /// operator overloads from the standard to a candidate set.
  6449. class BuiltinOperatorOverloadBuilder {
  6450. // Common instance state available to all overload candidate addition methods.
  6451. Sema &S;
  6452. ArrayRef<Expr *> Args;
  6453. Qualifiers VisibleTypeConversionsQuals;
  6454. bool HasArithmeticOrEnumeralCandidateType;
  6455. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  6456. OverloadCandidateSet &CandidateSet;
  6457. // Define some constants used to index and iterate over the arithemetic types
  6458. // provided via the getArithmeticType() method below.
  6459. // The "promoted arithmetic types" are the arithmetic
  6460. // types are that preserved by promotion (C++ [over.built]p2).
  6461. static const unsigned FirstIntegralType = 3;
  6462. static const unsigned LastIntegralType = 20;
  6463. static const unsigned FirstPromotedIntegralType = 3,
  6464. LastPromotedIntegralType = 11;
  6465. static const unsigned FirstPromotedArithmeticType = 0,
  6466. LastPromotedArithmeticType = 11;
  6467. static const unsigned NumArithmeticTypes = 20;
  6468. /// \brief Get the canonical type for a given arithmetic type index.
  6469. CanQualType getArithmeticType(unsigned index) {
  6470. assert(index < NumArithmeticTypes);
  6471. static CanQualType ASTContext::* const
  6472. ArithmeticTypes[NumArithmeticTypes] = {
  6473. // Start of promoted types.
  6474. &ASTContext::FloatTy,
  6475. &ASTContext::DoubleTy,
  6476. &ASTContext::LongDoubleTy,
  6477. // Start of integral types.
  6478. &ASTContext::IntTy,
  6479. &ASTContext::LongTy,
  6480. &ASTContext::LongLongTy,
  6481. &ASTContext::Int128Ty,
  6482. &ASTContext::UnsignedIntTy,
  6483. &ASTContext::UnsignedLongTy,
  6484. &ASTContext::UnsignedLongLongTy,
  6485. &ASTContext::UnsignedInt128Ty,
  6486. // End of promoted types.
  6487. &ASTContext::BoolTy,
  6488. &ASTContext::CharTy,
  6489. &ASTContext::WCharTy,
  6490. &ASTContext::Char16Ty,
  6491. &ASTContext::Char32Ty,
  6492. &ASTContext::SignedCharTy,
  6493. &ASTContext::ShortTy,
  6494. &ASTContext::UnsignedCharTy,
  6495. &ASTContext::UnsignedShortTy,
  6496. // End of integral types.
  6497. // FIXME: What about complex? What about half?
  6498. };
  6499. return S.Context.*ArithmeticTypes[index];
  6500. }
  6501. /// \brief Gets the canonical type resulting from the usual arithemetic
  6502. /// converions for the given arithmetic types.
  6503. CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
  6504. // Accelerator table for performing the usual arithmetic conversions.
  6505. // The rules are basically:
  6506. // - if either is floating-point, use the wider floating-point
  6507. // - if same signedness, use the higher rank
  6508. // - if same size, use unsigned of the higher rank
  6509. // - use the larger type
  6510. // These rules, together with the axiom that higher ranks are
  6511. // never smaller, are sufficient to precompute all of these results
  6512. // *except* when dealing with signed types of higher rank.
  6513. // (we could precompute SLL x UI for all known platforms, but it's
  6514. // better not to make any assumptions).
  6515. // We assume that int128 has a higher rank than long long on all platforms.
  6516. enum PromotedType {
  6517. Dep=-1,
  6518. Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
  6519. };
  6520. static const PromotedType ConversionsTable[LastPromotedArithmeticType]
  6521. [LastPromotedArithmeticType] = {
  6522. /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
  6523. /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
  6524. /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
  6525. /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
  6526. /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
  6527. /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
  6528. /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
  6529. /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
  6530. /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
  6531. /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
  6532. /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
  6533. };
  6534. assert(L < LastPromotedArithmeticType);
  6535. assert(R < LastPromotedArithmeticType);
  6536. int Idx = ConversionsTable[L][R];
  6537. // Fast path: the table gives us a concrete answer.
  6538. if (Idx != Dep) return getArithmeticType(Idx);
  6539. // Slow path: we need to compare widths.
  6540. // An invariant is that the signed type has higher rank.
  6541. CanQualType LT = getArithmeticType(L),
  6542. RT = getArithmeticType(R);
  6543. unsigned LW = S.Context.getIntWidth(LT),
  6544. RW = S.Context.getIntWidth(RT);
  6545. // If they're different widths, use the signed type.
  6546. if (LW > RW) return LT;
  6547. else if (LW < RW) return RT;
  6548. // Otherwise, use the unsigned type of the signed type's rank.
  6549. if (L == SL || R == SL) return S.Context.UnsignedLongTy;
  6550. assert(L == SLL || R == SLL);
  6551. return S.Context.UnsignedLongLongTy;
  6552. }
  6553. /// \brief Helper method to factor out the common pattern of adding overloads
  6554. /// for '++' and '--' builtin operators.
  6555. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  6556. bool HasVolatile,
  6557. bool HasRestrict) {
  6558. QualType ParamTypes[2] = {
  6559. S.Context.getLValueReferenceType(CandidateTy),
  6560. S.Context.IntTy
  6561. };
  6562. // Non-volatile version.
  6563. if (Args.size() == 1)
  6564. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6565. else
  6566. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6567. // Use a heuristic to reduce number of builtin candidates in the set:
  6568. // add volatile version only if there are conversions to a volatile type.
  6569. if (HasVolatile) {
  6570. ParamTypes[0] =
  6571. S.Context.getLValueReferenceType(
  6572. S.Context.getVolatileType(CandidateTy));
  6573. if (Args.size() == 1)
  6574. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6575. else
  6576. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6577. }
  6578. // Add restrict version only if there are conversions to a restrict type
  6579. // and our candidate type is a non-restrict-qualified pointer.
  6580. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  6581. !CandidateTy.isRestrictQualified()) {
  6582. ParamTypes[0]
  6583. = S.Context.getLValueReferenceType(
  6584. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  6585. if (Args.size() == 1)
  6586. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6587. else
  6588. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6589. if (HasVolatile) {
  6590. ParamTypes[0]
  6591. = S.Context.getLValueReferenceType(
  6592. S.Context.getCVRQualifiedType(CandidateTy,
  6593. (Qualifiers::Volatile |
  6594. Qualifiers::Restrict)));
  6595. if (Args.size() == 1)
  6596. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6597. else
  6598. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6599. }
  6600. }
  6601. }
  6602. public:
  6603. BuiltinOperatorOverloadBuilder(
  6604. Sema &S, ArrayRef<Expr *> Args,
  6605. Qualifiers VisibleTypeConversionsQuals,
  6606. bool HasArithmeticOrEnumeralCandidateType,
  6607. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  6608. OverloadCandidateSet &CandidateSet)
  6609. : S(S), Args(Args),
  6610. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  6611. HasArithmeticOrEnumeralCandidateType(
  6612. HasArithmeticOrEnumeralCandidateType),
  6613. CandidateTypes(CandidateTypes),
  6614. CandidateSet(CandidateSet) {
  6615. // Validate some of our static helper constants in debug builds.
  6616. assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
  6617. "Invalid first promoted integral type");
  6618. assert(getArithmeticType(LastPromotedIntegralType - 1)
  6619. == S.Context.UnsignedInt128Ty &&
  6620. "Invalid last promoted integral type");
  6621. assert(getArithmeticType(FirstPromotedArithmeticType)
  6622. == S.Context.FloatTy &&
  6623. "Invalid first promoted arithmetic type");
  6624. assert(getArithmeticType(LastPromotedArithmeticType - 1)
  6625. == S.Context.UnsignedInt128Ty &&
  6626. "Invalid last promoted arithmetic type");
  6627. }
  6628. // C++ [over.built]p3:
  6629. //
  6630. // For every pair (T, VQ), where T is an arithmetic type, and VQ
  6631. // is either volatile or empty, there exist candidate operator
  6632. // functions of the form
  6633. //
  6634. // VQ T& operator++(VQ T&);
  6635. // T operator++(VQ T&, int);
  6636. //
  6637. // C++ [over.built]p4:
  6638. //
  6639. // For every pair (T, VQ), where T is an arithmetic type other
  6640. // than bool, and VQ is either volatile or empty, there exist
  6641. // candidate operator functions of the form
  6642. //
  6643. // VQ T& operator--(VQ T&);
  6644. // T operator--(VQ T&, int);
  6645. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  6646. if (!HasArithmeticOrEnumeralCandidateType)
  6647. return;
  6648. for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
  6649. Arith < NumArithmeticTypes; ++Arith) {
  6650. addPlusPlusMinusMinusStyleOverloads(
  6651. getArithmeticType(Arith),
  6652. VisibleTypeConversionsQuals.hasVolatile(),
  6653. VisibleTypeConversionsQuals.hasRestrict());
  6654. }
  6655. }
  6656. // C++ [over.built]p5:
  6657. //
  6658. // For every pair (T, VQ), where T is a cv-qualified or
  6659. // cv-unqualified object type, and VQ is either volatile or
  6660. // empty, there exist candidate operator functions of the form
  6661. //
  6662. // T*VQ& operator++(T*VQ&);
  6663. // T*VQ& operator--(T*VQ&);
  6664. // T* operator++(T*VQ&, int);
  6665. // T* operator--(T*VQ&, int);
  6666. void addPlusPlusMinusMinusPointerOverloads() {
  6667. for (BuiltinCandidateTypeSet::iterator
  6668. Ptr = CandidateTypes[0].pointer_begin(),
  6669. PtrEnd = CandidateTypes[0].pointer_end();
  6670. Ptr != PtrEnd; ++Ptr) {
  6671. // Skip pointer types that aren't pointers to object types.
  6672. if (!(*Ptr)->getPointeeType()->isObjectType())
  6673. continue;
  6674. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  6675. (!(*Ptr).isVolatileQualified() &&
  6676. VisibleTypeConversionsQuals.hasVolatile()),
  6677. (!(*Ptr).isRestrictQualified() &&
  6678. VisibleTypeConversionsQuals.hasRestrict()));
  6679. }
  6680. }
  6681. // C++ [over.built]p6:
  6682. // For every cv-qualified or cv-unqualified object type T, there
  6683. // exist candidate operator functions of the form
  6684. //
  6685. // T& operator*(T*);
  6686. //
  6687. // C++ [over.built]p7:
  6688. // For every function type T that does not have cv-qualifiers or a
  6689. // ref-qualifier, there exist candidate operator functions of the form
  6690. // T& operator*(T*);
  6691. void addUnaryStarPointerOverloads() {
  6692. for (BuiltinCandidateTypeSet::iterator
  6693. Ptr = CandidateTypes[0].pointer_begin(),
  6694. PtrEnd = CandidateTypes[0].pointer_end();
  6695. Ptr != PtrEnd; ++Ptr) {
  6696. QualType ParamTy = *Ptr;
  6697. QualType PointeeTy = ParamTy->getPointeeType();
  6698. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  6699. continue;
  6700. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  6701. if (Proto->getTypeQuals() || Proto->getRefQualifier())
  6702. continue;
  6703. S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
  6704. &ParamTy, Args, CandidateSet);
  6705. }
  6706. }
  6707. // C++ [over.built]p9:
  6708. // For every promoted arithmetic type T, there exist candidate
  6709. // operator functions of the form
  6710. //
  6711. // T operator+(T);
  6712. // T operator-(T);
  6713. void addUnaryPlusOrMinusArithmeticOverloads() {
  6714. if (!HasArithmeticOrEnumeralCandidateType)
  6715. return;
  6716. for (unsigned Arith = FirstPromotedArithmeticType;
  6717. Arith < LastPromotedArithmeticType; ++Arith) {
  6718. QualType ArithTy = getArithmeticType(Arith);
  6719. S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
  6720. }
  6721. // Extension: We also add these operators for vector types.
  6722. for (BuiltinCandidateTypeSet::iterator
  6723. Vec = CandidateTypes[0].vector_begin(),
  6724. VecEnd = CandidateTypes[0].vector_end();
  6725. Vec != VecEnd; ++Vec) {
  6726. QualType VecTy = *Vec;
  6727. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6728. }
  6729. }
  6730. // C++ [over.built]p8:
  6731. // For every type T, there exist candidate operator functions of
  6732. // the form
  6733. //
  6734. // T* operator+(T*);
  6735. void addUnaryPlusPointerOverloads() {
  6736. for (BuiltinCandidateTypeSet::iterator
  6737. Ptr = CandidateTypes[0].pointer_begin(),
  6738. PtrEnd = CandidateTypes[0].pointer_end();
  6739. Ptr != PtrEnd; ++Ptr) {
  6740. QualType ParamTy = *Ptr;
  6741. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
  6742. }
  6743. }
  6744. // C++ [over.built]p10:
  6745. // For every promoted integral type T, there exist candidate
  6746. // operator functions of the form
  6747. //
  6748. // T operator~(T);
  6749. void addUnaryTildePromotedIntegralOverloads() {
  6750. if (!HasArithmeticOrEnumeralCandidateType)
  6751. return;
  6752. for (unsigned Int = FirstPromotedIntegralType;
  6753. Int < LastPromotedIntegralType; ++Int) {
  6754. QualType IntTy = getArithmeticType(Int);
  6755. S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
  6756. }
  6757. // Extension: We also add this operator for vector types.
  6758. for (BuiltinCandidateTypeSet::iterator
  6759. Vec = CandidateTypes[0].vector_begin(),
  6760. VecEnd = CandidateTypes[0].vector_end();
  6761. Vec != VecEnd; ++Vec) {
  6762. QualType VecTy = *Vec;
  6763. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6764. }
  6765. }
  6766. // C++ [over.match.oper]p16:
  6767. // For every pointer to member type T, there exist candidate operator
  6768. // functions of the form
  6769. //
  6770. // bool operator==(T,T);
  6771. // bool operator!=(T,T);
  6772. void addEqualEqualOrNotEqualMemberPointerOverloads() {
  6773. /// Set of (canonical) types that we've already handled.
  6774. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6775. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6776. for (BuiltinCandidateTypeSet::iterator
  6777. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6778. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6779. MemPtr != MemPtrEnd;
  6780. ++MemPtr) {
  6781. // Don't add the same builtin candidate twice.
  6782. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  6783. continue;
  6784. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  6785. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6786. }
  6787. }
  6788. }
  6789. // C++ [over.built]p15:
  6790. //
  6791. // For every T, where T is an enumeration type, a pointer type, or
  6792. // std::nullptr_t, there exist candidate operator functions of the form
  6793. //
  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. // bool operator!=(T, T);
  6800. void addRelationalPointerOrEnumeralOverloads() {
  6801. // C++ [over.match.oper]p3:
  6802. // [...]the built-in candidates include all of the candidate operator
  6803. // functions defined in 13.6 that, compared to the given operator, [...]
  6804. // do not have the same parameter-type-list as any non-template non-member
  6805. // candidate.
  6806. //
  6807. // Note that in practice, this only affects enumeration types because there
  6808. // aren't any built-in candidates of record type, and a user-defined operator
  6809. // must have an operand of record or enumeration type. Also, the only other
  6810. // overloaded operator with enumeration arguments, operator=,
  6811. // cannot be overloaded for enumeration types, so this is the only place
  6812. // where we must suppress candidates like this.
  6813. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  6814. UserDefinedBinaryOperators;
  6815. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6816. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  6817. CandidateTypes[ArgIdx].enumeration_end()) {
  6818. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  6819. CEnd = CandidateSet.end();
  6820. C != CEnd; ++C) {
  6821. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  6822. continue;
  6823. if (C->Function->isFunctionTemplateSpecialization())
  6824. continue;
  6825. QualType FirstParamType =
  6826. C->Function->getParamDecl(0)->getType().getUnqualifiedType();
  6827. QualType SecondParamType =
  6828. C->Function->getParamDecl(1)->getType().getUnqualifiedType();
  6829. // Skip if either parameter isn't of enumeral type.
  6830. if (!FirstParamType->isEnumeralType() ||
  6831. !SecondParamType->isEnumeralType())
  6832. continue;
  6833. // Add this operator to the set of known user-defined operators.
  6834. UserDefinedBinaryOperators.insert(
  6835. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  6836. S.Context.getCanonicalType(SecondParamType)));
  6837. }
  6838. }
  6839. }
  6840. /// Set of (canonical) types that we've already handled.
  6841. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6842. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6843. for (BuiltinCandidateTypeSet::iterator
  6844. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  6845. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  6846. Ptr != PtrEnd; ++Ptr) {
  6847. // Don't add the same builtin candidate twice.
  6848. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6849. continue;
  6850. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6851. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6852. }
  6853. for (BuiltinCandidateTypeSet::iterator
  6854. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6855. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6856. Enum != EnumEnd; ++Enum) {
  6857. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  6858. // Don't add the same builtin candidate twice, or if a user defined
  6859. // candidate exists.
  6860. if (!AddedTypes.insert(CanonType).second ||
  6861. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  6862. CanonType)))
  6863. continue;
  6864. QualType ParamTypes[2] = { *Enum, *Enum };
  6865. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6866. }
  6867. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  6868. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  6869. if (AddedTypes.insert(NullPtrTy).second &&
  6870. !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
  6871. NullPtrTy))) {
  6872. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  6873. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
  6874. CandidateSet);
  6875. }
  6876. }
  6877. }
  6878. }
  6879. // C++ [over.built]p13:
  6880. //
  6881. // For every cv-qualified or cv-unqualified object type T
  6882. // there exist candidate operator functions of the form
  6883. //
  6884. // T* operator+(T*, ptrdiff_t);
  6885. // T& operator[](T*, ptrdiff_t); [BELOW]
  6886. // T* operator-(T*, ptrdiff_t);
  6887. // T* operator+(ptrdiff_t, T*);
  6888. // T& operator[](ptrdiff_t, T*); [BELOW]
  6889. //
  6890. // C++ [over.built]p14:
  6891. //
  6892. // For every T, where T is a pointer to object type, there
  6893. // exist candidate operator functions of the form
  6894. //
  6895. // ptrdiff_t operator-(T, T);
  6896. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  6897. /// Set of (canonical) types that we've already handled.
  6898. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6899. for (int Arg = 0; Arg < 2; ++Arg) {
  6900. QualType AsymetricParamTypes[2] = {
  6901. S.Context.getPointerDiffType(),
  6902. S.Context.getPointerDiffType(),
  6903. };
  6904. for (BuiltinCandidateTypeSet::iterator
  6905. Ptr = CandidateTypes[Arg].pointer_begin(),
  6906. PtrEnd = CandidateTypes[Arg].pointer_end();
  6907. Ptr != PtrEnd; ++Ptr) {
  6908. QualType PointeeTy = (*Ptr)->getPointeeType();
  6909. if (!PointeeTy->isObjectType())
  6910. continue;
  6911. AsymetricParamTypes[Arg] = *Ptr;
  6912. if (Arg == 0 || Op == OO_Plus) {
  6913. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  6914. // T* operator+(ptrdiff_t, T*);
  6915. S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
  6916. }
  6917. if (Op == OO_Minus) {
  6918. // ptrdiff_t operator-(T, T);
  6919. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6920. continue;
  6921. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6922. S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
  6923. Args, CandidateSet);
  6924. }
  6925. }
  6926. }
  6927. }
  6928. // C++ [over.built]p12:
  6929. //
  6930. // For every pair of promoted arithmetic types L and R, there
  6931. // exist candidate operator functions of the form
  6932. //
  6933. // LR operator*(L, R);
  6934. // LR operator/(L, R);
  6935. // LR operator+(L, R);
  6936. // LR 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. // bool operator!=(L, R);
  6943. //
  6944. // where LR is the result of the usual arithmetic conversions
  6945. // between types L and R.
  6946. //
  6947. // C++ [over.built]p24:
  6948. //
  6949. // For every pair of promoted arithmetic types L and R, there exist
  6950. // candidate operator functions of the form
  6951. //
  6952. // LR operator?(bool, L, R);
  6953. //
  6954. // where LR is the result of the usual arithmetic conversions
  6955. // between types L and R.
  6956. // Our candidates ignore the first parameter.
  6957. void addGenericBinaryArithmeticOverloads(bool isComparison) {
  6958. if (!HasArithmeticOrEnumeralCandidateType)
  6959. return;
  6960. for (unsigned Left = FirstPromotedArithmeticType;
  6961. Left < LastPromotedArithmeticType; ++Left) {
  6962. for (unsigned Right = FirstPromotedArithmeticType;
  6963. Right < LastPromotedArithmeticType; ++Right) {
  6964. QualType LandR[2] = { getArithmeticType(Left),
  6965. getArithmeticType(Right) };
  6966. QualType Result =
  6967. isComparison ? S.Context.BoolTy
  6968. : getUsualArithmeticConversions(Left, Right);
  6969. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6970. }
  6971. }
  6972. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  6973. // conditional operator for vector types.
  6974. for (BuiltinCandidateTypeSet::iterator
  6975. Vec1 = CandidateTypes[0].vector_begin(),
  6976. Vec1End = CandidateTypes[0].vector_end();
  6977. Vec1 != Vec1End; ++Vec1) {
  6978. for (BuiltinCandidateTypeSet::iterator
  6979. Vec2 = CandidateTypes[1].vector_begin(),
  6980. Vec2End = CandidateTypes[1].vector_end();
  6981. Vec2 != Vec2End; ++Vec2) {
  6982. QualType LandR[2] = { *Vec1, *Vec2 };
  6983. QualType Result = S.Context.BoolTy;
  6984. if (!isComparison) {
  6985. if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
  6986. Result = *Vec1;
  6987. else
  6988. Result = *Vec2;
  6989. }
  6990. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6991. }
  6992. }
  6993. }
  6994. // C++ [over.built]p17:
  6995. //
  6996. // For every pair of promoted integral types L and R, there
  6997. // exist candidate operator functions of the form
  6998. //
  6999. // LR operator%(L, R);
  7000. // LR operator&(L, R);
  7001. // LR operator^(L, R);
  7002. // LR operator|(L, R);
  7003. // L operator<<(L, R);
  7004. // L operator>>(L, R);
  7005. //
  7006. // where LR is the result of the usual arithmetic conversions
  7007. // between types L and R.
  7008. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7009. if (!HasArithmeticOrEnumeralCandidateType)
  7010. return;
  7011. for (unsigned Left = FirstPromotedIntegralType;
  7012. Left < LastPromotedIntegralType; ++Left) {
  7013. for (unsigned Right = FirstPromotedIntegralType;
  7014. Right < LastPromotedIntegralType; ++Right) {
  7015. QualType LandR[2] = { getArithmeticType(Left),
  7016. getArithmeticType(Right) };
  7017. QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
  7018. ? LandR[0]
  7019. : getUsualArithmeticConversions(Left, Right);
  7020. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  7021. }
  7022. }
  7023. }
  7024. // C++ [over.built]p20:
  7025. //
  7026. // For every pair (T, VQ), where T is an enumeration or
  7027. // pointer to member type and VQ is either volatile or
  7028. // empty, there exist candidate operator functions of the form
  7029. //
  7030. // VQ T& operator=(VQ T&, T);
  7031. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7032. /// Set of (canonical) types that we've already handled.
  7033. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7034. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7035. for (BuiltinCandidateTypeSet::iterator
  7036. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7037. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7038. Enum != EnumEnd; ++Enum) {
  7039. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7040. continue;
  7041. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7042. }
  7043. for (BuiltinCandidateTypeSet::iterator
  7044. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7045. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7046. MemPtr != MemPtrEnd; ++MemPtr) {
  7047. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7048. continue;
  7049. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7050. }
  7051. }
  7052. }
  7053. // C++ [over.built]p19:
  7054. //
  7055. // For every pair (T, VQ), where T is any type and VQ is either
  7056. // volatile or empty, there exist candidate operator functions
  7057. // of the form
  7058. //
  7059. // T*VQ& operator=(T*VQ&, T*);
  7060. //
  7061. // C++ [over.built]p21:
  7062. //
  7063. // For every pair (T, VQ), where T is a cv-qualified or
  7064. // cv-unqualified object type and VQ is either volatile or
  7065. // empty, there exist candidate operator functions of the form
  7066. //
  7067. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7068. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7069. void addAssignmentPointerOverloads(bool isEqualOp) {
  7070. /// Set of (canonical) types that we've already handled.
  7071. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7072. for (BuiltinCandidateTypeSet::iterator
  7073. Ptr = CandidateTypes[0].pointer_begin(),
  7074. PtrEnd = CandidateTypes[0].pointer_end();
  7075. Ptr != PtrEnd; ++Ptr) {
  7076. // If this is operator=, keep track of the builtin candidates we added.
  7077. if (isEqualOp)
  7078. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7079. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7080. continue;
  7081. // non-volatile version
  7082. QualType ParamTypes[2] = {
  7083. S.Context.getLValueReferenceType(*Ptr),
  7084. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7085. };
  7086. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7087. /*IsAssigmentOperator=*/ isEqualOp);
  7088. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7089. VisibleTypeConversionsQuals.hasVolatile();
  7090. if (NeedVolatile) {
  7091. // volatile version
  7092. ParamTypes[0] =
  7093. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7094. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7095. /*IsAssigmentOperator=*/isEqualOp);
  7096. }
  7097. if (!(*Ptr).isRestrictQualified() &&
  7098. VisibleTypeConversionsQuals.hasRestrict()) {
  7099. // restrict version
  7100. ParamTypes[0]
  7101. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7102. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7103. /*IsAssigmentOperator=*/isEqualOp);
  7104. if (NeedVolatile) {
  7105. // volatile restrict version
  7106. ParamTypes[0]
  7107. = S.Context.getLValueReferenceType(
  7108. S.Context.getCVRQualifiedType(*Ptr,
  7109. (Qualifiers::Volatile |
  7110. Qualifiers::Restrict)));
  7111. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7112. /*IsAssigmentOperator=*/isEqualOp);
  7113. }
  7114. }
  7115. }
  7116. if (isEqualOp) {
  7117. for (BuiltinCandidateTypeSet::iterator
  7118. Ptr = CandidateTypes[1].pointer_begin(),
  7119. PtrEnd = CandidateTypes[1].pointer_end();
  7120. Ptr != PtrEnd; ++Ptr) {
  7121. // Make sure we don't add the same candidate twice.
  7122. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7123. continue;
  7124. QualType ParamTypes[2] = {
  7125. S.Context.getLValueReferenceType(*Ptr),
  7126. *Ptr,
  7127. };
  7128. // non-volatile version
  7129. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7130. /*IsAssigmentOperator=*/true);
  7131. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7132. VisibleTypeConversionsQuals.hasVolatile();
  7133. if (NeedVolatile) {
  7134. // volatile version
  7135. ParamTypes[0] =
  7136. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7137. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7138. /*IsAssigmentOperator=*/true);
  7139. }
  7140. if (!(*Ptr).isRestrictQualified() &&
  7141. VisibleTypeConversionsQuals.hasRestrict()) {
  7142. // restrict version
  7143. ParamTypes[0]
  7144. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7145. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7146. /*IsAssigmentOperator=*/true);
  7147. if (NeedVolatile) {
  7148. // volatile restrict version
  7149. ParamTypes[0]
  7150. = S.Context.getLValueReferenceType(
  7151. S.Context.getCVRQualifiedType(*Ptr,
  7152. (Qualifiers::Volatile |
  7153. Qualifiers::Restrict)));
  7154. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7155. /*IsAssigmentOperator=*/true);
  7156. }
  7157. }
  7158. }
  7159. }
  7160. }
  7161. // C++ [over.built]p18:
  7162. //
  7163. // For every triple (L, VQ, R), where L is an arithmetic type,
  7164. // VQ is either volatile or empty, and R is a promoted
  7165. // arithmetic type, there exist candidate operator functions of
  7166. // the form
  7167. //
  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. // VQ L& operator-=(VQ L&, R);
  7173. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7174. if (!HasArithmeticOrEnumeralCandidateType)
  7175. return;
  7176. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7177. for (unsigned Right = FirstPromotedArithmeticType;
  7178. Right < LastPromotedArithmeticType; ++Right) {
  7179. QualType ParamTypes[2];
  7180. ParamTypes[1] = getArithmeticType(Right);
  7181. // Add this built-in operator as a candidate (VQ is empty).
  7182. ParamTypes[0] =
  7183. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7184. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7185. /*IsAssigmentOperator=*/isEqualOp);
  7186. // Add this built-in operator as a candidate (VQ is 'volatile').
  7187. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7188. ParamTypes[0] =
  7189. S.Context.getVolatileType(getArithmeticType(Left));
  7190. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7191. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7192. /*IsAssigmentOperator=*/isEqualOp);
  7193. }
  7194. }
  7195. }
  7196. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7197. for (BuiltinCandidateTypeSet::iterator
  7198. Vec1 = CandidateTypes[0].vector_begin(),
  7199. Vec1End = CandidateTypes[0].vector_end();
  7200. Vec1 != Vec1End; ++Vec1) {
  7201. for (BuiltinCandidateTypeSet::iterator
  7202. Vec2 = CandidateTypes[1].vector_begin(),
  7203. Vec2End = CandidateTypes[1].vector_end();
  7204. Vec2 != Vec2End; ++Vec2) {
  7205. QualType ParamTypes[2];
  7206. ParamTypes[1] = *Vec2;
  7207. // Add this built-in operator as a candidate (VQ is empty).
  7208. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7209. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7210. /*IsAssigmentOperator=*/isEqualOp);
  7211. // Add this built-in operator as a candidate (VQ is 'volatile').
  7212. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7213. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7214. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7215. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7216. /*IsAssigmentOperator=*/isEqualOp);
  7217. }
  7218. }
  7219. }
  7220. }
  7221. // C++ [over.built]p22:
  7222. //
  7223. // For every triple (L, VQ, R), where L is an integral type, VQ
  7224. // is either volatile or empty, and R is a promoted integral
  7225. // type, there exist candidate operator functions of the form
  7226. //
  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. // VQ L& operator|=(VQ L&, R);
  7233. void addAssignmentIntegralOverloads() {
  7234. if (!HasArithmeticOrEnumeralCandidateType)
  7235. return;
  7236. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7237. for (unsigned Right = FirstPromotedIntegralType;
  7238. Right < LastPromotedIntegralType; ++Right) {
  7239. QualType ParamTypes[2];
  7240. ParamTypes[1] = getArithmeticType(Right);
  7241. // Add this built-in operator as a candidate (VQ is empty).
  7242. ParamTypes[0] =
  7243. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7244. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7245. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7246. // Add this built-in operator as a candidate (VQ is 'volatile').
  7247. ParamTypes[0] = getArithmeticType(Left);
  7248. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7249. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7250. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7251. }
  7252. }
  7253. }
  7254. }
  7255. // C++ [over.operator]p23:
  7256. //
  7257. // There also exist candidate operator functions of the form
  7258. //
  7259. // bool operator!(bool);
  7260. // bool operator&&(bool, bool);
  7261. // bool operator||(bool, bool);
  7262. void addExclaimOverload() {
  7263. QualType ParamTy = S.Context.BoolTy;
  7264. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
  7265. /*IsAssignmentOperator=*/false,
  7266. /*NumContextualBoolArguments=*/1);
  7267. }
  7268. void addAmpAmpOrPipePipeOverload() {
  7269. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7270. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
  7271. /*IsAssignmentOperator=*/false,
  7272. /*NumContextualBoolArguments=*/2);
  7273. }
  7274. // C++ [over.built]p13:
  7275. //
  7276. // For every cv-qualified or cv-unqualified object type T there
  7277. // exist candidate operator functions of the form
  7278. //
  7279. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7280. // T& operator[](T*, ptrdiff_t);
  7281. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7282. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7283. // T& operator[](ptrdiff_t, T*);
  7284. void addSubscriptOverloads() {
  7285. for (BuiltinCandidateTypeSet::iterator
  7286. Ptr = CandidateTypes[0].pointer_begin(),
  7287. PtrEnd = CandidateTypes[0].pointer_end();
  7288. Ptr != PtrEnd; ++Ptr) {
  7289. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7290. QualType PointeeType = (*Ptr)->getPointeeType();
  7291. if (!PointeeType->isObjectType())
  7292. continue;
  7293. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7294. // T& operator[](T*, ptrdiff_t)
  7295. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7296. }
  7297. for (BuiltinCandidateTypeSet::iterator
  7298. Ptr = CandidateTypes[1].pointer_begin(),
  7299. PtrEnd = CandidateTypes[1].pointer_end();
  7300. Ptr != PtrEnd; ++Ptr) {
  7301. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7302. QualType PointeeType = (*Ptr)->getPointeeType();
  7303. if (!PointeeType->isObjectType())
  7304. continue;
  7305. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7306. // T& operator[](ptrdiff_t, T*)
  7307. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7308. }
  7309. }
  7310. // C++ [over.built]p11:
  7311. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7312. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7313. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7314. // there exist candidate operator functions of the form
  7315. //
  7316. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7317. //
  7318. // where CV12 is the union of CV1 and CV2.
  7319. void addArrowStarOverloads() {
  7320. for (BuiltinCandidateTypeSet::iterator
  7321. Ptr = CandidateTypes[0].pointer_begin(),
  7322. PtrEnd = CandidateTypes[0].pointer_end();
  7323. Ptr != PtrEnd; ++Ptr) {
  7324. QualType C1Ty = (*Ptr);
  7325. QualType C1;
  7326. QualifierCollector Q1;
  7327. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7328. if (!isa<RecordType>(C1))
  7329. continue;
  7330. // heuristic to reduce number of builtin candidates in the set.
  7331. // Add volatile/restrict version only if there are conversions to a
  7332. // volatile/restrict type.
  7333. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7334. continue;
  7335. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7336. continue;
  7337. for (BuiltinCandidateTypeSet::iterator
  7338. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7339. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7340. MemPtr != MemPtrEnd; ++MemPtr) {
  7341. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7342. QualType C2 = QualType(mptr->getClass(), 0);
  7343. C2 = C2.getUnqualifiedType();
  7344. if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
  7345. break;
  7346. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7347. // build CV12 T&
  7348. QualType T = mptr->getPointeeType();
  7349. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7350. T.isVolatileQualified())
  7351. continue;
  7352. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7353. T.isRestrictQualified())
  7354. continue;
  7355. T = Q1.apply(S.Context, T);
  7356. QualType ResultTy = S.Context.getLValueReferenceType(T);
  7357. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7358. }
  7359. }
  7360. }
  7361. // Note that we don't consider the first argument, since it has been
  7362. // contextually converted to bool long ago. The candidates below are
  7363. // therefore added as binary.
  7364. //
  7365. // C++ [over.built]p25:
  7366. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7367. // enumeration type, there exist candidate operator functions of the form
  7368. //
  7369. // T operator?(bool, T, T);
  7370. //
  7371. void addConditionalOperatorOverloads() {
  7372. /// Set of (canonical) types that we've already handled.
  7373. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7374. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7375. for (BuiltinCandidateTypeSet::iterator
  7376. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7377. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7378. Ptr != PtrEnd; ++Ptr) {
  7379. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7380. continue;
  7381. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7382. S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
  7383. }
  7384. for (BuiltinCandidateTypeSet::iterator
  7385. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7386. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7387. MemPtr != MemPtrEnd; ++MemPtr) {
  7388. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7389. continue;
  7390. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7391. S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
  7392. }
  7393. if (S.getLangOpts().CPlusPlus11) {
  7394. for (BuiltinCandidateTypeSet::iterator
  7395. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7396. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7397. Enum != EnumEnd; ++Enum) {
  7398. if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
  7399. continue;
  7400. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7401. continue;
  7402. QualType ParamTypes[2] = { *Enum, *Enum };
  7403. S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
  7404. }
  7405. }
  7406. }
  7407. }
  7408. };
  7409. } // end anonymous namespace
  7410. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  7411. /// operator overloads to the candidate set (C++ [over.built]), based
  7412. /// on the operator @p Op and the arguments given. For example, if the
  7413. /// operator is a binary '+', this routine might add "int
  7414. /// operator+(int, int)" to cover integer addition.
  7415. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  7416. SourceLocation OpLoc,
  7417. ArrayRef<Expr *> Args,
  7418. OverloadCandidateSet &CandidateSet) {
  7419. // Find all of the types that the arguments can convert to, but only
  7420. // if the operator we're looking at has built-in operator candidates
  7421. // that make use of these types. Also record whether we encounter non-record
  7422. // candidate types or either arithmetic or enumeral candidate types.
  7423. Qualifiers VisibleTypeConversionsQuals;
  7424. VisibleTypeConversionsQuals.addConst();
  7425. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  7426. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  7427. bool HasNonRecordCandidateType = false;
  7428. bool HasArithmeticOrEnumeralCandidateType = false;
  7429. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  7430. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7431. CandidateTypes.emplace_back(*this);
  7432. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  7433. OpLoc,
  7434. true,
  7435. (Op == OO_Exclaim ||
  7436. Op == OO_AmpAmp ||
  7437. Op == OO_PipePipe),
  7438. VisibleTypeConversionsQuals);
  7439. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  7440. CandidateTypes[ArgIdx].hasNonRecordTypes();
  7441. HasArithmeticOrEnumeralCandidateType =
  7442. HasArithmeticOrEnumeralCandidateType ||
  7443. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  7444. }
  7445. // Exit early when no non-record types have been added to the candidate set
  7446. // for any of the arguments to the operator.
  7447. //
  7448. // We can't exit early for !, ||, or &&, since there we have always have
  7449. // 'bool' overloads.
  7450. if (!HasNonRecordCandidateType &&
  7451. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  7452. return;
  7453. // Setup an object to manage the common state for building overloads.
  7454. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  7455. VisibleTypeConversionsQuals,
  7456. HasArithmeticOrEnumeralCandidateType,
  7457. CandidateTypes, CandidateSet);
  7458. // Dispatch over the operation to add in only those overloads which apply.
  7459. switch (Op) {
  7460. case OO_None:
  7461. case NUM_OVERLOADED_OPERATORS:
  7462. llvm_unreachable("Expected an overloaded operator");
  7463. case OO_New:
  7464. case OO_Delete:
  7465. case OO_Array_New:
  7466. case OO_Array_Delete:
  7467. case OO_Call:
  7468. llvm_unreachable(
  7469. "Special operators don't use AddBuiltinOperatorCandidates");
  7470. case OO_Comma:
  7471. case OO_Arrow:
  7472. // C++ [over.match.oper]p3:
  7473. // -- For the operator ',', the unary operator '&', or the
  7474. // operator '->', the built-in candidates set is empty.
  7475. break;
  7476. case OO_Plus: // '+' is either unary or binary
  7477. if (Args.size() == 1)
  7478. OpBuilder.addUnaryPlusPointerOverloads();
  7479. // Fall through.
  7480. case OO_Minus: // '-' is either unary or binary
  7481. if (Args.size() == 1) {
  7482. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  7483. } else {
  7484. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  7485. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7486. }
  7487. break;
  7488. case OO_Star: // '*' is either unary or binary
  7489. if (Args.size() == 1)
  7490. OpBuilder.addUnaryStarPointerOverloads();
  7491. else
  7492. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7493. break;
  7494. case OO_Slash:
  7495. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7496. break;
  7497. case OO_PlusPlus:
  7498. case OO_MinusMinus:
  7499. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  7500. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  7501. break;
  7502. case OO_EqualEqual:
  7503. case OO_ExclaimEqual:
  7504. OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
  7505. // Fall through.
  7506. case OO_Less:
  7507. case OO_Greater:
  7508. case OO_LessEqual:
  7509. case OO_GreaterEqual:
  7510. OpBuilder.addRelationalPointerOrEnumeralOverloads();
  7511. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
  7512. break;
  7513. case OO_Percent:
  7514. case OO_Caret:
  7515. case OO_Pipe:
  7516. case OO_LessLess:
  7517. case OO_GreaterGreater:
  7518. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7519. break;
  7520. case OO_Amp: // '&' is either unary or binary
  7521. if (Args.size() == 1)
  7522. // C++ [over.match.oper]p3:
  7523. // -- For the operator ',', the unary operator '&', or the
  7524. // operator '->', the built-in candidates set is empty.
  7525. break;
  7526. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7527. break;
  7528. case OO_Tilde:
  7529. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  7530. break;
  7531. case OO_Equal:
  7532. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  7533. // Fall through.
  7534. case OO_PlusEqual:
  7535. case OO_MinusEqual:
  7536. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  7537. // Fall through.
  7538. case OO_StarEqual:
  7539. case OO_SlashEqual:
  7540. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  7541. break;
  7542. case OO_PercentEqual:
  7543. case OO_LessLessEqual:
  7544. case OO_GreaterGreaterEqual:
  7545. case OO_AmpEqual:
  7546. case OO_CaretEqual:
  7547. case OO_PipeEqual:
  7548. OpBuilder.addAssignmentIntegralOverloads();
  7549. break;
  7550. case OO_Exclaim:
  7551. OpBuilder.addExclaimOverload();
  7552. break;
  7553. case OO_AmpAmp:
  7554. case OO_PipePipe:
  7555. OpBuilder.addAmpAmpOrPipePipeOverload();
  7556. break;
  7557. case OO_Subscript:
  7558. OpBuilder.addSubscriptOverloads();
  7559. break;
  7560. case OO_ArrowStar:
  7561. OpBuilder.addArrowStarOverloads();
  7562. break;
  7563. case OO_Conditional:
  7564. OpBuilder.addConditionalOperatorOverloads();
  7565. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7566. break;
  7567. }
  7568. }
  7569. /// \brief Add function candidates found via argument-dependent lookup
  7570. /// to the set of overloading candidates.
  7571. ///
  7572. /// This routine performs argument-dependent name lookup based on the
  7573. /// given function name (which may also be an operator name) and adds
  7574. /// all of the overload candidates found by ADL to the overload
  7575. /// candidate set (C++ [basic.lookup.argdep]).
  7576. void
  7577. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  7578. SourceLocation Loc,
  7579. ArrayRef<Expr *> Args,
  7580. TemplateArgumentListInfo *ExplicitTemplateArgs,
  7581. OverloadCandidateSet& CandidateSet,
  7582. bool PartialOverloading) {
  7583. ADLResult Fns;
  7584. // FIXME: This approach for uniquing ADL results (and removing
  7585. // redundant candidates from the set) relies on pointer-equality,
  7586. // which means we need to key off the canonical decl. However,
  7587. // always going back to the canonical decl might not get us the
  7588. // right set of default arguments. What default arguments are
  7589. // we supposed to consider on ADL candidates, anyway?
  7590. // FIXME: Pass in the explicit template arguments?
  7591. ArgumentDependentLookup(Name, Loc, Args, Fns);
  7592. // Erase all of the candidates we already knew about.
  7593. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  7594. CandEnd = CandidateSet.end();
  7595. Cand != CandEnd; ++Cand)
  7596. if (Cand->Function) {
  7597. Fns.erase(Cand->Function);
  7598. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  7599. Fns.erase(FunTmpl);
  7600. }
  7601. // For each of the ADL candidates we found, add it to the overload
  7602. // set.
  7603. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  7604. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  7605. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  7606. if (ExplicitTemplateArgs)
  7607. continue;
  7608. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
  7609. PartialOverloading);
  7610. } else
  7611. AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
  7612. FoundDecl, ExplicitTemplateArgs,
  7613. Args, CandidateSet, PartialOverloading);
  7614. }
  7615. }
  7616. /// isBetterOverloadCandidate - Determines whether the first overload
  7617. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  7618. bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
  7619. const OverloadCandidate &Cand2,
  7620. SourceLocation Loc,
  7621. bool UserDefinedConversion) {
  7622. // Define viable functions to be better candidates than non-viable
  7623. // functions.
  7624. if (!Cand2.Viable)
  7625. return Cand1.Viable;
  7626. else if (!Cand1.Viable)
  7627. return false;
  7628. // C++ [over.match.best]p1:
  7629. //
  7630. // -- if F is a static member function, ICS1(F) is defined such
  7631. // that ICS1(F) is neither better nor worse than ICS1(G) for
  7632. // any function G, and, symmetrically, ICS1(G) is neither
  7633. // better nor worse than ICS1(F).
  7634. unsigned StartArg = 0;
  7635. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  7636. StartArg = 1;
  7637. // C++ [over.match.best]p1:
  7638. // A viable function F1 is defined to be a better function than another
  7639. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  7640. // conversion sequence than ICSi(F2), and then...
  7641. unsigned NumArgs = Cand1.NumConversions;
  7642. assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
  7643. bool HasBetterConversion = false;
  7644. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  7645. switch (CompareImplicitConversionSequences(S,
  7646. Cand1.Conversions[ArgIdx],
  7647. Cand2.Conversions[ArgIdx])) {
  7648. case ImplicitConversionSequence::Better:
  7649. // Cand1 has a better conversion sequence.
  7650. HasBetterConversion = true;
  7651. break;
  7652. case ImplicitConversionSequence::Worse:
  7653. // Cand1 can't be better than Cand2.
  7654. return false;
  7655. case ImplicitConversionSequence::Indistinguishable:
  7656. // Do nothing.
  7657. break;
  7658. }
  7659. }
  7660. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  7661. // ICSj(F2), or, if not that,
  7662. if (HasBetterConversion)
  7663. return true;
  7664. // -- the context is an initialization by user-defined conversion
  7665. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  7666. // from the return type of F1 to the destination type (i.e.,
  7667. // the type of the entity being initialized) is a better
  7668. // conversion sequence than the standard conversion sequence
  7669. // from the return type of F2 to the destination type.
  7670. if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
  7671. isa<CXXConversionDecl>(Cand1.Function) &&
  7672. isa<CXXConversionDecl>(Cand2.Function)) {
  7673. // First check whether we prefer one of the conversion functions over the
  7674. // other. This only distinguishes the results in non-standard, extension
  7675. // cases such as the conversion from a lambda closure type to a function
  7676. // pointer or block.
  7677. ImplicitConversionSequence::CompareKind Result =
  7678. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  7679. if (Result == ImplicitConversionSequence::Indistinguishable)
  7680. Result = CompareStandardConversionSequences(S,
  7681. Cand1.FinalConversion,
  7682. Cand2.FinalConversion);
  7683. if (Result != ImplicitConversionSequence::Indistinguishable)
  7684. return Result == ImplicitConversionSequence::Better;
  7685. // FIXME: Compare kind of reference binding if conversion functions
  7686. // convert to a reference type used in direct reference binding, per
  7687. // C++14 [over.match.best]p1 section 2 bullet 3.
  7688. }
  7689. // -- F1 is a non-template function and F2 is a function template
  7690. // specialization, or, if not that,
  7691. bool Cand1IsSpecialization = Cand1.Function &&
  7692. Cand1.Function->getPrimaryTemplate();
  7693. bool Cand2IsSpecialization = Cand2.Function &&
  7694. Cand2.Function->getPrimaryTemplate();
  7695. if (Cand1IsSpecialization != Cand2IsSpecialization)
  7696. return Cand2IsSpecialization;
  7697. // -- F1 and F2 are function template specializations, and the function
  7698. // template for F1 is more specialized than the template for F2
  7699. // according to the partial ordering rules described in 14.5.5.2, or,
  7700. // if not that,
  7701. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  7702. if (FunctionTemplateDecl *BetterTemplate
  7703. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  7704. Cand2.Function->getPrimaryTemplate(),
  7705. Loc,
  7706. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  7707. : TPOC_Call,
  7708. Cand1.ExplicitCallArguments,
  7709. Cand2.ExplicitCallArguments))
  7710. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  7711. }
  7712. // Check for enable_if value-based overload resolution.
  7713. if (Cand1.Function && Cand2.Function &&
  7714. (Cand1.Function->hasAttr<EnableIfAttr>() ||
  7715. Cand2.Function->hasAttr<EnableIfAttr>())) {
  7716. // FIXME: The next several lines are just
  7717. // specific_attr_iterator<EnableIfAttr> but going in declaration order,
  7718. // instead of reverse order which is how they're stored in the AST.
  7719. AttrVec Cand1Attrs;
  7720. if (Cand1.Function->hasAttrs()) {
  7721. Cand1Attrs = Cand1.Function->getAttrs();
  7722. Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
  7723. IsNotEnableIfAttr),
  7724. Cand1Attrs.end());
  7725. std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
  7726. }
  7727. AttrVec Cand2Attrs;
  7728. if (Cand2.Function->hasAttrs()) {
  7729. Cand2Attrs = Cand2.Function->getAttrs();
  7730. Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
  7731. IsNotEnableIfAttr),
  7732. Cand2Attrs.end());
  7733. std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
  7734. }
  7735. // Candidate 1 is better if it has strictly more attributes and
  7736. // the common sequence is identical.
  7737. if (Cand1Attrs.size() <= Cand2Attrs.size())
  7738. return false;
  7739. auto Cand1I = Cand1Attrs.begin();
  7740. for (auto &Cand2A : Cand2Attrs) {
  7741. auto &Cand1A = *Cand1I++;
  7742. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  7743. cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
  7744. S.getASTContext(), true);
  7745. cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
  7746. S.getASTContext(), true);
  7747. if (Cand1ID != Cand2ID)
  7748. return false;
  7749. }
  7750. return true;
  7751. }
  7752. return false;
  7753. }
  7754. /// \brief Computes the best viable function (C++ 13.3.3)
  7755. /// within an overload candidate set.
  7756. ///
  7757. /// \param Loc The location of the function name (or operator symbol) for
  7758. /// which overload resolution occurs.
  7759. ///
  7760. /// \param Best If overload resolution was successful or found a deleted
  7761. /// function, \p Best points to the candidate function found.
  7762. ///
  7763. /// \returns The result of overload resolution.
  7764. OverloadingResult
  7765. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  7766. iterator &Best,
  7767. bool UserDefinedConversion) {
  7768. // HLSL Change Starts
  7769. // Function calls should use HLSL-style overloading. operator[] overloads
  7770. // (used for const support) aren't supported by the defined rules, so
  7771. // use C++ overload resolution for those.
  7772. if (S.getLangOpts().HLSL && !empty() && begin()->Function != nullptr &&
  7773. (begin()->Function->getDeclName() !=
  7774. S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  7775. return ::hlsl::GetBestViableFunction(S, Loc, *this, Best);
  7776. }
  7777. // HLSL Change Ends
  7778. // Find the best viable function.
  7779. Best = end();
  7780. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7781. if (Cand->Viable)
  7782. if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
  7783. UserDefinedConversion))
  7784. Best = Cand;
  7785. }
  7786. // If we didn't find any viable functions, abort.
  7787. if (Best == end())
  7788. return OR_No_Viable_Function;
  7789. // Make sure that this function is better than every other viable
  7790. // function. If not, we have an ambiguity.
  7791. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7792. if (Cand->Viable &&
  7793. Cand != Best &&
  7794. !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
  7795. UserDefinedConversion)) {
  7796. Best = end();
  7797. return OR_Ambiguous;
  7798. }
  7799. }
  7800. // Best is the best viable function.
  7801. if (Best->Function &&
  7802. (Best->Function->isDeleted() ||
  7803. S.isFunctionConsideredUnavailable(Best->Function)))
  7804. return OR_Deleted;
  7805. return OR_Success;
  7806. }
  7807. namespace {
  7808. enum OverloadCandidateKind {
  7809. oc_function,
  7810. oc_method,
  7811. oc_constructor,
  7812. oc_function_template,
  7813. oc_method_template,
  7814. oc_constructor_template,
  7815. oc_implicit_default_constructor,
  7816. oc_implicit_copy_constructor,
  7817. oc_implicit_move_constructor,
  7818. oc_implicit_copy_assignment,
  7819. oc_implicit_move_assignment,
  7820. oc_implicit_inherited_constructor
  7821. };
  7822. OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
  7823. FunctionDecl *Fn,
  7824. std::string &Description) {
  7825. bool isTemplate = false;
  7826. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  7827. isTemplate = true;
  7828. Description = S.getTemplateArgumentBindingsText(
  7829. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  7830. }
  7831. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7832. if (!Ctor->isImplicit())
  7833. return isTemplate ? oc_constructor_template : oc_constructor;
  7834. if (Ctor->getInheritedConstructor())
  7835. return oc_implicit_inherited_constructor;
  7836. if (Ctor->isDefaultConstructor())
  7837. return oc_implicit_default_constructor;
  7838. if (Ctor->isMoveConstructor())
  7839. return oc_implicit_move_constructor;
  7840. assert(Ctor->isCopyConstructor() &&
  7841. "unexpected sort of implicit constructor");
  7842. return oc_implicit_copy_constructor;
  7843. }
  7844. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  7845. if (S.getLangOpts().HLSL) return isTemplate ? oc_method_template : oc_method; // HLSL Change - all intrinsics are implicit, doesn't imply conversion
  7846. // This actually gets spelled 'candidate function' for now, but
  7847. // it doesn't hurt to split it out.
  7848. if (!Meth->isImplicit())
  7849. return isTemplate ? oc_method_template : oc_method;
  7850. if (Meth->isMoveAssignmentOperator())
  7851. return oc_implicit_move_assignment;
  7852. if (Meth->isCopyAssignmentOperator())
  7853. return oc_implicit_copy_assignment;
  7854. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  7855. return oc_method;
  7856. }
  7857. return isTemplate ? oc_function_template : oc_function;
  7858. }
  7859. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
  7860. const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
  7861. if (!Ctor) return;
  7862. Ctor = Ctor->getInheritedConstructor();
  7863. if (!Ctor) return;
  7864. S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
  7865. }
  7866. } // end anonymous namespace
  7867. // Notes the location of an overload candidate.
  7868. void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
  7869. std::string FnDesc;
  7870. OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
  7871. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  7872. << (unsigned) K << FnDesc;
  7873. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  7874. Diag(Fn->getLocation(), PD);
  7875. MaybeEmitInheritedConstructorNote(*this, Fn);
  7876. }
  7877. // Notes the location of all overload candidates designated through
  7878. // OverloadedExpr
  7879. void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
  7880. assert(OverloadedExpr->getType() == Context.OverloadTy);
  7881. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  7882. OverloadExpr *OvlExpr = Ovl.Expression;
  7883. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  7884. IEnd = OvlExpr->decls_end();
  7885. I != IEnd; ++I) {
  7886. if (FunctionTemplateDecl *FunTmpl =
  7887. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  7888. NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
  7889. } else if (FunctionDecl *Fun
  7890. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  7891. NoteOverloadCandidate(Fun, DestType);
  7892. }
  7893. }
  7894. }
  7895. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  7896. /// "lead" diagnostic; it will be given two arguments, the source and
  7897. /// target types of the conversion.
  7898. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  7899. Sema &S,
  7900. SourceLocation CaretLoc,
  7901. const PartialDiagnostic &PDiag) const {
  7902. S.Diag(CaretLoc, PDiag)
  7903. << Ambiguous.getFromType() << Ambiguous.getToType();
  7904. // FIXME: The note limiting machinery is borrowed from
  7905. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  7906. // refactoring here.
  7907. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  7908. unsigned CandsShown = 0;
  7909. AmbiguousConversionSequence::const_iterator I, E;
  7910. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  7911. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  7912. break;
  7913. ++CandsShown;
  7914. S.NoteOverloadCandidate(*I);
  7915. }
  7916. if (I != E)
  7917. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  7918. }
  7919. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  7920. unsigned I, const ImplicitConversionSequence &Conv, SourceLocation OpLoc) { // HLSL Change: add OpLoc and Conv
  7921. // const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  7922. assert(Conv.isBad());
  7923. assert(Cand->Function && "for now, candidate must be a function");
  7924. FunctionDecl *Fn = Cand->Function;
  7925. // There's a conversion slot for the object argument if this is a
  7926. // non-constructor method. Note that 'I' corresponds the
  7927. // conversion-slot index.
  7928. bool isObjectArgument = false;
  7929. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  7930. if (I == 0)
  7931. isObjectArgument = true;
  7932. else
  7933. I--;
  7934. }
  7935. std::string FnDesc;
  7936. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  7937. Expr *FromExpr = Conv.Bad.FromExpr;
  7938. QualType FromTy = Conv.Bad.getFromType();
  7939. QualType ToTy = Conv.Bad.getToType();
  7940. // HLSL Change: replace Fn->getLocation() in diagnostics with FnDiagLocation
  7941. // and avoid notes that try to point to built-in targets
  7942. SourceLocation FnDiagLocation = Fn->getLocation().isValid() ? Fn->getLocation() : OpLoc;
  7943. if (FromTy == S.Context.OverloadTy) {
  7944. assert(FromExpr && "overload set argument came from implicit argument?");
  7945. Expr *E = FromExpr->IgnoreParens();
  7946. if (isa<UnaryOperator>(E))
  7947. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  7948. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  7949. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_overload) // HLSL Change - FnDiagLocation
  7950. << (unsigned) FnKind << FnDesc
  7951. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7952. << ToTy << Name << I+1;
  7953. MaybeEmitInheritedConstructorNote(S, Fn);
  7954. return;
  7955. }
  7956. // Do some hand-waving analysis to see if the non-viability is due
  7957. // to a qualifier mismatch.
  7958. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  7959. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  7960. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  7961. CToTy = RT->getPointeeType();
  7962. else {
  7963. // TODO: detect and diagnose the full richness of const mismatches.
  7964. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  7965. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
  7966. CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
  7967. }
  7968. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  7969. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  7970. Qualifiers FromQs = CFromTy.getQualifiers();
  7971. Qualifiers ToQs = CToTy.getQualifiers();
  7972. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  7973. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_addrspace)
  7974. << (unsigned) FnKind << FnDesc
  7975. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7976. << FromTy
  7977. << FromQs.getAddressSpace() << ToQs.getAddressSpace()
  7978. << (unsigned) isObjectArgument << I+1;
  7979. MaybeEmitInheritedConstructorNote(S, Fn);
  7980. return;
  7981. }
  7982. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  7983. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_ownership)
  7984. << (unsigned) FnKind << FnDesc
  7985. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7986. << FromTy
  7987. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  7988. << (unsigned) isObjectArgument << I+1;
  7989. MaybeEmitInheritedConstructorNote(S, Fn);
  7990. return;
  7991. }
  7992. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  7993. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_gc)
  7994. << (unsigned) FnKind << FnDesc
  7995. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7996. << FromTy
  7997. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  7998. << (unsigned) isObjectArgument << I+1;
  7999. MaybeEmitInheritedConstructorNote(S, Fn);
  8000. return;
  8001. }
  8002. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  8003. assert(CVR && "unexpected qualifiers mismatch");
  8004. if (isObjectArgument) {
  8005. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr_this)
  8006. << (unsigned) FnKind << FnDesc
  8007. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8008. << FromTy << (CVR - 1);
  8009. } else {
  8010. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr)
  8011. << (unsigned) FnKind << FnDesc
  8012. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8013. << FromTy << (CVR - 1) << I+1;
  8014. }
  8015. MaybeEmitInheritedConstructorNote(S, Fn);
  8016. return;
  8017. }
  8018. // Special diagnostic for failure to convert an initializer list, since
  8019. // telling the user that it has type void is not useful.
  8020. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8021. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_list_argument)
  8022. << (unsigned) FnKind << FnDesc
  8023. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8024. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8025. MaybeEmitInheritedConstructorNote(S, Fn);
  8026. return;
  8027. }
  8028. // Diagnose references or pointers to incomplete types differently,
  8029. // since it's far from impossible that the incompleteness triggered
  8030. // the failure.
  8031. QualType TempFromTy = FromTy.getNonReferenceType();
  8032. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8033. TempFromTy = PTy->getPointeeType();
  8034. if (TempFromTy->isIncompleteType()) {
  8035. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_conv_incomplete)
  8036. << (unsigned) FnKind << FnDesc
  8037. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8038. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8039. MaybeEmitInheritedConstructorNote(S, Fn);
  8040. return;
  8041. }
  8042. // Diagnose base -> derived pointer conversions.
  8043. unsigned BaseToDerivedConversion = 0;
  8044. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8045. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8046. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8047. FromPtrTy->getPointeeType()) &&
  8048. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8049. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8050. S.IsDerivedFrom(ToPtrTy->getPointeeType(),
  8051. FromPtrTy->getPointeeType()))
  8052. BaseToDerivedConversion = 1;
  8053. }
  8054. } else if (const ObjCObjectPointerType *FromPtrTy
  8055. = FromTy->getAs<ObjCObjectPointerType>()) {
  8056. if (const ObjCObjectPointerType *ToPtrTy
  8057. = ToTy->getAs<ObjCObjectPointerType>())
  8058. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8059. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8060. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8061. FromPtrTy->getPointeeType()) &&
  8062. FromIface->isSuperClassOf(ToIface))
  8063. BaseToDerivedConversion = 2;
  8064. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  8065. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  8066. !FromTy->isIncompleteType() &&
  8067. !ToRefTy->getPointeeType()->isIncompleteType() &&
  8068. S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
  8069. BaseToDerivedConversion = 3;
  8070. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  8071. ToTy.getNonReferenceType().getCanonicalType() ==
  8072. FromTy.getNonReferenceType().getCanonicalType()) {
  8073. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_lvalue)
  8074. << (unsigned) FnKind << FnDesc
  8075. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8076. << (unsigned) isObjectArgument << I + 1;
  8077. MaybeEmitInheritedConstructorNote(S, Fn);
  8078. return;
  8079. }
  8080. }
  8081. if (BaseToDerivedConversion) {
  8082. S.Diag(FnDiagLocation,
  8083. diag::note_ovl_candidate_bad_base_to_derived_conv)
  8084. << (unsigned) FnKind << FnDesc
  8085. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8086. << (BaseToDerivedConversion - 1)
  8087. << FromTy << ToTy << I+1;
  8088. MaybeEmitInheritedConstructorNote(S, Fn);
  8089. return;
  8090. }
  8091. if (isa<ObjCObjectPointerType>(CFromTy) &&
  8092. isa<PointerType>(CToTy)) {
  8093. Qualifiers FromQs = CFromTy.getQualifiers();
  8094. Qualifiers ToQs = CToTy.getQualifiers();
  8095. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8096. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_arc_conv)
  8097. << (unsigned) FnKind << FnDesc
  8098. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8099. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8100. MaybeEmitInheritedConstructorNote(S, Fn);
  8101. return;
  8102. }
  8103. }
  8104. // Emit the generic diagnostic and, optionally, add the hints to it.
  8105. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  8106. FDiag << (unsigned) FnKind << FnDesc
  8107. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8108. << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
  8109. << (unsigned) (Cand->Fix.Kind);
  8110. // If we can fix the conversion, suggest the FixIts.
  8111. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  8112. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  8113. FDiag << *HI;
  8114. S.Diag(FnDiagLocation, FDiag);
  8115. MaybeEmitInheritedConstructorNote(S, Fn);
  8116. }
  8117. /// Additional arity mismatch diagnosis specific to a function overload
  8118. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  8119. /// over a candidate in any candidate set.
  8120. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  8121. unsigned NumArgs) {
  8122. FunctionDecl *Fn = Cand->Function;
  8123. unsigned MinParams = Fn->getMinRequiredArguments();
  8124. // With invalid overloaded operators, it's possible that we think we
  8125. // have an arity mismatch when in fact it looks like we have the
  8126. // right number of arguments, because only overloaded operators have
  8127. // the weird behavior of overloading member and non-member functions.
  8128. // Just don't report anything.
  8129. if (Fn->isInvalidDecl() &&
  8130. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  8131. return true;
  8132. if (NumArgs < MinParams) {
  8133. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  8134. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8135. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  8136. } else {
  8137. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  8138. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8139. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  8140. }
  8141. return false;
  8142. }
  8143. /// General arity mismatch diagnosis over a candidate in a candidate set.
  8144. static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8145. assert(isa<FunctionDecl>(D) &&
  8146. "The templated declaration should at least be a function"
  8147. " when diagnosing bad template argument deduction due to too many"
  8148. " or too few arguments");
  8149. FunctionDecl *Fn = cast<FunctionDecl>(D);
  8150. // TODO: treat calls to a missing default constructor as a special case
  8151. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  8152. unsigned MinParams = Fn->getMinRequiredArguments();
  8153. // at least / at most / exactly
  8154. unsigned mode, modeCount;
  8155. if (NumFormalArgs < MinParams) {
  8156. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  8157. FnTy->isTemplateVariadic())
  8158. mode = 0; // "at least"
  8159. else
  8160. mode = 2; // "exactly"
  8161. modeCount = MinParams;
  8162. } else {
  8163. if (MinParams != FnTy->getNumParams())
  8164. mode = 1; // "at most"
  8165. else
  8166. mode = 2; // "exactly"
  8167. modeCount = FnTy->getNumParams();
  8168. }
  8169. std::string Description;
  8170. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
  8171. // HLSL Change Starts - fallback for built-ins
  8172. SourceLocation DiagLoc = Fn->getLocation();
  8173. if (DiagLoc.isInvalid()) DiagLoc = OpLoc;
  8174. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  8175. S.Diag(DiagLoc, diag::note_ovl_candidate_arity_one)
  8176. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8177. << mode << Fn->getParamDecl(0) << NumFormalArgs;
  8178. else
  8179. S.Diag(DiagLoc, diag::note_ovl_candidate_arity)
  8180. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8181. << mode << modeCount << NumFormalArgs;
  8182. // HLSL Change Ends
  8183. MaybeEmitInheritedConstructorNote(S, Fn);
  8184. }
  8185. /// Arity mismatch diagnosis specific to a function overload candidate.
  8186. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  8187. unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8188. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  8189. DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs, OpLoc);
  8190. }
  8191. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  8192. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
  8193. return FD->getDescribedFunctionTemplate();
  8194. else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
  8195. return RD->getDescribedClassTemplate();
  8196. llvm_unreachable("Unsupported: Getting the described template declaration"
  8197. " for bad deduction diagnosis");
  8198. }
  8199. /// Diagnose a failed template-argument deduction.
  8200. static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
  8201. DeductionFailureInfo &DeductionFailure,
  8202. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8203. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  8204. NamedDecl *ParamD;
  8205. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  8206. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  8207. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  8208. switch (DeductionFailure.Result) {
  8209. case Sema::TDK_Success:
  8210. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8211. case Sema::TDK_Incomplete: {
  8212. assert(ParamD && "no parameter found for incomplete deduction result");
  8213. S.Diag(Templated->getLocation(),
  8214. diag::note_ovl_candidate_incomplete_deduction)
  8215. << ParamD->getDeclName();
  8216. MaybeEmitInheritedConstructorNote(S, Templated);
  8217. return;
  8218. }
  8219. case Sema::TDK_Underqualified: {
  8220. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  8221. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  8222. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  8223. // Param will have been canonicalized, but it should just be a
  8224. // qualified version of ParamD, so move the qualifiers to that.
  8225. QualifierCollector Qs;
  8226. Qs.strip(Param);
  8227. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  8228. assert(S.Context.hasSameType(Param, NonCanonParam));
  8229. // Arg has also been canonicalized, but there's nothing we can do
  8230. // about that. It also doesn't matter as much, because it won't
  8231. // have any template parameters in it (because deduction isn't
  8232. // done on dependent types).
  8233. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  8234. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  8235. << ParamD->getDeclName() << Arg << NonCanonParam;
  8236. MaybeEmitInheritedConstructorNote(S, Templated);
  8237. return;
  8238. }
  8239. case Sema::TDK_Inconsistent: {
  8240. assert(ParamD && "no parameter found for inconsistent deduction result");
  8241. int which = 0;
  8242. if (isa<TemplateTypeParmDecl>(ParamD))
  8243. which = 0;
  8244. else if (isa<NonTypeTemplateParmDecl>(ParamD))
  8245. which = 1;
  8246. else {
  8247. which = 2;
  8248. }
  8249. S.Diag(Templated->getLocation(),
  8250. diag::note_ovl_candidate_inconsistent_deduction)
  8251. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  8252. << *DeductionFailure.getSecondArg();
  8253. MaybeEmitInheritedConstructorNote(S, Templated);
  8254. return;
  8255. }
  8256. case Sema::TDK_InvalidExplicitArguments:
  8257. assert(ParamD && "no parameter found for invalid explicit arguments");
  8258. if (ParamD->getDeclName())
  8259. S.Diag(Templated->getLocation(),
  8260. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  8261. << ParamD->getDeclName();
  8262. else {
  8263. int index = 0;
  8264. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  8265. index = TTP->getIndex();
  8266. else if (NonTypeTemplateParmDecl *NTTP
  8267. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  8268. index = NTTP->getIndex();
  8269. else
  8270. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  8271. S.Diag(Templated->getLocation(),
  8272. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  8273. << (index + 1);
  8274. }
  8275. MaybeEmitInheritedConstructorNote(S, Templated);
  8276. return;
  8277. case Sema::TDK_TooManyArguments:
  8278. case Sema::TDK_TooFewArguments:
  8279. DiagnoseArityMismatch(S, Templated, NumArgs, OpLoc);
  8280. return;
  8281. case Sema::TDK_InstantiationDepth:
  8282. S.Diag(Templated->getLocation(),
  8283. diag::note_ovl_candidate_instantiation_depth);
  8284. MaybeEmitInheritedConstructorNote(S, Templated);
  8285. return;
  8286. case Sema::TDK_SubstitutionFailure: {
  8287. // Format the template argument list into the argument string.
  8288. SmallString<128> TemplateArgString;
  8289. if (TemplateArgumentList *Args =
  8290. DeductionFailure.getTemplateArgumentList()) {
  8291. TemplateArgString = " ";
  8292. TemplateArgString += S.getTemplateArgumentBindingsText(
  8293. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  8294. }
  8295. // If this candidate was disabled by enable_if, say so.
  8296. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  8297. if (PDiag && PDiag->second.getDiagID() ==
  8298. diag::err_typename_nested_not_found_enable_if) {
  8299. // FIXME: Use the source range of the condition, and the fully-qualified
  8300. // name of the enable_if template. These are both present in PDiag.
  8301. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  8302. << "'enable_if'" << TemplateArgString;
  8303. return;
  8304. }
  8305. // Format the SFINAE diagnostic into the argument string.
  8306. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  8307. // formatted message in another diagnostic.
  8308. SmallString<128> SFINAEArgString;
  8309. SourceRange R;
  8310. if (PDiag) {
  8311. SFINAEArgString = ": ";
  8312. R = SourceRange(PDiag->first, PDiag->first);
  8313. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  8314. }
  8315. S.Diag(Templated->getLocation(),
  8316. diag::note_ovl_candidate_substitution_failure)
  8317. << TemplateArgString << SFINAEArgString << R;
  8318. MaybeEmitInheritedConstructorNote(S, Templated);
  8319. return;
  8320. }
  8321. case Sema::TDK_FailedOverloadResolution: {
  8322. OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
  8323. S.Diag(Templated->getLocation(),
  8324. diag::note_ovl_candidate_failed_overload_resolution)
  8325. << R.Expression->getName();
  8326. return;
  8327. }
  8328. case Sema::TDK_NonDeducedMismatch: {
  8329. // FIXME: Provide a source location to indicate what we couldn't match.
  8330. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  8331. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  8332. if (FirstTA.getKind() == TemplateArgument::Template &&
  8333. SecondTA.getKind() == TemplateArgument::Template) {
  8334. TemplateName FirstTN = FirstTA.getAsTemplate();
  8335. TemplateName SecondTN = SecondTA.getAsTemplate();
  8336. if (FirstTN.getKind() == TemplateName::Template &&
  8337. SecondTN.getKind() == TemplateName::Template) {
  8338. if (FirstTN.getAsTemplateDecl()->getName() ==
  8339. SecondTN.getAsTemplateDecl()->getName()) {
  8340. // FIXME: This fixes a bad diagnostic where both templates are named
  8341. // the same. This particular case is a bit difficult since:
  8342. // 1) It is passed as a string to the diagnostic printer.
  8343. // 2) The diagnostic printer only attempts to find a better
  8344. // name for types, not decls.
  8345. // Ideally, this should folded into the diagnostic printer.
  8346. S.Diag(Templated->getLocation(),
  8347. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  8348. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  8349. return;
  8350. }
  8351. }
  8352. }
  8353. // HLSL Change Starts
  8354. // The implementation for template argument deducation does not yet provide
  8355. // FirstArg and SecondArg information for failure cases; ellide the note in
  8356. // this case.
  8357. if (FirstTA.isNull() || SecondTA.isNull()) return;
  8358. // HLSL Change Ends
  8359. // FIXME: For generic lambda parameters, check if the function is a lambda
  8360. // call operator, and if so, emit a prettier and more informative
  8361. // diagnostic that mentions 'auto' and lambda in addition to
  8362. // (or instead of?) the canonical template type parameters.
  8363. S.Diag(Templated->getLocation(),
  8364. diag::note_ovl_candidate_non_deduced_mismatch)
  8365. << FirstTA << SecondTA;
  8366. return;
  8367. }
  8368. // TODO: diagnose these individually, then kill off
  8369. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  8370. case Sema::TDK_MiscellaneousDeductionFailure:
  8371. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  8372. MaybeEmitInheritedConstructorNote(S, Templated);
  8373. return;
  8374. }
  8375. }
  8376. /// Diagnose a failed template-argument deduction, for function calls.
  8377. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  8378. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8379. unsigned TDK = Cand->DeductionFailure.Result;
  8380. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  8381. if (CheckArityMismatch(S, Cand, NumArgs))
  8382. return;
  8383. }
  8384. DiagnoseBadDeduction(S, Cand->Function, // pattern
  8385. Cand->DeductionFailure, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8386. }
  8387. /// CUDA: diagnose an invalid call across targets.
  8388. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  8389. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  8390. FunctionDecl *Callee = Cand->Function;
  8391. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  8392. CalleeTarget = S.IdentifyCUDATarget(Callee);
  8393. std::string FnDesc;
  8394. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
  8395. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  8396. << (unsigned)FnKind << CalleeTarget << CallerTarget;
  8397. // This could be an implicit constructor for which we could not infer the
  8398. // target due to a collsion. Diagnose that case.
  8399. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  8400. if (Meth != nullptr && Meth->isImplicit()) {
  8401. CXXRecordDecl *ParentClass = Meth->getParent();
  8402. Sema::CXXSpecialMember CSM;
  8403. switch (FnKind) {
  8404. default:
  8405. return;
  8406. case oc_implicit_default_constructor:
  8407. CSM = Sema::CXXDefaultConstructor;
  8408. break;
  8409. case oc_implicit_copy_constructor:
  8410. CSM = Sema::CXXCopyConstructor;
  8411. break;
  8412. case oc_implicit_move_constructor:
  8413. CSM = Sema::CXXMoveConstructor;
  8414. break;
  8415. case oc_implicit_copy_assignment:
  8416. CSM = Sema::CXXCopyAssignment;
  8417. break;
  8418. case oc_implicit_move_assignment:
  8419. CSM = Sema::CXXMoveAssignment;
  8420. break;
  8421. };
  8422. bool ConstRHS = false;
  8423. if (Meth->getNumParams()) {
  8424. if (const ReferenceType *RT =
  8425. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  8426. ConstRHS = RT->getPointeeType().isConstQualified();
  8427. }
  8428. }
  8429. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  8430. /* ConstRHS */ ConstRHS,
  8431. /* Diagnose */ true);
  8432. }
  8433. }
  8434. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  8435. FunctionDecl *Callee = Cand->Function;
  8436. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  8437. S.Diag(Callee->getLocation(),
  8438. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  8439. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  8440. }
  8441. /// Generates a 'note' diagnostic for an overload candidate. We've
  8442. /// already generated a primary error at the call site.
  8443. ///
  8444. /// It really does need to be a single diagnostic with its caret
  8445. /// pointed at the candidate declaration. Yes, this creates some
  8446. /// major challenges of technical writing. Yes, this makes pointing
  8447. /// out problems with specific arguments quite awkward. It's still
  8448. /// better than generating twenty screens of text for every failed
  8449. /// overload.
  8450. ///
  8451. /// It would be great to be able to express per-candidate problems
  8452. /// more richly for those diagnostic clients that cared, but we'd
  8453. /// still have to be just as careful with the default diagnostics.
  8454. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  8455. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change: add OpLoc
  8456. FunctionDecl *Fn = Cand->Function;
  8457. // Note deleted candidates, but only if they're viable.
  8458. if (Cand->Viable && (Fn->isDeleted() ||
  8459. S.isFunctionConsideredUnavailable(Fn))) {
  8460. std::string FnDesc;
  8461. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  8462. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  8463. << FnKind << FnDesc
  8464. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  8465. MaybeEmitInheritedConstructorNote(S, Fn);
  8466. return;
  8467. }
  8468. // We don't really have anything else to say about viable candidates.
  8469. if (Cand->Viable) {
  8470. S.NoteOverloadCandidate(Fn);
  8471. return;
  8472. }
  8473. switch (Cand->FailureKind) {
  8474. case ovl_fail_too_many_arguments:
  8475. case ovl_fail_too_few_arguments:
  8476. return DiagnoseArityMismatch(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8477. case ovl_fail_bad_deduction:
  8478. return DiagnoseBadDeduction(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8479. case ovl_fail_illegal_constructor: {
  8480. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  8481. << (Fn->getPrimaryTemplate() ? 1 : 0);
  8482. MaybeEmitInheritedConstructorNote(S, Fn);
  8483. return;
  8484. }
  8485. case ovl_fail_trivial_conversion:
  8486. case ovl_fail_bad_final_conversion:
  8487. case ovl_fail_final_conversion_not_exact:
  8488. return S.NoteOverloadCandidate(Fn);
  8489. case ovl_fail_bad_conversion: {
  8490. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  8491. for (unsigned N = Cand->NumConversions; I != N; ++I)
  8492. if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8493. return DiagnoseBadConversion(S, Cand, I, Cand->Conversions[I], OpLoc); // HLSL Change: add OpLoc
  8494. if (Cand->OutConversions[I].isInitialized() && Cand->OutConversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8495. return DiagnoseBadConversion(S, Cand, I, Cand->OutConversions[I], OpLoc); // HLSL Change: add OpLoc
  8496. // FIXME: this currently happens when we're called from SemaInit
  8497. // when user-conversion overload fails. Figure out how to handle
  8498. // those conditions and diagnose them well.
  8499. return S.NoteOverloadCandidate(Fn);
  8500. }
  8501. case ovl_fail_bad_target:
  8502. return DiagnoseBadTarget(S, Cand);
  8503. case ovl_fail_enable_if:
  8504. return DiagnoseFailedEnableIfAttr(S, Cand);
  8505. }
  8506. }
  8507. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  8508. // Desugar the type of the surrogate down to a function type,
  8509. // retaining as many typedefs as possible while still showing
  8510. // the function type (and, therefore, its parameter types).
  8511. QualType FnType = Cand->Surrogate->getConversionType();
  8512. bool isLValueReference = false;
  8513. bool isRValueReference = false;
  8514. bool isPointer = false;
  8515. if (const LValueReferenceType *FnTypeRef =
  8516. FnType->getAs<LValueReferenceType>()) {
  8517. FnType = FnTypeRef->getPointeeType();
  8518. isLValueReference = true;
  8519. } else if (const RValueReferenceType *FnTypeRef =
  8520. FnType->getAs<RValueReferenceType>()) {
  8521. FnType = FnTypeRef->getPointeeType();
  8522. isRValueReference = true;
  8523. }
  8524. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  8525. FnType = FnTypePtr->getPointeeType();
  8526. isPointer = true;
  8527. }
  8528. // Desugar down to a function type.
  8529. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  8530. // Reconstruct the pointer/reference as appropriate.
  8531. if (isPointer) FnType = S.Context.getPointerType(FnType);
  8532. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  8533. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  8534. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  8535. << FnType;
  8536. MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
  8537. }
  8538. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  8539. SourceLocation OpLoc,
  8540. OverloadCandidate *Cand) {
  8541. assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
  8542. std::string TypeStr("operator");
  8543. TypeStr += Opc;
  8544. TypeStr += "(";
  8545. TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
  8546. if (Cand->NumConversions == 1) {
  8547. TypeStr += ")";
  8548. S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
  8549. } else {
  8550. TypeStr += ", ";
  8551. TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
  8552. TypeStr += ")";
  8553. S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
  8554. }
  8555. }
  8556. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  8557. OverloadCandidate *Cand) {
  8558. unsigned NoOperands = Cand->NumConversions;
  8559. for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
  8560. const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
  8561. if (ICS.isBad()) break; // all meaningless after first invalid
  8562. if (!ICS.isAmbiguous()) continue;
  8563. ICS.DiagnoseAmbiguousConversion(S, OpLoc,
  8564. S.PDiag(diag::note_ambiguous_type_conversion));
  8565. }
  8566. }
  8567. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  8568. if (Cand->Function)
  8569. return Cand->Function->getLocation();
  8570. if (Cand->IsSurrogate)
  8571. return Cand->Surrogate->getLocation();
  8572. return SourceLocation();
  8573. }
  8574. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  8575. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  8576. case Sema::TDK_Success:
  8577. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8578. case Sema::TDK_Invalid:
  8579. case Sema::TDK_Incomplete:
  8580. return 1;
  8581. case Sema::TDK_Underqualified:
  8582. case Sema::TDK_Inconsistent:
  8583. return 2;
  8584. case Sema::TDK_SubstitutionFailure:
  8585. case Sema::TDK_NonDeducedMismatch:
  8586. case Sema::TDK_MiscellaneousDeductionFailure:
  8587. return 3;
  8588. case Sema::TDK_InstantiationDepth:
  8589. case Sema::TDK_FailedOverloadResolution:
  8590. return 4;
  8591. case Sema::TDK_InvalidExplicitArguments:
  8592. return 5;
  8593. case Sema::TDK_TooManyArguments:
  8594. case Sema::TDK_TooFewArguments:
  8595. return 6;
  8596. }
  8597. llvm_unreachable("Unhandled deduction result");
  8598. }
  8599. namespace {
  8600. struct CompareOverloadCandidatesForDisplay {
  8601. Sema &S;
  8602. size_t NumArgs;
  8603. CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
  8604. : S(S), NumArgs(nArgs) {}
  8605. bool operator()(const OverloadCandidate *L,
  8606. const OverloadCandidate *R) {
  8607. // Fast-path this check.
  8608. if (L == R) return false;
  8609. // Order first by viability.
  8610. if (L->Viable) {
  8611. if (!R->Viable) return true;
  8612. // TODO: introduce a tri-valued comparison for overload
  8613. // candidates. Would be more worthwhile if we had a sort
  8614. // that could exploit it.
  8615. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
  8616. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
  8617. } else if (R->Viable)
  8618. return false;
  8619. assert(L->Viable == R->Viable);
  8620. // Criteria by which we can sort non-viable candidates:
  8621. if (!L->Viable) {
  8622. // 1. Arity mismatches come after other candidates.
  8623. if (L->FailureKind == ovl_fail_too_many_arguments ||
  8624. L->FailureKind == ovl_fail_too_few_arguments) {
  8625. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8626. R->FailureKind == ovl_fail_too_few_arguments) {
  8627. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  8628. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  8629. if (LDist == RDist) {
  8630. if (L->FailureKind == R->FailureKind)
  8631. // Sort non-surrogates before surrogates.
  8632. return !L->IsSurrogate && R->IsSurrogate;
  8633. // Sort candidates requiring fewer parameters than there were
  8634. // arguments given after candidates requiring more parameters
  8635. // than there were arguments given.
  8636. return L->FailureKind == ovl_fail_too_many_arguments;
  8637. }
  8638. return LDist < RDist;
  8639. }
  8640. return false;
  8641. }
  8642. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8643. R->FailureKind == ovl_fail_too_few_arguments)
  8644. return true;
  8645. // 2. Bad conversions come first and are ordered by the number
  8646. // of bad conversions and quality of good conversions.
  8647. if (L->FailureKind == ovl_fail_bad_conversion) {
  8648. if (R->FailureKind != ovl_fail_bad_conversion)
  8649. return true;
  8650. // The conversion that can be fixed with a smaller number of changes,
  8651. // comes first.
  8652. unsigned numLFixes = L->Fix.NumConversionsFixed;
  8653. unsigned numRFixes = R->Fix.NumConversionsFixed;
  8654. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  8655. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  8656. if (numLFixes != numRFixes) {
  8657. return numLFixes < numRFixes;
  8658. }
  8659. // If there's any ordering between the defined conversions...
  8660. // FIXME: this might not be transitive.
  8661. assert(L->NumConversions == R->NumConversions);
  8662. int leftBetter = 0;
  8663. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  8664. for (unsigned E = L->NumConversions; I != E; ++I) {
  8665. switch (CompareImplicitConversionSequences(S,
  8666. L->Conversions[I],
  8667. R->Conversions[I])) {
  8668. case ImplicitConversionSequence::Better:
  8669. leftBetter++;
  8670. break;
  8671. case ImplicitConversionSequence::Worse:
  8672. leftBetter--;
  8673. break;
  8674. case ImplicitConversionSequence::Indistinguishable:
  8675. break;
  8676. }
  8677. }
  8678. if (leftBetter > 0) return true;
  8679. if (leftBetter < 0) return false;
  8680. } else if (R->FailureKind == ovl_fail_bad_conversion)
  8681. return false;
  8682. if (L->FailureKind == ovl_fail_bad_deduction) {
  8683. if (R->FailureKind != ovl_fail_bad_deduction)
  8684. return true;
  8685. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8686. return RankDeductionFailure(L->DeductionFailure)
  8687. < RankDeductionFailure(R->DeductionFailure);
  8688. } else if (R->FailureKind == ovl_fail_bad_deduction)
  8689. return false;
  8690. // TODO: others?
  8691. }
  8692. // Sort everything else by location.
  8693. SourceLocation LLoc = GetLocationForCandidate(L);
  8694. SourceLocation RLoc = GetLocationForCandidate(R);
  8695. // Put candidates without locations (e.g. builtins) at the end.
  8696. if (LLoc.isInvalid()) return false;
  8697. if (RLoc.isInvalid()) return true;
  8698. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8699. }
  8700. };
  8701. }
  8702. /// CompleteNonViableCandidate - Normally, overload resolution only
  8703. /// computes up to the first. Produces the FixIt set if possible.
  8704. static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  8705. ArrayRef<Expr *> Args) {
  8706. assert(!Cand->Viable);
  8707. // Don't do anything on failures other than bad conversion.
  8708. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  8709. // We only want the FixIts if all the arguments can be corrected.
  8710. bool Unfixable = false;
  8711. // Use a implicit copy initialization to check conversion fixes.
  8712. Cand->Fix.setConversionChecker(TryCopyInitialization);
  8713. // Skip forward to the first bad conversion.
  8714. unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
  8715. unsigned ConvCount = Cand->NumConversions;
  8716. while (true) {
  8717. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  8718. ConvIdx++;
  8719. if (Cand->Conversions[ConvIdx - 1].isInitialized() && Cand->Conversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8720. Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
  8721. break;
  8722. }
  8723. // HLSL Change Starts - check out conversions
  8724. if (Cand->OutConversions[ConvIdx - 1].isInitialized() && Cand->OutConversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8725. // Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); - consider suggesting a fix
  8726. Unfixable = true;
  8727. break;
  8728. }
  8729. // HLSL Change End
  8730. }
  8731. if (ConvIdx == ConvCount)
  8732. return;
  8733. assert(!Cand->Conversions[ConvIdx].isInitialized() &&
  8734. "remaining conversion is initialized?");
  8735. // FIXME: this should probably be preserved from the overload
  8736. // operation somehow.
  8737. bool SuppressUserConversions = false;
  8738. const FunctionProtoType* Proto;
  8739. unsigned ArgIdx = ConvIdx;
  8740. if (Cand->IsSurrogate) {
  8741. QualType ConvType
  8742. = Cand->Surrogate->getConversionType().getNonReferenceType();
  8743. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  8744. ConvType = ConvPtrType->getPointeeType();
  8745. Proto = ConvType->getAs<FunctionProtoType>();
  8746. ArgIdx--;
  8747. } else if (Cand->Function) {
  8748. Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
  8749. if (isa<CXXMethodDecl>(Cand->Function) &&
  8750. !isa<CXXConstructorDecl>(Cand->Function))
  8751. ArgIdx--;
  8752. } else {
  8753. // Builtin binary operator with a bad first conversion.
  8754. assert(ConvCount <= 3);
  8755. for (; ConvIdx != ConvCount && ConvIdx < 3; ++ConvIdx) // HLSL Change: explicit about ConvIdx < 3
  8756. Cand->Conversions[ConvIdx]
  8757. = TryCopyInitialization(S, Args[ConvIdx],
  8758. Cand->BuiltinTypes.ParamTypes[ConvIdx],
  8759. SuppressUserConversions,
  8760. /*InOverloadResolution*/ true,
  8761. /*AllowObjCWritebackConversion=*/
  8762. S.getLangOpts().ObjCAutoRefCount);
  8763. return;
  8764. }
  8765. // Fill in the rest of the conversions.
  8766. unsigned NumParams = Proto->getNumParams();
  8767. for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
  8768. if (ArgIdx < NumParams) {
  8769. Cand->Conversions[ConvIdx] = TryCopyInitialization(
  8770. S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
  8771. /*InOverloadResolution=*/true,
  8772. /*AllowObjCWritebackConversion=*/
  8773. S.getLangOpts().ObjCAutoRefCount);
  8774. // Store the FixIt in the candidate if it exists.
  8775. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  8776. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  8777. }
  8778. else
  8779. Cand->Conversions[ConvIdx].setEllipsis();
  8780. }
  8781. }
  8782. /// PrintOverloadCandidates - When overload resolution fails, prints
  8783. /// diagnostic messages containing the candidates in the candidate
  8784. /// set.
  8785. void OverloadCandidateSet::NoteCandidates(Sema &S,
  8786. OverloadCandidateDisplayKind OCD,
  8787. ArrayRef<Expr *> Args,
  8788. StringRef Opc,
  8789. SourceLocation OpLoc) {
  8790. // Sort the candidates by viability and position. Sorting directly would
  8791. // be prohibitive, so we make a set of pointers and sort those.
  8792. SmallVector<OverloadCandidate*, 32> Cands;
  8793. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  8794. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8795. if (Cand->Viable)
  8796. Cands.push_back(Cand);
  8797. else if (OCD == OCD_AllCandidates) {
  8798. CompleteNonViableCandidate(S, Cand, Args);
  8799. if (Cand->Function || Cand->IsSurrogate)
  8800. Cands.push_back(Cand);
  8801. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  8802. // want to list every possible builtin candidate.
  8803. }
  8804. }
  8805. std::sort(Cands.begin(), Cands.end(),
  8806. CompareOverloadCandidatesForDisplay(S, Args.size()));
  8807. bool ReportedAmbiguousConversions = false;
  8808. SmallVectorImpl<OverloadCandidate*>::iterator I, E;
  8809. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8810. unsigned CandsShown = 0;
  8811. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8812. OverloadCandidate *Cand = *I;
  8813. // Set an arbitrary limit on the number of candidate functions we'll spam
  8814. // the user with. FIXME: This limit should depend on details of the
  8815. // candidate list.
  8816. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  8817. break;
  8818. }
  8819. ++CandsShown;
  8820. if (Cand->Function)
  8821. NoteFunctionCandidate(S, Cand, Args.size(), OpLoc); // HLSL Change: add OpLoc
  8822. else if (Cand->IsSurrogate)
  8823. NoteSurrogateCandidate(S, Cand);
  8824. else {
  8825. assert(Cand->Viable &&
  8826. "Non-viable built-in candidates are not added to Cands.");
  8827. // Generally we only see ambiguities including viable builtin
  8828. // operators if overload resolution got screwed up by an
  8829. // ambiguous user-defined conversion.
  8830. //
  8831. // FIXME: It's quite possible for different conversions to see
  8832. // different ambiguities, though.
  8833. if (!ReportedAmbiguousConversions) {
  8834. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  8835. ReportedAmbiguousConversions = true;
  8836. }
  8837. // If this is a viable builtin, print it.
  8838. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  8839. }
  8840. }
  8841. if (I != E)
  8842. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  8843. }
  8844. static SourceLocation
  8845. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  8846. return Cand->Specialization ? Cand->Specialization->getLocation()
  8847. : SourceLocation();
  8848. }
  8849. namespace {
  8850. struct CompareTemplateSpecCandidatesForDisplay {
  8851. Sema &S;
  8852. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  8853. bool operator()(const TemplateSpecCandidate *L,
  8854. const TemplateSpecCandidate *R) {
  8855. // Fast-path this check.
  8856. if (L == R)
  8857. return false;
  8858. // Assuming that both candidates are not matches...
  8859. // Sort by the ranking of deduction failures.
  8860. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8861. return RankDeductionFailure(L->DeductionFailure) <
  8862. RankDeductionFailure(R->DeductionFailure);
  8863. // Sort everything else by location.
  8864. SourceLocation LLoc = GetLocationForCandidate(L);
  8865. SourceLocation RLoc = GetLocationForCandidate(R);
  8866. // Put candidates without locations (e.g. builtins) at the end.
  8867. if (LLoc.isInvalid())
  8868. return false;
  8869. if (RLoc.isInvalid())
  8870. return true;
  8871. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8872. }
  8873. };
  8874. }
  8875. /// Diagnose a template argument deduction failure.
  8876. /// We are treating these failures as overload failures due to bad
  8877. /// deductions.
  8878. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
  8879. DiagnoseBadDeduction(S, Specialization, // pattern
  8880. DeductionFailure, /*NumArgs=*/0, SourceLocation()); // HLSL Change - add OpLoc
  8881. }
  8882. void TemplateSpecCandidateSet::destroyCandidates() {
  8883. for (iterator i = begin(), e = end(); i != e; ++i) {
  8884. i->DeductionFailure.Destroy();
  8885. }
  8886. }
  8887. void TemplateSpecCandidateSet::clear() {
  8888. destroyCandidates();
  8889. Candidates.clear();
  8890. }
  8891. /// NoteCandidates - When no template specialization match is found, prints
  8892. /// diagnostic messages containing the non-matching specializations that form
  8893. /// the candidate set.
  8894. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  8895. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  8896. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  8897. // Sort the candidates by position (assuming no candidate is a match).
  8898. // Sorting directly would be prohibitive, so we make a set of pointers
  8899. // and sort those.
  8900. SmallVector<TemplateSpecCandidate *, 32> Cands;
  8901. Cands.reserve(size());
  8902. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8903. if (Cand->Specialization)
  8904. Cands.push_back(Cand);
  8905. // Otherwise, this is a non-matching builtin candidate. We do not,
  8906. // in general, want to list every possible builtin candidate.
  8907. }
  8908. std::sort(Cands.begin(), Cands.end(),
  8909. CompareTemplateSpecCandidatesForDisplay(S));
  8910. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  8911. // for generalization purposes (?).
  8912. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8913. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  8914. unsigned CandsShown = 0;
  8915. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8916. TemplateSpecCandidate *Cand = *I;
  8917. // Set an arbitrary limit on the number of candidates we'll spam
  8918. // the user with. FIXME: This limit should depend on details of the
  8919. // candidate list.
  8920. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8921. break;
  8922. ++CandsShown;
  8923. assert(Cand->Specialization &&
  8924. "Non-matching built-in candidates are not added to Cands.");
  8925. Cand->NoteDeductionFailure(S);
  8926. }
  8927. if (I != E)
  8928. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  8929. }
  8930. // [PossiblyAFunctionType] --> [Return]
  8931. // NonFunctionType --> NonFunctionType
  8932. // R (A) --> R(A)
  8933. // R (*)(A) --> R (A)
  8934. // R (&)(A) --> R (A)
  8935. // R (S::*)(A) --> R (A)
  8936. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  8937. QualType Ret = PossiblyAFunctionType;
  8938. if (const PointerType *ToTypePtr =
  8939. PossiblyAFunctionType->getAs<PointerType>())
  8940. Ret = ToTypePtr->getPointeeType();
  8941. else if (const ReferenceType *ToTypeRef =
  8942. PossiblyAFunctionType->getAs<ReferenceType>())
  8943. Ret = ToTypeRef->getPointeeType();
  8944. else if (const MemberPointerType *MemTypePtr =
  8945. PossiblyAFunctionType->getAs<MemberPointerType>())
  8946. Ret = MemTypePtr->getPointeeType();
  8947. Ret =
  8948. Context.getCanonicalType(Ret).getUnqualifiedType();
  8949. return Ret;
  8950. }
  8951. namespace {
  8952. // A helper class to help with address of function resolution
  8953. // - allows us to avoid passing around all those ugly parameters
  8954. class AddressOfFunctionResolver {
  8955. Sema& S;
  8956. Expr* SourceExpr;
  8957. const QualType& TargetType;
  8958. QualType TargetFunctionType; // Extracted function type from target type
  8959. bool Complain;
  8960. //DeclAccessPair& ResultFunctionAccessPair;
  8961. ASTContext& Context;
  8962. bool TargetTypeIsNonStaticMemberFunction;
  8963. bool FoundNonTemplateFunction;
  8964. bool StaticMemberFunctionFromBoundPointer;
  8965. OverloadExpr::FindResult OvlExprInfo;
  8966. OverloadExpr *OvlExpr;
  8967. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  8968. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  8969. TemplateSpecCandidateSet FailedCandidates;
  8970. public:
  8971. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  8972. const QualType &TargetType, bool Complain)
  8973. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  8974. Complain(Complain), Context(S.getASTContext()),
  8975. TargetTypeIsNonStaticMemberFunction(
  8976. !!TargetType->getAs<MemberPointerType>()),
  8977. FoundNonTemplateFunction(false),
  8978. StaticMemberFunctionFromBoundPointer(false),
  8979. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  8980. OvlExpr(OvlExprInfo.Expression),
  8981. FailedCandidates(OvlExpr->getNameLoc()) {
  8982. ExtractUnqualifiedFunctionTypeFromTargetType();
  8983. if (TargetFunctionType->isFunctionType()) {
  8984. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  8985. if (!UME->isImplicitAccess() &&
  8986. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  8987. StaticMemberFunctionFromBoundPointer = true;
  8988. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  8989. DeclAccessPair dap;
  8990. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  8991. OvlExpr, false, &dap)) {
  8992. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  8993. if (!Method->isStatic()) {
  8994. // If the target type is a non-function type and the function found
  8995. // is a non-static member function, pretend as if that was the
  8996. // target, it's the only possible type to end up with.
  8997. TargetTypeIsNonStaticMemberFunction = true;
  8998. // And skip adding the function if its not in the proper form.
  8999. // We'll diagnose this due to an empty set of functions.
  9000. if (!OvlExprInfo.HasFormOfMemberPointer)
  9001. return;
  9002. }
  9003. Matches.push_back(std::make_pair(dap, Fn));
  9004. }
  9005. return;
  9006. }
  9007. if (OvlExpr->hasExplicitTemplateArgs())
  9008. OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
  9009. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  9010. // C++ [over.over]p4:
  9011. // If more than one function is selected, [...]
  9012. if (Matches.size() > 1) {
  9013. if (FoundNonTemplateFunction)
  9014. EliminateAllTemplateMatches();
  9015. else
  9016. EliminateAllExceptMostSpecializedTemplate();
  9017. }
  9018. }
  9019. }
  9020. private:
  9021. bool isTargetTypeAFunction() const {
  9022. return TargetFunctionType->isFunctionType();
  9023. }
  9024. // [ToType] [Return]
  9025. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  9026. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  9027. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  9028. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  9029. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  9030. }
  9031. // return true if any matching specializations were found
  9032. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  9033. const DeclAccessPair& CurAccessFunPair) {
  9034. if (CXXMethodDecl *Method
  9035. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  9036. // Skip non-static function templates when converting to pointer, and
  9037. // static when converting to member pointer.
  9038. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9039. return false;
  9040. }
  9041. else if (TargetTypeIsNonStaticMemberFunction)
  9042. return false;
  9043. // C++ [over.over]p2:
  9044. // If the name is a function template, template argument deduction is
  9045. // done (14.8.2.2), and if the argument deduction succeeds, the
  9046. // resulting template argument list is used to generate a single
  9047. // function template specialization, which is added to the set of
  9048. // overloaded functions considered.
  9049. FunctionDecl *Specialization = nullptr;
  9050. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9051. if (Sema::TemplateDeductionResult Result
  9052. = S.DeduceTemplateArguments(FunctionTemplate,
  9053. &OvlExplicitTemplateArgs,
  9054. TargetFunctionType, Specialization,
  9055. Info, /*InOverloadResolution=*/true)) {
  9056. // Make a note of the failed deduction for diagnostics.
  9057. FailedCandidates.addCandidate()
  9058. .set(FunctionTemplate->getTemplatedDecl(),
  9059. MakeDeductionFailureInfo(Context, Result, Info));
  9060. return false;
  9061. }
  9062. // Template argument deduction ensures that we have an exact match or
  9063. // compatible pointer-to-function arguments that would be adjusted by ICS.
  9064. // This function template specicalization works.
  9065. Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
  9066. assert(S.isSameOrCompatibleFunctionType(
  9067. Context.getCanonicalType(Specialization->getType()),
  9068. Context.getCanonicalType(TargetFunctionType)));
  9069. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  9070. return true;
  9071. }
  9072. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  9073. const DeclAccessPair& CurAccessFunPair) {
  9074. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  9075. // Skip non-static functions when converting to pointer, and static
  9076. // when converting to member pointer.
  9077. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9078. return false;
  9079. }
  9080. else if (TargetTypeIsNonStaticMemberFunction)
  9081. return false;
  9082. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  9083. if (S.getLangOpts().CUDA)
  9084. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  9085. if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
  9086. return false;
  9087. // If any candidate has a placeholder return type, trigger its deduction
  9088. // now.
  9089. if (S.getLangOpts().CPlusPlus14 &&
  9090. FunDecl->getReturnType()->isUndeducedType() &&
  9091. S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
  9092. return false;
  9093. QualType ResultTy;
  9094. if (Context.hasSameUnqualifiedType(TargetFunctionType,
  9095. FunDecl->getType()) ||
  9096. S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
  9097. ResultTy)) {
  9098. Matches.push_back(std::make_pair(CurAccessFunPair,
  9099. cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  9100. FoundNonTemplateFunction = true;
  9101. return true;
  9102. }
  9103. }
  9104. return false;
  9105. }
  9106. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  9107. bool Ret = false;
  9108. // If the overload expression doesn't have the form of a pointer to
  9109. // member, don't try to convert it to a pointer-to-member type.
  9110. if (IsInvalidFormOfPointerToMemberFunction())
  9111. return false;
  9112. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9113. E = OvlExpr->decls_end();
  9114. I != E; ++I) {
  9115. // Look through any using declarations to find the underlying function.
  9116. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  9117. // C++ [over.over]p3:
  9118. // Non-member functions and static member functions match
  9119. // targets of type "pointer-to-function" or "reference-to-function."
  9120. // Nonstatic member functions match targets of
  9121. // type "pointer-to-member-function."
  9122. // Note that according to DR 247, the containing class does not matter.
  9123. if (FunctionTemplateDecl *FunctionTemplate
  9124. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  9125. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  9126. Ret = true;
  9127. }
  9128. // If we have explicit template arguments supplied, skip non-templates.
  9129. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  9130. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  9131. Ret = true;
  9132. }
  9133. assert(Ret || Matches.empty());
  9134. return Ret;
  9135. }
  9136. void EliminateAllExceptMostSpecializedTemplate() {
  9137. // [...] and any given function template specialization F1 is
  9138. // eliminated if the set contains a second function template
  9139. // specialization whose function template is more specialized
  9140. // than the function template of F1 according to the partial
  9141. // ordering rules of 14.5.5.2.
  9142. // The algorithm specified above is quadratic. We instead use a
  9143. // two-pass algorithm (similar to the one used to identify the
  9144. // best viable function in an overload set) that identifies the
  9145. // best function template (if it exists).
  9146. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  9147. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  9148. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  9149. // TODO: It looks like FailedCandidates does not serve much purpose
  9150. // here, since the no_viable diagnostic has index 0.
  9151. UnresolvedSetIterator Result = S.getMostSpecialized(
  9152. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  9153. SourceExpr->getLocStart(), S.PDiag(),
  9154. S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
  9155. .second->getDeclName(),
  9156. S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
  9157. Complain, TargetFunctionType);
  9158. if (Result != MatchesCopy.end()) {
  9159. // Make it the first and only element
  9160. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  9161. Matches[0].second = cast<FunctionDecl>(*Result);
  9162. Matches.resize(1);
  9163. }
  9164. }
  9165. void EliminateAllTemplateMatches() {
  9166. // [...] any function template specializations in the set are
  9167. // eliminated if the set also contains a non-template function, [...]
  9168. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  9169. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  9170. ++I;
  9171. else {
  9172. Matches[I] = Matches[--N];
  9173. Matches.set_size(N);
  9174. }
  9175. }
  9176. }
  9177. public:
  9178. void ComplainNoMatchesFound() const {
  9179. assert(Matches.empty());
  9180. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
  9181. << OvlExpr->getName() << TargetFunctionType
  9182. << OvlExpr->getSourceRange();
  9183. if (FailedCandidates.empty())
  9184. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9185. else {
  9186. // We have some deduction failure messages. Use them to diagnose
  9187. // the function templates, and diagnose the non-template candidates
  9188. // normally.
  9189. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9190. IEnd = OvlExpr->decls_end();
  9191. I != IEnd; ++I)
  9192. if (FunctionDecl *Fun =
  9193. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  9194. S.NoteOverloadCandidate(Fun, TargetFunctionType);
  9195. FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
  9196. }
  9197. }
  9198. bool IsInvalidFormOfPointerToMemberFunction() const {
  9199. return TargetTypeIsNonStaticMemberFunction &&
  9200. !OvlExprInfo.HasFormOfMemberPointer;
  9201. }
  9202. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  9203. // TODO: Should we condition this on whether any functions might
  9204. // have matched, or is it more appropriate to do that in callers?
  9205. // TODO: a fixit wouldn't hurt.
  9206. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  9207. << TargetType << OvlExpr->getSourceRange();
  9208. }
  9209. bool IsStaticMemberFunctionFromBoundPointer() const {
  9210. return StaticMemberFunctionFromBoundPointer;
  9211. }
  9212. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  9213. S.Diag(OvlExpr->getLocStart(),
  9214. diag::err_invalid_form_pointer_member_function)
  9215. << OvlExpr->getSourceRange();
  9216. }
  9217. void ComplainOfInvalidConversion() const {
  9218. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
  9219. << OvlExpr->getName() << TargetType;
  9220. }
  9221. void ComplainMultipleMatchesFound() const {
  9222. assert(Matches.size() > 1);
  9223. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
  9224. << OvlExpr->getName()
  9225. << OvlExpr->getSourceRange();
  9226. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9227. }
  9228. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  9229. int getNumMatches() const { return Matches.size(); }
  9230. FunctionDecl* getMatchingFunctionDecl() const {
  9231. if (Matches.size() != 1) return nullptr;
  9232. return Matches[0].second;
  9233. }
  9234. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  9235. if (Matches.size() != 1) return nullptr;
  9236. return &Matches[0].first;
  9237. }
  9238. };
  9239. }
  9240. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  9241. /// an overloaded function (C++ [over.over]), where @p From is an
  9242. /// expression with overloaded function type and @p ToType is the type
  9243. /// we're trying to resolve to. For example:
  9244. ///
  9245. /// @code
  9246. /// int f(double);
  9247. /// int f(int);
  9248. ///
  9249. /// int (*pfd)(double) = f; // selects f(double)
  9250. /// @endcode
  9251. ///
  9252. /// This routine returns the resulting FunctionDecl if it could be
  9253. /// resolved, and NULL otherwise. When @p Complain is true, this
  9254. /// routine will emit diagnostics if there is an error.
  9255. FunctionDecl *
  9256. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  9257. QualType TargetType,
  9258. bool Complain,
  9259. DeclAccessPair &FoundResult,
  9260. bool *pHadMultipleCandidates) {
  9261. assert(AddressOfExpr->getType() == Context.OverloadTy);
  9262. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  9263. Complain);
  9264. int NumMatches = Resolver.getNumMatches();
  9265. FunctionDecl *Fn = nullptr;
  9266. if (NumMatches == 0 && Complain) {
  9267. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  9268. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  9269. else
  9270. Resolver.ComplainNoMatchesFound();
  9271. }
  9272. else if (NumMatches > 1 && Complain)
  9273. Resolver.ComplainMultipleMatchesFound();
  9274. else if (NumMatches == 1) {
  9275. Fn = Resolver.getMatchingFunctionDecl();
  9276. assert(Fn);
  9277. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  9278. if (Complain) {
  9279. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  9280. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  9281. else
  9282. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  9283. }
  9284. }
  9285. if (pHadMultipleCandidates)
  9286. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  9287. return Fn;
  9288. }
  9289. /// \brief Given an expression that refers to an overloaded function, try to
  9290. /// resolve that overloaded function expression down to a single function.
  9291. ///
  9292. /// This routine can only resolve template-ids that refer to a single function
  9293. /// template, where that template-id refers to a single template whose template
  9294. /// arguments are either provided by the template-id or have defaults,
  9295. /// as described in C++0x [temp.arg.explicit]p3.
  9296. ///
  9297. /// If no template-ids are found, no diagnostics are emitted and NULL is
  9298. /// returned.
  9299. FunctionDecl *
  9300. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  9301. bool Complain,
  9302. DeclAccessPair *FoundResult) {
  9303. // C++ [over.over]p1:
  9304. // [...] [Note: any redundant set of parentheses surrounding the
  9305. // overloaded function name is ignored (5.1). ]
  9306. // C++ [over.over]p1:
  9307. // [...] The overloaded function name can be preceded by the &
  9308. // operator.
  9309. // If we didn't actually find any template-ids, we're done.
  9310. if (!ovl->hasExplicitTemplateArgs())
  9311. return nullptr;
  9312. TemplateArgumentListInfo ExplicitTemplateArgs;
  9313. ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
  9314. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  9315. // Look through all of the overloaded functions, searching for one
  9316. // whose type matches exactly.
  9317. FunctionDecl *Matched = nullptr;
  9318. for (UnresolvedSetIterator I = ovl->decls_begin(),
  9319. E = ovl->decls_end(); I != E; ++I) {
  9320. // C++0x [temp.arg.explicit]p3:
  9321. // [...] In contexts where deduction is done and fails, or in contexts
  9322. // where deduction is not done, if a template argument list is
  9323. // specified and it, along with any default template arguments,
  9324. // identifies a single function template specialization, then the
  9325. // template-id is an lvalue for the function template specialization.
  9326. FunctionTemplateDecl *FunctionTemplate
  9327. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  9328. // C++ [over.over]p2:
  9329. // If the name is a function template, template argument deduction is
  9330. // done (14.8.2.2), and if the argument deduction succeeds, the
  9331. // resulting template argument list is used to generate a single
  9332. // function template specialization, which is added to the set of
  9333. // overloaded functions considered.
  9334. FunctionDecl *Specialization = nullptr;
  9335. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9336. if (TemplateDeductionResult Result
  9337. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  9338. Specialization, Info,
  9339. /*InOverloadResolution=*/true)) {
  9340. // Make a note of the failed deduction for diagnostics.
  9341. // TODO: Actually use the failed-deduction info?
  9342. FailedCandidates.addCandidate()
  9343. .set(FunctionTemplate->getTemplatedDecl(),
  9344. MakeDeductionFailureInfo(Context, Result, Info));
  9345. continue;
  9346. }
  9347. assert(Specialization && "no specialization and no error?");
  9348. // Multiple matches; we can't resolve to a single declaration.
  9349. if (Matched) {
  9350. if (Complain) {
  9351. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  9352. << ovl->getName();
  9353. NoteAllOverloadCandidates(ovl);
  9354. }
  9355. return nullptr;
  9356. }
  9357. Matched = Specialization;
  9358. if (FoundResult) *FoundResult = I.getPair();
  9359. }
  9360. if (Matched && getLangOpts().CPlusPlus14 &&
  9361. Matched->getReturnType()->isUndeducedType() &&
  9362. DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
  9363. return nullptr;
  9364. return Matched;
  9365. }
  9366. // Resolve and fix an overloaded expression that can be resolved
  9367. // because it identifies a single function template specialization.
  9368. //
  9369. // Last three arguments should only be supplied if Complain = true
  9370. //
  9371. // Return true if it was logically possible to so resolve the
  9372. // expression, regardless of whether or not it succeeded. Always
  9373. // returns true if 'complain' is set.
  9374. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  9375. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  9376. bool complain, const SourceRange& OpRangeForComplaining,
  9377. QualType DestTypeForComplaining,
  9378. unsigned DiagIDForComplaining) {
  9379. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  9380. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  9381. DeclAccessPair found;
  9382. ExprResult SingleFunctionExpression;
  9383. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  9384. ovl.Expression, /*complain*/ false, &found)) {
  9385. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
  9386. SrcExpr = ExprError();
  9387. return true;
  9388. }
  9389. // It is only correct to resolve to an instance method if we're
  9390. // resolving a form that's permitted to be a pointer to member.
  9391. // Otherwise we'll end up making a bound member expression, which
  9392. // is illegal in all the contexts we resolve like this.
  9393. if (!ovl.HasFormOfMemberPointer &&
  9394. isa<CXXMethodDecl>(fn) &&
  9395. cast<CXXMethodDecl>(fn)->isInstance()) {
  9396. if (!complain) return false;
  9397. Diag(ovl.Expression->getExprLoc(),
  9398. diag::err_bound_member_function)
  9399. << 0 << ovl.Expression->getSourceRange();
  9400. // TODO: I believe we only end up here if there's a mix of
  9401. // static and non-static candidates (otherwise the expression
  9402. // would have 'bound member' type, not 'overload' type).
  9403. // Ideally we would note which candidate was chosen and why
  9404. // the static candidates were rejected.
  9405. SrcExpr = ExprError();
  9406. return true;
  9407. }
  9408. // Fix the expression to refer to 'fn'.
  9409. SingleFunctionExpression =
  9410. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  9411. // If desired, do function-to-pointer decay.
  9412. if (doFunctionPointerConverion) {
  9413. SingleFunctionExpression =
  9414. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  9415. if (SingleFunctionExpression.isInvalid()) {
  9416. SrcExpr = ExprError();
  9417. return true;
  9418. }
  9419. }
  9420. }
  9421. if (!SingleFunctionExpression.isUsable()) {
  9422. if (complain) {
  9423. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  9424. << ovl.Expression->getName()
  9425. << DestTypeForComplaining
  9426. << OpRangeForComplaining
  9427. << ovl.Expression->getQualifierLoc().getSourceRange();
  9428. NoteAllOverloadCandidates(SrcExpr.get());
  9429. SrcExpr = ExprError();
  9430. return true;
  9431. }
  9432. return false;
  9433. }
  9434. SrcExpr = SingleFunctionExpression;
  9435. return true;
  9436. }
  9437. /// \brief Add a single candidate to the overload set.
  9438. static void AddOverloadedCallCandidate(Sema &S,
  9439. DeclAccessPair FoundDecl,
  9440. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9441. ArrayRef<Expr *> Args,
  9442. OverloadCandidateSet &CandidateSet,
  9443. bool PartialOverloading,
  9444. bool KnownValid) {
  9445. NamedDecl *Callee = FoundDecl.getDecl();
  9446. if (isa<UsingShadowDecl>(Callee))
  9447. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  9448. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  9449. if (ExplicitTemplateArgs) {
  9450. assert(!KnownValid && "Explicit template arguments?");
  9451. return;
  9452. }
  9453. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  9454. /*SuppressUsedConversions=*/false,
  9455. PartialOverloading);
  9456. return;
  9457. }
  9458. if (FunctionTemplateDecl *FuncTemplate
  9459. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  9460. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  9461. ExplicitTemplateArgs, Args, CandidateSet,
  9462. /*SuppressUsedConversions=*/false,
  9463. PartialOverloading);
  9464. return;
  9465. }
  9466. assert(!KnownValid && "unhandled case in overloaded call candidate");
  9467. }
  9468. /// \brief Add the overload candidates named by callee and/or found by argument
  9469. /// dependent lookup to the given overload set.
  9470. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  9471. ArrayRef<Expr *> Args,
  9472. OverloadCandidateSet &CandidateSet,
  9473. bool PartialOverloading) {
  9474. #ifndef NDEBUG
  9475. // Verify that ArgumentDependentLookup is consistent with the rules
  9476. // in C++0x [basic.lookup.argdep]p3:
  9477. //
  9478. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9479. // and let Y be the lookup set produced by argument dependent
  9480. // lookup (defined as follows). If X contains
  9481. //
  9482. // -- a declaration of a class member, or
  9483. //
  9484. // -- a block-scope function declaration that is not a
  9485. // using-declaration, or
  9486. //
  9487. // -- a declaration that is neither a function or a function
  9488. // template
  9489. //
  9490. // then Y is empty.
  9491. if (ULE->requiresADL()) {
  9492. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9493. E = ULE->decls_end(); I != E; ++I) {
  9494. assert(!(*I)->getDeclContext()->isRecord());
  9495. assert(isa<UsingShadowDecl>(*I) ||
  9496. !(*I)->getDeclContext()->isFunctionOrMethod());
  9497. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  9498. }
  9499. }
  9500. #endif
  9501. // HLSL Change - allow ExternalSource the ability to add the overloads for a call.
  9502. if (ExternalSource &&
  9503. ExternalSource->AddOverloadedCallCandidates(ULE, Args, CandidateSet, PartialOverloading)) {
  9504. return;
  9505. }
  9506. // It would be nice to avoid this copy.
  9507. TemplateArgumentListInfo TABuffer;
  9508. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9509. if (ULE->hasExplicitTemplateArgs()) {
  9510. ULE->copyTemplateArgumentsInto(TABuffer);
  9511. ExplicitTemplateArgs = &TABuffer;
  9512. }
  9513. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9514. E = ULE->decls_end(); I != E; ++I)
  9515. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  9516. CandidateSet, PartialOverloading,
  9517. /*KnownValid*/ true);
  9518. if (ULE->requiresADL())
  9519. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  9520. Args, ExplicitTemplateArgs,
  9521. CandidateSet, PartialOverloading);
  9522. }
  9523. /// Determine whether a declaration with the specified name could be moved into
  9524. /// a different namespace.
  9525. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  9526. switch (Name.getCXXOverloadedOperator()) {
  9527. case OO_New: case OO_Array_New:
  9528. case OO_Delete: case OO_Array_Delete:
  9529. return false;
  9530. default:
  9531. return true;
  9532. }
  9533. }
  9534. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  9535. /// template, where the non-dependent name was declared after the template
  9536. /// was defined. This is common in code written for a compilers which do not
  9537. /// correctly implement two-stage name lookup.
  9538. ///
  9539. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9540. static bool
  9541. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  9542. const CXXScopeSpec &SS, LookupResult &R,
  9543. OverloadCandidateSet::CandidateSetKind CSK,
  9544. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9545. ArrayRef<Expr *> Args,
  9546. bool *DoDiagnoseEmptyLookup = nullptr) {
  9547. if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
  9548. return false;
  9549. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  9550. if (DC->isTransparentContext())
  9551. continue;
  9552. SemaRef.LookupQualifiedName(R, DC);
  9553. if (!R.empty()) {
  9554. R.suppressDiagnostics();
  9555. if (isa<CXXRecordDecl>(DC)) {
  9556. // Don't diagnose names we find in classes; we get much better
  9557. // diagnostics for these from DiagnoseEmptyLookup.
  9558. R.clear();
  9559. if (DoDiagnoseEmptyLookup)
  9560. *DoDiagnoseEmptyLookup = true;
  9561. return false;
  9562. }
  9563. OverloadCandidateSet Candidates(FnLoc, CSK);
  9564. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  9565. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  9566. ExplicitTemplateArgs, Args,
  9567. Candidates, false, /*KnownValid*/ false);
  9568. OverloadCandidateSet::iterator Best;
  9569. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  9570. // No viable functions. Don't bother the user with notes for functions
  9571. // which don't work and shouldn't be found anyway.
  9572. R.clear();
  9573. return false;
  9574. }
  9575. // Find the namespaces where ADL would have looked, and suggest
  9576. // declaring the function there instead.
  9577. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9578. Sema::AssociatedClassSet AssociatedClasses;
  9579. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  9580. AssociatedNamespaces,
  9581. AssociatedClasses);
  9582. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  9583. if (canBeDeclaredInNamespace(R.getLookupName())) {
  9584. DeclContext *Std = SemaRef.getStdNamespace();
  9585. for (Sema::AssociatedNamespaceSet::iterator
  9586. it = AssociatedNamespaces.begin(),
  9587. end = AssociatedNamespaces.end(); it != end; ++it) {
  9588. // Never suggest declaring a function within namespace 'std'.
  9589. if (Std && Std->Encloses(*it))
  9590. continue;
  9591. // Never suggest declaring a function within a namespace with a
  9592. // reserved name, like __gnu_cxx.
  9593. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  9594. if (NS &&
  9595. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  9596. continue;
  9597. SuggestedNamespaces.insert(*it);
  9598. }
  9599. }
  9600. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  9601. << R.getLookupName();
  9602. if (SuggestedNamespaces.empty()) {
  9603. SemaRef.Diag(Best->Function->getLocation(),
  9604. diag::note_not_found_by_two_phase_lookup)
  9605. << R.getLookupName() << 0;
  9606. } else if (SuggestedNamespaces.size() == 1) {
  9607. SemaRef.Diag(Best->Function->getLocation(),
  9608. diag::note_not_found_by_two_phase_lookup)
  9609. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  9610. } else {
  9611. // FIXME: It would be useful to list the associated namespaces here,
  9612. // but the diagnostics infrastructure doesn't provide a way to produce
  9613. // a localized representation of a list of items.
  9614. SemaRef.Diag(Best->Function->getLocation(),
  9615. diag::note_not_found_by_two_phase_lookup)
  9616. << R.getLookupName() << 2;
  9617. }
  9618. // Try to recover by calling this function.
  9619. return true;
  9620. }
  9621. R.clear();
  9622. }
  9623. return false;
  9624. }
  9625. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  9626. /// template, where the non-dependent operator was declared after the template
  9627. /// was defined.
  9628. ///
  9629. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9630. static bool
  9631. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  9632. SourceLocation OpLoc,
  9633. ArrayRef<Expr *> Args) {
  9634. DeclarationName OpName =
  9635. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  9636. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  9637. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  9638. OverloadCandidateSet::CSK_Operator,
  9639. /*ExplicitTemplateArgs=*/nullptr, Args);
  9640. }
  9641. namespace {
  9642. class BuildRecoveryCallExprRAII {
  9643. Sema &SemaRef;
  9644. public:
  9645. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  9646. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  9647. SemaRef.IsBuildingRecoveryCallExpr = true;
  9648. }
  9649. ~BuildRecoveryCallExprRAII() {
  9650. SemaRef.IsBuildingRecoveryCallExpr = false;
  9651. }
  9652. };
  9653. }
  9654. static std::unique_ptr<CorrectionCandidateCallback>
  9655. MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
  9656. bool HasTemplateArgs, bool AllowTypoCorrection) {
  9657. if (!AllowTypoCorrection)
  9658. return llvm::make_unique<NoTypoCorrectionCCC>();
  9659. return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
  9660. HasTemplateArgs, ME);
  9661. }
  9662. /// Attempts to recover from a call where no functions were found.
  9663. ///
  9664. /// Returns true if new candidates were found.
  9665. static ExprResult
  9666. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9667. UnresolvedLookupExpr *ULE,
  9668. SourceLocation LParenLoc,
  9669. MutableArrayRef<Expr *> Args,
  9670. SourceLocation RParenLoc,
  9671. bool EmptyLookup, bool AllowTypoCorrection) {
  9672. // Do not try to recover if it is already building a recovery call.
  9673. // This stops infinite loops for template instantiations like
  9674. //
  9675. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  9676. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  9677. //
  9678. if (SemaRef.IsBuildingRecoveryCallExpr)
  9679. return ExprError();
  9680. BuildRecoveryCallExprRAII RCE(SemaRef);
  9681. CXXScopeSpec SS;
  9682. SS.Adopt(ULE->getQualifierLoc());
  9683. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  9684. TemplateArgumentListInfo TABuffer;
  9685. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9686. if (ULE->hasExplicitTemplateArgs()) {
  9687. ULE->copyTemplateArgumentsInto(TABuffer);
  9688. ExplicitTemplateArgs = &TABuffer;
  9689. }
  9690. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  9691. Sema::LookupOrdinaryName);
  9692. bool DoDiagnoseEmptyLookup = EmptyLookup;
  9693. if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
  9694. OverloadCandidateSet::CSK_Normal,
  9695. ExplicitTemplateArgs, Args,
  9696. &DoDiagnoseEmptyLookup) &&
  9697. (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
  9698. S, SS, R,
  9699. MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
  9700. ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
  9701. ExplicitTemplateArgs, Args)))
  9702. return ExprError();
  9703. assert(!R.empty() && "lookup results empty despite recovery");
  9704. // Build an implicit member call if appropriate. Just drop the
  9705. // casts and such from the call, we don't really care.
  9706. ExprResult NewFn = ExprError();
  9707. if ((*R.begin())->isCXXClassMember())
  9708. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  9709. R, ExplicitTemplateArgs);
  9710. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  9711. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  9712. ExplicitTemplateArgs);
  9713. else
  9714. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  9715. if (NewFn.isInvalid())
  9716. return ExprError();
  9717. // This shouldn't cause an infinite loop because we're giving it
  9718. // an expression with viable lookup results, which should never
  9719. // end up here.
  9720. return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  9721. MultiExprArg(Args.data(), Args.size()),
  9722. RParenLoc);
  9723. }
  9724. /// \brief Constructs and populates an OverloadedCandidateSet from
  9725. /// the given function.
  9726. /// \returns true when an the ExprResult output parameter has been set.
  9727. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  9728. UnresolvedLookupExpr *ULE,
  9729. MultiExprArg Args,
  9730. SourceLocation RParenLoc,
  9731. OverloadCandidateSet *CandidateSet,
  9732. ExprResult *Result) {
  9733. #ifndef NDEBUG
  9734. if (ULE->requiresADL()) {
  9735. // To do ADL, we must have found an unqualified name.
  9736. // HLSL Change Begins
  9737. //
  9738. // We do want to allow argument-dependent lookup for intrinsic
  9739. // function names inside the "vk" namespace (which are by definition
  9740. // qualified names).
  9741. bool isVkNamespace =
  9742. ULE->getQualifier() &&
  9743. ULE->getQualifier()->getKind() == NestedNameSpecifier::Namespace &&
  9744. ULE->getQualifier()->getAsNamespace()->getName() == "vk";
  9745. assert((!ULE->getQualifier() || isVkNamespace) && "non-vk qualified name with ADL");
  9746. // HLSL Change Ends
  9747. // We don't perform ADL for implicit declarations of builtins.
  9748. // Verify that this was correctly set up.
  9749. FunctionDecl *F;
  9750. if (ULE->decls_begin() + 1 == ULE->decls_end() &&
  9751. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  9752. F->getBuiltinID() && F->isImplicit())
  9753. llvm_unreachable("performing ADL for builtin");
  9754. // We don't perform ADL in C.
  9755. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  9756. }
  9757. #endif
  9758. UnbridgedCastsSet UnbridgedCasts;
  9759. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  9760. *Result = ExprError();
  9761. return true;
  9762. }
  9763. // Add the functions denoted by the callee to the set of candidate
  9764. // functions, including those from argument-dependent lookup.
  9765. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  9766. if (getLangOpts().MSVCCompat &&
  9767. CurContext->isDependentContext() && !isSFINAEContext() &&
  9768. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  9769. OverloadCandidateSet::iterator Best;
  9770. if (CandidateSet->empty() ||
  9771. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
  9772. OR_No_Viable_Function) {
  9773. // In Microsoft mode, if we are inside a template class member function then
  9774. // create a type dependent CallExpr. The goal is to postpone name lookup
  9775. // to instantiation time to be able to search into type dependent base
  9776. // classes.
  9777. CallExpr *CE = new (Context) CallExpr(
  9778. Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
  9779. CE->setTypeDependent(true);
  9780. *Result = CE;
  9781. return true;
  9782. }
  9783. }
  9784. if (CandidateSet->empty())
  9785. return false;
  9786. UnbridgedCasts.restore();
  9787. return false;
  9788. }
  9789. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  9790. /// the completed call expression. If overload resolution fails, emits
  9791. /// diagnostics and returns ExprError()
  9792. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9793. UnresolvedLookupExpr *ULE,
  9794. SourceLocation LParenLoc,
  9795. MultiExprArg Args,
  9796. SourceLocation RParenLoc,
  9797. Expr *ExecConfig,
  9798. OverloadCandidateSet *CandidateSet,
  9799. OverloadCandidateSet::iterator *Best,
  9800. OverloadingResult OverloadResult,
  9801. bool AllowTypoCorrection) {
  9802. if (CandidateSet->empty())
  9803. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  9804. RParenLoc, /*EmptyLookup=*/true,
  9805. AllowTypoCorrection);
  9806. switch (OverloadResult) {
  9807. case OR_Success: {
  9808. FunctionDecl *FDecl = (*Best)->Function;
  9809. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  9810. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  9811. return ExprError();
  9812. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9813. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9814. ExecConfig);
  9815. }
  9816. case OR_No_Viable_Function: {
  9817. // Try to recover by looking for viable functions which the user might
  9818. // have meant to call.
  9819. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  9820. Args, RParenLoc,
  9821. /*EmptyLookup=*/false,
  9822. AllowTypoCorrection);
  9823. if (!Recovery.isInvalid())
  9824. return Recovery;
  9825. SemaRef.Diag(Fn->getLocStart(),
  9826. diag::err_ovl_no_viable_function_in_call)
  9827. << ULE->getName() << Fn->getSourceRange();
  9828. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9829. break;
  9830. }
  9831. case OR_Ambiguous:
  9832. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
  9833. << ULE->getName() << Fn->getSourceRange();
  9834. CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
  9835. break;
  9836. case OR_Deleted: {
  9837. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
  9838. << (*Best)->Function->isDeleted()
  9839. << ULE->getName()
  9840. << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
  9841. << Fn->getSourceRange();
  9842. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9843. // We emitted an error for the unvailable/deleted function call but keep
  9844. // the call in the AST.
  9845. FunctionDecl *FDecl = (*Best)->Function;
  9846. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9847. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9848. ExecConfig);
  9849. }
  9850. }
  9851. // Overload resolution failed.
  9852. return ExprError();
  9853. }
  9854. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  9855. /// (which eventually refers to the declaration Func) and the call
  9856. /// arguments Args/NumArgs, attempt to resolve the function call down
  9857. /// to a specific function. If overload resolution succeeds, returns
  9858. /// the call expression produced by overload resolution.
  9859. /// Otherwise, emits diagnostics and returns ExprError.
  9860. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  9861. UnresolvedLookupExpr *ULE,
  9862. SourceLocation LParenLoc,
  9863. MultiExprArg Args,
  9864. SourceLocation RParenLoc,
  9865. Expr *ExecConfig,
  9866. bool AllowTypoCorrection) {
  9867. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  9868. OverloadCandidateSet::CSK_Normal);
  9869. ExprResult result;
  9870. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  9871. &result))
  9872. return result;
  9873. OverloadCandidateSet::iterator Best;
  9874. OverloadingResult OverloadResult =
  9875. CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
  9876. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
  9877. RParenLoc, ExecConfig, &CandidateSet,
  9878. &Best, OverloadResult,
  9879. AllowTypoCorrection);
  9880. }
  9881. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  9882. return Functions.size() > 1 ||
  9883. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  9884. }
  9885. /// \brief Create a unary operation that may resolve to an overloaded
  9886. /// operator.
  9887. ///
  9888. /// \param OpLoc The location of the operator itself (e.g., '*').
  9889. ///
  9890. /// \param OpcIn The UnaryOperator::Opcode that describes this
  9891. /// operator.
  9892. ///
  9893. /// \param Fns The set of non-member functions that will be
  9894. /// considered by overload resolution. The caller needs to build this
  9895. /// set based on the context using, e.g.,
  9896. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  9897. /// set should not contain any member functions; those will be added
  9898. /// by CreateOverloadedUnaryOp().
  9899. ///
  9900. /// \param Input The input argument.
  9901. ExprResult
  9902. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
  9903. const UnresolvedSetImpl &Fns,
  9904. Expr *Input) {
  9905. UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
  9906. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  9907. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  9908. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  9909. // TODO: provide better source location info.
  9910. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  9911. if (checkPlaceholderForOverload(*this, Input))
  9912. return ExprError();
  9913. Expr *Args[2] = { Input, nullptr };
  9914. unsigned NumArgs = 1;
  9915. // For post-increment and post-decrement, add the implicit '0' as
  9916. // the second argument, so that we know this is a post-increment or
  9917. // post-decrement.
  9918. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  9919. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  9920. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  9921. SourceLocation());
  9922. NumArgs = 2;
  9923. }
  9924. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  9925. if (Input->isTypeDependent()) {
  9926. if (Fns.empty())
  9927. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  9928. VK_RValue, OK_Ordinary, OpLoc);
  9929. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  9930. UnresolvedLookupExpr *Fn
  9931. = UnresolvedLookupExpr::Create(Context, NamingClass,
  9932. NestedNameSpecifierLoc(), OpNameInfo,
  9933. /*ADL*/ true, IsOverloaded(Fns),
  9934. Fns.begin(), Fns.end());
  9935. return new (Context)
  9936. CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
  9937. VK_RValue, OpLoc, false);
  9938. }
  9939. // Build an empty overload set.
  9940. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  9941. // Add the candidates from the given function set.
  9942. AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
  9943. // Add operator candidates that are member functions.
  9944. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9945. // Add candidates from ADL.
  9946. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  9947. /*ExplicitTemplateArgs*/nullptr,
  9948. CandidateSet);
  9949. // Add builtin operator candidates.
  9950. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9951. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9952. // Perform overload resolution.
  9953. OverloadCandidateSet::iterator Best;
  9954. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  9955. case OR_Success: {
  9956. // We found a built-in operator or an overloaded operator.
  9957. FunctionDecl *FnDecl = Best->Function;
  9958. if (FnDecl) {
  9959. // We matched an overloaded operator. Build a call to that
  9960. // operator.
  9961. // Convert the arguments.
  9962. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  9963. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  9964. ExprResult InputRes =
  9965. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  9966. Best->FoundDecl, Method);
  9967. if (InputRes.isInvalid())
  9968. return ExprError();
  9969. Input = InputRes.get();
  9970. } else {
  9971. // Convert the arguments.
  9972. ExprResult InputInit
  9973. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  9974. Context,
  9975. FnDecl->getParamDecl(0)),
  9976. SourceLocation(),
  9977. Input);
  9978. if (InputInit.isInvalid())
  9979. return ExprError();
  9980. Input = InputInit.get();
  9981. }
  9982. // Build the actual expression node.
  9983. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  9984. HadMultipleCandidates, OpLoc);
  9985. if (FnExpr.isInvalid())
  9986. return ExprError();
  9987. // Determine the result type.
  9988. QualType ResultTy = FnDecl->getReturnType();
  9989. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9990. ResultTy = ResultTy.getNonLValueExprType(Context);
  9991. Args[0] = Input;
  9992. CallExpr *TheCall =
  9993. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
  9994. ResultTy, VK, OpLoc, false);
  9995. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  9996. return ExprError();
  9997. return MaybeBindToTemporary(TheCall);
  9998. } else {
  9999. // We matched a built-in operator. Convert the arguments, then
  10000. // break out so that we will build the appropriate built-in
  10001. // operator node.
  10002. ExprResult InputRes =
  10003. PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
  10004. Best->Conversions[0], AA_Passing);
  10005. if (InputRes.isInvalid())
  10006. return ExprError();
  10007. Input = InputRes.get();
  10008. break;
  10009. }
  10010. }
  10011. case OR_No_Viable_Function:
  10012. // This is an erroneous use of an operator which can be overloaded by
  10013. // a non-member function. Check for non-member operators which were
  10014. // defined too late to be candidates.
  10015. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  10016. // FIXME: Recover by calling the found function.
  10017. return ExprError();
  10018. // No viable function; fall through to handling this as a
  10019. // built-in operator, which will produce an error message for us.
  10020. break;
  10021. case OR_Ambiguous:
  10022. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10023. << UnaryOperator::getOpcodeStr(Opc)
  10024. << Input->getType()
  10025. << Input->getSourceRange();
  10026. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
  10027. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10028. return ExprError();
  10029. case OR_Deleted:
  10030. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10031. << Best->Function->isDeleted()
  10032. << UnaryOperator::getOpcodeStr(Opc)
  10033. << getDeletedOrUnavailableSuffix(Best->Function)
  10034. << Input->getSourceRange();
  10035. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
  10036. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10037. return ExprError();
  10038. }
  10039. // Either we found no viable overloaded operator or we matched a
  10040. // built-in operator. In either case, fall through to trying to
  10041. // build a built-in operation.
  10042. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10043. }
  10044. /// \brief Create a binary operation that may resolve to an overloaded
  10045. /// operator.
  10046. ///
  10047. /// \param OpLoc The location of the operator itself (e.g., '+').
  10048. ///
  10049. /// \param OpcIn The BinaryOperator::Opcode that describes this
  10050. /// operator.
  10051. ///
  10052. /// \param Fns The set of non-member functions that will be
  10053. /// considered by overload resolution. The caller needs to build this
  10054. /// set based on the context using, e.g.,
  10055. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  10056. /// set should not contain any member functions; those will be added
  10057. /// by CreateOverloadedBinOp().
  10058. ///
  10059. /// \param LHS Left-hand argument.
  10060. /// \param RHS Right-hand argument.
  10061. ExprResult
  10062. Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  10063. unsigned OpcIn,
  10064. const UnresolvedSetImpl &Fns,
  10065. Expr *LHS, Expr *RHS) {
  10066. Expr *Args[2] = { LHS, RHS };
  10067. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  10068. BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
  10069. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  10070. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  10071. // If either side is type-dependent, create an appropriate dependent
  10072. // expression.
  10073. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10074. if (Fns.empty()) {
  10075. // If there are no functions to store, just build a dependent
  10076. // BinaryOperator or CompoundAssignment.
  10077. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  10078. return new (Context) BinaryOperator(
  10079. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  10080. OpLoc, FPFeatures.fp_contract);
  10081. return new (Context) CompoundAssignOperator(
  10082. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  10083. Context.DependentTy, Context.DependentTy, OpLoc,
  10084. FPFeatures.fp_contract);
  10085. }
  10086. // FIXME: save results of ADL from here?
  10087. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10088. // TODO: provide better source location info in DNLoc component.
  10089. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  10090. UnresolvedLookupExpr *Fn
  10091. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10092. NestedNameSpecifierLoc(), OpNameInfo,
  10093. /*ADL*/ true, IsOverloaded(Fns),
  10094. Fns.begin(), Fns.end());
  10095. return new (Context)
  10096. CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
  10097. VK_RValue, OpLoc, FPFeatures.fp_contract);
  10098. }
  10099. // Always do placeholder-like conversions on the RHS.
  10100. if (checkPlaceholderForOverload(*this, Args[1]))
  10101. return ExprError();
  10102. // Do placeholder-like conversion on the LHS; note that we should
  10103. // not get here with a PseudoObject LHS.
  10104. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  10105. if (checkPlaceholderForOverload(*this, Args[0]))
  10106. return ExprError();
  10107. // If this is the assignment operator, we only perform overload resolution
  10108. // if the left-hand side is a class or enumeration type. This is actually
  10109. // a hack. The standard requires that we do overload resolution between the
  10110. // various built-in candidates, but as DR507 points out, this can lead to
  10111. // problems. So we do it this way, which pretty much follows what GCC does.
  10112. // Note that we go the traditional code path for compound assignment forms.
  10113. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  10114. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10115. // If this is the .* operator, which is not overloadable, just
  10116. // create a built-in binary operator.
  10117. if (Opc == BO_PtrMemD)
  10118. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10119. // Build an empty overload set.
  10120. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  10121. // Add the candidates from the given function set.
  10122. AddFunctionCandidates(Fns, Args, CandidateSet);
  10123. // Add operator candidates that are member functions.
  10124. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10125. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  10126. // performed for an assignment operator (nor for operator[] nor operator->,
  10127. // which don't get here).
  10128. if (Opc != BO_Assign)
  10129. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  10130. /*ExplicitTemplateArgs*/ nullptr,
  10131. CandidateSet);
  10132. // Add builtin operator candidates.
  10133. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10134. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10135. // Perform overload resolution.
  10136. OverloadCandidateSet::iterator Best;
  10137. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10138. case OR_Success: {
  10139. // We found a built-in operator or an overloaded operator.
  10140. FunctionDecl *FnDecl = Best->Function;
  10141. if (FnDecl) {
  10142. // We matched an overloaded operator. Build a call to that
  10143. // operator.
  10144. // Convert the arguments.
  10145. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  10146. // Best->Access is only meaningful for class members.
  10147. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  10148. ExprResult Arg1 =
  10149. PerformCopyInitialization(
  10150. InitializedEntity::InitializeParameter(Context,
  10151. FnDecl->getParamDecl(0)),
  10152. SourceLocation(), Args[1]);
  10153. if (Arg1.isInvalid())
  10154. return ExprError();
  10155. ExprResult Arg0 =
  10156. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10157. Best->FoundDecl, Method);
  10158. if (Arg0.isInvalid())
  10159. return ExprError();
  10160. Args[0] = Arg0.getAs<Expr>();
  10161. Args[1] = RHS = Arg1.getAs<Expr>();
  10162. } else {
  10163. // Convert the arguments.
  10164. ExprResult Arg0 = PerformCopyInitialization(
  10165. InitializedEntity::InitializeParameter(Context,
  10166. FnDecl->getParamDecl(0)),
  10167. SourceLocation(), Args[0]);
  10168. if (Arg0.isInvalid())
  10169. return ExprError();
  10170. ExprResult Arg1 =
  10171. PerformCopyInitialization(
  10172. InitializedEntity::InitializeParameter(Context,
  10173. FnDecl->getParamDecl(1)),
  10174. SourceLocation(), Args[1]);
  10175. if (Arg1.isInvalid())
  10176. return ExprError();
  10177. Args[0] = LHS = Arg0.getAs<Expr>();
  10178. Args[1] = RHS = Arg1.getAs<Expr>();
  10179. }
  10180. // Build the actual expression node.
  10181. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10182. Best->FoundDecl,
  10183. HadMultipleCandidates, OpLoc);
  10184. if (FnExpr.isInvalid())
  10185. return ExprError();
  10186. // Determine the result type.
  10187. QualType ResultTy = FnDecl->getReturnType();
  10188. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10189. ResultTy = ResultTy.getNonLValueExprType(Context);
  10190. CXXOperatorCallExpr *TheCall =
  10191. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
  10192. Args, ResultTy, VK, OpLoc,
  10193. FPFeatures.fp_contract);
  10194. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  10195. FnDecl))
  10196. return ExprError();
  10197. ArrayRef<const Expr *> ArgsArray(Args, 2);
  10198. // Cut off the implicit 'this'.
  10199. if (isa<CXXMethodDecl>(FnDecl))
  10200. ArgsArray = ArgsArray.slice(1);
  10201. // Check for a self move.
  10202. if (Op == OO_Equal)
  10203. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  10204. checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
  10205. TheCall->getSourceRange(), VariadicDoesNotApply);
  10206. return MaybeBindToTemporary(TheCall);
  10207. } else {
  10208. // We matched a built-in operator. Convert the arguments, then
  10209. // break out so that we will build the appropriate built-in
  10210. // operator node.
  10211. ExprResult ArgsRes0 =
  10212. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10213. Best->Conversions[0], AA_Passing);
  10214. if (ArgsRes0.isInvalid())
  10215. return ExprError();
  10216. Args[0] = ArgsRes0.get();
  10217. ExprResult ArgsRes1 =
  10218. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10219. Best->Conversions[1], AA_Passing);
  10220. if (ArgsRes1.isInvalid())
  10221. return ExprError();
  10222. Args[1] = ArgsRes1.get();
  10223. break;
  10224. }
  10225. }
  10226. case OR_No_Viable_Function: {
  10227. // C++ [over.match.oper]p9:
  10228. // If the operator is the operator , [...] and there are no
  10229. // viable functions, then the operator is assumed to be the
  10230. // built-in operator and interpreted according to clause 5.
  10231. if (Opc == BO_Comma)
  10232. break;
  10233. // For class as left operand for assignment or compound assigment
  10234. // operator do not fall through to handling in built-in, but report that
  10235. // no overloaded assignment operator found
  10236. ExprResult Result = ExprError();
  10237. if (Args[0]->getType()->isRecordType() &&
  10238. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  10239. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10240. << BinaryOperator::getOpcodeStr(Opc)
  10241. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10242. if (Args[0]->getType()->isIncompleteType()) {
  10243. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  10244. << Args[0]->getType()
  10245. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10246. }
  10247. } else {
  10248. // This is an erroneous use of an operator which can be overloaded by
  10249. // a non-member function. Check for non-member operators which were
  10250. // defined too late to be candidates.
  10251. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  10252. // FIXME: Recover by calling the found function.
  10253. return ExprError();
  10254. // No viable function; try to create a built-in operation, which will
  10255. // produce an error. Then, show the non-viable candidates.
  10256. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10257. }
  10258. assert(Result.isInvalid() &&
  10259. "C++ binary operator overloading is missing candidates!");
  10260. if (Result.isInvalid())
  10261. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10262. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10263. return Result;
  10264. }
  10265. case OR_Ambiguous:
  10266. Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
  10267. << BinaryOperator::getOpcodeStr(Opc)
  10268. << Args[0]->getType() << Args[1]->getType()
  10269. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10270. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10271. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10272. return ExprError();
  10273. case OR_Deleted:
  10274. if (isImplicitlyDeleted(Best->Function)) {
  10275. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10276. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  10277. << Context.getRecordType(Method->getParent())
  10278. << getSpecialMember(Method);
  10279. // The user probably meant to call this special member. Just
  10280. // explain why it's deleted.
  10281. NoteDeletedFunction(Method);
  10282. return ExprError();
  10283. } else {
  10284. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10285. << Best->Function->isDeleted()
  10286. << BinaryOperator::getOpcodeStr(Opc)
  10287. << getDeletedOrUnavailableSuffix(Best->Function)
  10288. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10289. }
  10290. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10291. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10292. return ExprError();
  10293. }
  10294. // We matched a built-in operator; build it.
  10295. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10296. }
  10297. ExprResult
  10298. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  10299. SourceLocation RLoc,
  10300. Expr *Base, Expr *Idx) {
  10301. Expr *Args[2] = { Base, Idx };
  10302. DeclarationName OpName =
  10303. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  10304. // If either side is type-dependent, create an appropriate dependent
  10305. // expression.
  10306. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10307. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10308. // CHECKME: no 'operator' keyword?
  10309. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  10310. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10311. UnresolvedLookupExpr *Fn
  10312. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10313. NestedNameSpecifierLoc(), OpNameInfo,
  10314. /*ADL*/ true, /*Overloaded*/ false,
  10315. UnresolvedSetIterator(),
  10316. UnresolvedSetIterator());
  10317. // Can't add any actual overloads yet
  10318. return new (Context)
  10319. CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
  10320. Context.DependentTy, VK_RValue, RLoc, false);
  10321. }
  10322. // Handle placeholders on both operands.
  10323. if (checkPlaceholderForOverload(*this, Args[0]))
  10324. return ExprError();
  10325. if (checkPlaceholderForOverload(*this, Args[1]))
  10326. return ExprError();
  10327. // Build an empty overload set.
  10328. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  10329. // Subscript can only be overloaded as a member function.
  10330. // Add operator candidates that are member functions.
  10331. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10332. // Add builtin operator candidates.
  10333. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10334. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10335. // Perform overload resolution.
  10336. OverloadCandidateSet::iterator Best;
  10337. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  10338. case OR_Success: {
  10339. // We found a built-in operator or an overloaded operator.
  10340. FunctionDecl *FnDecl = Best->Function;
  10341. if (FnDecl) {
  10342. // We matched an overloaded operator. Build a call to that
  10343. // operator.
  10344. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  10345. // Convert the arguments.
  10346. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  10347. ExprResult Arg0 =
  10348. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10349. Best->FoundDecl, Method);
  10350. if (Arg0.isInvalid())
  10351. return ExprError();
  10352. Args[0] = Arg0.get();
  10353. // Convert the arguments.
  10354. ExprResult InputInit
  10355. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10356. Context,
  10357. FnDecl->getParamDecl(0)),
  10358. SourceLocation(),
  10359. Args[1]);
  10360. if (InputInit.isInvalid())
  10361. return ExprError();
  10362. Args[1] = InputInit.getAs<Expr>();
  10363. // Build the actual expression node.
  10364. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  10365. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10366. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10367. Best->FoundDecl,
  10368. HadMultipleCandidates,
  10369. OpLocInfo.getLoc(),
  10370. OpLocInfo.getInfo());
  10371. if (FnExpr.isInvalid())
  10372. return ExprError();
  10373. // Determine the result type
  10374. QualType ResultTy = FnDecl->getReturnType();
  10375. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10376. ResultTy = ResultTy.getNonLValueExprType(Context);
  10377. CXXOperatorCallExpr *TheCall =
  10378. new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
  10379. FnExpr.get(), Args,
  10380. ResultTy, VK, RLoc,
  10381. false);
  10382. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  10383. return ExprError();
  10384. return MaybeBindToTemporary(TheCall);
  10385. } else {
  10386. // We matched a built-in operator. Convert the arguments, then
  10387. // break out so that we will build the appropriate built-in
  10388. // operator node.
  10389. ExprResult ArgsRes0 =
  10390. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10391. Best->Conversions[0], AA_Passing);
  10392. if (ArgsRes0.isInvalid())
  10393. return ExprError();
  10394. Args[0] = ArgsRes0.get();
  10395. ExprResult ArgsRes1 =
  10396. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10397. Best->Conversions[1], AA_Passing);
  10398. if (ArgsRes1.isInvalid())
  10399. return ExprError();
  10400. Args[1] = ArgsRes1.get();
  10401. break;
  10402. }
  10403. }
  10404. case OR_No_Viable_Function: {
  10405. if (CandidateSet.empty())
  10406. Diag(LLoc, diag::err_ovl_no_oper)
  10407. << Args[0]->getType() << /*subscript*/ 0
  10408. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10409. else
  10410. Diag(LLoc, diag::err_ovl_no_viable_subscript)
  10411. << Args[0]->getType()
  10412. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10413. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10414. "[]", LLoc);
  10415. return ExprError();
  10416. }
  10417. case OR_Ambiguous:
  10418. Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
  10419. << "[]"
  10420. << Args[0]->getType() << Args[1]->getType()
  10421. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10422. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10423. "[]", LLoc);
  10424. return ExprError();
  10425. case OR_Deleted:
  10426. Diag(LLoc, diag::err_ovl_deleted_oper)
  10427. << Best->Function->isDeleted() << "[]"
  10428. << getDeletedOrUnavailableSuffix(Best->Function)
  10429. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10430. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10431. "[]", LLoc);
  10432. return ExprError();
  10433. }
  10434. // We matched a built-in operator; build it.
  10435. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  10436. }
  10437. /// BuildCallToMemberFunction - Build a call to a member
  10438. /// function. MemExpr is the expression that refers to the member
  10439. /// function (and includes the object parameter), Args/NumArgs are the
  10440. /// arguments to the function call (not including the object
  10441. /// parameter). The caller needs to validate that the member
  10442. /// expression refers to a non-static member function or an overloaded
  10443. /// member function.
  10444. ExprResult
  10445. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  10446. SourceLocation LParenLoc,
  10447. MultiExprArg Args,
  10448. SourceLocation RParenLoc) {
  10449. assert(MemExprE->getType() == Context.BoundMemberTy ||
  10450. MemExprE->getType() == Context.OverloadTy);
  10451. // Dig out the member expression. This holds both the object
  10452. // argument and the member function we're referring to.
  10453. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  10454. // Determine whether this is a call to a pointer-to-member function.
  10455. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  10456. assert(op->getType() == Context.BoundMemberTy);
  10457. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  10458. QualType fnType =
  10459. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  10460. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  10461. QualType resultType = proto->getCallResultType(Context);
  10462. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  10463. // Check that the object type isn't more qualified than the
  10464. // member function we're calling.
  10465. Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
  10466. QualType objectType = op->getLHS()->getType();
  10467. if (op->getOpcode() == BO_PtrMemI)
  10468. objectType = objectType->castAs<PointerType>()->getPointeeType();
  10469. Qualifiers objectQuals = objectType.getQualifiers();
  10470. Qualifiers difference = objectQuals - funcQuals;
  10471. difference.removeObjCGCAttr();
  10472. difference.removeAddressSpace();
  10473. if (difference) {
  10474. std::string qualsString = difference.getAsString();
  10475. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  10476. << fnType.getUnqualifiedType()
  10477. << qualsString
  10478. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  10479. }
  10480. if (resultType->isMemberPointerType())
  10481. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10482. RequireCompleteType(LParenLoc, resultType, 0);
  10483. CXXMemberCallExpr *call
  10484. = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10485. resultType, valueKind, RParenLoc);
  10486. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
  10487. call, nullptr))
  10488. return ExprError();
  10489. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  10490. return ExprError();
  10491. if (CheckOtherCall(call, proto))
  10492. return ExprError();
  10493. return MaybeBindToTemporary(call);
  10494. }
  10495. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  10496. return new (Context)
  10497. CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
  10498. UnbridgedCastsSet UnbridgedCasts;
  10499. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10500. return ExprError();
  10501. MemberExpr *MemExpr;
  10502. CXXMethodDecl *Method = nullptr;
  10503. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  10504. NestedNameSpecifier *Qualifier = nullptr;
  10505. if (isa<MemberExpr>(NakedMemExpr)) {
  10506. MemExpr = cast<MemberExpr>(NakedMemExpr);
  10507. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  10508. FoundDecl = MemExpr->getFoundDecl();
  10509. Qualifier = MemExpr->getQualifier();
  10510. UnbridgedCasts.restore();
  10511. } else {
  10512. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  10513. Qualifier = UnresExpr->getQualifier();
  10514. QualType ObjectType = UnresExpr->getBaseType();
  10515. Expr::Classification ObjectClassification
  10516. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  10517. : UnresExpr->getBase()->Classify(Context);
  10518. // Add overload candidates
  10519. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  10520. OverloadCandidateSet::CSK_Normal);
  10521. // FIXME: avoid copy.
  10522. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  10523. if (UnresExpr->hasExplicitTemplateArgs()) {
  10524. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  10525. TemplateArgs = &TemplateArgsBuffer;
  10526. }
  10527. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  10528. E = UnresExpr->decls_end(); I != E; ++I) {
  10529. NamedDecl *Func = *I;
  10530. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  10531. if (isa<UsingShadowDecl>(Func))
  10532. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  10533. // Microsoft supports direct constructor calls.
  10534. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  10535. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
  10536. Args, CandidateSet);
  10537. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  10538. // If explicit template arguments were provided, we can't call a
  10539. // non-template member function.
  10540. if (TemplateArgs)
  10541. continue;
  10542. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  10543. ObjectClassification, Args, CandidateSet,
  10544. /*SuppressUserConversions=*/false);
  10545. } else {
  10546. AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
  10547. I.getPair(), ActingDC, TemplateArgs,
  10548. ObjectType, ObjectClassification,
  10549. Args, CandidateSet,
  10550. /*SuppressUsedConversions=*/false);
  10551. }
  10552. }
  10553. DeclarationName DeclName = UnresExpr->getMemberName();
  10554. UnbridgedCasts.restore();
  10555. OverloadCandidateSet::iterator Best;
  10556. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
  10557. Best)) {
  10558. case OR_Success:
  10559. Method = cast<CXXMethodDecl>(Best->Function);
  10560. FoundDecl = Best->FoundDecl;
  10561. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  10562. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  10563. return ExprError();
  10564. // If FoundDecl is different from Method (such as if one is a template
  10565. // and the other a specialization), make sure DiagnoseUseOfDecl is
  10566. // called on both.
  10567. // FIXME: This would be more comprehensively addressed by modifying
  10568. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  10569. // being used.
  10570. if (Method != FoundDecl.getDecl() &&
  10571. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  10572. return ExprError();
  10573. break;
  10574. case OR_No_Viable_Function:
  10575. Diag(UnresExpr->getMemberLoc(),
  10576. diag::err_ovl_no_viable_member_function_in_call)
  10577. << DeclName << MemExprE->getSourceRange();
  10578. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, StringRef(), UnresExpr->getMemberLoc()); // HLSL Change - add member loc
  10579. // FIXME: Leaking incoming expressions!
  10580. return ExprError();
  10581. case OR_Ambiguous:
  10582. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
  10583. << DeclName << MemExprE->getSourceRange();
  10584. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10585. // FIXME: Leaking incoming expressions!
  10586. return ExprError();
  10587. case OR_Deleted:
  10588. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
  10589. << Best->Function->isDeleted()
  10590. << DeclName
  10591. << getDeletedOrUnavailableSuffix(Best->Function)
  10592. << MemExprE->getSourceRange();
  10593. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10594. // FIXME: Leaking incoming expressions!
  10595. return ExprError();
  10596. }
  10597. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  10598. // If overload resolution picked a static member, build a
  10599. // non-member call based on that function.
  10600. if (Method->isStatic()) {
  10601. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  10602. RParenLoc);
  10603. }
  10604. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  10605. }
  10606. QualType ResultType = Method->getReturnType();
  10607. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  10608. ResultType = ResultType.getNonLValueExprType(Context);
  10609. assert(Method && "Member call to something that isn't a method?");
  10610. CXXMemberCallExpr *TheCall =
  10611. new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10612. ResultType, VK, RParenLoc);
  10613. // (CUDA B.1): Check for invalid calls between targets.
  10614. if (getLangOpts().CUDA) {
  10615. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
  10616. if (CheckCUDATarget(Caller, Method)) {
  10617. Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
  10618. << IdentifyCUDATarget(Method) << Method->getIdentifier()
  10619. << IdentifyCUDATarget(Caller);
  10620. return ExprError();
  10621. }
  10622. }
  10623. }
  10624. // Check for a valid return type.
  10625. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  10626. TheCall, Method))
  10627. return ExprError();
  10628. // Convert the object argument (for a non-static member function call).
  10629. // We only need to do this if there was actually an overload; otherwise
  10630. // it was done at lookup.
  10631. if (!Method->isStatic()) {
  10632. ExprResult ObjectArg =
  10633. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  10634. FoundDecl, Method);
  10635. if (ObjectArg.isInvalid())
  10636. return ExprError();
  10637. MemExpr->setBase(ObjectArg.get());
  10638. }
  10639. // Convert the rest of the arguments
  10640. const FunctionProtoType *Proto =
  10641. Method->getType()->getAs<FunctionProtoType>();
  10642. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  10643. RParenLoc))
  10644. return ExprError();
  10645. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10646. if (CheckFunctionCall(Method, TheCall, Proto))
  10647. return ExprError();
  10648. if ((isa<CXXConstructorDecl>(CurContext) ||
  10649. isa<CXXDestructorDecl>(CurContext)) &&
  10650. TheCall->getMethodDecl()->isPure()) {
  10651. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  10652. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
  10653. Diag(MemExpr->getLocStart(),
  10654. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  10655. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  10656. << MD->getParent()->getDeclName();
  10657. Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
  10658. }
  10659. }
  10660. return MaybeBindToTemporary(TheCall);
  10661. }
  10662. /// BuildCallToObjectOfClassType - Build a call to an object of class
  10663. /// type (C++ [over.call.object]), which can end up invoking an
  10664. /// overloaded function call operator (@c operator()) or performing a
  10665. /// user-defined conversion on the object argument.
  10666. ExprResult
  10667. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  10668. SourceLocation LParenLoc,
  10669. MultiExprArg Args,
  10670. SourceLocation RParenLoc) {
  10671. if (checkPlaceholderForOverload(*this, Obj))
  10672. return ExprError();
  10673. ExprResult Object = Obj;
  10674. UnbridgedCastsSet UnbridgedCasts;
  10675. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10676. return ExprError();
  10677. assert(Object.get()->getType()->isRecordType() &&
  10678. "Requires object type argument");
  10679. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  10680. // C++ [over.call.object]p1:
  10681. // If the primary-expression E in the function call syntax
  10682. // evaluates to a class object of type "cv T", then the set of
  10683. // candidate functions includes at least the function call
  10684. // operators of T. The function call operators of T are obtained by
  10685. // ordinary lookup of the name operator() in the context of
  10686. // (E).operator().
  10687. OverloadCandidateSet CandidateSet(LParenLoc,
  10688. OverloadCandidateSet::CSK_Operator);
  10689. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  10690. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  10691. diag::err_incomplete_object_call, Object.get()))
  10692. return true;
  10693. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  10694. LookupQualifiedName(R, Record->getDecl());
  10695. R.suppressDiagnostics();
  10696. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10697. Oper != OperEnd; ++Oper) {
  10698. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  10699. Object.get()->Classify(Context),
  10700. Args, CandidateSet,
  10701. /*SuppressUserConversions=*/ false);
  10702. }
  10703. // C++ [over.call.object]p2:
  10704. // In addition, for each (non-explicit in C++0x) conversion function
  10705. // declared in T of the form
  10706. //
  10707. // operator conversion-type-id () cv-qualifier;
  10708. //
  10709. // where cv-qualifier is the same cv-qualification as, or a
  10710. // greater cv-qualification than, cv, and where conversion-type-id
  10711. // denotes the type "pointer to function of (P1,...,Pn) returning
  10712. // R", or the type "reference to pointer to function of
  10713. // (P1,...,Pn) returning R", or the type "reference to function
  10714. // of (P1,...,Pn) returning R", a surrogate call function [...]
  10715. // is also considered as a candidate function. Similarly,
  10716. // surrogate call functions are added to the set of candidate
  10717. // functions for each conversion function declared in an
  10718. // accessible base class provided the function is not hidden
  10719. // within T by another intervening declaration.
  10720. const auto &Conversions =
  10721. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  10722. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  10723. NamedDecl *D = *I;
  10724. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  10725. if (isa<UsingShadowDecl>(D))
  10726. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  10727. // Skip over templated conversion functions; they aren't
  10728. // surrogates.
  10729. if (isa<FunctionTemplateDecl>(D))
  10730. continue;
  10731. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  10732. if (!Conv->isExplicit()) {
  10733. // Strip the reference type (if any) and then the pointer type (if
  10734. // any) to get down to what might be a function type.
  10735. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  10736. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  10737. ConvType = ConvPtrType->getPointeeType();
  10738. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  10739. {
  10740. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  10741. Object.get(), Args, CandidateSet);
  10742. }
  10743. }
  10744. }
  10745. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10746. // Perform overload resolution.
  10747. OverloadCandidateSet::iterator Best;
  10748. switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
  10749. Best)) {
  10750. case OR_Success:
  10751. // Overload resolution succeeded; we'll build the appropriate call
  10752. // below.
  10753. break;
  10754. case OR_No_Viable_Function:
  10755. if (CandidateSet.empty())
  10756. Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
  10757. << Object.get()->getType() << /*call*/ 1
  10758. << Object.get()->getSourceRange();
  10759. else
  10760. Diag(Object.get()->getLocStart(),
  10761. diag::err_ovl_no_viable_object_call)
  10762. << Object.get()->getType() << Object.get()->getSourceRange();
  10763. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10764. break;
  10765. case OR_Ambiguous:
  10766. Diag(Object.get()->getLocStart(),
  10767. diag::err_ovl_ambiguous_object_call)
  10768. << Object.get()->getType() << Object.get()->getSourceRange();
  10769. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  10770. break;
  10771. case OR_Deleted:
  10772. Diag(Object.get()->getLocStart(),
  10773. diag::err_ovl_deleted_object_call)
  10774. << Best->Function->isDeleted()
  10775. << Object.get()->getType()
  10776. << getDeletedOrUnavailableSuffix(Best->Function)
  10777. << Object.get()->getSourceRange();
  10778. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10779. break;
  10780. }
  10781. if (Best == CandidateSet.end())
  10782. return true;
  10783. UnbridgedCasts.restore();
  10784. if (Best->Function == nullptr) {
  10785. // Since there is no function declaration, this is one of the
  10786. // surrogate candidates. Dig out the conversion function.
  10787. CXXConversionDecl *Conv
  10788. = cast<CXXConversionDecl>(
  10789. Best->Conversions[0].UserDefined.ConversionFunction);
  10790. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  10791. Best->FoundDecl);
  10792. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  10793. return ExprError();
  10794. assert(Conv == Best->FoundDecl.getDecl() &&
  10795. "Found Decl & conversion-to-functionptr should be same, right?!");
  10796. // We selected one of the surrogate functions that converts the
  10797. // object parameter to a function pointer. Perform the conversion
  10798. // on the object argument, then let ActOnCallExpr finish the job.
  10799. // Create an implicit member expr to refer to the conversion operator.
  10800. // and then call it.
  10801. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  10802. Conv, HadMultipleCandidates);
  10803. if (Call.isInvalid())
  10804. return ExprError();
  10805. // Record usage of conversion in an implicit cast.
  10806. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  10807. CK_UserDefinedConversion, Call.get(),
  10808. nullptr, VK_RValue);
  10809. return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  10810. }
  10811. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  10812. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  10813. // that calls this method, using Object for the implicit object
  10814. // parameter and passing along the remaining arguments.
  10815. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10816. // An error diagnostic has already been printed when parsing the declaration.
  10817. if (Method->isInvalidDecl())
  10818. return ExprError();
  10819. const FunctionProtoType *Proto =
  10820. Method->getType()->getAs<FunctionProtoType>();
  10821. unsigned NumParams = Proto->getNumParams();
  10822. DeclarationNameInfo OpLocInfo(
  10823. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  10824. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  10825. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10826. HadMultipleCandidates,
  10827. OpLocInfo.getLoc(),
  10828. OpLocInfo.getInfo());
  10829. if (NewFn.isInvalid())
  10830. return true;
  10831. // Build the full argument list for the method call (the implicit object
  10832. // parameter is placed at the beginning of the list).
  10833. std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
  10834. MethodArgs[0] = Object.get();
  10835. std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
  10836. // Once we've built TheCall, all of the expressions are properly
  10837. // owned.
  10838. QualType ResultTy = Method->getReturnType();
  10839. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10840. ResultTy = ResultTy.getNonLValueExprType(Context);
  10841. CXXOperatorCallExpr *TheCall = new (Context)
  10842. CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
  10843. llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
  10844. ResultTy, VK, RParenLoc, false);
  10845. MethodArgs.reset();
  10846. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  10847. return true;
  10848. // We may have default arguments. If so, we need to allocate more
  10849. // slots in the call for them.
  10850. if (Args.size() < NumParams)
  10851. TheCall->setNumArgs(Context, NumParams + 1);
  10852. bool IsError = false;
  10853. // Initialize the implicit object parameter.
  10854. ExprResult ObjRes =
  10855. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  10856. Best->FoundDecl, Method);
  10857. if (ObjRes.isInvalid())
  10858. IsError = true;
  10859. else
  10860. Object = ObjRes;
  10861. TheCall->setArg(0, Object.get());
  10862. // Check the argument types.
  10863. for (unsigned i = 0; i != NumParams; i++) {
  10864. Expr *Arg;
  10865. if (i < Args.size()) {
  10866. Arg = Args[i];
  10867. // Pass the argument.
  10868. ExprResult InputInit
  10869. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10870. Context,
  10871. Method->getParamDecl(i)),
  10872. SourceLocation(), Arg);
  10873. IsError |= InputInit.isInvalid();
  10874. Arg = InputInit.getAs<Expr>();
  10875. } else {
  10876. ExprResult DefArg
  10877. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  10878. if (DefArg.isInvalid()) {
  10879. IsError = true;
  10880. break;
  10881. }
  10882. Arg = DefArg.getAs<Expr>();
  10883. }
  10884. TheCall->setArg(i + 1, Arg);
  10885. }
  10886. // If this is a variadic call, handle args passed through "...".
  10887. if (Proto->isVariadic()) {
  10888. // Promote the arguments (C99 6.5.2.2p7).
  10889. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  10890. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  10891. nullptr);
  10892. IsError |= Arg.isInvalid();
  10893. TheCall->setArg(i + 1, Arg.get());
  10894. }
  10895. }
  10896. if (IsError) return true;
  10897. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10898. if (CheckFunctionCall(Method, TheCall, Proto))
  10899. return true;
  10900. return MaybeBindToTemporary(TheCall);
  10901. }
  10902. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  10903. /// (if one exists), where @c Base is an expression of class type and
  10904. /// @c Member is the name of the member we're trying to find.
  10905. ExprResult
  10906. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  10907. bool *NoArrowOperatorFound) {
  10908. assert(Base->getType()->isRecordType() &&
  10909. "left-hand side must have class type");
  10910. if (checkPlaceholderForOverload(*this, Base))
  10911. return ExprError();
  10912. SourceLocation Loc = Base->getExprLoc();
  10913. // C++ [over.ref]p1:
  10914. //
  10915. // [...] An expression x->m is interpreted as (x.operator->())->m
  10916. // for a class object x of type T if T::operator->() exists and if
  10917. // the operator is selected as the best match function by the
  10918. // overload resolution mechanism (13.3).
  10919. DeclarationName OpName =
  10920. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  10921. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  10922. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  10923. if (RequireCompleteType(Loc, Base->getType(),
  10924. diag::err_typecheck_incomplete_tag, Base))
  10925. return ExprError();
  10926. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  10927. LookupQualifiedName(R, BaseRecord->getDecl());
  10928. R.suppressDiagnostics();
  10929. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10930. Oper != OperEnd; ++Oper) {
  10931. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  10932. None, CandidateSet, /*SuppressUserConversions=*/false);
  10933. }
  10934. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10935. // Perform overload resolution.
  10936. OverloadCandidateSet::iterator Best;
  10937. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10938. case OR_Success:
  10939. // Overload resolution succeeded; we'll build the call below.
  10940. break;
  10941. case OR_No_Viable_Function:
  10942. if (CandidateSet.empty()) {
  10943. QualType BaseType = Base->getType();
  10944. if (NoArrowOperatorFound) {
  10945. // Report this specific error to the caller instead of emitting a
  10946. // diagnostic, as requested.
  10947. *NoArrowOperatorFound = true;
  10948. return ExprError();
  10949. }
  10950. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  10951. << BaseType << Base->getSourceRange();
  10952. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  10953. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  10954. << FixItHint::CreateReplacement(OpLoc, ".");
  10955. }
  10956. } else
  10957. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10958. << "operator->" << Base->getSourceRange();
  10959. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10960. return ExprError();
  10961. case OR_Ambiguous:
  10962. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10963. << "->" << Base->getType() << Base->getSourceRange();
  10964. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
  10965. return ExprError();
  10966. case OR_Deleted:
  10967. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10968. << Best->Function->isDeleted()
  10969. << "->"
  10970. << getDeletedOrUnavailableSuffix(Best->Function)
  10971. << Base->getSourceRange();
  10972. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10973. return ExprError();
  10974. }
  10975. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  10976. // Convert the object parameter.
  10977. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10978. ExprResult BaseResult =
  10979. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  10980. Best->FoundDecl, Method);
  10981. if (BaseResult.isInvalid())
  10982. return ExprError();
  10983. Base = BaseResult.get();
  10984. // Build the operator call.
  10985. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10986. HadMultipleCandidates, OpLoc);
  10987. if (FnExpr.isInvalid())
  10988. return ExprError();
  10989. QualType ResultTy = Method->getReturnType();
  10990. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10991. ResultTy = ResultTy.getNonLValueExprType(Context);
  10992. CXXOperatorCallExpr *TheCall =
  10993. new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
  10994. Base, ResultTy, VK, OpLoc, false);
  10995. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  10996. return ExprError();
  10997. return MaybeBindToTemporary(TheCall);
  10998. }
  10999. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  11000. /// a literal operator described by the provided lookup results.
  11001. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  11002. DeclarationNameInfo &SuffixInfo,
  11003. ArrayRef<Expr*> Args,
  11004. SourceLocation LitEndLoc,
  11005. TemplateArgumentListInfo *TemplateArgs) {
  11006. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  11007. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  11008. OverloadCandidateSet::CSK_Normal);
  11009. AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
  11010. /*SuppressUserConversions=*/true);
  11011. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11012. // Perform overload resolution. This will usually be trivial, but might need
  11013. // to perform substitutions for a literal operator template.
  11014. OverloadCandidateSet::iterator Best;
  11015. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  11016. case OR_Success:
  11017. case OR_Deleted:
  11018. break;
  11019. case OR_No_Viable_Function:
  11020. Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
  11021. << R.getLookupName();
  11022. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  11023. return ExprError();
  11024. case OR_Ambiguous:
  11025. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  11026. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  11027. return ExprError();
  11028. }
  11029. FunctionDecl *FD = Best->Function;
  11030. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  11031. HadMultipleCandidates,
  11032. SuffixInfo.getLoc(),
  11033. SuffixInfo.getInfo());
  11034. if (Fn.isInvalid())
  11035. return true;
  11036. // Check the argument types. This should almost always be a no-op, except
  11037. // that array-to-pointer decay is applied to string literals.
  11038. Expr *ConvArgs[2];
  11039. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  11040. ExprResult InputInit = PerformCopyInitialization(
  11041. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  11042. SourceLocation(), Args[ArgIdx]);
  11043. if (InputInit.isInvalid())
  11044. return true;
  11045. ConvArgs[ArgIdx] = InputInit.get();
  11046. }
  11047. QualType ResultTy = FD->getReturnType();
  11048. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11049. ResultTy = ResultTy.getNonLValueExprType(Context);
  11050. UserDefinedLiteral *UDL =
  11051. new (Context) UserDefinedLiteral(Context, Fn.get(),
  11052. llvm::makeArrayRef(ConvArgs, Args.size()),
  11053. ResultTy, VK, LitEndLoc, UDSuffixLoc);
  11054. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  11055. return ExprError();
  11056. if (CheckFunctionCall(FD, UDL, nullptr))
  11057. return ExprError();
  11058. return MaybeBindToTemporary(UDL);
  11059. }
  11060. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  11061. /// given LookupResult is non-empty, it is assumed to describe a member which
  11062. /// will be invoked. Otherwise, the function will be found via argument
  11063. /// dependent lookup.
  11064. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  11065. /// otherwise CallExpr is set to ExprError() and some non-success value
  11066. /// is returned.
  11067. Sema::ForRangeStatus
  11068. Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
  11069. SourceLocation RangeLoc, VarDecl *Decl,
  11070. BeginEndFunction BEF,
  11071. const DeclarationNameInfo &NameInfo,
  11072. LookupResult &MemberLookup,
  11073. OverloadCandidateSet *CandidateSet,
  11074. Expr *Range, ExprResult *CallExpr) {
  11075. CandidateSet->clear();
  11076. if (!MemberLookup.empty()) {
  11077. ExprResult MemberRef =
  11078. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  11079. /*IsPtr=*/false, CXXScopeSpec(),
  11080. /*TemplateKWLoc=*/SourceLocation(),
  11081. /*FirstQualifierInScope=*/nullptr,
  11082. MemberLookup,
  11083. /*TemplateArgs=*/nullptr);
  11084. if (MemberRef.isInvalid()) {
  11085. *CallExpr = ExprError();
  11086. Diag(Range->getLocStart(), diag::note_in_for_range)
  11087. << RangeLoc << BEF << Range->getType();
  11088. return FRS_DiagnosticIssued;
  11089. }
  11090. *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  11091. if (CallExpr->isInvalid()) {
  11092. *CallExpr = ExprError();
  11093. Diag(Range->getLocStart(), diag::note_in_for_range)
  11094. << RangeLoc << BEF << Range->getType();
  11095. return FRS_DiagnosticIssued;
  11096. }
  11097. } else {
  11098. UnresolvedSet<0> FoundNames;
  11099. UnresolvedLookupExpr *Fn =
  11100. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  11101. NestedNameSpecifierLoc(), NameInfo,
  11102. /*NeedsADL=*/true, /*Overloaded=*/false,
  11103. FoundNames.begin(), FoundNames.end());
  11104. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  11105. CandidateSet, CallExpr);
  11106. if (CandidateSet->empty() || CandidateSetError) {
  11107. *CallExpr = ExprError();
  11108. return FRS_NoViableFunction;
  11109. }
  11110. OverloadCandidateSet::iterator Best;
  11111. OverloadingResult OverloadResult =
  11112. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
  11113. if (OverloadResult == OR_No_Viable_Function) {
  11114. *CallExpr = ExprError();
  11115. return FRS_NoViableFunction;
  11116. }
  11117. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  11118. Loc, nullptr, CandidateSet, &Best,
  11119. OverloadResult,
  11120. /*AllowTypoCorrection=*/false);
  11121. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  11122. *CallExpr = ExprError();
  11123. Diag(Range->getLocStart(), diag::note_in_for_range)
  11124. << RangeLoc << BEF << Range->getType();
  11125. return FRS_DiagnosticIssued;
  11126. }
  11127. }
  11128. return FRS_Success;
  11129. }
  11130. /// FixOverloadedFunctionReference - E is an expression that refers to
  11131. /// a C++ overloaded function (possibly with some parentheses and
  11132. /// perhaps a '&' around it). We have resolved the overloaded function
  11133. /// to the function declaration Fn, so patch up the expression E to
  11134. /// refer (possibly indirectly) to Fn. Returns the new expr.
  11135. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  11136. FunctionDecl *Fn) {
  11137. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  11138. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  11139. Found, Fn);
  11140. if (SubExpr == PE->getSubExpr())
  11141. return PE;
  11142. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  11143. }
  11144. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  11145. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  11146. Found, Fn);
  11147. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  11148. SubExpr->getType()) &&
  11149. "Implicit cast type cannot be determined from overload");
  11150. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  11151. if (SubExpr == ICE->getSubExpr())
  11152. return ICE;
  11153. return ImplicitCastExpr::Create(Context, ICE->getType(),
  11154. ICE->getCastKind(),
  11155. SubExpr, nullptr,
  11156. ICE->getValueKind());
  11157. }
  11158. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  11159. assert(UnOp->getOpcode() == UO_AddrOf &&
  11160. "Can only take the address of an overloaded function");
  11161. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  11162. if (Method->isStatic()) {
  11163. // Do nothing: static member functions aren't any different
  11164. // from non-member functions.
  11165. } else {
  11166. // Fix the subexpression, which really has to be an
  11167. // UnresolvedLookupExpr holding an overloaded member function
  11168. // or template.
  11169. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11170. Found, Fn);
  11171. if (SubExpr == UnOp->getSubExpr())
  11172. return UnOp;
  11173. assert(isa<DeclRefExpr>(SubExpr)
  11174. && "fixed to something other than a decl ref");
  11175. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  11176. && "fixed to a member ref with no nested name qualifier");
  11177. // We have taken the address of a pointer to member
  11178. // function. Perform the computation here so that we get the
  11179. // appropriate pointer to member type.
  11180. QualType ClassType
  11181. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  11182. QualType MemPtrType
  11183. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  11184. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  11185. VK_RValue, OK_Ordinary,
  11186. UnOp->getOperatorLoc());
  11187. }
  11188. }
  11189. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11190. Found, Fn);
  11191. if (SubExpr == UnOp->getSubExpr())
  11192. return UnOp;
  11193. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  11194. Context.getPointerType(SubExpr->getType()),
  11195. VK_RValue, OK_Ordinary,
  11196. UnOp->getOperatorLoc());
  11197. }
  11198. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11199. // FIXME: avoid copy.
  11200. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11201. if (ULE->hasExplicitTemplateArgs()) {
  11202. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11203. TemplateArgs = &TemplateArgsBuffer;
  11204. }
  11205. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11206. ULE->getQualifierLoc(),
  11207. ULE->getTemplateKeywordLoc(),
  11208. Fn,
  11209. /*enclosing*/ false, // FIXME?
  11210. ULE->getNameLoc(),
  11211. Fn->getType(),
  11212. VK_LValue,
  11213. Found.getDecl(),
  11214. TemplateArgs);
  11215. MarkDeclRefReferenced(DRE);
  11216. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  11217. return DRE;
  11218. }
  11219. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  11220. // FIXME: avoid copy.
  11221. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11222. if (MemExpr->hasExplicitTemplateArgs()) {
  11223. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11224. TemplateArgs = &TemplateArgsBuffer;
  11225. }
  11226. Expr *Base;
  11227. // If we're filling in a static method where we used to have an
  11228. // implicit member access, rewrite to a simple decl ref.
  11229. if (MemExpr->isImplicitAccess()) {
  11230. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11231. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11232. MemExpr->getQualifierLoc(),
  11233. MemExpr->getTemplateKeywordLoc(),
  11234. Fn,
  11235. /*enclosing*/ false,
  11236. MemExpr->getMemberLoc(),
  11237. Fn->getType(),
  11238. VK_LValue,
  11239. Found.getDecl(),
  11240. TemplateArgs);
  11241. MarkDeclRefReferenced(DRE);
  11242. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  11243. return DRE;
  11244. } else {
  11245. SourceLocation Loc = MemExpr->getMemberLoc();
  11246. if (MemExpr->getQualifier())
  11247. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  11248. CheckCXXThisCapture(Loc);
  11249. Base = new (Context) CXXThisExpr(Loc,
  11250. MemExpr->getBaseType(),
  11251. /*isImplicit=*/true);
  11252. }
  11253. } else
  11254. Base = MemExpr->getBase();
  11255. ExprValueKind valueKind;
  11256. QualType type;
  11257. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11258. valueKind = VK_LValue;
  11259. type = Fn->getType();
  11260. } else {
  11261. valueKind = VK_RValue;
  11262. type = Context.BoundMemberTy;
  11263. }
  11264. MemberExpr *ME = MemberExpr::Create(
  11265. Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  11266. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  11267. MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
  11268. OK_Ordinary);
  11269. ME->setHadMultipleCandidates(true);
  11270. MarkMemberReferenced(ME);
  11271. return ME;
  11272. }
  11273. llvm_unreachable("Invalid reference to overloaded function");
  11274. }
  11275. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  11276. DeclAccessPair Found,
  11277. FunctionDecl *Fn) {
  11278. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  11279. }