SelectionDAGBuilder.cpp 378 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827
  1. //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
  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 implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SelectionDAGBuilder.h"
  14. #include "SDNodeDbgValue.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/BranchProbabilityInfo.h"
  21. #include "llvm/Analysis/ConstantFolding.h"
  22. #include "llvm/Analysis/Loads.h"
  23. #include "llvm/Analysis/TargetLibraryInfo.h"
  24. #include "llvm/Analysis/ValueTracking.h"
  25. #include "llvm/Analysis/VectorUtils.h"
  26. #include "llvm/CodeGen/Analysis.h"
  27. #include "llvm/CodeGen/FastISel.h"
  28. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  29. #include "llvm/CodeGen/GCMetadata.h"
  30. #include "llvm/CodeGen/GCStrategy.h"
  31. #include "llvm/CodeGen/MachineFrameInfo.h"
  32. #include "llvm/CodeGen/MachineFunction.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  35. #include "llvm/CodeGen/MachineModuleInfo.h"
  36. #include "llvm/CodeGen/MachineRegisterInfo.h"
  37. #include "llvm/CodeGen/SelectionDAG.h"
  38. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  39. #include "llvm/CodeGen/StackMaps.h"
  40. #include "llvm/CodeGen/WinEHFuncInfo.h"
  41. #include "llvm/IR/CallingConv.h"
  42. #include "llvm/IR/ConstantRange.h"
  43. #include "llvm/IR/Constants.h"
  44. #include "llvm/IR/DataLayout.h"
  45. #include "llvm/IR/DebugInfo.h"
  46. #include "llvm/IR/DerivedTypes.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/GetElementPtrTypeIterator.h"
  49. #include "llvm/IR/GlobalVariable.h"
  50. #include "llvm/IR/InlineAsm.h"
  51. #include "llvm/IR/Instructions.h"
  52. #include "llvm/IR/IntrinsicInst.h"
  53. #include "llvm/IR/Intrinsics.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/Module.h"
  56. #include "llvm/IR/Statepoint.h"
  57. #include "llvm/MC/MCSymbol.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Debug.h"
  60. #include "llvm/Support/ErrorHandling.h"
  61. #include "llvm/Support/MathExtras.h"
  62. #include "llvm/Support/raw_ostream.h"
  63. #include "llvm/Target/TargetFrameLowering.h"
  64. #include "llvm/Target/TargetInstrInfo.h"
  65. #include "llvm/Target/TargetIntrinsicInfo.h"
  66. #include "llvm/Target/TargetLowering.h"
  67. #include "llvm/Target/TargetOptions.h"
  68. #include "llvm/Target/TargetSubtargetInfo.h"
  69. #include <algorithm>
  70. #include <utility>
  71. using namespace llvm;
  72. #define DEBUG_TYPE "isel"
  73. /// LimitFloatPrecision - Generate low-precision inline sequences for
  74. /// some float libcalls (6, 8 or 12 bits).
  75. static unsigned LimitFloatPrecision;
  76. static cl::opt<unsigned, true>
  77. LimitFPPrecision("limit-float-precision",
  78. cl::desc("Generate low-precision inline sequences "
  79. "for some float libcalls"),
  80. cl::location(LimitFloatPrecision),
  81. cl::init(0));
  82. // Limit the width of DAG chains. This is important in general to prevent
  83. // DAG-based analysis from blowing up. For example, alias analysis and
  84. // load clustering may not complete in reasonable time. It is difficult to
  85. // recognize and avoid this situation within each individual analysis, and
  86. // future analyses are likely to have the same behavior. Limiting DAG width is
  87. // the safe approach and will be especially important with global DAGs.
  88. //
  89. // MaxParallelChains default is arbitrarily high to avoid affecting
  90. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  91. // sequence over this should have been converted to llvm.memcpy by the
  92. // frontend. It is easy to induce this behavior with .ll code such as:
  93. // %buffer = alloca [4096 x i8]
  94. // %data = load [4096 x i8]* %argPtr
  95. // store [4096 x i8] %data, [4096 x i8]* %buffer
  96. static const unsigned MaxParallelChains = 64;
  97. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  98. const SDValue *Parts, unsigned NumParts,
  99. MVT PartVT, EVT ValueVT, const Value *V,
  100. bool IsABIRegCopy);
  101. /// getCopyFromParts - Create a value that contains the specified legal parts
  102. /// combined into the value they represent. If the parts combine to a type
  103. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  104. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  105. /// (ISD::AssertSext).
  106. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  107. const SDValue *Parts, unsigned NumParts,
  108. MVT PartVT, EVT ValueVT, const Value *V,
  109. Optional<ISD::NodeType> AssertOp = None,
  110. bool IsABIRegCopy = false) {
  111. if (ValueVT.isVector())
  112. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  113. PartVT, ValueVT, V, IsABIRegCopy);
  114. assert(NumParts > 0 && "No parts to assemble!");
  115. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  116. SDValue Val = Parts[0];
  117. if (NumParts > 1) {
  118. // Assemble the value from multiple parts.
  119. if (ValueVT.isInteger()) {
  120. unsigned PartBits = PartVT.getSizeInBits();
  121. unsigned ValueBits = ValueVT.getSizeInBits();
  122. // Assemble the power of 2 part.
  123. unsigned RoundParts = NumParts & (NumParts - 1) ?
  124. 1 << Log2_32(NumParts) : NumParts;
  125. unsigned RoundBits = PartBits * RoundParts;
  126. EVT RoundVT = RoundBits == ValueBits ?
  127. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  128. SDValue Lo, Hi;
  129. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  130. if (RoundParts > 2) {
  131. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  132. PartVT, HalfVT, V);
  133. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  134. RoundParts / 2, PartVT, HalfVT, V);
  135. } else {
  136. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  137. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  138. }
  139. if (DAG.getDataLayout().isBigEndian())
  140. std::swap(Lo, Hi);
  141. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  142. if (RoundParts < NumParts) {
  143. // Assemble the trailing non-power-of-2 part.
  144. unsigned OddParts = NumParts - RoundParts;
  145. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  146. Hi = getCopyFromParts(DAG, DL,
  147. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  148. // Combine the round and odd parts.
  149. Lo = Val;
  150. if (DAG.getDataLayout().isBigEndian())
  151. std::swap(Lo, Hi);
  152. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  153. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  154. Hi =
  155. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  156. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  157. TLI.getPointerTy(DAG.getDataLayout())));
  158. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  159. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  160. }
  161. } else if (PartVT.isFloatingPoint()) {
  162. // FP split into multiple FP parts (for ppcf128)
  163. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  164. "Unexpected split");
  165. SDValue Lo, Hi;
  166. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  167. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  168. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  169. std::swap(Lo, Hi);
  170. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  171. } else {
  172. // FP split into integer parts (soft fp)
  173. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  174. !PartVT.isVector() && "Unexpected split");
  175. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  176. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  177. }
  178. }
  179. // There is now one part, held in Val. Correct it to match ValueVT.
  180. // PartEVT is the type of the register class that holds the value.
  181. // ValueVT is the type of the inline asm operation.
  182. EVT PartEVT = Val.getValueType();
  183. if (PartEVT == ValueVT)
  184. return Val;
  185. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  186. ValueVT.bitsLT(PartEVT)) {
  187. // For an FP value in an integer part, we need to truncate to the right
  188. // width first.
  189. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  190. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  191. }
  192. // Handle types that have the same size.
  193. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  194. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  195. // Handle types with different sizes.
  196. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  197. if (ValueVT.bitsLT(PartEVT)) {
  198. // For a truncate, see if we have any information to
  199. // indicate whether the truncated bits will always be
  200. // zero or sign-extension.
  201. if (AssertOp.hasValue())
  202. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  203. DAG.getValueType(ValueVT));
  204. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  205. }
  206. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  207. }
  208. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  209. // FP_ROUND's are always exact here.
  210. if (ValueVT.bitsLT(Val.getValueType()))
  211. return DAG.getNode(
  212. ISD::FP_ROUND, DL, ValueVT, Val,
  213. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  214. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  215. }
  216. llvm_unreachable("Unknown mismatch!");
  217. }
  218. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  219. const Twine &ErrMsg) {
  220. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  221. if (!V)
  222. return Ctx.emitError(ErrMsg);
  223. const char *AsmError = ", possible invalid constraint for vector type";
  224. if (const CallInst *CI = dyn_cast<CallInst>(I))
  225. if (isa<InlineAsm>(CI->getCalledValue()))
  226. return Ctx.emitError(I, ErrMsg + AsmError);
  227. return Ctx.emitError(I, ErrMsg);
  228. }
  229. /// getCopyFromPartsVector - Create a value that contains the specified legal
  230. /// parts combined into the value they represent. If the parts combine to a
  231. /// type larger than ValueVT then AssertOp can be used to specify whether the
  232. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  233. /// ValueVT (ISD::AssertSext).
  234. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  235. const SDValue *Parts, unsigned NumParts,
  236. MVT PartVT, EVT ValueVT, const Value *V,
  237. bool IsABIRegCopy) {
  238. assert(ValueVT.isVector() && "Not a vector value");
  239. assert(NumParts > 0 && "No parts to assemble!");
  240. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  241. SDValue Val = Parts[0];
  242. // Handle a multi-element vector.
  243. if (NumParts > 1) {
  244. EVT IntermediateVT;
  245. MVT RegisterVT;
  246. unsigned NumIntermediates;
  247. unsigned NumRegs;
  248. if (IsABIRegCopy) {
  249. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  250. *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
  251. RegisterVT);
  252. } else {
  253. NumRegs =
  254. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  255. NumIntermediates, RegisterVT);
  256. }
  257. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  258. NumParts = NumRegs; // Silence a compiler warning.
  259. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  260. assert(RegisterVT.getSizeInBits() ==
  261. Parts[0].getSimpleValueType().getSizeInBits() &&
  262. "Part type sizes don't match!");
  263. // Assemble the parts into intermediate operands.
  264. SmallVector<SDValue, 8> Ops(NumIntermediates);
  265. if (NumIntermediates == NumParts) {
  266. // If the register was not expanded, truncate or copy the value,
  267. // as appropriate.
  268. for (unsigned i = 0; i != NumParts; ++i)
  269. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  270. PartVT, IntermediateVT, V);
  271. } else if (NumParts > 0) {
  272. // If the intermediate type was expanded, build the intermediate
  273. // operands from the parts.
  274. assert(NumParts % NumIntermediates == 0 &&
  275. "Must expand into a divisible number of parts!");
  276. unsigned Factor = NumParts / NumIntermediates;
  277. for (unsigned i = 0; i != NumIntermediates; ++i)
  278. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  279. PartVT, IntermediateVT, V);
  280. }
  281. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  282. // intermediate operands.
  283. EVT BuiltVectorTy =
  284. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  285. (IntermediateVT.isVector()
  286. ? IntermediateVT.getVectorNumElements() * NumParts
  287. : NumIntermediates));
  288. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  289. : ISD::BUILD_VECTOR,
  290. DL, BuiltVectorTy, Ops);
  291. }
  292. // There is now one part, held in Val. Correct it to match ValueVT.
  293. EVT PartEVT = Val.getValueType();
  294. if (PartEVT == ValueVT)
  295. return Val;
  296. if (PartEVT.isVector()) {
  297. // If the element type of the source/dest vectors are the same, but the
  298. // parts vector has more elements than the value vector, then we have a
  299. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  300. // elements we want.
  301. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  302. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  303. "Cannot narrow, it would be a lossy transformation");
  304. return DAG.getNode(
  305. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  306. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  307. }
  308. // Vector/Vector bitcast.
  309. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  310. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  311. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  312. "Cannot handle this kind of promotion");
  313. // Promoted vector extract
  314. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  315. }
  316. // Trivial bitcast if the types are the same size and the destination
  317. // vector type is legal.
  318. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  319. TLI.isTypeLegal(ValueVT))
  320. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  321. if (ValueVT.getVectorNumElements() != 1) {
  322. // Certain ABIs require that vectors are passed as integers. For vectors
  323. // are the same size, this is an obvious bitcast.
  324. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  325. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  326. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  327. // Bitcast Val back the original type and extract the corresponding
  328. // vector we want.
  329. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  330. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  331. ValueVT.getVectorElementType(), Elts);
  332. Val = DAG.getBitcast(WiderVecType, Val);
  333. return DAG.getNode(
  334. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  335. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  336. }
  337. diagnosePossiblyInvalidConstraint(
  338. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  339. return DAG.getUNDEF(ValueVT);
  340. }
  341. // Handle cases such as i8 -> <1 x i1>
  342. EVT ValueSVT = ValueVT.getVectorElementType();
  343. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  344. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  345. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  346. return DAG.getBuildVector(ValueVT, DL, Val);
  347. }
  348. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  349. SDValue Val, SDValue *Parts, unsigned NumParts,
  350. MVT PartVT, const Value *V, bool IsABIRegCopy);
  351. /// getCopyToParts - Create a series of nodes that contain the specified value
  352. /// split into legal parts. If the parts contain more bits than Val, then, for
  353. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  354. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  355. SDValue *Parts, unsigned NumParts, MVT PartVT,
  356. const Value *V,
  357. ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
  358. bool IsABIRegCopy = false) {
  359. EVT ValueVT = Val.getValueType();
  360. // Handle the vector case separately.
  361. if (ValueVT.isVector())
  362. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  363. IsABIRegCopy);
  364. unsigned PartBits = PartVT.getSizeInBits();
  365. unsigned OrigNumParts = NumParts;
  366. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  367. "Copying to an illegal type!");
  368. if (NumParts == 0)
  369. return;
  370. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  371. EVT PartEVT = PartVT;
  372. if (PartEVT == ValueVT) {
  373. assert(NumParts == 1 && "No-op copy with multiple parts!");
  374. Parts[0] = Val;
  375. return;
  376. }
  377. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  378. // If the parts cover more bits than the value has, promote the value.
  379. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  380. assert(NumParts == 1 && "Do not know what to promote to!");
  381. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  382. } else {
  383. if (ValueVT.isFloatingPoint()) {
  384. // FP values need to be bitcast, then extended if they are being put
  385. // into a larger container.
  386. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  387. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  388. }
  389. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  390. ValueVT.isInteger() &&
  391. "Unknown mismatch!");
  392. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  393. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  394. if (PartVT == MVT::x86mmx)
  395. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  396. }
  397. } else if (PartBits == ValueVT.getSizeInBits()) {
  398. // Different types of the same size.
  399. assert(NumParts == 1 && PartEVT != ValueVT);
  400. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  401. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  402. // If the parts cover less bits than value has, truncate the value.
  403. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  404. ValueVT.isInteger() &&
  405. "Unknown mismatch!");
  406. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  407. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  408. if (PartVT == MVT::x86mmx)
  409. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  410. }
  411. // The value may have changed - recompute ValueVT.
  412. ValueVT = Val.getValueType();
  413. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  414. "Failed to tile the value with PartVT!");
  415. if (NumParts == 1) {
  416. if (PartEVT != ValueVT) {
  417. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  418. "scalar-to-vector conversion failed");
  419. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  420. }
  421. Parts[0] = Val;
  422. return;
  423. }
  424. // Expand the value into multiple parts.
  425. if (NumParts & (NumParts - 1)) {
  426. // The number of parts is not a power of 2. Split off and copy the tail.
  427. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  428. "Do not know what to expand to!");
  429. unsigned RoundParts = 1 << Log2_32(NumParts);
  430. unsigned RoundBits = RoundParts * PartBits;
  431. unsigned OddParts = NumParts - RoundParts;
  432. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  433. DAG.getIntPtrConstant(RoundBits, DL));
  434. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  435. if (DAG.getDataLayout().isBigEndian())
  436. // The odd parts were reversed by getCopyToParts - unreverse them.
  437. std::reverse(Parts + RoundParts, Parts + NumParts);
  438. NumParts = RoundParts;
  439. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  440. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  441. }
  442. // The number of parts is a power of 2. Repeatedly bisect the value using
  443. // EXTRACT_ELEMENT.
  444. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  445. EVT::getIntegerVT(*DAG.getContext(),
  446. ValueVT.getSizeInBits()),
  447. Val);
  448. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  449. for (unsigned i = 0; i < NumParts; i += StepSize) {
  450. unsigned ThisBits = StepSize * PartBits / 2;
  451. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  452. SDValue &Part0 = Parts[i];
  453. SDValue &Part1 = Parts[i+StepSize/2];
  454. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  455. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  456. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  457. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  458. if (ThisBits == PartBits && ThisVT != PartVT) {
  459. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  460. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  461. }
  462. }
  463. }
  464. if (DAG.getDataLayout().isBigEndian())
  465. std::reverse(Parts, Parts + OrigNumParts);
  466. }
  467. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  468. /// value split into legal parts.
  469. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  470. SDValue Val, SDValue *Parts, unsigned NumParts,
  471. MVT PartVT, const Value *V,
  472. bool IsABIRegCopy) {
  473. EVT ValueVT = Val.getValueType();
  474. assert(ValueVT.isVector() && "Not a vector");
  475. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  476. if (NumParts == 1) {
  477. EVT PartEVT = PartVT;
  478. if (PartEVT == ValueVT) {
  479. // Nothing to do.
  480. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  481. // Bitconvert vector->vector case.
  482. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  483. } else if (PartVT.isVector() &&
  484. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  485. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  486. EVT ElementVT = PartVT.getVectorElementType();
  487. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  488. // undef elements.
  489. SmallVector<SDValue, 16> Ops;
  490. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  491. Ops.push_back(DAG.getNode(
  492. ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
  493. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
  494. for (unsigned i = ValueVT.getVectorNumElements(),
  495. e = PartVT.getVectorNumElements(); i != e; ++i)
  496. Ops.push_back(DAG.getUNDEF(ElementVT));
  497. Val = DAG.getBuildVector(PartVT, DL, Ops);
  498. // FIXME: Use CONCAT for 2x -> 4x.
  499. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  500. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  501. } else if (PartVT.isVector() &&
  502. PartEVT.getVectorElementType().bitsGE(
  503. ValueVT.getVectorElementType()) &&
  504. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  505. // Promoted vector extract
  506. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  507. } else {
  508. if (ValueVT.getVectorNumElements() == 1) {
  509. Val = DAG.getNode(
  510. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  511. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  512. } else {
  513. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  514. "lossy conversion of vector to scalar type");
  515. EVT IntermediateType =
  516. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  517. Val = DAG.getBitcast(IntermediateType, Val);
  518. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  519. }
  520. }
  521. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  522. Parts[0] = Val;
  523. return;
  524. }
  525. // Handle a multi-element vector.
  526. EVT IntermediateVT;
  527. MVT RegisterVT;
  528. unsigned NumIntermediates;
  529. unsigned NumRegs;
  530. if (IsABIRegCopy) {
  531. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  532. *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
  533. RegisterVT);
  534. } else {
  535. NumRegs =
  536. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  537. NumIntermediates, RegisterVT);
  538. }
  539. unsigned NumElements = ValueVT.getVectorNumElements();
  540. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  541. NumParts = NumRegs; // Silence a compiler warning.
  542. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  543. // Convert the vector to the appropiate type if necessary.
  544. unsigned DestVectorNoElts =
  545. NumIntermediates *
  546. (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
  547. EVT BuiltVectorTy = EVT::getVectorVT(
  548. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  549. if (Val.getValueType() != BuiltVectorTy)
  550. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  551. // Split the vector into intermediate operands.
  552. SmallVector<SDValue, 8> Ops(NumIntermediates);
  553. for (unsigned i = 0; i != NumIntermediates; ++i) {
  554. if (IntermediateVT.isVector())
  555. Ops[i] =
  556. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  557. DAG.getConstant(i * (NumElements / NumIntermediates), DL,
  558. TLI.getVectorIdxTy(DAG.getDataLayout())));
  559. else
  560. Ops[i] = DAG.getNode(
  561. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  562. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  563. }
  564. // Split the intermediate operands into legal parts.
  565. if (NumParts == NumIntermediates) {
  566. // If the register was not expanded, promote or copy the value,
  567. // as appropriate.
  568. for (unsigned i = 0; i != NumParts; ++i)
  569. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  570. } else if (NumParts > 0) {
  571. // If the intermediate type was expanded, split each the value into
  572. // legal parts.
  573. assert(NumIntermediates != 0 && "division by zero");
  574. assert(NumParts % NumIntermediates == 0 &&
  575. "Must expand into a divisible number of parts!");
  576. unsigned Factor = NumParts / NumIntermediates;
  577. for (unsigned i = 0; i != NumIntermediates; ++i)
  578. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  579. }
  580. }
  581. RegsForValue::RegsForValue() { IsABIMangled = false; }
  582. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  583. EVT valuevt, bool IsABIMangledValue)
  584. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  585. RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
  586. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  587. const DataLayout &DL, unsigned Reg, Type *Ty,
  588. bool IsABIMangledValue) {
  589. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  590. IsABIMangled = IsABIMangledValue;
  591. for (EVT ValueVT : ValueVTs) {
  592. unsigned NumRegs = IsABIMangledValue
  593. ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
  594. : TLI.getNumRegisters(Context, ValueVT);
  595. MVT RegisterVT = IsABIMangledValue
  596. ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
  597. : TLI.getRegisterType(Context, ValueVT);
  598. for (unsigned i = 0; i != NumRegs; ++i)
  599. Regs.push_back(Reg + i);
  600. RegVTs.push_back(RegisterVT);
  601. RegCount.push_back(NumRegs);
  602. Reg += NumRegs;
  603. }
  604. }
  605. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  606. FunctionLoweringInfo &FuncInfo,
  607. const SDLoc &dl, SDValue &Chain,
  608. SDValue *Flag, const Value *V) const {
  609. // A Value with type {} or [0 x %t] needs no registers.
  610. if (ValueVTs.empty())
  611. return SDValue();
  612. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  613. // Assemble the legal parts into the final values.
  614. SmallVector<SDValue, 4> Values(ValueVTs.size());
  615. SmallVector<SDValue, 8> Parts;
  616. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  617. // Copy the legal parts from the registers.
  618. EVT ValueVT = ValueVTs[Value];
  619. unsigned NumRegs = RegCount[Value];
  620. MVT RegisterVT = IsABIMangled
  621. ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
  622. : RegVTs[Value];
  623. Parts.resize(NumRegs);
  624. for (unsigned i = 0; i != NumRegs; ++i) {
  625. SDValue P;
  626. if (!Flag) {
  627. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  628. } else {
  629. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  630. *Flag = P.getValue(2);
  631. }
  632. Chain = P.getValue(1);
  633. Parts[i] = P;
  634. // If the source register was virtual and if we know something about it,
  635. // add an assert node.
  636. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  637. !RegisterVT.isInteger() || RegisterVT.isVector())
  638. continue;
  639. const FunctionLoweringInfo::LiveOutInfo *LOI =
  640. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  641. if (!LOI)
  642. continue;
  643. unsigned RegSize = RegisterVT.getSizeInBits();
  644. unsigned NumSignBits = LOI->NumSignBits;
  645. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  646. if (NumZeroBits == RegSize) {
  647. // The current value is a zero.
  648. // Explicitly express that as it would be easier for
  649. // optimizations to kick in.
  650. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  651. continue;
  652. }
  653. // FIXME: We capture more information than the dag can represent. For
  654. // now, just use the tightest assertzext/assertsext possible.
  655. bool isSExt = true;
  656. EVT FromVT(MVT::Other);
  657. if (NumSignBits == RegSize) {
  658. isSExt = true; // ASSERT SEXT 1
  659. FromVT = MVT::i1;
  660. } else if (NumZeroBits >= RegSize - 1) {
  661. isSExt = false; // ASSERT ZEXT 1
  662. FromVT = MVT::i1;
  663. } else if (NumSignBits > RegSize - 8) {
  664. isSExt = true; // ASSERT SEXT 8
  665. FromVT = MVT::i8;
  666. } else if (NumZeroBits >= RegSize - 8) {
  667. isSExt = false; // ASSERT ZEXT 8
  668. FromVT = MVT::i8;
  669. } else if (NumSignBits > RegSize - 16) {
  670. isSExt = true; // ASSERT SEXT 16
  671. FromVT = MVT::i16;
  672. } else if (NumZeroBits >= RegSize - 16) {
  673. isSExt = false; // ASSERT ZEXT 16
  674. FromVT = MVT::i16;
  675. } else if (NumSignBits > RegSize - 32) {
  676. isSExt = true; // ASSERT SEXT 32
  677. FromVT = MVT::i32;
  678. } else if (NumZeroBits >= RegSize - 32) {
  679. isSExt = false; // ASSERT ZEXT 32
  680. FromVT = MVT::i32;
  681. } else {
  682. continue;
  683. }
  684. // Add an assertion node.
  685. assert(FromVT != MVT::Other);
  686. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  687. RegisterVT, P, DAG.getValueType(FromVT));
  688. }
  689. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  690. NumRegs, RegisterVT, ValueVT, V);
  691. Part += NumRegs;
  692. Parts.clear();
  693. }
  694. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  695. }
  696. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  697. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  698. const Value *V,
  699. ISD::NodeType PreferredExtendType) const {
  700. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  701. ISD::NodeType ExtendKind = PreferredExtendType;
  702. // Get the list of the values's legal parts.
  703. unsigned NumRegs = Regs.size();
  704. SmallVector<SDValue, 8> Parts(NumRegs);
  705. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  706. unsigned NumParts = RegCount[Value];
  707. MVT RegisterVT = IsABIMangled
  708. ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
  709. : RegVTs[Value];
  710. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  711. ExtendKind = ISD::ZERO_EXTEND;
  712. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  713. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  714. Part += NumParts;
  715. }
  716. // Copy the parts into the registers.
  717. SmallVector<SDValue, 8> Chains(NumRegs);
  718. for (unsigned i = 0; i != NumRegs; ++i) {
  719. SDValue Part;
  720. if (!Flag) {
  721. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  722. } else {
  723. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  724. *Flag = Part.getValue(1);
  725. }
  726. Chains[i] = Part.getValue(0);
  727. }
  728. if (NumRegs == 1 || Flag)
  729. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  730. // flagged to it. That is the CopyToReg nodes and the user are considered
  731. // a single scheduling unit. If we create a TokenFactor and return it as
  732. // chain, then the TokenFactor is both a predecessor (operand) of the
  733. // user as well as a successor (the TF operands are flagged to the user).
  734. // c1, f1 = CopyToReg
  735. // c2, f2 = CopyToReg
  736. // c3 = TokenFactor c1, c2
  737. // ...
  738. // = op c3, ..., f2
  739. Chain = Chains[NumRegs-1];
  740. else
  741. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  742. }
  743. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  744. unsigned MatchingIdx, const SDLoc &dl,
  745. SelectionDAG &DAG,
  746. std::vector<SDValue> &Ops) const {
  747. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  748. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  749. if (HasMatching)
  750. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  751. else if (!Regs.empty() &&
  752. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  753. // Put the register class of the virtual registers in the flag word. That
  754. // way, later passes can recompute register class constraints for inline
  755. // assembly as well as normal instructions.
  756. // Don't do this for tied operands that can use the regclass information
  757. // from the def.
  758. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  759. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  760. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  761. }
  762. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  763. Ops.push_back(Res);
  764. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  765. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  766. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  767. MVT RegisterVT = RegVTs[Value];
  768. for (unsigned i = 0; i != NumRegs; ++i) {
  769. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  770. unsigned TheReg = Regs[Reg++];
  771. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  772. if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
  773. // If we clobbered the stack pointer, MFI should know about it.
  774. assert(DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment());
  775. }
  776. }
  777. }
  778. }
  779. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  780. const TargetLibraryInfo *li) {
  781. AA = aa;
  782. GFI = gfi;
  783. LibInfo = li;
  784. DL = &DAG.getDataLayout();
  785. Context = DAG.getContext();
  786. LPadToCallSiteMap.clear();
  787. }
  788. void SelectionDAGBuilder::clear() {
  789. NodeMap.clear();
  790. UnusedArgNodeMap.clear();
  791. PendingLoads.clear();
  792. PendingExports.clear();
  793. CurInst = nullptr;
  794. HasTailCall = false;
  795. SDNodeOrder = LowestSDNodeOrder;
  796. StatepointLowering.clear();
  797. }
  798. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  799. DanglingDebugInfoMap.clear();
  800. }
  801. SDValue SelectionDAGBuilder::getRoot() {
  802. if (PendingLoads.empty())
  803. return DAG.getRoot();
  804. if (PendingLoads.size() == 1) {
  805. SDValue Root = PendingLoads[0];
  806. DAG.setRoot(Root);
  807. PendingLoads.clear();
  808. return Root;
  809. }
  810. // Otherwise, we have to make a token factor node.
  811. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  812. PendingLoads);
  813. PendingLoads.clear();
  814. DAG.setRoot(Root);
  815. return Root;
  816. }
  817. SDValue SelectionDAGBuilder::getControlRoot() {
  818. SDValue Root = DAG.getRoot();
  819. if (PendingExports.empty())
  820. return Root;
  821. // Turn all of the CopyToReg chains into one factored node.
  822. if (Root.getOpcode() != ISD::EntryToken) {
  823. unsigned i = 0, e = PendingExports.size();
  824. for (; i != e; ++i) {
  825. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  826. if (PendingExports[i].getNode()->getOperand(0) == Root)
  827. break; // Don't add the root if we already indirectly depend on it.
  828. }
  829. if (i == e)
  830. PendingExports.push_back(Root);
  831. }
  832. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  833. PendingExports);
  834. PendingExports.clear();
  835. DAG.setRoot(Root);
  836. return Root;
  837. }
  838. void SelectionDAGBuilder::visit(const Instruction &I) {
  839. // Set up outgoing PHI node register values before emitting the terminator.
  840. if (isa<TerminatorInst>(&I)) {
  841. HandlePHINodesInSuccessorBlocks(I.getParent());
  842. }
  843. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  844. if (!isa<DbgInfoIntrinsic>(I))
  845. ++SDNodeOrder;
  846. CurInst = &I;
  847. visit(I.getOpcode(), I);
  848. if (!isa<TerminatorInst>(&I) && !HasTailCall &&
  849. !isStatepoint(&I)) // statepoints handle their exports internally
  850. CopyToExportRegsIfNeeded(&I);
  851. CurInst = nullptr;
  852. }
  853. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  854. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  855. }
  856. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  857. // Note: this doesn't use InstVisitor, because it has to work with
  858. // ConstantExpr's in addition to instructions.
  859. switch (Opcode) {
  860. default: llvm_unreachable("Unknown instruction type encountered!");
  861. // Build the switch statement using the Instruction.def file.
  862. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  863. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  864. #include "llvm/IR/Instruction.def"
  865. }
  866. }
  867. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  868. // generate the debug data structures now that we've seen its definition.
  869. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  870. SDValue Val) {
  871. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  872. if (DDI.getDI()) {
  873. const DbgValueInst *DI = DDI.getDI();
  874. DebugLoc dl = DDI.getdl();
  875. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  876. DILocalVariable *Variable = DI->getVariable();
  877. DIExpression *Expr = DI->getExpression();
  878. assert(Variable->isValidLocationForIntrinsic(dl) &&
  879. "Expected inlined-at fields to agree");
  880. uint64_t Offset = 0;
  881. SDDbgValue *SDV;
  882. if (Val.getNode()) {
  883. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, false,
  884. Val)) {
  885. SDV = getDbgValue(Val, Variable, Expr, Offset, dl, DbgSDNodeOrder);
  886. DAG.AddDbgValue(SDV, Val.getNode(), false);
  887. }
  888. } else
  889. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  890. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  891. }
  892. }
  893. /// getCopyFromRegs - If there was virtual register allocated for the value V
  894. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  895. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  896. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  897. SDValue Result;
  898. if (It != FuncInfo.ValueMap.end()) {
  899. unsigned InReg = It->second;
  900. bool IsABIRegCopy =
  901. V && ((isa<CallInst>(V) &&
  902. !(static_cast<const CallInst *>(V))->isInlineAsm()) ||
  903. isa<ReturnInst>(V));
  904. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  905. DAG.getDataLayout(), InReg, Ty, IsABIRegCopy);
  906. SDValue Chain = DAG.getEntryNode();
  907. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  908. V);
  909. resolveDanglingDebugInfo(V, Result);
  910. }
  911. return Result;
  912. }
  913. /// getValue - Return an SDValue for the given Value.
  914. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  915. // If we already have an SDValue for this value, use it. It's important
  916. // to do this first, so that we don't create a CopyFromReg if we already
  917. // have a regular SDValue.
  918. SDValue &N = NodeMap[V];
  919. if (N.getNode()) return N;
  920. // If there's a virtual register allocated and initialized for this
  921. // value, use it.
  922. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  923. return copyFromReg;
  924. // Otherwise create a new SDValue and remember it.
  925. SDValue Val = getValueImpl(V);
  926. NodeMap[V] = Val;
  927. resolveDanglingDebugInfo(V, Val);
  928. return Val;
  929. }
  930. // Return true if SDValue exists for the given Value
  931. bool SelectionDAGBuilder::findValue(const Value *V) const {
  932. return (NodeMap.find(V) != NodeMap.end()) ||
  933. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  934. }
  935. /// getNonRegisterValue - Return an SDValue for the given Value, but
  936. /// don't look in FuncInfo.ValueMap for a virtual register.
  937. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  938. // If we already have an SDValue for this value, use it.
  939. SDValue &N = NodeMap[V];
  940. if (N.getNode()) {
  941. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  942. // Remove the debug location from the node as the node is about to be used
  943. // in a location which may differ from the original debug location. This
  944. // is relevant to Constant and ConstantFP nodes because they can appear
  945. // as constant expressions inside PHI nodes.
  946. N->setDebugLoc(DebugLoc());
  947. }
  948. return N;
  949. }
  950. // Otherwise create a new SDValue and remember it.
  951. SDValue Val = getValueImpl(V);
  952. NodeMap[V] = Val;
  953. resolveDanglingDebugInfo(V, Val);
  954. return Val;
  955. }
  956. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  957. /// Create an SDValue for the given value.
  958. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  959. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  960. if (const Constant *C = dyn_cast<Constant>(V)) {
  961. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  962. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  963. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  964. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  965. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  966. if (isa<ConstantPointerNull>(C)) {
  967. unsigned AS = V->getType()->getPointerAddressSpace();
  968. return DAG.getConstant(0, getCurSDLoc(),
  969. TLI.getPointerTy(DAG.getDataLayout(), AS));
  970. }
  971. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  972. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  973. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  974. return DAG.getUNDEF(VT);
  975. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  976. visit(CE->getOpcode(), *CE);
  977. SDValue N1 = NodeMap[V];
  978. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  979. return N1;
  980. }
  981. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  982. SmallVector<SDValue, 4> Constants;
  983. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  984. OI != OE; ++OI) {
  985. SDNode *Val = getValue(*OI).getNode();
  986. // If the operand is an empty aggregate, there are no values.
  987. if (!Val) continue;
  988. // Add each leaf value from the operand to the Constants list
  989. // to form a flattened list of all the values.
  990. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  991. Constants.push_back(SDValue(Val, i));
  992. }
  993. return DAG.getMergeValues(Constants, getCurSDLoc());
  994. }
  995. if (const ConstantDataSequential *CDS =
  996. dyn_cast<ConstantDataSequential>(C)) {
  997. SmallVector<SDValue, 4> Ops;
  998. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  999. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1000. // Add each leaf value from the operand to the Constants list
  1001. // to form a flattened list of all the values.
  1002. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1003. Ops.push_back(SDValue(Val, i));
  1004. }
  1005. if (isa<ArrayType>(CDS->getType()))
  1006. return DAG.getMergeValues(Ops, getCurSDLoc());
  1007. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1008. }
  1009. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1010. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1011. "Unknown struct or array constant!");
  1012. SmallVector<EVT, 4> ValueVTs;
  1013. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1014. unsigned NumElts = ValueVTs.size();
  1015. if (NumElts == 0)
  1016. return SDValue(); // empty struct
  1017. SmallVector<SDValue, 4> Constants(NumElts);
  1018. for (unsigned i = 0; i != NumElts; ++i) {
  1019. EVT EltVT = ValueVTs[i];
  1020. if (isa<UndefValue>(C))
  1021. Constants[i] = DAG.getUNDEF(EltVT);
  1022. else if (EltVT.isFloatingPoint())
  1023. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1024. else
  1025. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1026. }
  1027. return DAG.getMergeValues(Constants, getCurSDLoc());
  1028. }
  1029. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1030. return DAG.getBlockAddress(BA, VT);
  1031. VectorType *VecTy = cast<VectorType>(V->getType());
  1032. unsigned NumElements = VecTy->getNumElements();
  1033. // Now that we know the number and type of the elements, get that number of
  1034. // elements into the Ops array based on what kind of constant it is.
  1035. SmallVector<SDValue, 16> Ops;
  1036. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1037. for (unsigned i = 0; i != NumElements; ++i)
  1038. Ops.push_back(getValue(CV->getOperand(i)));
  1039. } else {
  1040. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1041. EVT EltVT =
  1042. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1043. SDValue Op;
  1044. if (EltVT.isFloatingPoint())
  1045. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1046. else
  1047. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1048. Ops.assign(NumElements, Op);
  1049. }
  1050. // Create a BUILD_VECTOR node.
  1051. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1052. }
  1053. // If this is a static alloca, generate it as the frameindex instead of
  1054. // computation.
  1055. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1056. DenseMap<const AllocaInst*, int>::iterator SI =
  1057. FuncInfo.StaticAllocaMap.find(AI);
  1058. if (SI != FuncInfo.StaticAllocaMap.end())
  1059. return DAG.getFrameIndex(SI->second,
  1060. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1061. }
  1062. // If this is an instruction which fast-isel has deferred, select it now.
  1063. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1064. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1065. bool IsABIRegCopy =
  1066. V && ((isa<CallInst>(V) &&
  1067. !(static_cast<const CallInst *>(V))->isInlineAsm()) ||
  1068. isa<ReturnInst>(V));
  1069. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1070. Inst->getType(), IsABIRegCopy);
  1071. SDValue Chain = DAG.getEntryNode();
  1072. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1073. }
  1074. llvm_unreachable("Can't get register for value!");
  1075. }
  1076. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1077. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1078. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1079. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1080. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1081. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1082. if (IsMSVCCXX || IsCoreCLR)
  1083. CatchPadMBB->setIsEHFuncletEntry();
  1084. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
  1085. }
  1086. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1087. // Update machine-CFG edge.
  1088. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1089. FuncInfo.MBB->addSuccessor(TargetMBB);
  1090. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1091. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1092. if (IsSEH) {
  1093. // If this is not a fall-through branch or optimizations are switched off,
  1094. // emit the branch.
  1095. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1096. TM.getOptLevel() == CodeGenOpt::None)
  1097. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1098. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1099. return;
  1100. }
  1101. // Figure out the funclet membership for the catchret's successor.
  1102. // This will be used by the FuncletLayout pass to determine how to order the
  1103. // BB's.
  1104. // A 'catchret' returns to the outer scope's color.
  1105. Value *ParentPad = I.getCatchSwitchParentPad();
  1106. const BasicBlock *SuccessorColor;
  1107. if (isa<ConstantTokenNone>(ParentPad))
  1108. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1109. else
  1110. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1111. assert(SuccessorColor && "No parent funclet for catchret!");
  1112. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1113. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1114. // Create the terminator node.
  1115. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1116. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1117. DAG.getBasicBlock(SuccessorColorMBB));
  1118. DAG.setRoot(Ret);
  1119. }
  1120. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1121. // Don't emit any special code for the cleanuppad instruction. It just marks
  1122. // the start of a funclet.
  1123. FuncInfo.MBB->setIsEHFuncletEntry();
  1124. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1125. }
  1126. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1127. /// many places it could ultimately go. In the IR, we have a single unwind
  1128. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1129. /// This function skips over imaginary basic blocks that hold catchswitch
  1130. /// instructions, and finds all the "real" machine
  1131. /// basic block destinations. As those destinations may not be successors of
  1132. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1133. /// The passed-in Prob is the edge probability to EHPadBB.
  1134. static void findUnwindDestinations(
  1135. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1136. BranchProbability Prob,
  1137. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1138. &UnwindDests) {
  1139. EHPersonality Personality =
  1140. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1141. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1142. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1143. while (EHPadBB) {
  1144. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1145. BasicBlock *NewEHPadBB = nullptr;
  1146. if (isa<LandingPadInst>(Pad)) {
  1147. // Stop on landingpads. They are not funclets.
  1148. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1149. break;
  1150. } else if (isa<CleanupPadInst>(Pad)) {
  1151. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1152. // personalities.
  1153. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1154. UnwindDests.back().first->setIsEHFuncletEntry();
  1155. break;
  1156. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1157. // Add the catchpad handlers to the possible destinations.
  1158. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1159. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1160. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1161. if (IsMSVCCXX || IsCoreCLR)
  1162. UnwindDests.back().first->setIsEHFuncletEntry();
  1163. }
  1164. NewEHPadBB = CatchSwitch->getUnwindDest();
  1165. } else {
  1166. continue;
  1167. }
  1168. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1169. if (BPI && NewEHPadBB)
  1170. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1171. EHPadBB = NewEHPadBB;
  1172. }
  1173. }
  1174. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1175. // Update successor info.
  1176. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1177. auto UnwindDest = I.getUnwindDest();
  1178. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1179. BranchProbability UnwindDestProb =
  1180. (BPI && UnwindDest)
  1181. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1182. : BranchProbability::getZero();
  1183. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1184. for (auto &UnwindDest : UnwindDests) {
  1185. UnwindDest.first->setIsEHPad();
  1186. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1187. }
  1188. FuncInfo.MBB->normalizeSuccProbs();
  1189. // Create the terminator node.
  1190. SDValue Ret =
  1191. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1192. DAG.setRoot(Ret);
  1193. }
  1194. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1195. report_fatal_error("visitCatchSwitch not yet implemented!");
  1196. }
  1197. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1198. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1199. auto &DL = DAG.getDataLayout();
  1200. SDValue Chain = getControlRoot();
  1201. SmallVector<ISD::OutputArg, 8> Outs;
  1202. SmallVector<SDValue, 8> OutVals;
  1203. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1204. // lower
  1205. //
  1206. // %val = call <ty> @llvm.experimental.deoptimize()
  1207. // ret <ty> %val
  1208. //
  1209. // differently.
  1210. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1211. LowerDeoptimizingReturn();
  1212. return;
  1213. }
  1214. if (!FuncInfo.CanLowerReturn) {
  1215. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1216. const Function *F = I.getParent()->getParent();
  1217. // Emit a store of the return value through the virtual register.
  1218. // Leave Outs empty so that LowerReturn won't try to load return
  1219. // registers the usual way.
  1220. SmallVector<EVT, 1> PtrValueVTs;
  1221. ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
  1222. PtrValueVTs);
  1223. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1224. DemoteReg, PtrValueVTs[0]);
  1225. SDValue RetOp = getValue(I.getOperand(0));
  1226. SmallVector<EVT, 4> ValueVTs;
  1227. SmallVector<uint64_t, 4> Offsets;
  1228. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1229. unsigned NumValues = ValueVTs.size();
  1230. // An aggregate return value cannot wrap around the address space, so
  1231. // offsets to its parts don't wrap either.
  1232. SDNodeFlags Flags;
  1233. Flags.setNoUnsignedWrap(true);
  1234. SmallVector<SDValue, 4> Chains(NumValues);
  1235. for (unsigned i = 0; i != NumValues; ++i) {
  1236. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
  1237. RetPtr.getValueType(), RetPtr,
  1238. DAG.getIntPtrConstant(Offsets[i],
  1239. getCurSDLoc()),
  1240. Flags);
  1241. Chains[i] = DAG.getStore(Chain, getCurSDLoc(),
  1242. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1243. // FIXME: better loc info would be nice.
  1244. Add, MachinePointerInfo());
  1245. }
  1246. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1247. MVT::Other, Chains);
  1248. } else if (I.getNumOperands() != 0) {
  1249. SmallVector<EVT, 4> ValueVTs;
  1250. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1251. unsigned NumValues = ValueVTs.size();
  1252. if (NumValues) {
  1253. SDValue RetOp = getValue(I.getOperand(0));
  1254. const Function *F = I.getParent()->getParent();
  1255. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1256. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1257. Attribute::SExt))
  1258. ExtendKind = ISD::SIGN_EXTEND;
  1259. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1260. Attribute::ZExt))
  1261. ExtendKind = ISD::ZERO_EXTEND;
  1262. LLVMContext &Context = F->getContext();
  1263. bool RetInReg = F->getAttributes().hasAttribute(
  1264. AttributeList::ReturnIndex, Attribute::InReg);
  1265. for (unsigned j = 0; j != NumValues; ++j) {
  1266. EVT VT = ValueVTs[j];
  1267. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1268. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1269. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
  1270. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
  1271. SmallVector<SDValue, 4> Parts(NumParts);
  1272. getCopyToParts(DAG, getCurSDLoc(),
  1273. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1274. &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
  1275. // 'inreg' on function refers to return value
  1276. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1277. if (RetInReg)
  1278. Flags.setInReg();
  1279. // Propagate extension type if any
  1280. if (ExtendKind == ISD::SIGN_EXTEND)
  1281. Flags.setSExt();
  1282. else if (ExtendKind == ISD::ZERO_EXTEND)
  1283. Flags.setZExt();
  1284. for (unsigned i = 0; i < NumParts; ++i) {
  1285. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1286. VT, /*isfixed=*/true, 0, 0));
  1287. OutVals.push_back(Parts[i]);
  1288. }
  1289. }
  1290. }
  1291. }
  1292. // Push in swifterror virtual register as the last element of Outs. This makes
  1293. // sure swifterror virtual register will be returned in the swifterror
  1294. // physical register.
  1295. const Function *F = I.getParent()->getParent();
  1296. if (TLI.supportSwiftError() &&
  1297. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1298. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1299. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1300. Flags.setSwiftError();
  1301. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1302. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1303. true /*isfixed*/, 1 /*origidx*/,
  1304. 0 /*partOffs*/));
  1305. // Create SDNode for the swifterror virtual register.
  1306. OutVals.push_back(
  1307. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
  1308. &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
  1309. EVT(TLI.getPointerTy(DL))));
  1310. }
  1311. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1312. CallingConv::ID CallConv =
  1313. DAG.getMachineFunction().getFunction()->getCallingConv();
  1314. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1315. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1316. // Verify that the target's LowerReturn behaved as expected.
  1317. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1318. "LowerReturn didn't return a valid chain!");
  1319. // Update the DAG with the new chain value resulting from return lowering.
  1320. DAG.setRoot(Chain);
  1321. }
  1322. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1323. /// created for it, emit nodes to copy the value into the virtual
  1324. /// registers.
  1325. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1326. // Skip empty types
  1327. if (V->getType()->isEmptyTy())
  1328. return;
  1329. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1330. if (VMI != FuncInfo.ValueMap.end()) {
  1331. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1332. CopyValueToVirtualRegister(V, VMI->second);
  1333. }
  1334. }
  1335. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1336. /// the current basic block, add it to ValueMap now so that we'll get a
  1337. /// CopyTo/FromReg.
  1338. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1339. // No need to export constants.
  1340. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1341. // Already exported?
  1342. if (FuncInfo.isExportedInst(V)) return;
  1343. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1344. CopyValueToVirtualRegister(V, Reg);
  1345. }
  1346. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1347. const BasicBlock *FromBB) {
  1348. // The operands of the setcc have to be in this block. We don't know
  1349. // how to export them from some other block.
  1350. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1351. // Can export from current BB.
  1352. if (VI->getParent() == FromBB)
  1353. return true;
  1354. // Is already exported, noop.
  1355. return FuncInfo.isExportedInst(V);
  1356. }
  1357. // If this is an argument, we can export it if the BB is the entry block or
  1358. // if it is already exported.
  1359. if (isa<Argument>(V)) {
  1360. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1361. return true;
  1362. // Otherwise, can only export this if it is already exported.
  1363. return FuncInfo.isExportedInst(V);
  1364. }
  1365. // Otherwise, constants can always be exported.
  1366. return true;
  1367. }
  1368. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1369. BranchProbability
  1370. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1371. const MachineBasicBlock *Dst) const {
  1372. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1373. const BasicBlock *SrcBB = Src->getBasicBlock();
  1374. const BasicBlock *DstBB = Dst->getBasicBlock();
  1375. if (!BPI) {
  1376. // If BPI is not available, set the default probability as 1 / N, where N is
  1377. // the number of successors.
  1378. auto SuccSize = std::max<uint32_t>(
  1379. std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
  1380. return BranchProbability(1, SuccSize);
  1381. }
  1382. return BPI->getEdgeProbability(SrcBB, DstBB);
  1383. }
  1384. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1385. MachineBasicBlock *Dst,
  1386. BranchProbability Prob) {
  1387. if (!FuncInfo.BPI)
  1388. Src->addSuccessorWithoutProb(Dst);
  1389. else {
  1390. if (Prob.isUnknown())
  1391. Prob = getEdgeProbability(Src, Dst);
  1392. Src->addSuccessor(Dst, Prob);
  1393. }
  1394. }
  1395. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1396. if (const Instruction *I = dyn_cast<Instruction>(V))
  1397. return I->getParent() == BB;
  1398. return true;
  1399. }
  1400. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1401. /// This function emits a branch and is used at the leaves of an OR or an
  1402. /// AND operator tree.
  1403. ///
  1404. void
  1405. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1406. MachineBasicBlock *TBB,
  1407. MachineBasicBlock *FBB,
  1408. MachineBasicBlock *CurBB,
  1409. MachineBasicBlock *SwitchBB,
  1410. BranchProbability TProb,
  1411. BranchProbability FProb,
  1412. bool InvertCond) {
  1413. const BasicBlock *BB = CurBB->getBasicBlock();
  1414. // If the leaf of the tree is a comparison, merge the condition into
  1415. // the caseblock.
  1416. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1417. // The operands of the cmp have to be in this block. We don't know
  1418. // how to export them from some other block. If this is the first block
  1419. // of the sequence, no exporting is needed.
  1420. if (CurBB == SwitchBB ||
  1421. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1422. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1423. ISD::CondCode Condition;
  1424. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1425. ICmpInst::Predicate Pred =
  1426. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1427. Condition = getICmpCondCode(Pred);
  1428. } else {
  1429. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1430. FCmpInst::Predicate Pred =
  1431. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1432. Condition = getFCmpCondCode(Pred);
  1433. if (TM.Options.NoNaNsFPMath)
  1434. Condition = getFCmpCodeWithoutNaN(Condition);
  1435. }
  1436. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1437. TBB, FBB, CurBB, TProb, FProb);
  1438. SwitchCases.push_back(CB);
  1439. return;
  1440. }
  1441. }
  1442. // Create a CaseBlock record representing this branch.
  1443. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1444. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1445. nullptr, TBB, FBB, CurBB, TProb, FProb);
  1446. SwitchCases.push_back(CB);
  1447. }
  1448. /// FindMergedConditions - If Cond is an expression like
  1449. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1450. MachineBasicBlock *TBB,
  1451. MachineBasicBlock *FBB,
  1452. MachineBasicBlock *CurBB,
  1453. MachineBasicBlock *SwitchBB,
  1454. Instruction::BinaryOps Opc,
  1455. BranchProbability TProb,
  1456. BranchProbability FProb,
  1457. bool InvertCond) {
  1458. // Skip over not part of the tree and remember to invert op and operands at
  1459. // next level.
  1460. if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
  1461. const Value *CondOp = BinaryOperator::getNotArgument(Cond);
  1462. if (InBlock(CondOp, CurBB->getBasicBlock())) {
  1463. FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1464. !InvertCond);
  1465. return;
  1466. }
  1467. }
  1468. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1469. // Compute the effective opcode for Cond, taking into account whether it needs
  1470. // to be inverted, e.g.
  1471. // and (not (or A, B)), C
  1472. // gets lowered as
  1473. // and (and (not A, not B), C)
  1474. unsigned BOpc = 0;
  1475. if (BOp) {
  1476. BOpc = BOp->getOpcode();
  1477. if (InvertCond) {
  1478. if (BOpc == Instruction::And)
  1479. BOpc = Instruction::Or;
  1480. else if (BOpc == Instruction::Or)
  1481. BOpc = Instruction::And;
  1482. }
  1483. }
  1484. // If this node is not part of the or/and tree, emit it as a branch.
  1485. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1486. BOpc != Opc || !BOp->hasOneUse() ||
  1487. BOp->getParent() != CurBB->getBasicBlock() ||
  1488. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1489. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1490. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1491. TProb, FProb, InvertCond);
  1492. return;
  1493. }
  1494. // Create TmpBB after CurBB.
  1495. MachineFunction::iterator BBI(CurBB);
  1496. MachineFunction &MF = DAG.getMachineFunction();
  1497. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1498. CurBB->getParent()->insert(++BBI, TmpBB);
  1499. if (Opc == Instruction::Or) {
  1500. // Codegen X | Y as:
  1501. // BB1:
  1502. // jmp_if_X TBB
  1503. // jmp TmpBB
  1504. // TmpBB:
  1505. // jmp_if_Y TBB
  1506. // jmp FBB
  1507. //
  1508. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1509. // The requirement is that
  1510. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1511. // = TrueProb for original BB.
  1512. // Assuming the original probabilities are A and B, one choice is to set
  1513. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1514. // A/(1+B) and 2B/(1+B). This choice assumes that
  1515. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1516. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1517. // TmpBB, but the math is more complicated.
  1518. auto NewTrueProb = TProb / 2;
  1519. auto NewFalseProb = TProb / 2 + FProb;
  1520. // Emit the LHS condition.
  1521. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1522. NewTrueProb, NewFalseProb, InvertCond);
  1523. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1524. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1525. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1526. // Emit the RHS condition into TmpBB.
  1527. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1528. Probs[0], Probs[1], InvertCond);
  1529. } else {
  1530. assert(Opc == Instruction::And && "Unknown merge op!");
  1531. // Codegen X & Y as:
  1532. // BB1:
  1533. // jmp_if_X TmpBB
  1534. // jmp FBB
  1535. // TmpBB:
  1536. // jmp_if_Y TBB
  1537. // jmp FBB
  1538. //
  1539. // This requires creation of TmpBB after CurBB.
  1540. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1541. // The requirement is that
  1542. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1543. // = FalseProb for original BB.
  1544. // Assuming the original probabilities are A and B, one choice is to set
  1545. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1546. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1547. // TrueProb for BB1 * FalseProb for TmpBB.
  1548. auto NewTrueProb = TProb + FProb / 2;
  1549. auto NewFalseProb = FProb / 2;
  1550. // Emit the LHS condition.
  1551. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1552. NewTrueProb, NewFalseProb, InvertCond);
  1553. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1554. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1555. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1556. // Emit the RHS condition into TmpBB.
  1557. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1558. Probs[0], Probs[1], InvertCond);
  1559. }
  1560. }
  1561. /// If the set of cases should be emitted as a series of branches, return true.
  1562. /// If we should emit this as a bunch of and/or'd together conditions, return
  1563. /// false.
  1564. bool
  1565. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1566. if (Cases.size() != 2) return true;
  1567. // If this is two comparisons of the same values or'd or and'd together, they
  1568. // will get folded into a single comparison, so don't emit two blocks.
  1569. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1570. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1571. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1572. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1573. return false;
  1574. }
  1575. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1576. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1577. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1578. Cases[0].CC == Cases[1].CC &&
  1579. isa<Constant>(Cases[0].CmpRHS) &&
  1580. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1581. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1582. return false;
  1583. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1584. return false;
  1585. }
  1586. return true;
  1587. }
  1588. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1589. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1590. // Update machine-CFG edges.
  1591. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1592. if (I.isUnconditional()) {
  1593. // Update machine-CFG edges.
  1594. BrMBB->addSuccessor(Succ0MBB);
  1595. // If this is not a fall-through branch or optimizations are switched off,
  1596. // emit the branch.
  1597. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1598. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1599. MVT::Other, getControlRoot(),
  1600. DAG.getBasicBlock(Succ0MBB)));
  1601. return;
  1602. }
  1603. // If this condition is one of the special cases we handle, do special stuff
  1604. // now.
  1605. const Value *CondVal = I.getCondition();
  1606. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1607. // If this is a series of conditions that are or'd or and'd together, emit
  1608. // this as a sequence of branches instead of setcc's with and/or operations.
  1609. // As long as jumps are not expensive, this should improve performance.
  1610. // For example, instead of something like:
  1611. // cmp A, B
  1612. // C = seteq
  1613. // cmp D, E
  1614. // F = setle
  1615. // or C, F
  1616. // jnz foo
  1617. // Emit:
  1618. // cmp A, B
  1619. // je foo
  1620. // cmp D, E
  1621. // jle foo
  1622. //
  1623. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1624. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1625. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1626. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1627. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1628. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1629. Opcode,
  1630. getEdgeProbability(BrMBB, Succ0MBB),
  1631. getEdgeProbability(BrMBB, Succ1MBB),
  1632. /*InvertCond=*/false);
  1633. // If the compares in later blocks need to use values not currently
  1634. // exported from this block, export them now. This block should always
  1635. // be the first entry.
  1636. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1637. // Allow some cases to be rejected.
  1638. if (ShouldEmitAsBranches(SwitchCases)) {
  1639. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1640. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1641. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1642. }
  1643. // Emit the branch for this block.
  1644. visitSwitchCase(SwitchCases[0], BrMBB);
  1645. SwitchCases.erase(SwitchCases.begin());
  1646. return;
  1647. }
  1648. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1649. // SwitchCases.
  1650. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1651. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1652. SwitchCases.clear();
  1653. }
  1654. }
  1655. // Create a CaseBlock record representing this branch.
  1656. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1657. nullptr, Succ0MBB, Succ1MBB, BrMBB);
  1658. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1659. // cond branch.
  1660. visitSwitchCase(CB, BrMBB);
  1661. }
  1662. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1663. /// the binary search tree resulting from lowering a switch instruction.
  1664. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1665. MachineBasicBlock *SwitchBB) {
  1666. SDValue Cond;
  1667. SDValue CondLHS = getValue(CB.CmpLHS);
  1668. SDLoc dl = getCurSDLoc();
  1669. // Build the setcc now.
  1670. if (!CB.CmpMHS) {
  1671. // Fold "(X == true)" to X and "(X == false)" to !X to
  1672. // handle common cases produced by branch lowering.
  1673. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1674. CB.CC == ISD::SETEQ)
  1675. Cond = CondLHS;
  1676. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1677. CB.CC == ISD::SETEQ) {
  1678. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  1679. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1680. } else
  1681. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1682. } else {
  1683. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1684. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1685. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1686. SDValue CmpOp = getValue(CB.CmpMHS);
  1687. EVT VT = CmpOp.getValueType();
  1688. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1689. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  1690. ISD::SETLE);
  1691. } else {
  1692. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1693. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  1694. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1695. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  1696. }
  1697. }
  1698. // Update successor info
  1699. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  1700. // TrueBB and FalseBB are always different unless the incoming IR is
  1701. // degenerate. This only happens when running llc on weird IR.
  1702. if (CB.TrueBB != CB.FalseBB)
  1703. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  1704. SwitchBB->normalizeSuccProbs();
  1705. // If the lhs block is the next block, invert the condition so that we can
  1706. // fall through to the lhs instead of the rhs block.
  1707. if (CB.TrueBB == NextBlock(SwitchBB)) {
  1708. std::swap(CB.TrueBB, CB.FalseBB);
  1709. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  1710. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1711. }
  1712. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1713. MVT::Other, getControlRoot(), Cond,
  1714. DAG.getBasicBlock(CB.TrueBB));
  1715. // Insert the false branch. Do this even if it's a fall through branch,
  1716. // this makes it easier to do DAG optimizations which require inverting
  1717. // the branch condition.
  1718. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1719. DAG.getBasicBlock(CB.FalseBB));
  1720. DAG.setRoot(BrCond);
  1721. }
  1722. /// visitJumpTable - Emit JumpTable node in the current MBB
  1723. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1724. // Emit the code for the jump table
  1725. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1726. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  1727. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1728. JT.Reg, PTy);
  1729. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1730. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1731. MVT::Other, Index.getValue(1),
  1732. Table, Index);
  1733. DAG.setRoot(BrJumpTable);
  1734. }
  1735. /// visitJumpTableHeader - This function emits necessary code to produce index
  1736. /// in the JumpTable from switch case.
  1737. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1738. JumpTableHeader &JTH,
  1739. MachineBasicBlock *SwitchBB) {
  1740. SDLoc dl = getCurSDLoc();
  1741. // Subtract the lowest switch case value from the value being switched on and
  1742. // conditional branch to default mbb if the result is greater than the
  1743. // difference between smallest and largest cases.
  1744. SDValue SwitchOp = getValue(JTH.SValue);
  1745. EVT VT = SwitchOp.getValueType();
  1746. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1747. DAG.getConstant(JTH.First, dl, VT));
  1748. // The SDNode we just created, which holds the value being switched on minus
  1749. // the smallest case value, needs to be copied to a virtual register so it
  1750. // can be used as an index into the jump table in a subsequent basic block.
  1751. // This value may be smaller or larger than the target's pointer type, and
  1752. // therefore require extension or truncating.
  1753. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1754. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1755. unsigned JumpTableReg =
  1756. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  1757. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  1758. JumpTableReg, SwitchOp);
  1759. JT.Reg = JumpTableReg;
  1760. // Emit the range check for the jump table, and branch to the default block
  1761. // for the switch statement if the value being switched on exceeds the largest
  1762. // case in the switch.
  1763. SDValue CMP = DAG.getSetCC(
  1764. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1765. Sub.getValueType()),
  1766. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  1767. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1768. MVT::Other, CopyTo, CMP,
  1769. DAG.getBasicBlock(JT.Default));
  1770. // Avoid emitting unnecessary branches to the next block.
  1771. if (JT.MBB != NextBlock(SwitchBB))
  1772. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1773. DAG.getBasicBlock(JT.MBB));
  1774. DAG.setRoot(BrCond);
  1775. }
  1776. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  1777. /// variable if there exists one.
  1778. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  1779. SDValue &Chain) {
  1780. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1781. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1782. MachineFunction &MF = DAG.getMachineFunction();
  1783. Value *Global = TLI.getSDagStackGuard(*MF.getFunction()->getParent());
  1784. MachineSDNode *Node =
  1785. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  1786. if (Global) {
  1787. MachinePointerInfo MPInfo(Global);
  1788. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  1789. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  1790. MachineMemOperand::MODereferenceable;
  1791. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
  1792. DAG.getEVTAlignment(PtrTy));
  1793. Node->setMemRefs(MemRefs, MemRefs + 1);
  1794. }
  1795. return SDValue(Node, 0);
  1796. }
  1797. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1798. /// tail spliced into a stack protector check success bb.
  1799. ///
  1800. /// For a high level explanation of how this fits into the stack protector
  1801. /// generation see the comment on the declaration of class
  1802. /// StackProtectorDescriptor.
  1803. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1804. MachineBasicBlock *ParentBB) {
  1805. // First create the loads to the guard/stack slot for the comparison.
  1806. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1807. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1808. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  1809. int FI = MFI.getStackProtectorIndex();
  1810. SDValue Guard;
  1811. SDLoc dl = getCurSDLoc();
  1812. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1813. const Module &M = *ParentBB->getParent()->getFunction()->getParent();
  1814. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  1815. // Generate code to load the content of the guard slot.
  1816. SDValue StackSlot = DAG.getLoad(
  1817. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  1818. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  1819. MachineMemOperand::MOVolatile);
  1820. // Retrieve guard check function, nullptr if instrumentation is inlined.
  1821. if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
  1822. // The target provides a guard check function to validate the guard value.
  1823. // Generate a call to that function with the content of the guard slot as
  1824. // argument.
  1825. auto *Fn = cast<Function>(GuardCheck);
  1826. FunctionType *FnTy = Fn->getFunctionType();
  1827. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  1828. TargetLowering::ArgListTy Args;
  1829. TargetLowering::ArgListEntry Entry;
  1830. Entry.Node = StackSlot;
  1831. Entry.Ty = FnTy->getParamType(0);
  1832. if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
  1833. Entry.IsInReg = true;
  1834. Args.push_back(Entry);
  1835. TargetLowering::CallLoweringInfo CLI(DAG);
  1836. CLI.setDebugLoc(getCurSDLoc())
  1837. .setChain(DAG.getEntryNode())
  1838. .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
  1839. getValue(GuardCheck), std::move(Args));
  1840. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  1841. DAG.setRoot(Result.second);
  1842. return;
  1843. }
  1844. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  1845. // Otherwise, emit a volatile load to retrieve the stack guard value.
  1846. SDValue Chain = DAG.getEntryNode();
  1847. if (TLI.useLoadStackGuardNode()) {
  1848. Guard = getLoadStackGuard(DAG, dl, Chain);
  1849. } else {
  1850. const Value *IRGuard = TLI.getSDagStackGuard(M);
  1851. SDValue GuardPtr = getValue(IRGuard);
  1852. Guard =
  1853. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  1854. Align, MachineMemOperand::MOVolatile);
  1855. }
  1856. // Perform the comparison via a subtract/getsetcc.
  1857. EVT VT = Guard.getValueType();
  1858. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
  1859. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  1860. *DAG.getContext(),
  1861. Sub.getValueType()),
  1862. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1863. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1864. // branch to failure MBB.
  1865. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1866. MVT::Other, StackSlot.getOperand(0),
  1867. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1868. // Otherwise branch to success MBB.
  1869. SDValue Br = DAG.getNode(ISD::BR, dl,
  1870. MVT::Other, BrCond,
  1871. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1872. DAG.setRoot(Br);
  1873. }
  1874. /// Codegen the failure basic block for a stack protector check.
  1875. ///
  1876. /// A failure stack protector machine basic block consists simply of a call to
  1877. /// __stack_chk_fail().
  1878. ///
  1879. /// For a high level explanation of how this fits into the stack protector
  1880. /// generation see the comment on the declaration of class
  1881. /// StackProtectorDescriptor.
  1882. void
  1883. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1884. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1885. SDValue Chain =
  1886. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  1887. None, false, getCurSDLoc(), false, false).second;
  1888. DAG.setRoot(Chain);
  1889. }
  1890. /// visitBitTestHeader - This function emits necessary code to produce value
  1891. /// suitable for "bit tests"
  1892. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1893. MachineBasicBlock *SwitchBB) {
  1894. SDLoc dl = getCurSDLoc();
  1895. // Subtract the minimum value
  1896. SDValue SwitchOp = getValue(B.SValue);
  1897. EVT VT = SwitchOp.getValueType();
  1898. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1899. DAG.getConstant(B.First, dl, VT));
  1900. // Check range
  1901. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1902. SDValue RangeCmp = DAG.getSetCC(
  1903. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1904. Sub.getValueType()),
  1905. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  1906. // Determine the type of the test operands.
  1907. bool UsePtrType = false;
  1908. if (!TLI.isTypeLegal(VT))
  1909. UsePtrType = true;
  1910. else {
  1911. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1912. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1913. // Switch table case range are encoded into series of masks.
  1914. // Just use pointer type, it's guaranteed to fit.
  1915. UsePtrType = true;
  1916. break;
  1917. }
  1918. }
  1919. if (UsePtrType) {
  1920. VT = TLI.getPointerTy(DAG.getDataLayout());
  1921. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  1922. }
  1923. B.RegVT = VT.getSimpleVT();
  1924. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1925. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  1926. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1927. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  1928. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  1929. SwitchBB->normalizeSuccProbs();
  1930. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  1931. MVT::Other, CopyTo, RangeCmp,
  1932. DAG.getBasicBlock(B.Default));
  1933. // Avoid emitting unnecessary branches to the next block.
  1934. if (MBB != NextBlock(SwitchBB))
  1935. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  1936. DAG.getBasicBlock(MBB));
  1937. DAG.setRoot(BrRange);
  1938. }
  1939. /// visitBitTestCase - this function produces one "bit test"
  1940. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1941. MachineBasicBlock* NextMBB,
  1942. BranchProbability BranchProbToNext,
  1943. unsigned Reg,
  1944. BitTestCase &B,
  1945. MachineBasicBlock *SwitchBB) {
  1946. SDLoc dl = getCurSDLoc();
  1947. MVT VT = BB.RegVT;
  1948. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  1949. SDValue Cmp;
  1950. unsigned PopCount = countPopulation(B.Mask);
  1951. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1952. if (PopCount == 1) {
  1953. // Testing for a single bit; just compare the shift count with what it
  1954. // would need to be to shift a 1 bit in that position.
  1955. Cmp = DAG.getSetCC(
  1956. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1957. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  1958. ISD::SETEQ);
  1959. } else if (PopCount == BB.Range) {
  1960. // There is only one zero bit in the range, test for it directly.
  1961. Cmp = DAG.getSetCC(
  1962. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1963. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  1964. ISD::SETNE);
  1965. } else {
  1966. // Make desired shift
  1967. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  1968. DAG.getConstant(1, dl, VT), ShiftOp);
  1969. // Emit bit tests and jumps
  1970. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  1971. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  1972. Cmp = DAG.getSetCC(
  1973. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1974. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1975. }
  1976. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  1977. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  1978. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  1979. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  1980. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  1981. // one as they are relative probabilities (and thus work more like weights),
  1982. // and hence we need to normalize them to let the sum of them become one.
  1983. SwitchBB->normalizeSuccProbs();
  1984. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  1985. MVT::Other, getControlRoot(),
  1986. Cmp, DAG.getBasicBlock(B.TargetBB));
  1987. // Avoid emitting unnecessary branches to the next block.
  1988. if (NextMBB != NextBlock(SwitchBB))
  1989. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  1990. DAG.getBasicBlock(NextMBB));
  1991. DAG.setRoot(BrAnd);
  1992. }
  1993. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1994. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1995. // Retrieve successors. Look through artificial IR level blocks like
  1996. // catchswitch for successors.
  1997. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1998. const BasicBlock *EHPadBB = I.getSuccessor(1);
  1999. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2000. // have to do anything here to lower funclet bundles.
  2001. assert(!I.hasOperandBundlesOtherThan(
  2002. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2003. "Cannot lower invokes with arbitrary operand bundles yet!");
  2004. const Value *Callee(I.getCalledValue());
  2005. const Function *Fn = dyn_cast<Function>(Callee);
  2006. if (isa<InlineAsm>(Callee))
  2007. visitInlineAsm(&I);
  2008. else if (Fn && Fn->isIntrinsic()) {
  2009. switch (Fn->getIntrinsicID()) {
  2010. default:
  2011. llvm_unreachable("Cannot invoke this intrinsic");
  2012. case Intrinsic::donothing:
  2013. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2014. break;
  2015. case Intrinsic::experimental_patchpoint_void:
  2016. case Intrinsic::experimental_patchpoint_i64:
  2017. visitPatchpoint(&I, EHPadBB);
  2018. break;
  2019. case Intrinsic::experimental_gc_statepoint:
  2020. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2021. break;
  2022. }
  2023. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2024. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2025. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2026. // intrinsic, and right now there are no plans to support other intrinsics
  2027. // with deopt state.
  2028. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2029. } else {
  2030. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2031. }
  2032. // If the value of the invoke is used outside of its defining block, make it
  2033. // available as a virtual register.
  2034. // We already took care of the exported value for the statepoint instruction
  2035. // during call to the LowerStatepoint.
  2036. if (!isStatepoint(I)) {
  2037. CopyToExportRegsIfNeeded(&I);
  2038. }
  2039. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2040. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2041. BranchProbability EHPadBBProb =
  2042. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2043. : BranchProbability::getZero();
  2044. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2045. // Update successor info.
  2046. addSuccessorWithProb(InvokeMBB, Return);
  2047. for (auto &UnwindDest : UnwindDests) {
  2048. UnwindDest.first->setIsEHPad();
  2049. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2050. }
  2051. InvokeMBB->normalizeSuccProbs();
  2052. // Drop into normal successor.
  2053. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2054. MVT::Other, getControlRoot(),
  2055. DAG.getBasicBlock(Return)));
  2056. }
  2057. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2058. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2059. }
  2060. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2061. assert(FuncInfo.MBB->isEHPad() &&
  2062. "Call to landingpad not in landing pad!");
  2063. MachineBasicBlock *MBB = FuncInfo.MBB;
  2064. addLandingPadInfo(LP, *MBB);
  2065. // If there aren't registers to copy the values into (e.g., during SjLj
  2066. // exceptions), then don't bother to create these DAG nodes.
  2067. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2068. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2069. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2070. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2071. return;
  2072. // If landingpad's return type is token type, we don't create DAG nodes
  2073. // for its exception pointer and selector value. The extraction of exception
  2074. // pointer or selector value from token type landingpads is not currently
  2075. // supported.
  2076. if (LP.getType()->isTokenTy())
  2077. return;
  2078. SmallVector<EVT, 2> ValueVTs;
  2079. SDLoc dl = getCurSDLoc();
  2080. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2081. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2082. // Get the two live-in registers as SDValues. The physregs have already been
  2083. // copied into virtual registers.
  2084. SDValue Ops[2];
  2085. if (FuncInfo.ExceptionPointerVirtReg) {
  2086. Ops[0] = DAG.getZExtOrTrunc(
  2087. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2088. FuncInfo.ExceptionPointerVirtReg,
  2089. TLI.getPointerTy(DAG.getDataLayout())),
  2090. dl, ValueVTs[0]);
  2091. } else {
  2092. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2093. }
  2094. Ops[1] = DAG.getZExtOrTrunc(
  2095. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2096. FuncInfo.ExceptionSelectorVirtReg,
  2097. TLI.getPointerTy(DAG.getDataLayout())),
  2098. dl, ValueVTs[1]);
  2099. // Merge into one.
  2100. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2101. DAG.getVTList(ValueVTs), Ops);
  2102. setValue(&LP, Res);
  2103. }
  2104. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2105. #ifndef NDEBUG
  2106. for (const CaseCluster &CC : Clusters)
  2107. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2108. #endif
  2109. std::sort(Clusters.begin(), Clusters.end(),
  2110. [](const CaseCluster &a, const CaseCluster &b) {
  2111. return a.Low->getValue().slt(b.Low->getValue());
  2112. });
  2113. // Merge adjacent clusters with the same destination.
  2114. const unsigned N = Clusters.size();
  2115. unsigned DstIndex = 0;
  2116. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2117. CaseCluster &CC = Clusters[SrcIndex];
  2118. const ConstantInt *CaseVal = CC.Low;
  2119. MachineBasicBlock *Succ = CC.MBB;
  2120. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2121. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2122. // If this case has the same successor and is a neighbour, merge it into
  2123. // the previous cluster.
  2124. Clusters[DstIndex - 1].High = CaseVal;
  2125. Clusters[DstIndex - 1].Prob += CC.Prob;
  2126. } else {
  2127. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2128. sizeof(Clusters[SrcIndex]));
  2129. }
  2130. }
  2131. Clusters.resize(DstIndex);
  2132. }
  2133. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2134. MachineBasicBlock *Last) {
  2135. // Update JTCases.
  2136. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2137. if (JTCases[i].first.HeaderBB == First)
  2138. JTCases[i].first.HeaderBB = Last;
  2139. // Update BitTestCases.
  2140. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2141. if (BitTestCases[i].Parent == First)
  2142. BitTestCases[i].Parent = Last;
  2143. }
  2144. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2145. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2146. // Update machine-CFG edges with unique successors.
  2147. SmallSet<BasicBlock*, 32> Done;
  2148. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2149. BasicBlock *BB = I.getSuccessor(i);
  2150. bool Inserted = Done.insert(BB).second;
  2151. if (!Inserted)
  2152. continue;
  2153. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2154. addSuccessorWithProb(IndirectBrMBB, Succ);
  2155. }
  2156. IndirectBrMBB->normalizeSuccProbs();
  2157. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2158. MVT::Other, getControlRoot(),
  2159. getValue(I.getAddress())));
  2160. }
  2161. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2162. if (DAG.getTarget().Options.TrapUnreachable)
  2163. DAG.setRoot(
  2164. DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2165. }
  2166. void SelectionDAGBuilder::visitFSub(const User &I) {
  2167. // -0.0 - X --> fneg
  2168. Type *Ty = I.getType();
  2169. if (isa<Constant>(I.getOperand(0)) &&
  2170. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2171. SDValue Op2 = getValue(I.getOperand(1));
  2172. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2173. Op2.getValueType(), Op2));
  2174. return;
  2175. }
  2176. visitBinary(I, ISD::FSUB);
  2177. }
  2178. /// Checks if the given instruction performs a vector reduction, in which case
  2179. /// we have the freedom to alter the elements in the result as long as the
  2180. /// reduction of them stays unchanged.
  2181. static bool isVectorReductionOp(const User *I) {
  2182. const Instruction *Inst = dyn_cast<Instruction>(I);
  2183. if (!Inst || !Inst->getType()->isVectorTy())
  2184. return false;
  2185. auto OpCode = Inst->getOpcode();
  2186. switch (OpCode) {
  2187. case Instruction::Add:
  2188. case Instruction::Mul:
  2189. case Instruction::And:
  2190. case Instruction::Or:
  2191. case Instruction::Xor:
  2192. break;
  2193. case Instruction::FAdd:
  2194. case Instruction::FMul:
  2195. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2196. if (FPOp->getFastMathFlags().unsafeAlgebra())
  2197. break;
  2198. LLVM_FALLTHROUGH;
  2199. default:
  2200. return false;
  2201. }
  2202. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2203. unsigned ElemNumToReduce = ElemNum;
  2204. // Do DFS search on the def-use chain from the given instruction. We only
  2205. // allow four kinds of operations during the search until we reach the
  2206. // instruction that extracts the first element from the vector:
  2207. //
  2208. // 1. The reduction operation of the same opcode as the given instruction.
  2209. //
  2210. // 2. PHI node.
  2211. //
  2212. // 3. ShuffleVector instruction together with a reduction operation that
  2213. // does a partial reduction.
  2214. //
  2215. // 4. ExtractElement that extracts the first element from the vector, and we
  2216. // stop searching the def-use chain here.
  2217. //
  2218. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2219. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2220. // a reduction operation if we meet any other instructions other than those
  2221. // listed above.
  2222. SmallVector<const User *, 16> UsersToVisit{Inst};
  2223. SmallPtrSet<const User *, 16> Visited;
  2224. bool ReduxExtracted = false;
  2225. while (!UsersToVisit.empty()) {
  2226. auto User = UsersToVisit.back();
  2227. UsersToVisit.pop_back();
  2228. if (!Visited.insert(User).second)
  2229. continue;
  2230. for (const auto &U : User->users()) {
  2231. auto Inst = dyn_cast<Instruction>(U);
  2232. if (!Inst)
  2233. return false;
  2234. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2235. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2236. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra())
  2237. return false;
  2238. UsersToVisit.push_back(U);
  2239. } else if (const ShuffleVectorInst *ShufInst =
  2240. dyn_cast<ShuffleVectorInst>(U)) {
  2241. // Detect the following pattern: A ShuffleVector instruction together
  2242. // with a reduction that do partial reduction on the first and second
  2243. // ElemNumToReduce / 2 elements, and store the result in
  2244. // ElemNumToReduce / 2 elements in another vector.
  2245. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2246. if (ResultElements < ElemNum)
  2247. return false;
  2248. if (ElemNumToReduce == 1)
  2249. return false;
  2250. if (!isa<UndefValue>(U->getOperand(1)))
  2251. return false;
  2252. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2253. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2254. return false;
  2255. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2256. if (ShufInst->getMaskValue(i) != -1)
  2257. return false;
  2258. // There is only one user of this ShuffleVector instruction, which
  2259. // must be a reduction operation.
  2260. if (!U->hasOneUse())
  2261. return false;
  2262. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2263. if (!U2 || U2->getOpcode() != OpCode)
  2264. return false;
  2265. // Check operands of the reduction operation.
  2266. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2267. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2268. UsersToVisit.push_back(U2);
  2269. ElemNumToReduce /= 2;
  2270. } else
  2271. return false;
  2272. } else if (isa<ExtractElementInst>(U)) {
  2273. // At this moment we should have reduced all elements in the vector.
  2274. if (ElemNumToReduce != 1)
  2275. return false;
  2276. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2277. if (!Val || Val->getZExtValue() != 0)
  2278. return false;
  2279. ReduxExtracted = true;
  2280. } else
  2281. return false;
  2282. }
  2283. }
  2284. return ReduxExtracted;
  2285. }
  2286. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2287. SDValue Op1 = getValue(I.getOperand(0));
  2288. SDValue Op2 = getValue(I.getOperand(1));
  2289. bool nuw = false;
  2290. bool nsw = false;
  2291. bool exact = false;
  2292. bool vec_redux = false;
  2293. FastMathFlags FMF;
  2294. if (const OverflowingBinaryOperator *OFBinOp =
  2295. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2296. nuw = OFBinOp->hasNoUnsignedWrap();
  2297. nsw = OFBinOp->hasNoSignedWrap();
  2298. }
  2299. if (const PossiblyExactOperator *ExactOp =
  2300. dyn_cast<const PossiblyExactOperator>(&I))
  2301. exact = ExactOp->isExact();
  2302. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
  2303. FMF = FPOp->getFastMathFlags();
  2304. if (isVectorReductionOp(&I)) {
  2305. vec_redux = true;
  2306. DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2307. }
  2308. SDNodeFlags Flags;
  2309. Flags.setExact(exact);
  2310. Flags.setNoSignedWrap(nsw);
  2311. Flags.setNoUnsignedWrap(nuw);
  2312. Flags.setVectorReduction(vec_redux);
  2313. Flags.setAllowReciprocal(FMF.allowReciprocal());
  2314. Flags.setAllowContract(FMF.allowContract());
  2315. Flags.setNoInfs(FMF.noInfs());
  2316. Flags.setNoNaNs(FMF.noNaNs());
  2317. Flags.setNoSignedZeros(FMF.noSignedZeros());
  2318. Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
  2319. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  2320. Op1, Op2, Flags);
  2321. setValue(&I, BinNodeValue);
  2322. }
  2323. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2324. SDValue Op1 = getValue(I.getOperand(0));
  2325. SDValue Op2 = getValue(I.getOperand(1));
  2326. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2327. Op2.getValueType(), DAG.getDataLayout());
  2328. // Coerce the shift amount to the right type if we can.
  2329. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2330. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2331. unsigned Op2Size = Op2.getValueSizeInBits();
  2332. SDLoc DL = getCurSDLoc();
  2333. // If the operand is smaller than the shift count type, promote it.
  2334. if (ShiftSize > Op2Size)
  2335. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2336. // If the operand is larger than the shift count type but the shift
  2337. // count type has enough bits to represent any shift value, truncate
  2338. // it now. This is a common case and it exposes the truncate to
  2339. // optimization early.
  2340. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2341. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2342. // Otherwise we'll need to temporarily settle for some other convenient
  2343. // type. Type legalization will make adjustments once the shiftee is split.
  2344. else
  2345. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2346. }
  2347. bool nuw = false;
  2348. bool nsw = false;
  2349. bool exact = false;
  2350. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2351. if (const OverflowingBinaryOperator *OFBinOp =
  2352. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2353. nuw = OFBinOp->hasNoUnsignedWrap();
  2354. nsw = OFBinOp->hasNoSignedWrap();
  2355. }
  2356. if (const PossiblyExactOperator *ExactOp =
  2357. dyn_cast<const PossiblyExactOperator>(&I))
  2358. exact = ExactOp->isExact();
  2359. }
  2360. SDNodeFlags Flags;
  2361. Flags.setExact(exact);
  2362. Flags.setNoSignedWrap(nsw);
  2363. Flags.setNoUnsignedWrap(nuw);
  2364. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2365. Flags);
  2366. setValue(&I, Res);
  2367. }
  2368. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2369. SDValue Op1 = getValue(I.getOperand(0));
  2370. SDValue Op2 = getValue(I.getOperand(1));
  2371. SDNodeFlags Flags;
  2372. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2373. cast<PossiblyExactOperator>(&I)->isExact());
  2374. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2375. Op2, Flags));
  2376. }
  2377. void SelectionDAGBuilder::visitICmp(const User &I) {
  2378. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2379. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2380. predicate = IC->getPredicate();
  2381. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2382. predicate = ICmpInst::Predicate(IC->getPredicate());
  2383. SDValue Op1 = getValue(I.getOperand(0));
  2384. SDValue Op2 = getValue(I.getOperand(1));
  2385. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2386. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2387. I.getType());
  2388. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2389. }
  2390. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2391. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2392. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2393. predicate = FC->getPredicate();
  2394. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2395. predicate = FCmpInst::Predicate(FC->getPredicate());
  2396. SDValue Op1 = getValue(I.getOperand(0));
  2397. SDValue Op2 = getValue(I.getOperand(1));
  2398. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2399. // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
  2400. // FIXME: We should propagate the fast-math-flags to the DAG node itself for
  2401. // further optimization, but currently FMF is only applicable to binary nodes.
  2402. if (TM.Options.NoNaNsFPMath)
  2403. Condition = getFCmpCodeWithoutNaN(Condition);
  2404. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2405. I.getType());
  2406. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2407. }
  2408. // Check if the condition of the select has one use or two users that are both
  2409. // selects with the same condition.
  2410. static bool hasOnlySelectUsers(const Value *Cond) {
  2411. return all_of(Cond->users(), [](const Value *V) {
  2412. return isa<SelectInst>(V);
  2413. });
  2414. }
  2415. void SelectionDAGBuilder::visitSelect(const User &I) {
  2416. SmallVector<EVT, 4> ValueVTs;
  2417. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2418. ValueVTs);
  2419. unsigned NumValues = ValueVTs.size();
  2420. if (NumValues == 0) return;
  2421. SmallVector<SDValue, 4> Values(NumValues);
  2422. SDValue Cond = getValue(I.getOperand(0));
  2423. SDValue LHSVal = getValue(I.getOperand(1));
  2424. SDValue RHSVal = getValue(I.getOperand(2));
  2425. auto BaseOps = {Cond};
  2426. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2427. ISD::VSELECT : ISD::SELECT;
  2428. // Min/max matching is only viable if all output VTs are the same.
  2429. if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
  2430. EVT VT = ValueVTs[0];
  2431. LLVMContext &Ctx = *DAG.getContext();
  2432. auto &TLI = DAG.getTargetLoweringInfo();
  2433. // We care about the legality of the operation after it has been type
  2434. // legalized.
  2435. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2436. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2437. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2438. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2439. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2440. // min/max is legal on the scalar type.
  2441. bool UseScalarMinMax = VT.isVector() &&
  2442. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2443. Value *LHS, *RHS;
  2444. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2445. ISD::NodeType Opc = ISD::DELETED_NODE;
  2446. switch (SPR.Flavor) {
  2447. case SPF_UMAX: Opc = ISD::UMAX; break;
  2448. case SPF_UMIN: Opc = ISD::UMIN; break;
  2449. case SPF_SMAX: Opc = ISD::SMAX; break;
  2450. case SPF_SMIN: Opc = ISD::SMIN; break;
  2451. case SPF_FMINNUM:
  2452. switch (SPR.NaNBehavior) {
  2453. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2454. case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
  2455. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2456. case SPNB_RETURNS_ANY: {
  2457. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2458. Opc = ISD::FMINNUM;
  2459. else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
  2460. Opc = ISD::FMINNAN;
  2461. else if (UseScalarMinMax)
  2462. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2463. ISD::FMINNUM : ISD::FMINNAN;
  2464. break;
  2465. }
  2466. }
  2467. break;
  2468. case SPF_FMAXNUM:
  2469. switch (SPR.NaNBehavior) {
  2470. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2471. case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
  2472. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2473. case SPNB_RETURNS_ANY:
  2474. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2475. Opc = ISD::FMAXNUM;
  2476. else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
  2477. Opc = ISD::FMAXNAN;
  2478. else if (UseScalarMinMax)
  2479. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2480. ISD::FMAXNUM : ISD::FMAXNAN;
  2481. break;
  2482. }
  2483. break;
  2484. default: break;
  2485. }
  2486. if (Opc != ISD::DELETED_NODE &&
  2487. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2488. (UseScalarMinMax &&
  2489. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2490. // If the underlying comparison instruction is used by any other
  2491. // instruction, the consumed instructions won't be destroyed, so it is
  2492. // not profitable to convert to a min/max.
  2493. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2494. OpCode = Opc;
  2495. LHSVal = getValue(LHS);
  2496. RHSVal = getValue(RHS);
  2497. BaseOps = {};
  2498. }
  2499. }
  2500. for (unsigned i = 0; i != NumValues; ++i) {
  2501. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2502. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2503. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2504. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2505. LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
  2506. Ops);
  2507. }
  2508. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2509. DAG.getVTList(ValueVTs), Values));
  2510. }
  2511. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2512. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2513. SDValue N = getValue(I.getOperand(0));
  2514. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2515. I.getType());
  2516. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2517. }
  2518. void SelectionDAGBuilder::visitZExt(const User &I) {
  2519. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2520. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2521. SDValue N = getValue(I.getOperand(0));
  2522. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2523. I.getType());
  2524. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2525. }
  2526. void SelectionDAGBuilder::visitSExt(const User &I) {
  2527. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2528. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2529. SDValue N = getValue(I.getOperand(0));
  2530. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2531. I.getType());
  2532. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2533. }
  2534. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2535. // FPTrunc is never a no-op cast, no need to check
  2536. SDValue N = getValue(I.getOperand(0));
  2537. SDLoc dl = getCurSDLoc();
  2538. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2539. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2540. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2541. DAG.getTargetConstant(
  2542. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2543. }
  2544. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2545. // FPExt is never a no-op cast, no need to check
  2546. SDValue N = getValue(I.getOperand(0));
  2547. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2548. I.getType());
  2549. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2550. }
  2551. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2552. // FPToUI is never a no-op cast, no need to check
  2553. SDValue N = getValue(I.getOperand(0));
  2554. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2555. I.getType());
  2556. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2557. }
  2558. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2559. // FPToSI is never a no-op cast, no need to check
  2560. SDValue N = getValue(I.getOperand(0));
  2561. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2562. I.getType());
  2563. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2564. }
  2565. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2566. // UIToFP is never a no-op cast, no need to check
  2567. SDValue N = getValue(I.getOperand(0));
  2568. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2569. I.getType());
  2570. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2571. }
  2572. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2573. // SIToFP is never a no-op cast, no need to check
  2574. SDValue N = getValue(I.getOperand(0));
  2575. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2576. I.getType());
  2577. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2578. }
  2579. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2580. // What to do depends on the size of the integer and the size of the pointer.
  2581. // We can either truncate, zero extend, or no-op, accordingly.
  2582. SDValue N = getValue(I.getOperand(0));
  2583. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2584. I.getType());
  2585. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2586. }
  2587. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2588. // What to do depends on the size of the integer and the size of the pointer.
  2589. // We can either truncate, zero extend, or no-op, accordingly.
  2590. SDValue N = getValue(I.getOperand(0));
  2591. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2592. I.getType());
  2593. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2594. }
  2595. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2596. SDValue N = getValue(I.getOperand(0));
  2597. SDLoc dl = getCurSDLoc();
  2598. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2599. I.getType());
  2600. // BitCast assures us that source and destination are the same size so this is
  2601. // either a BITCAST or a no-op.
  2602. if (DestVT != N.getValueType())
  2603. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2604. DestVT, N)); // convert types.
  2605. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2606. // might fold any kind of constant expression to an integer constant and that
  2607. // is not what we are looking for. Only recognize a bitcast of a genuine
  2608. // constant integer as an opaque constant.
  2609. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2610. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2611. /*isOpaque*/true));
  2612. else
  2613. setValue(&I, N); // noop cast.
  2614. }
  2615. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2616. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2617. const Value *SV = I.getOperand(0);
  2618. SDValue N = getValue(SV);
  2619. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2620. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2621. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2622. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2623. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2624. setValue(&I, N);
  2625. }
  2626. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2627. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2628. SDValue InVec = getValue(I.getOperand(0));
  2629. SDValue InVal = getValue(I.getOperand(1));
  2630. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  2631. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2632. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2633. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2634. InVec, InVal, InIdx));
  2635. }
  2636. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2637. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2638. SDValue InVec = getValue(I.getOperand(0));
  2639. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  2640. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2641. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2642. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2643. InVec, InIdx));
  2644. }
  2645. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2646. SDValue Src1 = getValue(I.getOperand(0));
  2647. SDValue Src2 = getValue(I.getOperand(1));
  2648. SDLoc DL = getCurSDLoc();
  2649. SmallVector<int, 8> Mask;
  2650. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2651. unsigned MaskNumElts = Mask.size();
  2652. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2653. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2654. EVT SrcVT = Src1.getValueType();
  2655. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2656. if (SrcNumElts == MaskNumElts) {
  2657. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  2658. return;
  2659. }
  2660. // Normalize the shuffle vector since mask and vector length don't match.
  2661. if (SrcNumElts < MaskNumElts) {
  2662. // Mask is longer than the source vectors. We can use concatenate vector to
  2663. // make the mask and vectors lengths match.
  2664. if (MaskNumElts % SrcNumElts == 0) {
  2665. // Mask length is a multiple of the source vector length.
  2666. // Check if the shuffle is some kind of concatenation of the input
  2667. // vectors.
  2668. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2669. bool IsConcat = true;
  2670. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  2671. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2672. int Idx = Mask[i];
  2673. if (Idx < 0)
  2674. continue;
  2675. // Ensure the indices in each SrcVT sized piece are sequential and that
  2676. // the same source is used for the whole piece.
  2677. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  2678. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  2679. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  2680. IsConcat = false;
  2681. break;
  2682. }
  2683. // Remember which source this index came from.
  2684. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  2685. }
  2686. // The shuffle is concatenating multiple vectors together. Just emit
  2687. // a CONCAT_VECTORS operation.
  2688. if (IsConcat) {
  2689. SmallVector<SDValue, 8> ConcatOps;
  2690. for (auto Src : ConcatSrcs) {
  2691. if (Src < 0)
  2692. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  2693. else if (Src == 0)
  2694. ConcatOps.push_back(Src1);
  2695. else
  2696. ConcatOps.push_back(Src2);
  2697. }
  2698. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  2699. return;
  2700. }
  2701. }
  2702. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  2703. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  2704. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  2705. PaddedMaskNumElts);
  2706. // Pad both vectors with undefs to make them the same length as the mask.
  2707. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2708. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2709. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2710. MOps1[0] = Src1;
  2711. MOps2[0] = Src2;
  2712. Src1 = Src1.isUndef()
  2713. ? DAG.getUNDEF(PaddedVT)
  2714. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  2715. Src2 = Src2.isUndef()
  2716. ? DAG.getUNDEF(PaddedVT)
  2717. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  2718. // Readjust mask for new input vector length.
  2719. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  2720. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2721. int Idx = Mask[i];
  2722. if (Idx >= (int)SrcNumElts)
  2723. Idx -= SrcNumElts - PaddedMaskNumElts;
  2724. MappedOps[i] = Idx;
  2725. }
  2726. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  2727. // If the concatenated vector was padded, extract a subvector with the
  2728. // correct number of elements.
  2729. if (MaskNumElts != PaddedMaskNumElts)
  2730. Result = DAG.getNode(
  2731. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  2732. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  2733. setValue(&I, Result);
  2734. return;
  2735. }
  2736. if (SrcNumElts > MaskNumElts) {
  2737. // Analyze the access pattern of the vector to see if we can extract
  2738. // two subvectors and do the shuffle.
  2739. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  2740. bool CanExtract = true;
  2741. for (int Idx : Mask) {
  2742. unsigned Input = 0;
  2743. if (Idx < 0)
  2744. continue;
  2745. if (Idx >= (int)SrcNumElts) {
  2746. Input = 1;
  2747. Idx -= SrcNumElts;
  2748. }
  2749. // If all the indices come from the same MaskNumElts sized portion of
  2750. // the sources we can use extract. Also make sure the extract wouldn't
  2751. // extract past the end of the source.
  2752. int NewStartIdx = alignDown(Idx, MaskNumElts);
  2753. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  2754. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  2755. CanExtract = false;
  2756. // Make sure we always update StartIdx as we use it to track if all
  2757. // elements are undef.
  2758. StartIdx[Input] = NewStartIdx;
  2759. }
  2760. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  2761. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2762. return;
  2763. }
  2764. if (CanExtract) {
  2765. // Extract appropriate subvector and generate a vector shuffle
  2766. for (unsigned Input = 0; Input < 2; ++Input) {
  2767. SDValue &Src = Input == 0 ? Src1 : Src2;
  2768. if (StartIdx[Input] < 0)
  2769. Src = DAG.getUNDEF(VT);
  2770. else {
  2771. Src = DAG.getNode(
  2772. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  2773. DAG.getConstant(StartIdx[Input], DL,
  2774. TLI.getVectorIdxTy(DAG.getDataLayout())));
  2775. }
  2776. }
  2777. // Calculate new mask.
  2778. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  2779. for (int &Idx : MappedOps) {
  2780. if (Idx >= (int)SrcNumElts)
  2781. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2782. else if (Idx >= 0)
  2783. Idx -= StartIdx[0];
  2784. }
  2785. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  2786. return;
  2787. }
  2788. }
  2789. // We can't use either concat vectors or extract subvectors so fall back to
  2790. // replacing the shuffle with extract and build vector.
  2791. // to insert and build vector.
  2792. EVT EltVT = VT.getVectorElementType();
  2793. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  2794. SmallVector<SDValue,8> Ops;
  2795. for (int Idx : Mask) {
  2796. SDValue Res;
  2797. if (Idx < 0) {
  2798. Res = DAG.getUNDEF(EltVT);
  2799. } else {
  2800. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2801. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2802. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  2803. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  2804. }
  2805. Ops.push_back(Res);
  2806. }
  2807. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  2808. }
  2809. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  2810. ArrayRef<unsigned> Indices;
  2811. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  2812. Indices = IV->getIndices();
  2813. else
  2814. Indices = cast<ConstantExpr>(&I)->getIndices();
  2815. const Value *Op0 = I.getOperand(0);
  2816. const Value *Op1 = I.getOperand(1);
  2817. Type *AggTy = I.getType();
  2818. Type *ValTy = Op1->getType();
  2819. bool IntoUndef = isa<UndefValue>(Op0);
  2820. bool FromUndef = isa<UndefValue>(Op1);
  2821. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2822. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2823. SmallVector<EVT, 4> AggValueVTs;
  2824. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  2825. SmallVector<EVT, 4> ValValueVTs;
  2826. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2827. unsigned NumAggValues = AggValueVTs.size();
  2828. unsigned NumValValues = ValValueVTs.size();
  2829. SmallVector<SDValue, 4> Values(NumAggValues);
  2830. // Ignore an insertvalue that produces an empty object
  2831. if (!NumAggValues) {
  2832. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2833. return;
  2834. }
  2835. SDValue Agg = getValue(Op0);
  2836. unsigned i = 0;
  2837. // Copy the beginning value(s) from the original aggregate.
  2838. for (; i != LinearIndex; ++i)
  2839. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2840. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2841. // Copy values from the inserted value(s).
  2842. if (NumValValues) {
  2843. SDValue Val = getValue(Op1);
  2844. for (; i != LinearIndex + NumValValues; ++i)
  2845. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2846. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2847. }
  2848. // Copy remaining value(s) from the original aggregate.
  2849. for (; i != NumAggValues; ++i)
  2850. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2851. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2852. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2853. DAG.getVTList(AggValueVTs), Values));
  2854. }
  2855. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  2856. ArrayRef<unsigned> Indices;
  2857. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  2858. Indices = EV->getIndices();
  2859. else
  2860. Indices = cast<ConstantExpr>(&I)->getIndices();
  2861. const Value *Op0 = I.getOperand(0);
  2862. Type *AggTy = Op0->getType();
  2863. Type *ValTy = I.getType();
  2864. bool OutOfUndef = isa<UndefValue>(Op0);
  2865. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2866. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2867. SmallVector<EVT, 4> ValValueVTs;
  2868. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2869. unsigned NumValValues = ValValueVTs.size();
  2870. // Ignore a extractvalue that produces an empty object
  2871. if (!NumValValues) {
  2872. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2873. return;
  2874. }
  2875. SmallVector<SDValue, 4> Values(NumValValues);
  2876. SDValue Agg = getValue(Op0);
  2877. // Copy out the selected value(s).
  2878. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2879. Values[i - LinearIndex] =
  2880. OutOfUndef ?
  2881. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2882. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2883. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2884. DAG.getVTList(ValValueVTs), Values));
  2885. }
  2886. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2887. Value *Op0 = I.getOperand(0);
  2888. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2889. // element which holds a pointer.
  2890. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  2891. SDValue N = getValue(Op0);
  2892. SDLoc dl = getCurSDLoc();
  2893. // Normalize Vector GEP - all scalar operands should be converted to the
  2894. // splat vector.
  2895. unsigned VectorWidth = I.getType()->isVectorTy() ?
  2896. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  2897. if (VectorWidth && !N.getValueType().isVector()) {
  2898. LLVMContext &Context = *DAG.getContext();
  2899. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  2900. N = DAG.getSplatBuildVector(VT, dl, N);
  2901. }
  2902. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  2903. GTI != E; ++GTI) {
  2904. const Value *Idx = GTI.getOperand();
  2905. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  2906. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2907. if (Field) {
  2908. // N = N + Offset
  2909. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  2910. // In an inbounds GEP with an offset that is nonnegative even when
  2911. // interpreted as signed, assume there is no unsigned overflow.
  2912. SDNodeFlags Flags;
  2913. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  2914. Flags.setNoUnsignedWrap(true);
  2915. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  2916. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  2917. }
  2918. } else {
  2919. MVT PtrTy =
  2920. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
  2921. unsigned PtrSize = PtrTy.getSizeInBits();
  2922. APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  2923. // If this is a scalar constant or a splat vector of constants,
  2924. // handle it quickly.
  2925. const auto *CI = dyn_cast<ConstantInt>(Idx);
  2926. if (!CI && isa<ConstantDataVector>(Idx) &&
  2927. cast<ConstantDataVector>(Idx)->getSplatValue())
  2928. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  2929. if (CI) {
  2930. if (CI->isZero())
  2931. continue;
  2932. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
  2933. LLVMContext &Context = *DAG.getContext();
  2934. SDValue OffsVal = VectorWidth ?
  2935. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) :
  2936. DAG.getConstant(Offs, dl, PtrTy);
  2937. // In an inbouds GEP with an offset that is nonnegative even when
  2938. // interpreted as signed, assume there is no unsigned overflow.
  2939. SDNodeFlags Flags;
  2940. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  2941. Flags.setNoUnsignedWrap(true);
  2942. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  2943. continue;
  2944. }
  2945. // N = N + Idx * ElementSize;
  2946. SDValue IdxN = getValue(Idx);
  2947. if (!IdxN.getValueType().isVector() && VectorWidth) {
  2948. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  2949. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  2950. }
  2951. // If the index is smaller or larger than intptr_t, truncate or extend
  2952. // it.
  2953. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  2954. // If this is a multiply by a power of two, turn it into a shl
  2955. // immediately. This is a very common case.
  2956. if (ElementSize != 1) {
  2957. if (ElementSize.isPowerOf2()) {
  2958. unsigned Amt = ElementSize.logBase2();
  2959. IdxN = DAG.getNode(ISD::SHL, dl,
  2960. N.getValueType(), IdxN,
  2961. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  2962. } else {
  2963. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  2964. IdxN = DAG.getNode(ISD::MUL, dl,
  2965. N.getValueType(), IdxN, Scale);
  2966. }
  2967. }
  2968. N = DAG.getNode(ISD::ADD, dl,
  2969. N.getValueType(), N, IdxN);
  2970. }
  2971. }
  2972. setValue(&I, N);
  2973. }
  2974. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2975. // If this is a fixed sized alloca in the entry block of the function,
  2976. // allocate it statically on the stack.
  2977. if (FuncInfo.StaticAllocaMap.count(&I))
  2978. return; // getValue will auto-populate this.
  2979. SDLoc dl = getCurSDLoc();
  2980. Type *Ty = I.getAllocatedType();
  2981. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2982. auto &DL = DAG.getDataLayout();
  2983. uint64_t TySize = DL.getTypeAllocSize(Ty);
  2984. unsigned Align =
  2985. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  2986. SDValue AllocSize = getValue(I.getArraySize());
  2987. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
  2988. if (AllocSize.getValueType() != IntPtr)
  2989. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  2990. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  2991. AllocSize,
  2992. DAG.getConstant(TySize, dl, IntPtr));
  2993. // Handle alignment. If the requested alignment is less than or equal to
  2994. // the stack alignment, ignore it. If the size is greater than or equal to
  2995. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2996. unsigned StackAlign =
  2997. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  2998. if (Align <= StackAlign)
  2999. Align = 0;
  3000. // Round the size of the allocation up to the stack alignment size
  3001. // by add SA-1 to the size. This doesn't overflow because we're computing
  3002. // an address inside an alloca.
  3003. SDNodeFlags Flags;
  3004. Flags.setNoUnsignedWrap(true);
  3005. AllocSize = DAG.getNode(ISD::ADD, dl,
  3006. AllocSize.getValueType(), AllocSize,
  3007. DAG.getIntPtrConstant(StackAlign - 1, dl), Flags);
  3008. // Mask out the low bits for alignment purposes.
  3009. AllocSize = DAG.getNode(ISD::AND, dl,
  3010. AllocSize.getValueType(), AllocSize,
  3011. DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
  3012. dl));
  3013. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
  3014. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3015. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3016. setValue(&I, DSA);
  3017. DAG.setRoot(DSA.getValue(1));
  3018. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3019. }
  3020. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3021. if (I.isAtomic())
  3022. return visitAtomicLoad(I);
  3023. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3024. const Value *SV = I.getOperand(0);
  3025. if (TLI.supportSwiftError()) {
  3026. // Swifterror values can come from either a function parameter with
  3027. // swifterror attribute or an alloca with swifterror attribute.
  3028. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3029. if (Arg->hasSwiftErrorAttr())
  3030. return visitLoadFromSwiftError(I);
  3031. }
  3032. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3033. if (Alloca->isSwiftError())
  3034. return visitLoadFromSwiftError(I);
  3035. }
  3036. }
  3037. SDValue Ptr = getValue(SV);
  3038. Type *Ty = I.getType();
  3039. bool isVolatile = I.isVolatile();
  3040. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3041. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3042. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3043. unsigned Alignment = I.getAlignment();
  3044. AAMDNodes AAInfo;
  3045. I.getAAMetadata(AAInfo);
  3046. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3047. SmallVector<EVT, 4> ValueVTs;
  3048. SmallVector<uint64_t, 4> Offsets;
  3049. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  3050. unsigned NumValues = ValueVTs.size();
  3051. if (NumValues == 0)
  3052. return;
  3053. SDValue Root;
  3054. bool ConstantMemory = false;
  3055. if (isVolatile || NumValues > MaxParallelChains)
  3056. // Serialize volatile loads with other side effects.
  3057. Root = getRoot();
  3058. else if (AA && AA->pointsToConstantMemory(MemoryLocation(
  3059. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
  3060. // Do not serialize (non-volatile) loads of constant memory with anything.
  3061. Root = DAG.getEntryNode();
  3062. ConstantMemory = true;
  3063. } else {
  3064. // Do not serialize non-volatile loads against each other.
  3065. Root = DAG.getRoot();
  3066. }
  3067. SDLoc dl = getCurSDLoc();
  3068. if (isVolatile)
  3069. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3070. // An aggregate load cannot wrap around the address space, so offsets to its
  3071. // parts don't wrap either.
  3072. SDNodeFlags Flags;
  3073. Flags.setNoUnsignedWrap(true);
  3074. SmallVector<SDValue, 4> Values(NumValues);
  3075. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3076. EVT PtrVT = Ptr.getValueType();
  3077. unsigned ChainI = 0;
  3078. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3079. // Serializing loads here may result in excessive register pressure, and
  3080. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3081. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3082. // they are side-effect free or do not alias. The optimizer should really
  3083. // avoid this case by converting large object/array copies to llvm.memcpy
  3084. // (MaxParallelChains should always remain as failsafe).
  3085. if (ChainI == MaxParallelChains) {
  3086. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3087. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3088. makeArrayRef(Chains.data(), ChainI));
  3089. Root = Chain;
  3090. ChainI = 0;
  3091. }
  3092. SDValue A = DAG.getNode(ISD::ADD, dl,
  3093. PtrVT, Ptr,
  3094. DAG.getConstant(Offsets[i], dl, PtrVT),
  3095. Flags);
  3096. auto MMOFlags = MachineMemOperand::MONone;
  3097. if (isVolatile)
  3098. MMOFlags |= MachineMemOperand::MOVolatile;
  3099. if (isNonTemporal)
  3100. MMOFlags |= MachineMemOperand::MONonTemporal;
  3101. if (isInvariant)
  3102. MMOFlags |= MachineMemOperand::MOInvariant;
  3103. if (isDereferenceable)
  3104. MMOFlags |= MachineMemOperand::MODereferenceable;
  3105. MMOFlags |= TLI.getMMOFlags(I);
  3106. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3107. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3108. MMOFlags, AAInfo, Ranges);
  3109. Values[i] = L;
  3110. Chains[ChainI] = L.getValue(1);
  3111. }
  3112. if (!ConstantMemory) {
  3113. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3114. makeArrayRef(Chains.data(), ChainI));
  3115. if (isVolatile)
  3116. DAG.setRoot(Chain);
  3117. else
  3118. PendingLoads.push_back(Chain);
  3119. }
  3120. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3121. DAG.getVTList(ValueVTs), Values));
  3122. }
  3123. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3124. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3125. "call visitStoreToSwiftError when backend supports swifterror");
  3126. SmallVector<EVT, 4> ValueVTs;
  3127. SmallVector<uint64_t, 4> Offsets;
  3128. const Value *SrcV = I.getOperand(0);
  3129. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3130. SrcV->getType(), ValueVTs, &Offsets);
  3131. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3132. "expect a single EVT for swifterror");
  3133. SDValue Src = getValue(SrcV);
  3134. // Create a virtual register, then update the virtual register.
  3135. unsigned VReg; bool CreatedVReg;
  3136. std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
  3137. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3138. // Chain can be getRoot or getControlRoot.
  3139. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3140. SDValue(Src.getNode(), Src.getResNo()));
  3141. DAG.setRoot(CopyNode);
  3142. if (CreatedVReg)
  3143. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3144. }
  3145. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3146. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3147. "call visitLoadFromSwiftError when backend supports swifterror");
  3148. assert(!I.isVolatile() &&
  3149. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3150. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3151. "Support volatile, non temporal, invariant for load_from_swift_error");
  3152. const Value *SV = I.getOperand(0);
  3153. Type *Ty = I.getType();
  3154. AAMDNodes AAInfo;
  3155. I.getAAMetadata(AAInfo);
  3156. assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
  3157. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
  3158. "load_from_swift_error should not be constant memory");
  3159. SmallVector<EVT, 4> ValueVTs;
  3160. SmallVector<uint64_t, 4> Offsets;
  3161. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3162. ValueVTs, &Offsets);
  3163. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3164. "expect a single EVT for swifterror");
  3165. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3166. SDValue L = DAG.getCopyFromReg(
  3167. getRoot(), getCurSDLoc(),
  3168. FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
  3169. ValueVTs[0]);
  3170. setValue(&I, L);
  3171. }
  3172. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3173. if (I.isAtomic())
  3174. return visitAtomicStore(I);
  3175. const Value *SrcV = I.getOperand(0);
  3176. const Value *PtrV = I.getOperand(1);
  3177. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3178. if (TLI.supportSwiftError()) {
  3179. // Swifterror values can come from either a function parameter with
  3180. // swifterror attribute or an alloca with swifterror attribute.
  3181. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3182. if (Arg->hasSwiftErrorAttr())
  3183. return visitStoreToSwiftError(I);
  3184. }
  3185. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3186. if (Alloca->isSwiftError())
  3187. return visitStoreToSwiftError(I);
  3188. }
  3189. }
  3190. SmallVector<EVT, 4> ValueVTs;
  3191. SmallVector<uint64_t, 4> Offsets;
  3192. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3193. SrcV->getType(), ValueVTs, &Offsets);
  3194. unsigned NumValues = ValueVTs.size();
  3195. if (NumValues == 0)
  3196. return;
  3197. // Get the lowered operands. Note that we do this after
  3198. // checking if NumResults is zero, because with zero results
  3199. // the operands won't have values in the map.
  3200. SDValue Src = getValue(SrcV);
  3201. SDValue Ptr = getValue(PtrV);
  3202. SDValue Root = getRoot();
  3203. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3204. SDLoc dl = getCurSDLoc();
  3205. EVT PtrVT = Ptr.getValueType();
  3206. unsigned Alignment = I.getAlignment();
  3207. AAMDNodes AAInfo;
  3208. I.getAAMetadata(AAInfo);
  3209. auto MMOFlags = MachineMemOperand::MONone;
  3210. if (I.isVolatile())
  3211. MMOFlags |= MachineMemOperand::MOVolatile;
  3212. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3213. MMOFlags |= MachineMemOperand::MONonTemporal;
  3214. MMOFlags |= TLI.getMMOFlags(I);
  3215. // An aggregate load cannot wrap around the address space, so offsets to its
  3216. // parts don't wrap either.
  3217. SDNodeFlags Flags;
  3218. Flags.setNoUnsignedWrap(true);
  3219. unsigned ChainI = 0;
  3220. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3221. // See visitLoad comments.
  3222. if (ChainI == MaxParallelChains) {
  3223. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3224. makeArrayRef(Chains.data(), ChainI));
  3225. Root = Chain;
  3226. ChainI = 0;
  3227. }
  3228. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3229. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3230. SDValue St = DAG.getStore(
  3231. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3232. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3233. Chains[ChainI] = St;
  3234. }
  3235. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3236. makeArrayRef(Chains.data(), ChainI));
  3237. DAG.setRoot(StoreNode);
  3238. }
  3239. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3240. bool IsCompressing) {
  3241. SDLoc sdl = getCurSDLoc();
  3242. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3243. unsigned& Alignment) {
  3244. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3245. Src0 = I.getArgOperand(0);
  3246. Ptr = I.getArgOperand(1);
  3247. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3248. Mask = I.getArgOperand(3);
  3249. };
  3250. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3251. unsigned& Alignment) {
  3252. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3253. Src0 = I.getArgOperand(0);
  3254. Ptr = I.getArgOperand(1);
  3255. Mask = I.getArgOperand(2);
  3256. Alignment = 0;
  3257. };
  3258. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3259. unsigned Alignment;
  3260. if (IsCompressing)
  3261. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3262. else
  3263. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3264. SDValue Ptr = getValue(PtrOperand);
  3265. SDValue Src0 = getValue(Src0Operand);
  3266. SDValue Mask = getValue(MaskOperand);
  3267. EVT VT = Src0.getValueType();
  3268. if (!Alignment)
  3269. Alignment = DAG.getEVTAlignment(VT);
  3270. AAMDNodes AAInfo;
  3271. I.getAAMetadata(AAInfo);
  3272. MachineMemOperand *MMO =
  3273. DAG.getMachineFunction().
  3274. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3275. MachineMemOperand::MOStore, VT.getStoreSize(),
  3276. Alignment, AAInfo);
  3277. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3278. MMO, false /* Truncating */,
  3279. IsCompressing);
  3280. DAG.setRoot(StoreNode);
  3281. setValue(&I, StoreNode);
  3282. }
  3283. // Get a uniform base for the Gather/Scatter intrinsic.
  3284. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3285. // We try to represent it as a base pointer + vector of indices.
  3286. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3287. // The first operand of the GEP may be a single pointer or a vector of pointers
  3288. // Example:
  3289. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3290. // or
  3291. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3292. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3293. //
  3294. // When the first GEP operand is a single pointer - it is the uniform base we
  3295. // are looking for. If first operand of the GEP is a splat vector - we
  3296. // extract the spalt value and use it as a uniform base.
  3297. // In all other cases the function returns 'false'.
  3298. //
  3299. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3300. SelectionDAGBuilder* SDB) {
  3301. SelectionDAG& DAG = SDB->DAG;
  3302. LLVMContext &Context = *DAG.getContext();
  3303. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3304. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3305. if (!GEP || GEP->getNumOperands() > 2)
  3306. return false;
  3307. const Value *GEPPtr = GEP->getPointerOperand();
  3308. if (!GEPPtr->getType()->isVectorTy())
  3309. Ptr = GEPPtr;
  3310. else if (!(Ptr = getSplatValue(GEPPtr)))
  3311. return false;
  3312. Value *IndexVal = GEP->getOperand(1);
  3313. // The operands of the GEP may be defined in another basic block.
  3314. // In this case we'll not find nodes for the operands.
  3315. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3316. return false;
  3317. Base = SDB->getValue(Ptr);
  3318. Index = SDB->getValue(IndexVal);
  3319. // Suppress sign extension.
  3320. if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
  3321. if (SDB->findValue(Sext->getOperand(0))) {
  3322. IndexVal = Sext->getOperand(0);
  3323. Index = SDB->getValue(IndexVal);
  3324. }
  3325. }
  3326. if (!Index.getValueType().isVector()) {
  3327. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3328. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3329. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3330. }
  3331. return true;
  3332. }
  3333. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3334. SDLoc sdl = getCurSDLoc();
  3335. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3336. const Value *Ptr = I.getArgOperand(1);
  3337. SDValue Src0 = getValue(I.getArgOperand(0));
  3338. SDValue Mask = getValue(I.getArgOperand(3));
  3339. EVT VT = Src0.getValueType();
  3340. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3341. if (!Alignment)
  3342. Alignment = DAG.getEVTAlignment(VT);
  3343. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3344. AAMDNodes AAInfo;
  3345. I.getAAMetadata(AAInfo);
  3346. SDValue Base;
  3347. SDValue Index;
  3348. const Value *BasePtr = Ptr;
  3349. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  3350. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3351. MachineMemOperand *MMO = DAG.getMachineFunction().
  3352. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3353. MachineMemOperand::MOStore, VT.getStoreSize(),
  3354. Alignment, AAInfo);
  3355. if (!UniformBase) {
  3356. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3357. Index = getValue(Ptr);
  3358. }
  3359. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
  3360. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3361. Ops, MMO);
  3362. DAG.setRoot(Scatter);
  3363. setValue(&I, Scatter);
  3364. }
  3365. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3366. SDLoc sdl = getCurSDLoc();
  3367. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3368. unsigned& Alignment) {
  3369. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3370. Ptr = I.getArgOperand(0);
  3371. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3372. Mask = I.getArgOperand(2);
  3373. Src0 = I.getArgOperand(3);
  3374. };
  3375. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3376. unsigned& Alignment) {
  3377. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3378. Ptr = I.getArgOperand(0);
  3379. Alignment = 0;
  3380. Mask = I.getArgOperand(1);
  3381. Src0 = I.getArgOperand(2);
  3382. };
  3383. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3384. unsigned Alignment;
  3385. if (IsExpanding)
  3386. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3387. else
  3388. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3389. SDValue Ptr = getValue(PtrOperand);
  3390. SDValue Src0 = getValue(Src0Operand);
  3391. SDValue Mask = getValue(MaskOperand);
  3392. EVT VT = Src0.getValueType();
  3393. if (!Alignment)
  3394. Alignment = DAG.getEVTAlignment(VT);
  3395. AAMDNodes AAInfo;
  3396. I.getAAMetadata(AAInfo);
  3397. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3398. // Do not serialize masked loads of constant memory with anything.
  3399. bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3400. PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
  3401. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3402. MachineMemOperand *MMO =
  3403. DAG.getMachineFunction().
  3404. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3405. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3406. Alignment, AAInfo, Ranges);
  3407. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3408. ISD::NON_EXTLOAD, IsExpanding);
  3409. if (AddToChain) {
  3410. SDValue OutChain = Load.getValue(1);
  3411. DAG.setRoot(OutChain);
  3412. }
  3413. setValue(&I, Load);
  3414. }
  3415. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3416. SDLoc sdl = getCurSDLoc();
  3417. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3418. const Value *Ptr = I.getArgOperand(0);
  3419. SDValue Src0 = getValue(I.getArgOperand(3));
  3420. SDValue Mask = getValue(I.getArgOperand(2));
  3421. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3422. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3423. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3424. if (!Alignment)
  3425. Alignment = DAG.getEVTAlignment(VT);
  3426. AAMDNodes AAInfo;
  3427. I.getAAMetadata(AAInfo);
  3428. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3429. SDValue Root = DAG.getRoot();
  3430. SDValue Base;
  3431. SDValue Index;
  3432. const Value *BasePtr = Ptr;
  3433. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  3434. bool ConstantMemory = false;
  3435. if (UniformBase &&
  3436. AA && AA->pointsToConstantMemory(MemoryLocation(
  3437. BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
  3438. AAInfo))) {
  3439. // Do not serialize (non-volatile) loads of constant memory with anything.
  3440. Root = DAG.getEntryNode();
  3441. ConstantMemory = true;
  3442. }
  3443. MachineMemOperand *MMO =
  3444. DAG.getMachineFunction().
  3445. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3446. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3447. Alignment, AAInfo, Ranges);
  3448. if (!UniformBase) {
  3449. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3450. Index = getValue(Ptr);
  3451. }
  3452. SDValue Ops[] = { Root, Src0, Mask, Base, Index };
  3453. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3454. Ops, MMO);
  3455. SDValue OutChain = Gather.getValue(1);
  3456. if (!ConstantMemory)
  3457. PendingLoads.push_back(OutChain);
  3458. setValue(&I, Gather);
  3459. }
  3460. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3461. SDLoc dl = getCurSDLoc();
  3462. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3463. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3464. SyncScope::ID SSID = I.getSyncScopeID();
  3465. SDValue InChain = getRoot();
  3466. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3467. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3468. SDValue L = DAG.getAtomicCmpSwap(
  3469. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3470. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3471. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3472. /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
  3473. SDValue OutChain = L.getValue(2);
  3474. setValue(&I, L);
  3475. DAG.setRoot(OutChain);
  3476. }
  3477. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3478. SDLoc dl = getCurSDLoc();
  3479. ISD::NodeType NT;
  3480. switch (I.getOperation()) {
  3481. default: llvm_unreachable("Unknown atomicrmw operation");
  3482. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3483. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3484. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3485. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3486. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3487. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3488. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3489. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3490. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3491. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3492. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3493. }
  3494. AtomicOrdering Order = I.getOrdering();
  3495. SyncScope::ID SSID = I.getSyncScopeID();
  3496. SDValue InChain = getRoot();
  3497. SDValue L =
  3498. DAG.getAtomic(NT, dl,
  3499. getValue(I.getValOperand()).getSimpleValueType(),
  3500. InChain,
  3501. getValue(I.getPointerOperand()),
  3502. getValue(I.getValOperand()),
  3503. I.getPointerOperand(),
  3504. /* Alignment=*/ 0, Order, SSID);
  3505. SDValue OutChain = L.getValue(1);
  3506. setValue(&I, L);
  3507. DAG.setRoot(OutChain);
  3508. }
  3509. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3510. SDLoc dl = getCurSDLoc();
  3511. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3512. SDValue Ops[3];
  3513. Ops[0] = getRoot();
  3514. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3515. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3516. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  3517. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3518. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3519. }
  3520. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3521. SDLoc dl = getCurSDLoc();
  3522. AtomicOrdering Order = I.getOrdering();
  3523. SyncScope::ID SSID = I.getSyncScopeID();
  3524. SDValue InChain = getRoot();
  3525. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3526. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3527. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3528. report_fatal_error("Cannot generate unaligned atomic load");
  3529. MachineMemOperand *MMO =
  3530. DAG.getMachineFunction().
  3531. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3532. MachineMemOperand::MOVolatile |
  3533. MachineMemOperand::MOLoad,
  3534. VT.getStoreSize(),
  3535. I.getAlignment() ? I.getAlignment() :
  3536. DAG.getEVTAlignment(VT),
  3537. AAMDNodes(), nullptr, SSID, Order);
  3538. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3539. SDValue L =
  3540. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3541. getValue(I.getPointerOperand()), MMO);
  3542. SDValue OutChain = L.getValue(1);
  3543. setValue(&I, L);
  3544. DAG.setRoot(OutChain);
  3545. }
  3546. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3547. SDLoc dl = getCurSDLoc();
  3548. AtomicOrdering Order = I.getOrdering();
  3549. SyncScope::ID SSID = I.getSyncScopeID();
  3550. SDValue InChain = getRoot();
  3551. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3552. EVT VT =
  3553. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  3554. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3555. report_fatal_error("Cannot generate unaligned atomic store");
  3556. SDValue OutChain =
  3557. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3558. InChain,
  3559. getValue(I.getPointerOperand()),
  3560. getValue(I.getValueOperand()),
  3561. I.getPointerOperand(), I.getAlignment(),
  3562. Order, SSID);
  3563. DAG.setRoot(OutChain);
  3564. }
  3565. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3566. /// node.
  3567. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3568. unsigned Intrinsic) {
  3569. // Ignore the callsite's attributes. A specific call site may be marked with
  3570. // readnone, but the lowering code will expect the chain based on the
  3571. // definition.
  3572. const Function *F = I.getCalledFunction();
  3573. bool HasChain = !F->doesNotAccessMemory();
  3574. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  3575. // Build the operand list.
  3576. SmallVector<SDValue, 8> Ops;
  3577. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3578. if (OnlyLoad) {
  3579. // We don't need to serialize loads against other loads.
  3580. Ops.push_back(DAG.getRoot());
  3581. } else {
  3582. Ops.push_back(getRoot());
  3583. }
  3584. }
  3585. // Info is set by getTgtMemInstrinsic
  3586. TargetLowering::IntrinsicInfo Info;
  3587. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3588. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  3589. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3590. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3591. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3592. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  3593. TLI.getPointerTy(DAG.getDataLayout())));
  3594. // Add all operands of the call to the operand list.
  3595. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3596. SDValue Op = getValue(I.getArgOperand(i));
  3597. Ops.push_back(Op);
  3598. }
  3599. SmallVector<EVT, 4> ValueVTs;
  3600. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  3601. if (HasChain)
  3602. ValueVTs.push_back(MVT::Other);
  3603. SDVTList VTs = DAG.getVTList(ValueVTs);
  3604. // Create the node.
  3605. SDValue Result;
  3606. if (IsTgtIntrinsic) {
  3607. // This is target intrinsic that touches memory
  3608. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
  3609. VTs, Ops, Info.memVT,
  3610. MachinePointerInfo(Info.ptrVal, Info.offset),
  3611. Info.align, Info.vol,
  3612. Info.readMem, Info.writeMem, Info.size);
  3613. } else if (!HasChain) {
  3614. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3615. } else if (!I.getType()->isVoidTy()) {
  3616. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3617. } else {
  3618. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3619. }
  3620. if (HasChain) {
  3621. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3622. if (OnlyLoad)
  3623. PendingLoads.push_back(Chain);
  3624. else
  3625. DAG.setRoot(Chain);
  3626. }
  3627. if (!I.getType()->isVoidTy()) {
  3628. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3629. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  3630. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3631. } else
  3632. Result = lowerRangeToAssertZExt(DAG, I, Result);
  3633. setValue(&I, Result);
  3634. }
  3635. }
  3636. /// GetSignificand - Get the significand and build it into a floating-point
  3637. /// number with exponent of 1:
  3638. ///
  3639. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3640. ///
  3641. /// where Op is the hexadecimal representation of floating point value.
  3642. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  3643. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3644. DAG.getConstant(0x007fffff, dl, MVT::i32));
  3645. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3646. DAG.getConstant(0x3f800000, dl, MVT::i32));
  3647. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3648. }
  3649. /// GetExponent - Get the exponent:
  3650. ///
  3651. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3652. ///
  3653. /// where Op is the hexadecimal representation of floating point value.
  3654. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  3655. const TargetLowering &TLI, const SDLoc &dl) {
  3656. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3657. DAG.getConstant(0x7f800000, dl, MVT::i32));
  3658. SDValue t1 = DAG.getNode(
  3659. ISD::SRL, dl, MVT::i32, t0,
  3660. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  3661. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3662. DAG.getConstant(127, dl, MVT::i32));
  3663. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3664. }
  3665. /// getF32Constant - Get 32-bit floating point constant.
  3666. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  3667. const SDLoc &dl) {
  3668. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  3669. MVT::f32);
  3670. }
  3671. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  3672. SelectionDAG &DAG) {
  3673. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3674. // IntegerPartOfX = ((int32_t)(t0);
  3675. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3676. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  3677. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3678. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3679. // IntegerPartOfX <<= 23;
  3680. IntegerPartOfX = DAG.getNode(
  3681. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3682. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  3683. DAG.getDataLayout())));
  3684. SDValue TwoToFractionalPartOfX;
  3685. if (LimitFloatPrecision <= 6) {
  3686. // For floating-point precision of 6:
  3687. //
  3688. // TwoToFractionalPartOfX =
  3689. // 0.997535578f +
  3690. // (0.735607626f + 0.252464424f * x) * x;
  3691. //
  3692. // error 0.0144103317, which is 6 bits
  3693. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3694. getF32Constant(DAG, 0x3e814304, dl));
  3695. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3696. getF32Constant(DAG, 0x3f3c50c8, dl));
  3697. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3698. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3699. getF32Constant(DAG, 0x3f7f5e7e, dl));
  3700. } else if (LimitFloatPrecision <= 12) {
  3701. // For floating-point precision of 12:
  3702. //
  3703. // TwoToFractionalPartOfX =
  3704. // 0.999892986f +
  3705. // (0.696457318f +
  3706. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3707. //
  3708. // error 0.000107046256, which is 13 to 14 bits
  3709. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3710. getF32Constant(DAG, 0x3da235e3, dl));
  3711. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3712. getF32Constant(DAG, 0x3e65b8f3, dl));
  3713. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3714. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3715. getF32Constant(DAG, 0x3f324b07, dl));
  3716. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3717. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3718. getF32Constant(DAG, 0x3f7ff8fd, dl));
  3719. } else { // LimitFloatPrecision <= 18
  3720. // For floating-point precision of 18:
  3721. //
  3722. // TwoToFractionalPartOfX =
  3723. // 0.999999982f +
  3724. // (0.693148872f +
  3725. // (0.240227044f +
  3726. // (0.554906021e-1f +
  3727. // (0.961591928e-2f +
  3728. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3729. // error 2.47208000*10^(-7), which is better than 18 bits
  3730. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3731. getF32Constant(DAG, 0x3924b03e, dl));
  3732. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3733. getF32Constant(DAG, 0x3ab24b87, dl));
  3734. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3735. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3736. getF32Constant(DAG, 0x3c1d8c17, dl));
  3737. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3738. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3739. getF32Constant(DAG, 0x3d634a1d, dl));
  3740. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3741. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3742. getF32Constant(DAG, 0x3e75fe14, dl));
  3743. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3744. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3745. getF32Constant(DAG, 0x3f317234, dl));
  3746. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3747. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3748. getF32Constant(DAG, 0x3f800000, dl));
  3749. }
  3750. // Add the exponent into the result in integer domain.
  3751. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  3752. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3753. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  3754. }
  3755. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3756. /// limited-precision mode.
  3757. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3758. const TargetLowering &TLI) {
  3759. if (Op.getValueType() == MVT::f32 &&
  3760. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3761. // Put the exponent in the right bit position for later addition to the
  3762. // final result:
  3763. //
  3764. // #define LOG2OFe 1.4426950f
  3765. // t0 = Op * LOG2OFe
  3766. // TODO: What fast-math-flags should be set here?
  3767. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3768. getF32Constant(DAG, 0x3fb8aa3b, dl));
  3769. return getLimitedPrecisionExp2(t0, dl, DAG);
  3770. }
  3771. // No special expansion.
  3772. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3773. }
  3774. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3775. /// limited-precision mode.
  3776. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3777. const TargetLowering &TLI) {
  3778. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3779. if (Op.getValueType() == MVT::f32 &&
  3780. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3781. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3782. // Scale the exponent by log(2) [0.69314718f].
  3783. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3784. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3785. getF32Constant(DAG, 0x3f317218, dl));
  3786. // Get the significand and build it into a floating-point number with
  3787. // exponent of 1.
  3788. SDValue X = GetSignificand(DAG, Op1, dl);
  3789. SDValue LogOfMantissa;
  3790. if (LimitFloatPrecision <= 6) {
  3791. // For floating-point precision of 6:
  3792. //
  3793. // LogofMantissa =
  3794. // -1.1609546f +
  3795. // (1.4034025f - 0.23903021f * x) * x;
  3796. //
  3797. // error 0.0034276066, which is better than 8 bits
  3798. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3799. getF32Constant(DAG, 0xbe74c456, dl));
  3800. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3801. getF32Constant(DAG, 0x3fb3a2b1, dl));
  3802. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3803. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3804. getF32Constant(DAG, 0x3f949a29, dl));
  3805. } else if (LimitFloatPrecision <= 12) {
  3806. // For floating-point precision of 12:
  3807. //
  3808. // LogOfMantissa =
  3809. // -1.7417939f +
  3810. // (2.8212026f +
  3811. // (-1.4699568f +
  3812. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3813. //
  3814. // error 0.000061011436, which is 14 bits
  3815. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3816. getF32Constant(DAG, 0xbd67b6d6, dl));
  3817. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3818. getF32Constant(DAG, 0x3ee4f4b8, dl));
  3819. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3820. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3821. getF32Constant(DAG, 0x3fbc278b, dl));
  3822. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3823. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3824. getF32Constant(DAG, 0x40348e95, dl));
  3825. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3826. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3827. getF32Constant(DAG, 0x3fdef31a, dl));
  3828. } else { // LimitFloatPrecision <= 18
  3829. // For floating-point precision of 18:
  3830. //
  3831. // LogOfMantissa =
  3832. // -2.1072184f +
  3833. // (4.2372794f +
  3834. // (-3.7029485f +
  3835. // (2.2781945f +
  3836. // (-0.87823314f +
  3837. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3838. //
  3839. // error 0.0000023660568, which is better than 18 bits
  3840. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3841. getF32Constant(DAG, 0xbc91e5ac, dl));
  3842. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3843. getF32Constant(DAG, 0x3e4350aa, dl));
  3844. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3845. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3846. getF32Constant(DAG, 0x3f60d3e3, dl));
  3847. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3848. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3849. getF32Constant(DAG, 0x4011cdf0, dl));
  3850. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3851. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3852. getF32Constant(DAG, 0x406cfd1c, dl));
  3853. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3854. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3855. getF32Constant(DAG, 0x408797cb, dl));
  3856. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3857. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3858. getF32Constant(DAG, 0x4006dcab, dl));
  3859. }
  3860. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3861. }
  3862. // No special expansion.
  3863. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3864. }
  3865. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3866. /// limited-precision mode.
  3867. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3868. const TargetLowering &TLI) {
  3869. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3870. if (Op.getValueType() == MVT::f32 &&
  3871. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3872. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3873. // Get the exponent.
  3874. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3875. // Get the significand and build it into a floating-point number with
  3876. // exponent of 1.
  3877. SDValue X = GetSignificand(DAG, Op1, dl);
  3878. // Different possible minimax approximations of significand in
  3879. // floating-point for various degrees of accuracy over [1,2].
  3880. SDValue Log2ofMantissa;
  3881. if (LimitFloatPrecision <= 6) {
  3882. // For floating-point precision of 6:
  3883. //
  3884. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3885. //
  3886. // error 0.0049451742, which is more than 7 bits
  3887. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3888. getF32Constant(DAG, 0xbeb08fe0, dl));
  3889. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3890. getF32Constant(DAG, 0x40019463, dl));
  3891. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3892. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3893. getF32Constant(DAG, 0x3fd6633d, dl));
  3894. } else if (LimitFloatPrecision <= 12) {
  3895. // For floating-point precision of 12:
  3896. //
  3897. // Log2ofMantissa =
  3898. // -2.51285454f +
  3899. // (4.07009056f +
  3900. // (-2.12067489f +
  3901. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3902. //
  3903. // error 0.0000876136000, which is better than 13 bits
  3904. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3905. getF32Constant(DAG, 0xbda7262e, dl));
  3906. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3907. getF32Constant(DAG, 0x3f25280b, dl));
  3908. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3909. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3910. getF32Constant(DAG, 0x4007b923, dl));
  3911. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3912. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3913. getF32Constant(DAG, 0x40823e2f, dl));
  3914. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3915. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3916. getF32Constant(DAG, 0x4020d29c, dl));
  3917. } else { // LimitFloatPrecision <= 18
  3918. // For floating-point precision of 18:
  3919. //
  3920. // Log2ofMantissa =
  3921. // -3.0400495f +
  3922. // (6.1129976f +
  3923. // (-5.3420409f +
  3924. // (3.2865683f +
  3925. // (-1.2669343f +
  3926. // (0.27515199f -
  3927. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3928. //
  3929. // error 0.0000018516, which is better than 18 bits
  3930. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3931. getF32Constant(DAG, 0xbcd2769e, dl));
  3932. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3933. getF32Constant(DAG, 0x3e8ce0b9, dl));
  3934. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3935. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3936. getF32Constant(DAG, 0x3fa22ae7, dl));
  3937. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3938. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3939. getF32Constant(DAG, 0x40525723, dl));
  3940. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3941. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3942. getF32Constant(DAG, 0x40aaf200, dl));
  3943. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3944. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3945. getF32Constant(DAG, 0x40c39dad, dl));
  3946. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3947. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3948. getF32Constant(DAG, 0x4042902c, dl));
  3949. }
  3950. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  3951. }
  3952. // No special expansion.
  3953. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  3954. }
  3955. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3956. /// limited-precision mode.
  3957. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3958. const TargetLowering &TLI) {
  3959. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3960. if (Op.getValueType() == MVT::f32 &&
  3961. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3962. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3963. // Scale the exponent by log10(2) [0.30102999f].
  3964. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3965. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3966. getF32Constant(DAG, 0x3e9a209a, dl));
  3967. // Get the significand and build it into a floating-point number with
  3968. // exponent of 1.
  3969. SDValue X = GetSignificand(DAG, Op1, dl);
  3970. SDValue Log10ofMantissa;
  3971. if (LimitFloatPrecision <= 6) {
  3972. // For floating-point precision of 6:
  3973. //
  3974. // Log10ofMantissa =
  3975. // -0.50419619f +
  3976. // (0.60948995f - 0.10380950f * x) * x;
  3977. //
  3978. // error 0.0014886165, which is 6 bits
  3979. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3980. getF32Constant(DAG, 0xbdd49a13, dl));
  3981. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3982. getF32Constant(DAG, 0x3f1c0789, dl));
  3983. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3984. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3985. getF32Constant(DAG, 0x3f011300, dl));
  3986. } else if (LimitFloatPrecision <= 12) {
  3987. // For floating-point precision of 12:
  3988. //
  3989. // Log10ofMantissa =
  3990. // -0.64831180f +
  3991. // (0.91751397f +
  3992. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3993. //
  3994. // error 0.00019228036, which is better than 12 bits
  3995. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3996. getF32Constant(DAG, 0x3d431f31, dl));
  3997. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3998. getF32Constant(DAG, 0x3ea21fb2, dl));
  3999. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4000. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4001. getF32Constant(DAG, 0x3f6ae232, dl));
  4002. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4003. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4004. getF32Constant(DAG, 0x3f25f7c3, dl));
  4005. } else { // LimitFloatPrecision <= 18
  4006. // For floating-point precision of 18:
  4007. //
  4008. // Log10ofMantissa =
  4009. // -0.84299375f +
  4010. // (1.5327582f +
  4011. // (-1.0688956f +
  4012. // (0.49102474f +
  4013. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4014. //
  4015. // error 0.0000037995730, which is better than 18 bits
  4016. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4017. getF32Constant(DAG, 0x3c5d51ce, dl));
  4018. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4019. getF32Constant(DAG, 0x3e00685a, dl));
  4020. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4021. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4022. getF32Constant(DAG, 0x3efb6798, dl));
  4023. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4024. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4025. getF32Constant(DAG, 0x3f88d192, dl));
  4026. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4027. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4028. getF32Constant(DAG, 0x3fc4316c, dl));
  4029. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4030. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4031. getF32Constant(DAG, 0x3f57ce70, dl));
  4032. }
  4033. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4034. }
  4035. // No special expansion.
  4036. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4037. }
  4038. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4039. /// limited-precision mode.
  4040. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4041. const TargetLowering &TLI) {
  4042. if (Op.getValueType() == MVT::f32 &&
  4043. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4044. return getLimitedPrecisionExp2(Op, dl, DAG);
  4045. // No special expansion.
  4046. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4047. }
  4048. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4049. /// limited-precision mode with x == 10.0f.
  4050. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4051. SelectionDAG &DAG, const TargetLowering &TLI) {
  4052. bool IsExp10 = false;
  4053. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4054. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4055. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4056. APFloat Ten(10.0f);
  4057. IsExp10 = LHSC->isExactlyValue(Ten);
  4058. }
  4059. }
  4060. // TODO: What fast-math-flags should be set on the FMUL node?
  4061. if (IsExp10) {
  4062. // Put the exponent in the right bit position for later addition to the
  4063. // final result:
  4064. //
  4065. // #define LOG2OF10 3.3219281f
  4066. // t0 = Op * LOG2OF10;
  4067. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4068. getF32Constant(DAG, 0x40549a78, dl));
  4069. return getLimitedPrecisionExp2(t0, dl, DAG);
  4070. }
  4071. // No special expansion.
  4072. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4073. }
  4074. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4075. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4076. SelectionDAG &DAG) {
  4077. // If RHS is a constant, we can expand this out to a multiplication tree,
  4078. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4079. // optimizing for size, we only want to do this if the expansion would produce
  4080. // a small number of multiplies, otherwise we do the full expansion.
  4081. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4082. // Get the exponent as a positive value.
  4083. unsigned Val = RHSC->getSExtValue();
  4084. if ((int)Val < 0) Val = -Val;
  4085. // powi(x, 0) -> 1.0
  4086. if (Val == 0)
  4087. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4088. const Function *F = DAG.getMachineFunction().getFunction();
  4089. if (!F->optForSize() ||
  4090. // If optimizing for size, don't insert too many multiplies.
  4091. // This inserts up to 5 multiplies.
  4092. countPopulation(Val) + Log2_32(Val) < 7) {
  4093. // We use the simple binary decomposition method to generate the multiply
  4094. // sequence. There are more optimal ways to do this (for example,
  4095. // powi(x,15) generates one more multiply than it should), but this has
  4096. // the benefit of being both really simple and much better than a libcall.
  4097. SDValue Res; // Logically starts equal to 1.0
  4098. SDValue CurSquare = LHS;
  4099. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4100. // nodes.
  4101. while (Val) {
  4102. if (Val & 1) {
  4103. if (Res.getNode())
  4104. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4105. else
  4106. Res = CurSquare; // 1.0*CurSquare.
  4107. }
  4108. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4109. CurSquare, CurSquare);
  4110. Val >>= 1;
  4111. }
  4112. // If the original was negative, invert the result, producing 1/(x*x*x).
  4113. if (RHSC->getSExtValue() < 0)
  4114. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4115. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4116. return Res;
  4117. }
  4118. }
  4119. // Otherwise, expand to a libcall.
  4120. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4121. }
  4122. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4123. // bitcasted argument.
  4124. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4125. switch (N.getOpcode()) {
  4126. case ISD::CopyFromReg:
  4127. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4128. case ISD::BITCAST:
  4129. case ISD::AssertZext:
  4130. case ISD::AssertSext:
  4131. case ISD::TRUNCATE:
  4132. return getUnderlyingArgReg(N.getOperand(0));
  4133. default:
  4134. return 0;
  4135. }
  4136. }
  4137. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  4138. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  4139. /// At the end of instruction selection, they will be inserted to the entry BB.
  4140. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4141. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4142. DILocation *DL, int64_t Offset, bool IsDbgDeclare, const SDValue &N) {
  4143. const Argument *Arg = dyn_cast<Argument>(V);
  4144. if (!Arg)
  4145. return false;
  4146. MachineFunction &MF = DAG.getMachineFunction();
  4147. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4148. // Ignore inlined function arguments here.
  4149. //
  4150. // FIXME: Should we be checking DL->inlinedAt() to determine this?
  4151. if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
  4152. return false;
  4153. bool IsIndirect = false;
  4154. Optional<MachineOperand> Op;
  4155. // Some arguments' frame index is recorded during argument lowering.
  4156. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4157. if (FI != INT_MAX)
  4158. Op = MachineOperand::CreateFI(FI);
  4159. if (!Op && N.getNode()) {
  4160. unsigned Reg = getUnderlyingArgReg(N);
  4161. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4162. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4163. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4164. if (PR)
  4165. Reg = PR;
  4166. }
  4167. if (Reg) {
  4168. Op = MachineOperand::CreateReg(Reg, false);
  4169. IsIndirect = IsDbgDeclare;
  4170. }
  4171. }
  4172. if (!Op) {
  4173. // Check if ValueMap has reg number.
  4174. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4175. if (VMI != FuncInfo.ValueMap.end()) {
  4176. Op = MachineOperand::CreateReg(VMI->second, false);
  4177. IsIndirect = IsDbgDeclare;
  4178. }
  4179. }
  4180. if (!Op && N.getNode())
  4181. // Check if frame index is available.
  4182. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4183. if (FrameIndexSDNode *FINode =
  4184. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4185. Op = MachineOperand::CreateFI(FINode->getIndex());
  4186. if (!Op)
  4187. return false;
  4188. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4189. "Expected inlined-at fields to agree");
  4190. if (Op->isReg())
  4191. FuncInfo.ArgDbgValues.push_back(
  4192. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4193. Op->getReg(), Offset, Variable, Expr));
  4194. else
  4195. FuncInfo.ArgDbgValues.push_back(
  4196. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
  4197. .add(*Op)
  4198. .addImm(Offset)
  4199. .addMetadata(Variable)
  4200. .addMetadata(Expr));
  4201. return true;
  4202. }
  4203. /// Return the appropriate SDDbgValue based on N.
  4204. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4205. DILocalVariable *Variable,
  4206. DIExpression *Expr, int64_t Offset,
  4207. const DebugLoc &dl,
  4208. unsigned DbgSDNodeOrder) {
  4209. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4210. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4211. // stack slot locations as such instead of as indirectly addressed
  4212. // locations.
  4213. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 0, dl,
  4214. DbgSDNodeOrder);
  4215. }
  4216. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false,
  4217. Offset, dl, DbgSDNodeOrder);
  4218. }
  4219. // VisualStudio defines setjmp as _setjmp
  4220. #if defined(_MSC_VER) && defined(setjmp) && \
  4221. !defined(setjmp_undefined_for_msvc)
  4222. # pragma push_macro("setjmp")
  4223. # undef setjmp
  4224. # define setjmp_undefined_for_msvc
  4225. #endif
  4226. /// Lower the call to the specified intrinsic function. If we want to emit this
  4227. /// as a call to a named external function, return the name. Otherwise, lower it
  4228. /// and return null.
  4229. const char *
  4230. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4231. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4232. SDLoc sdl = getCurSDLoc();
  4233. DebugLoc dl = getCurDebugLoc();
  4234. SDValue Res;
  4235. switch (Intrinsic) {
  4236. default:
  4237. // By default, turn this into a target intrinsic node.
  4238. visitTargetIntrinsic(I, Intrinsic);
  4239. return nullptr;
  4240. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4241. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4242. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4243. case Intrinsic::returnaddress:
  4244. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4245. TLI.getPointerTy(DAG.getDataLayout()),
  4246. getValue(I.getArgOperand(0))));
  4247. return nullptr;
  4248. case Intrinsic::addressofreturnaddress:
  4249. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4250. TLI.getPointerTy(DAG.getDataLayout())));
  4251. return nullptr;
  4252. case Intrinsic::frameaddress:
  4253. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4254. TLI.getPointerTy(DAG.getDataLayout()),
  4255. getValue(I.getArgOperand(0))));
  4256. return nullptr;
  4257. case Intrinsic::read_register: {
  4258. Value *Reg = I.getArgOperand(0);
  4259. SDValue Chain = getRoot();
  4260. SDValue RegName =
  4261. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4262. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4263. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4264. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4265. setValue(&I, Res);
  4266. DAG.setRoot(Res.getValue(1));
  4267. return nullptr;
  4268. }
  4269. case Intrinsic::write_register: {
  4270. Value *Reg = I.getArgOperand(0);
  4271. Value *RegValue = I.getArgOperand(1);
  4272. SDValue Chain = getRoot();
  4273. SDValue RegName =
  4274. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4275. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4276. RegName, getValue(RegValue)));
  4277. return nullptr;
  4278. }
  4279. case Intrinsic::setjmp:
  4280. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4281. case Intrinsic::longjmp:
  4282. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4283. case Intrinsic::memcpy: {
  4284. SDValue Op1 = getValue(I.getArgOperand(0));
  4285. SDValue Op2 = getValue(I.getArgOperand(1));
  4286. SDValue Op3 = getValue(I.getArgOperand(2));
  4287. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4288. if (!Align)
  4289. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4290. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4291. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4292. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4293. false, isTC,
  4294. MachinePointerInfo(I.getArgOperand(0)),
  4295. MachinePointerInfo(I.getArgOperand(1)));
  4296. updateDAGForMaybeTailCall(MC);
  4297. return nullptr;
  4298. }
  4299. case Intrinsic::memset: {
  4300. SDValue Op1 = getValue(I.getArgOperand(0));
  4301. SDValue Op2 = getValue(I.getArgOperand(1));
  4302. SDValue Op3 = getValue(I.getArgOperand(2));
  4303. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4304. if (!Align)
  4305. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  4306. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4307. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4308. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4309. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4310. updateDAGForMaybeTailCall(MS);
  4311. return nullptr;
  4312. }
  4313. case Intrinsic::memmove: {
  4314. SDValue Op1 = getValue(I.getArgOperand(0));
  4315. SDValue Op2 = getValue(I.getArgOperand(1));
  4316. SDValue Op3 = getValue(I.getArgOperand(2));
  4317. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4318. if (!Align)
  4319. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4320. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4321. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4322. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4323. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4324. MachinePointerInfo(I.getArgOperand(1)));
  4325. updateDAGForMaybeTailCall(MM);
  4326. return nullptr;
  4327. }
  4328. case Intrinsic::memcpy_element_unordered_atomic: {
  4329. const ElementUnorderedAtomicMemCpyInst &MI =
  4330. cast<ElementUnorderedAtomicMemCpyInst>(I);
  4331. SDValue Dst = getValue(MI.getRawDest());
  4332. SDValue Src = getValue(MI.getRawSource());
  4333. SDValue Length = getValue(MI.getLength());
  4334. // Emit a library call.
  4335. TargetLowering::ArgListTy Args;
  4336. TargetLowering::ArgListEntry Entry;
  4337. Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  4338. Entry.Node = Dst;
  4339. Args.push_back(Entry);
  4340. Entry.Node = Src;
  4341. Args.push_back(Entry);
  4342. Entry.Ty = MI.getLength()->getType();
  4343. Entry.Node = Length;
  4344. Args.push_back(Entry);
  4345. uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
  4346. RTLIB::Libcall LibraryCall =
  4347. RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
  4348. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  4349. report_fatal_error("Unsupported element size");
  4350. TargetLowering::CallLoweringInfo CLI(DAG);
  4351. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  4352. TLI.getLibcallCallingConv(LibraryCall),
  4353. Type::getVoidTy(*DAG.getContext()),
  4354. DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
  4355. TLI.getPointerTy(DAG.getDataLayout())),
  4356. std::move(Args));
  4357. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  4358. DAG.setRoot(CallResult.second);
  4359. return nullptr;
  4360. }
  4361. case Intrinsic::memmove_element_unordered_atomic: {
  4362. auto &MI = cast<ElementUnorderedAtomicMemMoveInst>(I);
  4363. SDValue Dst = getValue(MI.getRawDest());
  4364. SDValue Src = getValue(MI.getRawSource());
  4365. SDValue Length = getValue(MI.getLength());
  4366. // Emit a library call.
  4367. TargetLowering::ArgListTy Args;
  4368. TargetLowering::ArgListEntry Entry;
  4369. Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  4370. Entry.Node = Dst;
  4371. Args.push_back(Entry);
  4372. Entry.Node = Src;
  4373. Args.push_back(Entry);
  4374. Entry.Ty = MI.getLength()->getType();
  4375. Entry.Node = Length;
  4376. Args.push_back(Entry);
  4377. uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
  4378. RTLIB::Libcall LibraryCall =
  4379. RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
  4380. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  4381. report_fatal_error("Unsupported element size");
  4382. TargetLowering::CallLoweringInfo CLI(DAG);
  4383. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  4384. TLI.getLibcallCallingConv(LibraryCall),
  4385. Type::getVoidTy(*DAG.getContext()),
  4386. DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
  4387. TLI.getPointerTy(DAG.getDataLayout())),
  4388. std::move(Args));
  4389. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  4390. DAG.setRoot(CallResult.second);
  4391. return nullptr;
  4392. }
  4393. case Intrinsic::memset_element_unordered_atomic: {
  4394. auto &MI = cast<ElementUnorderedAtomicMemSetInst>(I);
  4395. SDValue Dst = getValue(MI.getRawDest());
  4396. SDValue Val = getValue(MI.getValue());
  4397. SDValue Length = getValue(MI.getLength());
  4398. // Emit a library call.
  4399. TargetLowering::ArgListTy Args;
  4400. TargetLowering::ArgListEntry Entry;
  4401. Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  4402. Entry.Node = Dst;
  4403. Args.push_back(Entry);
  4404. Entry.Ty = Type::getInt8Ty(*DAG.getContext());
  4405. Entry.Node = Val;
  4406. Args.push_back(Entry);
  4407. Entry.Ty = MI.getLength()->getType();
  4408. Entry.Node = Length;
  4409. Args.push_back(Entry);
  4410. uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
  4411. RTLIB::Libcall LibraryCall =
  4412. RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
  4413. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  4414. report_fatal_error("Unsupported element size");
  4415. TargetLowering::CallLoweringInfo CLI(DAG);
  4416. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  4417. TLI.getLibcallCallingConv(LibraryCall),
  4418. Type::getVoidTy(*DAG.getContext()),
  4419. DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
  4420. TLI.getPointerTy(DAG.getDataLayout())),
  4421. std::move(Args));
  4422. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  4423. DAG.setRoot(CallResult.second);
  4424. return nullptr;
  4425. }
  4426. case Intrinsic::dbg_declare: {
  4427. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  4428. DILocalVariable *Variable = DI.getVariable();
  4429. DIExpression *Expression = DI.getExpression();
  4430. const Value *Address = DI.getAddress();
  4431. assert(Variable && "Missing variable");
  4432. if (!Address) {
  4433. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4434. return nullptr;
  4435. }
  4436. // Check if address has undef value.
  4437. if (isa<UndefValue>(Address) ||
  4438. (Address->use_empty() && !isa<Argument>(Address))) {
  4439. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4440. return nullptr;
  4441. }
  4442. // Byval arguments with frame indices were already handled after argument
  4443. // lowering and before isel.
  4444. const auto *Arg =
  4445. dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
  4446. if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
  4447. return nullptr;
  4448. SDValue &N = NodeMap[Address];
  4449. if (!N.getNode() && isa<Argument>(Address))
  4450. // Check unused arguments map.
  4451. N = UnusedArgNodeMap[Address];
  4452. SDDbgValue *SDV;
  4453. if (N.getNode()) {
  4454. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4455. Address = BCI->getOperand(0);
  4456. // Parameters are handled specially.
  4457. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4458. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4459. if (isParameter && FINode) {
  4460. // Byval parameter. We have a frame index at this point.
  4461. SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
  4462. FINode->getIndex(), 0, dl, SDNodeOrder);
  4463. } else if (isa<Argument>(Address)) {
  4464. // Address is an argument, so try to emit its dbg value using
  4465. // virtual register info from the FuncInfo.ValueMap.
  4466. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, true, N);
  4467. return nullptr;
  4468. } else {
  4469. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4470. true, 0, dl, SDNodeOrder);
  4471. }
  4472. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4473. } else {
  4474. // If Address is an argument then try to emit its dbg value using
  4475. // virtual register info from the FuncInfo.ValueMap.
  4476. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, true,
  4477. N)) {
  4478. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4479. }
  4480. }
  4481. return nullptr;
  4482. }
  4483. case Intrinsic::dbg_value: {
  4484. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4485. assert(DI.getVariable() && "Missing variable");
  4486. DILocalVariable *Variable = DI.getVariable();
  4487. DIExpression *Expression = DI.getExpression();
  4488. uint64_t Offset = 0;
  4489. const Value *V = DI.getValue();
  4490. if (!V)
  4491. return nullptr;
  4492. SDDbgValue *SDV;
  4493. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4494. SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
  4495. SDNodeOrder);
  4496. DAG.AddDbgValue(SDV, nullptr, false);
  4497. return nullptr;
  4498. }
  4499. // Do not use getValue() in here; we don't want to generate code at
  4500. // this point if it hasn't been done yet.
  4501. SDValue N = NodeMap[V];
  4502. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  4503. N = UnusedArgNodeMap[V];
  4504. if (N.getNode()) {
  4505. if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset, false,
  4506. N))
  4507. return nullptr;
  4508. SDV = getDbgValue(N, Variable, Expression, Offset, dl, SDNodeOrder);
  4509. DAG.AddDbgValue(SDV, N.getNode(), false);
  4510. return nullptr;
  4511. }
  4512. if (!V->use_empty() ) {
  4513. // Do not call getValue(V) yet, as we don't want to generate code.
  4514. // Remember it for later.
  4515. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4516. DanglingDebugInfoMap[V] = DDI;
  4517. return nullptr;
  4518. }
  4519. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4520. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4521. return nullptr;
  4522. }
  4523. case Intrinsic::eh_typeid_for: {
  4524. // Find the type id for the given typeinfo.
  4525. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  4526. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  4527. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  4528. setValue(&I, Res);
  4529. return nullptr;
  4530. }
  4531. case Intrinsic::eh_return_i32:
  4532. case Intrinsic::eh_return_i64:
  4533. DAG.getMachineFunction().setCallsEHReturn(true);
  4534. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4535. MVT::Other,
  4536. getControlRoot(),
  4537. getValue(I.getArgOperand(0)),
  4538. getValue(I.getArgOperand(1))));
  4539. return nullptr;
  4540. case Intrinsic::eh_unwind_init:
  4541. DAG.getMachineFunction().setCallsUnwindInit(true);
  4542. return nullptr;
  4543. case Intrinsic::eh_dwarf_cfa: {
  4544. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  4545. TLI.getPointerTy(DAG.getDataLayout()),
  4546. getValue(I.getArgOperand(0))));
  4547. return nullptr;
  4548. }
  4549. case Intrinsic::eh_sjlj_callsite: {
  4550. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4551. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4552. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4553. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4554. MMI.setCurrentCallSite(CI->getZExtValue());
  4555. return nullptr;
  4556. }
  4557. case Intrinsic::eh_sjlj_functioncontext: {
  4558. // Get and store the index of the function context.
  4559. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  4560. AllocaInst *FnCtx =
  4561. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4562. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4563. MFI.setFunctionContextIndex(FI);
  4564. return nullptr;
  4565. }
  4566. case Intrinsic::eh_sjlj_setjmp: {
  4567. SDValue Ops[2];
  4568. Ops[0] = getRoot();
  4569. Ops[1] = getValue(I.getArgOperand(0));
  4570. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4571. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4572. setValue(&I, Op.getValue(0));
  4573. DAG.setRoot(Op.getValue(1));
  4574. return nullptr;
  4575. }
  4576. case Intrinsic::eh_sjlj_longjmp: {
  4577. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4578. getRoot(), getValue(I.getArgOperand(0))));
  4579. return nullptr;
  4580. }
  4581. case Intrinsic::eh_sjlj_setup_dispatch: {
  4582. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  4583. getRoot()));
  4584. return nullptr;
  4585. }
  4586. case Intrinsic::masked_gather:
  4587. visitMaskedGather(I);
  4588. return nullptr;
  4589. case Intrinsic::masked_load:
  4590. visitMaskedLoad(I);
  4591. return nullptr;
  4592. case Intrinsic::masked_scatter:
  4593. visitMaskedScatter(I);
  4594. return nullptr;
  4595. case Intrinsic::masked_store:
  4596. visitMaskedStore(I);
  4597. return nullptr;
  4598. case Intrinsic::masked_expandload:
  4599. visitMaskedLoad(I, true /* IsExpanding */);
  4600. return nullptr;
  4601. case Intrinsic::masked_compressstore:
  4602. visitMaskedStore(I, true /* IsCompressing */);
  4603. return nullptr;
  4604. case Intrinsic::x86_mmx_pslli_w:
  4605. case Intrinsic::x86_mmx_pslli_d:
  4606. case Intrinsic::x86_mmx_pslli_q:
  4607. case Intrinsic::x86_mmx_psrli_w:
  4608. case Intrinsic::x86_mmx_psrli_d:
  4609. case Intrinsic::x86_mmx_psrli_q:
  4610. case Intrinsic::x86_mmx_psrai_w:
  4611. case Intrinsic::x86_mmx_psrai_d: {
  4612. SDValue ShAmt = getValue(I.getArgOperand(1));
  4613. if (isa<ConstantSDNode>(ShAmt)) {
  4614. visitTargetIntrinsic(I, Intrinsic);
  4615. return nullptr;
  4616. }
  4617. unsigned NewIntrinsic = 0;
  4618. EVT ShAmtVT = MVT::v2i32;
  4619. switch (Intrinsic) {
  4620. case Intrinsic::x86_mmx_pslli_w:
  4621. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4622. break;
  4623. case Intrinsic::x86_mmx_pslli_d:
  4624. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4625. break;
  4626. case Intrinsic::x86_mmx_pslli_q:
  4627. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4628. break;
  4629. case Intrinsic::x86_mmx_psrli_w:
  4630. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4631. break;
  4632. case Intrinsic::x86_mmx_psrli_d:
  4633. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4634. break;
  4635. case Intrinsic::x86_mmx_psrli_q:
  4636. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4637. break;
  4638. case Intrinsic::x86_mmx_psrai_w:
  4639. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4640. break;
  4641. case Intrinsic::x86_mmx_psrai_d:
  4642. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4643. break;
  4644. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4645. }
  4646. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4647. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4648. // to be zero.
  4649. // We must do this early because v2i32 is not a legal type.
  4650. SDValue ShOps[2];
  4651. ShOps[0] = ShAmt;
  4652. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  4653. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  4654. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4655. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4656. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4657. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  4658. getValue(I.getArgOperand(0)), ShAmt);
  4659. setValue(&I, Res);
  4660. return nullptr;
  4661. }
  4662. case Intrinsic::powi:
  4663. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4664. getValue(I.getArgOperand(1)), DAG));
  4665. return nullptr;
  4666. case Intrinsic::log:
  4667. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4668. return nullptr;
  4669. case Intrinsic::log2:
  4670. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4671. return nullptr;
  4672. case Intrinsic::log10:
  4673. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4674. return nullptr;
  4675. case Intrinsic::exp:
  4676. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4677. return nullptr;
  4678. case Intrinsic::exp2:
  4679. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4680. return nullptr;
  4681. case Intrinsic::pow:
  4682. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4683. getValue(I.getArgOperand(1)), DAG, TLI));
  4684. return nullptr;
  4685. case Intrinsic::sqrt:
  4686. case Intrinsic::fabs:
  4687. case Intrinsic::sin:
  4688. case Intrinsic::cos:
  4689. case Intrinsic::floor:
  4690. case Intrinsic::ceil:
  4691. case Intrinsic::trunc:
  4692. case Intrinsic::rint:
  4693. case Intrinsic::nearbyint:
  4694. case Intrinsic::round:
  4695. case Intrinsic::canonicalize: {
  4696. unsigned Opcode;
  4697. switch (Intrinsic) {
  4698. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4699. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4700. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4701. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4702. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4703. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4704. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4705. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4706. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4707. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4708. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4709. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  4710. }
  4711. setValue(&I, DAG.getNode(Opcode, sdl,
  4712. getValue(I.getArgOperand(0)).getValueType(),
  4713. getValue(I.getArgOperand(0))));
  4714. return nullptr;
  4715. }
  4716. case Intrinsic::minnum: {
  4717. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4718. unsigned Opc =
  4719. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
  4720. ? ISD::FMINNAN
  4721. : ISD::FMINNUM;
  4722. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4723. getValue(I.getArgOperand(0)),
  4724. getValue(I.getArgOperand(1))));
  4725. return nullptr;
  4726. }
  4727. case Intrinsic::maxnum: {
  4728. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4729. unsigned Opc =
  4730. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
  4731. ? ISD::FMAXNAN
  4732. : ISD::FMAXNUM;
  4733. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4734. getValue(I.getArgOperand(0)),
  4735. getValue(I.getArgOperand(1))));
  4736. return nullptr;
  4737. }
  4738. case Intrinsic::copysign:
  4739. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4740. getValue(I.getArgOperand(0)).getValueType(),
  4741. getValue(I.getArgOperand(0)),
  4742. getValue(I.getArgOperand(1))));
  4743. return nullptr;
  4744. case Intrinsic::fma:
  4745. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4746. getValue(I.getArgOperand(0)).getValueType(),
  4747. getValue(I.getArgOperand(0)),
  4748. getValue(I.getArgOperand(1)),
  4749. getValue(I.getArgOperand(2))));
  4750. return nullptr;
  4751. case Intrinsic::experimental_constrained_fadd:
  4752. case Intrinsic::experimental_constrained_fsub:
  4753. case Intrinsic::experimental_constrained_fmul:
  4754. case Intrinsic::experimental_constrained_fdiv:
  4755. case Intrinsic::experimental_constrained_frem:
  4756. case Intrinsic::experimental_constrained_sqrt:
  4757. case Intrinsic::experimental_constrained_pow:
  4758. case Intrinsic::experimental_constrained_powi:
  4759. case Intrinsic::experimental_constrained_sin:
  4760. case Intrinsic::experimental_constrained_cos:
  4761. case Intrinsic::experimental_constrained_exp:
  4762. case Intrinsic::experimental_constrained_exp2:
  4763. case Intrinsic::experimental_constrained_log:
  4764. case Intrinsic::experimental_constrained_log10:
  4765. case Intrinsic::experimental_constrained_log2:
  4766. case Intrinsic::experimental_constrained_rint:
  4767. case Intrinsic::experimental_constrained_nearbyint:
  4768. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  4769. return nullptr;
  4770. case Intrinsic::fmuladd: {
  4771. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4772. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4773. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4774. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4775. getValue(I.getArgOperand(0)).getValueType(),
  4776. getValue(I.getArgOperand(0)),
  4777. getValue(I.getArgOperand(1)),
  4778. getValue(I.getArgOperand(2))));
  4779. } else {
  4780. // TODO: Intrinsic calls should have fast-math-flags.
  4781. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4782. getValue(I.getArgOperand(0)).getValueType(),
  4783. getValue(I.getArgOperand(0)),
  4784. getValue(I.getArgOperand(1)));
  4785. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4786. getValue(I.getArgOperand(0)).getValueType(),
  4787. Mul,
  4788. getValue(I.getArgOperand(2)));
  4789. setValue(&I, Add);
  4790. }
  4791. return nullptr;
  4792. }
  4793. case Intrinsic::convert_to_fp16:
  4794. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4795. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4796. getValue(I.getArgOperand(0)),
  4797. DAG.getTargetConstant(0, sdl,
  4798. MVT::i32))));
  4799. return nullptr;
  4800. case Intrinsic::convert_from_fp16:
  4801. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  4802. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  4803. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4804. getValue(I.getArgOperand(0)))));
  4805. return nullptr;
  4806. case Intrinsic::pcmarker: {
  4807. SDValue Tmp = getValue(I.getArgOperand(0));
  4808. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4809. return nullptr;
  4810. }
  4811. case Intrinsic::readcyclecounter: {
  4812. SDValue Op = getRoot();
  4813. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4814. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4815. setValue(&I, Res);
  4816. DAG.setRoot(Res.getValue(1));
  4817. return nullptr;
  4818. }
  4819. case Intrinsic::bitreverse:
  4820. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  4821. getValue(I.getArgOperand(0)).getValueType(),
  4822. getValue(I.getArgOperand(0))));
  4823. return nullptr;
  4824. case Intrinsic::bswap:
  4825. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4826. getValue(I.getArgOperand(0)).getValueType(),
  4827. getValue(I.getArgOperand(0))));
  4828. return nullptr;
  4829. case Intrinsic::cttz: {
  4830. SDValue Arg = getValue(I.getArgOperand(0));
  4831. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4832. EVT Ty = Arg.getValueType();
  4833. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4834. sdl, Ty, Arg));
  4835. return nullptr;
  4836. }
  4837. case Intrinsic::ctlz: {
  4838. SDValue Arg = getValue(I.getArgOperand(0));
  4839. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4840. EVT Ty = Arg.getValueType();
  4841. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4842. sdl, Ty, Arg));
  4843. return nullptr;
  4844. }
  4845. case Intrinsic::ctpop: {
  4846. SDValue Arg = getValue(I.getArgOperand(0));
  4847. EVT Ty = Arg.getValueType();
  4848. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4849. return nullptr;
  4850. }
  4851. case Intrinsic::stacksave: {
  4852. SDValue Op = getRoot();
  4853. Res = DAG.getNode(
  4854. ISD::STACKSAVE, sdl,
  4855. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  4856. setValue(&I, Res);
  4857. DAG.setRoot(Res.getValue(1));
  4858. return nullptr;
  4859. }
  4860. case Intrinsic::stackrestore: {
  4861. Res = getValue(I.getArgOperand(0));
  4862. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4863. return nullptr;
  4864. }
  4865. case Intrinsic::get_dynamic_area_offset: {
  4866. SDValue Op = getRoot();
  4867. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4868. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4869. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  4870. // target.
  4871. if (PtrTy != ResTy)
  4872. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  4873. " intrinsic!");
  4874. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  4875. Op);
  4876. DAG.setRoot(Op);
  4877. setValue(&I, Res);
  4878. return nullptr;
  4879. }
  4880. case Intrinsic::stackguard: {
  4881. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4882. MachineFunction &MF = DAG.getMachineFunction();
  4883. const Module &M = *MF.getFunction()->getParent();
  4884. SDValue Chain = getRoot();
  4885. if (TLI.useLoadStackGuardNode()) {
  4886. Res = getLoadStackGuard(DAG, sdl, Chain);
  4887. } else {
  4888. const Value *Global = TLI.getSDagStackGuard(M);
  4889. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  4890. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  4891. MachinePointerInfo(Global, 0), Align,
  4892. MachineMemOperand::MOVolatile);
  4893. }
  4894. DAG.setRoot(Chain);
  4895. setValue(&I, Res);
  4896. return nullptr;
  4897. }
  4898. case Intrinsic::stackprotector: {
  4899. // Emit code into the DAG to store the stack guard onto the stack.
  4900. MachineFunction &MF = DAG.getMachineFunction();
  4901. MachineFrameInfo &MFI = MF.getFrameInfo();
  4902. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4903. SDValue Src, Chain = getRoot();
  4904. if (TLI.useLoadStackGuardNode())
  4905. Src = getLoadStackGuard(DAG, sdl, Chain);
  4906. else
  4907. Src = getValue(I.getArgOperand(0)); // The guard's value.
  4908. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4909. int FI = FuncInfo.StaticAllocaMap[Slot];
  4910. MFI.setStackProtectorIndex(FI);
  4911. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4912. // Store the stack protector onto the stack.
  4913. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  4914. DAG.getMachineFunction(), FI),
  4915. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  4916. setValue(&I, Res);
  4917. DAG.setRoot(Res);
  4918. return nullptr;
  4919. }
  4920. case Intrinsic::objectsize: {
  4921. // If we don't know by now, we're never going to know.
  4922. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4923. assert(CI && "Non-constant type in __builtin_object_size?");
  4924. SDValue Arg = getValue(I.getCalledValue());
  4925. EVT Ty = Arg.getValueType();
  4926. if (CI->isZero())
  4927. Res = DAG.getConstant(-1ULL, sdl, Ty);
  4928. else
  4929. Res = DAG.getConstant(0, sdl, Ty);
  4930. setValue(&I, Res);
  4931. return nullptr;
  4932. }
  4933. case Intrinsic::annotation:
  4934. case Intrinsic::ptr_annotation:
  4935. case Intrinsic::invariant_group_barrier:
  4936. // Drop the intrinsic, but forward the value
  4937. setValue(&I, getValue(I.getOperand(0)));
  4938. return nullptr;
  4939. case Intrinsic::assume:
  4940. case Intrinsic::var_annotation:
  4941. // Discard annotate attributes and assumptions
  4942. return nullptr;
  4943. case Intrinsic::init_trampoline: {
  4944. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4945. SDValue Ops[6];
  4946. Ops[0] = getRoot();
  4947. Ops[1] = getValue(I.getArgOperand(0));
  4948. Ops[2] = getValue(I.getArgOperand(1));
  4949. Ops[3] = getValue(I.getArgOperand(2));
  4950. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4951. Ops[5] = DAG.getSrcValue(F);
  4952. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  4953. DAG.setRoot(Res);
  4954. return nullptr;
  4955. }
  4956. case Intrinsic::adjust_trampoline: {
  4957. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  4958. TLI.getPointerTy(DAG.getDataLayout()),
  4959. getValue(I.getArgOperand(0))));
  4960. return nullptr;
  4961. }
  4962. case Intrinsic::gcroot: {
  4963. MachineFunction &MF = DAG.getMachineFunction();
  4964. const Function *F = MF.getFunction();
  4965. (void)F;
  4966. assert(F->hasGC() &&
  4967. "only valid in functions with gc specified, enforced by Verifier");
  4968. assert(GFI && "implied by previous");
  4969. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  4970. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4971. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4972. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4973. return nullptr;
  4974. }
  4975. case Intrinsic::gcread:
  4976. case Intrinsic::gcwrite:
  4977. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4978. case Intrinsic::flt_rounds:
  4979. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  4980. return nullptr;
  4981. case Intrinsic::expect: {
  4982. // Just replace __builtin_expect(exp, c) with EXP.
  4983. setValue(&I, getValue(I.getArgOperand(0)));
  4984. return nullptr;
  4985. }
  4986. case Intrinsic::debugtrap:
  4987. case Intrinsic::trap: {
  4988. StringRef TrapFuncName =
  4989. I.getAttributes()
  4990. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  4991. .getValueAsString();
  4992. if (TrapFuncName.empty()) {
  4993. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  4994. ISD::TRAP : ISD::DEBUGTRAP;
  4995. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  4996. return nullptr;
  4997. }
  4998. TargetLowering::ArgListTy Args;
  4999. TargetLowering::CallLoweringInfo CLI(DAG);
  5000. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5001. CallingConv::C, I.getType(),
  5002. DAG.getExternalSymbol(TrapFuncName.data(),
  5003. TLI.getPointerTy(DAG.getDataLayout())),
  5004. std::move(Args));
  5005. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5006. DAG.setRoot(Result.second);
  5007. return nullptr;
  5008. }
  5009. case Intrinsic::uadd_with_overflow:
  5010. case Intrinsic::sadd_with_overflow:
  5011. case Intrinsic::usub_with_overflow:
  5012. case Intrinsic::ssub_with_overflow:
  5013. case Intrinsic::umul_with_overflow:
  5014. case Intrinsic::smul_with_overflow: {
  5015. ISD::NodeType Op;
  5016. switch (Intrinsic) {
  5017. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5018. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5019. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5020. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5021. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5022. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5023. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5024. }
  5025. SDValue Op1 = getValue(I.getArgOperand(0));
  5026. SDValue Op2 = getValue(I.getArgOperand(1));
  5027. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  5028. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5029. return nullptr;
  5030. }
  5031. case Intrinsic::prefetch: {
  5032. SDValue Ops[5];
  5033. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5034. Ops[0] = getRoot();
  5035. Ops[1] = getValue(I.getArgOperand(0));
  5036. Ops[2] = getValue(I.getArgOperand(1));
  5037. Ops[3] = getValue(I.getArgOperand(2));
  5038. Ops[4] = getValue(I.getArgOperand(3));
  5039. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5040. DAG.getVTList(MVT::Other), Ops,
  5041. EVT::getIntegerVT(*Context, 8),
  5042. MachinePointerInfo(I.getArgOperand(0)),
  5043. 0, /* align */
  5044. false, /* volatile */
  5045. rw==0, /* read */
  5046. rw==1)); /* write */
  5047. return nullptr;
  5048. }
  5049. case Intrinsic::lifetime_start:
  5050. case Intrinsic::lifetime_end: {
  5051. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5052. // Stack coloring is not enabled in O0, discard region information.
  5053. if (TM.getOptLevel() == CodeGenOpt::None)
  5054. return nullptr;
  5055. SmallVector<Value *, 4> Allocas;
  5056. GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
  5057. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  5058. E = Allocas.end(); Object != E; ++Object) {
  5059. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5060. // Could not find an Alloca.
  5061. if (!LifetimeObject)
  5062. continue;
  5063. // First check that the Alloca is static, otherwise it won't have a
  5064. // valid frame index.
  5065. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5066. if (SI == FuncInfo.StaticAllocaMap.end())
  5067. return nullptr;
  5068. int FI = SI->second;
  5069. SDValue Ops[2];
  5070. Ops[0] = getRoot();
  5071. Ops[1] =
  5072. DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
  5073. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  5074. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  5075. DAG.setRoot(Res);
  5076. }
  5077. return nullptr;
  5078. }
  5079. case Intrinsic::invariant_start:
  5080. // Discard region information.
  5081. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5082. return nullptr;
  5083. case Intrinsic::invariant_end:
  5084. // Discard region information.
  5085. return nullptr;
  5086. case Intrinsic::clear_cache:
  5087. return TLI.getClearCacheBuiltinName();
  5088. case Intrinsic::donothing:
  5089. // ignore
  5090. return nullptr;
  5091. case Intrinsic::experimental_stackmap: {
  5092. visitStackmap(I);
  5093. return nullptr;
  5094. }
  5095. case Intrinsic::experimental_patchpoint_void:
  5096. case Intrinsic::experimental_patchpoint_i64: {
  5097. visitPatchpoint(&I);
  5098. return nullptr;
  5099. }
  5100. case Intrinsic::experimental_gc_statepoint: {
  5101. LowerStatepoint(ImmutableStatepoint(&I));
  5102. return nullptr;
  5103. }
  5104. case Intrinsic::experimental_gc_result: {
  5105. visitGCResult(cast<GCResultInst>(I));
  5106. return nullptr;
  5107. }
  5108. case Intrinsic::experimental_gc_relocate: {
  5109. visitGCRelocate(cast<GCRelocateInst>(I));
  5110. return nullptr;
  5111. }
  5112. case Intrinsic::instrprof_increment:
  5113. llvm_unreachable("instrprof failed to lower an increment");
  5114. case Intrinsic::instrprof_value_profile:
  5115. llvm_unreachable("instrprof failed to lower a value profiling call");
  5116. case Intrinsic::localescape: {
  5117. MachineFunction &MF = DAG.getMachineFunction();
  5118. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5119. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5120. // is the same on all targets.
  5121. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5122. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5123. if (isa<ConstantPointerNull>(Arg))
  5124. continue; // Skip null pointers. They represent a hole in index space.
  5125. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5126. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5127. "can only escape static allocas");
  5128. int FI = FuncInfo.StaticAllocaMap[Slot];
  5129. MCSymbol *FrameAllocSym =
  5130. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5131. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5132. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5133. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5134. .addSym(FrameAllocSym)
  5135. .addFrameIndex(FI);
  5136. }
  5137. return nullptr;
  5138. }
  5139. case Intrinsic::localrecover: {
  5140. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5141. MachineFunction &MF = DAG.getMachineFunction();
  5142. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5143. // Get the symbol that defines the frame offset.
  5144. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5145. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5146. unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
  5147. MCSymbol *FrameAllocSym =
  5148. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5149. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5150. // Create a MCSymbol for the label to avoid any target lowering
  5151. // that would make this PC relative.
  5152. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5153. SDValue OffsetVal =
  5154. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5155. // Add the offset to the FP.
  5156. Value *FP = I.getArgOperand(1);
  5157. SDValue FPVal = getValue(FP);
  5158. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5159. setValue(&I, Add);
  5160. return nullptr;
  5161. }
  5162. case Intrinsic::eh_exceptionpointer:
  5163. case Intrinsic::eh_exceptioncode: {
  5164. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5165. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5166. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5167. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5168. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5169. SDValue N =
  5170. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5171. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5172. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5173. setValue(&I, N);
  5174. return nullptr;
  5175. }
  5176. case Intrinsic::xray_customevent: {
  5177. // Here we want to make sure that the intrinsic behaves as if it has a
  5178. // specific calling convention, and only for x86_64.
  5179. // FIXME: Support other platforms later.
  5180. const auto &Triple = DAG.getTarget().getTargetTriple();
  5181. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5182. return nullptr;
  5183. SDLoc DL = getCurSDLoc();
  5184. SmallVector<SDValue, 8> Ops;
  5185. // We want to say that we always want the arguments in registers.
  5186. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5187. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5188. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5189. SDValue Chain = getRoot();
  5190. Ops.push_back(LogEntryVal);
  5191. Ops.push_back(StrSizeVal);
  5192. Ops.push_back(Chain);
  5193. // We need to enforce the calling convention for the callsite, so that
  5194. // argument ordering is enforced correctly, and that register allocation can
  5195. // see that some registers may be assumed clobbered and have to preserve
  5196. // them across calls to the intrinsic.
  5197. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5198. DL, NodeTys, Ops);
  5199. SDValue patchableNode = SDValue(MN, 0);
  5200. DAG.setRoot(patchableNode);
  5201. setValue(&I, patchableNode);
  5202. return nullptr;
  5203. }
  5204. case Intrinsic::experimental_deoptimize:
  5205. LowerDeoptimizeCall(&I);
  5206. return nullptr;
  5207. case Intrinsic::experimental_vector_reduce_fadd:
  5208. case Intrinsic::experimental_vector_reduce_fmul:
  5209. case Intrinsic::experimental_vector_reduce_add:
  5210. case Intrinsic::experimental_vector_reduce_mul:
  5211. case Intrinsic::experimental_vector_reduce_and:
  5212. case Intrinsic::experimental_vector_reduce_or:
  5213. case Intrinsic::experimental_vector_reduce_xor:
  5214. case Intrinsic::experimental_vector_reduce_smax:
  5215. case Intrinsic::experimental_vector_reduce_smin:
  5216. case Intrinsic::experimental_vector_reduce_umax:
  5217. case Intrinsic::experimental_vector_reduce_umin:
  5218. case Intrinsic::experimental_vector_reduce_fmax:
  5219. case Intrinsic::experimental_vector_reduce_fmin: {
  5220. visitVectorReduce(I, Intrinsic);
  5221. return nullptr;
  5222. }
  5223. }
  5224. }
  5225. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  5226. const ConstrainedFPIntrinsic &FPI) {
  5227. SDLoc sdl = getCurSDLoc();
  5228. unsigned Opcode;
  5229. switch (FPI.getIntrinsicID()) {
  5230. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5231. case Intrinsic::experimental_constrained_fadd:
  5232. Opcode = ISD::STRICT_FADD;
  5233. break;
  5234. case Intrinsic::experimental_constrained_fsub:
  5235. Opcode = ISD::STRICT_FSUB;
  5236. break;
  5237. case Intrinsic::experimental_constrained_fmul:
  5238. Opcode = ISD::STRICT_FMUL;
  5239. break;
  5240. case Intrinsic::experimental_constrained_fdiv:
  5241. Opcode = ISD::STRICT_FDIV;
  5242. break;
  5243. case Intrinsic::experimental_constrained_frem:
  5244. Opcode = ISD::STRICT_FREM;
  5245. break;
  5246. case Intrinsic::experimental_constrained_sqrt:
  5247. Opcode = ISD::STRICT_FSQRT;
  5248. break;
  5249. case Intrinsic::experimental_constrained_pow:
  5250. Opcode = ISD::STRICT_FPOW;
  5251. break;
  5252. case Intrinsic::experimental_constrained_powi:
  5253. Opcode = ISD::STRICT_FPOWI;
  5254. break;
  5255. case Intrinsic::experimental_constrained_sin:
  5256. Opcode = ISD::STRICT_FSIN;
  5257. break;
  5258. case Intrinsic::experimental_constrained_cos:
  5259. Opcode = ISD::STRICT_FCOS;
  5260. break;
  5261. case Intrinsic::experimental_constrained_exp:
  5262. Opcode = ISD::STRICT_FEXP;
  5263. break;
  5264. case Intrinsic::experimental_constrained_exp2:
  5265. Opcode = ISD::STRICT_FEXP2;
  5266. break;
  5267. case Intrinsic::experimental_constrained_log:
  5268. Opcode = ISD::STRICT_FLOG;
  5269. break;
  5270. case Intrinsic::experimental_constrained_log10:
  5271. Opcode = ISD::STRICT_FLOG10;
  5272. break;
  5273. case Intrinsic::experimental_constrained_log2:
  5274. Opcode = ISD::STRICT_FLOG2;
  5275. break;
  5276. case Intrinsic::experimental_constrained_rint:
  5277. Opcode = ISD::STRICT_FRINT;
  5278. break;
  5279. case Intrinsic::experimental_constrained_nearbyint:
  5280. Opcode = ISD::STRICT_FNEARBYINT;
  5281. break;
  5282. }
  5283. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5284. SDValue Chain = getRoot();
  5285. SmallVector<EVT, 4> ValueVTs;
  5286. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  5287. ValueVTs.push_back(MVT::Other); // Out chain
  5288. SDVTList VTs = DAG.getVTList(ValueVTs);
  5289. SDValue Result;
  5290. if (FPI.isUnaryOp())
  5291. Result = DAG.getNode(Opcode, sdl, VTs,
  5292. { Chain, getValue(FPI.getArgOperand(0)) });
  5293. else
  5294. Result = DAG.getNode(Opcode, sdl, VTs,
  5295. { Chain, getValue(FPI.getArgOperand(0)),
  5296. getValue(FPI.getArgOperand(1)) });
  5297. assert(Result.getNode()->getNumValues() == 2);
  5298. SDValue OutChain = Result.getValue(1);
  5299. DAG.setRoot(OutChain);
  5300. SDValue FPResult = Result.getValue(0);
  5301. setValue(&FPI, FPResult);
  5302. }
  5303. std::pair<SDValue, SDValue>
  5304. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  5305. const BasicBlock *EHPadBB) {
  5306. MachineFunction &MF = DAG.getMachineFunction();
  5307. MachineModuleInfo &MMI = MF.getMMI();
  5308. MCSymbol *BeginLabel = nullptr;
  5309. if (EHPadBB) {
  5310. // Insert a label before the invoke call to mark the try range. This can be
  5311. // used to detect deletion of the invoke via the MachineModuleInfo.
  5312. BeginLabel = MMI.getContext().createTempSymbol();
  5313. // For SjLj, keep track of which landing pads go with which invokes
  5314. // so as to maintain the ordering of pads in the LSDA.
  5315. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  5316. if (CallSiteIndex) {
  5317. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  5318. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  5319. // Now that the call site is handled, stop tracking it.
  5320. MMI.setCurrentCallSite(0);
  5321. }
  5322. // Both PendingLoads and PendingExports must be flushed here;
  5323. // this call might not return.
  5324. (void)getRoot();
  5325. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  5326. CLI.setChain(getRoot());
  5327. }
  5328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5329. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5330. assert((CLI.IsTailCall || Result.second.getNode()) &&
  5331. "Non-null chain expected with non-tail call!");
  5332. assert((Result.second.getNode() || !Result.first.getNode()) &&
  5333. "Null value expected with tail call!");
  5334. if (!Result.second.getNode()) {
  5335. // As a special case, a null chain means that a tail call has been emitted
  5336. // and the DAG root is already updated.
  5337. HasTailCall = true;
  5338. // Since there's no actual continuation from this block, nothing can be
  5339. // relying on us setting vregs for them.
  5340. PendingExports.clear();
  5341. } else {
  5342. DAG.setRoot(Result.second);
  5343. }
  5344. if (EHPadBB) {
  5345. // Insert a label at the end of the invoke call to mark the try range. This
  5346. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  5347. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  5348. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  5349. // Inform MachineModuleInfo of range.
  5350. if (MF.hasEHFunclets()) {
  5351. assert(CLI.CS);
  5352. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  5353. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  5354. BeginLabel, EndLabel);
  5355. } else {
  5356. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  5357. }
  5358. }
  5359. return Result;
  5360. }
  5361. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  5362. bool isTailCall,
  5363. const BasicBlock *EHPadBB) {
  5364. auto &DL = DAG.getDataLayout();
  5365. FunctionType *FTy = CS.getFunctionType();
  5366. Type *RetTy = CS.getType();
  5367. TargetLowering::ArgListTy Args;
  5368. Args.reserve(CS.arg_size());
  5369. const Value *SwiftErrorVal = nullptr;
  5370. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5371. // We can't tail call inside a function with a swifterror argument. Lowering
  5372. // does not support this yet. It would have to move into the swifterror
  5373. // register before the call.
  5374. auto *Caller = CS.getInstruction()->getParent()->getParent();
  5375. if (TLI.supportSwiftError() &&
  5376. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  5377. isTailCall = false;
  5378. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  5379. i != e; ++i) {
  5380. TargetLowering::ArgListEntry Entry;
  5381. const Value *V = *i;
  5382. // Skip empty types
  5383. if (V->getType()->isEmptyTy())
  5384. continue;
  5385. SDValue ArgNode = getValue(V);
  5386. Entry.Node = ArgNode; Entry.Ty = V->getType();
  5387. Entry.setAttributes(&CS, i - CS.arg_begin());
  5388. // Use swifterror virtual register as input to the call.
  5389. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  5390. SwiftErrorVal = V;
  5391. // We find the virtual register for the actual swifterror argument.
  5392. // Instead of using the Value, we use the virtual register instead.
  5393. Entry.Node = DAG.getRegister(FuncInfo
  5394. .getOrCreateSwiftErrorVRegUseAt(
  5395. CS.getInstruction(), FuncInfo.MBB, V)
  5396. .first,
  5397. EVT(TLI.getPointerTy(DL)));
  5398. }
  5399. Args.push_back(Entry);
  5400. // If we have an explicit sret argument that is an Instruction, (i.e., it
  5401. // might point to function-local memory), we can't meaningfully tail-call.
  5402. if (Entry.IsSRet && isa<Instruction>(V))
  5403. isTailCall = false;
  5404. }
  5405. // Check if target-independent constraints permit a tail call here.
  5406. // Target-dependent constraints are checked within TLI->LowerCallTo.
  5407. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  5408. isTailCall = false;
  5409. // Disable tail calls if there is an swifterror argument. Targets have not
  5410. // been updated to support tail calls.
  5411. if (TLI.supportSwiftError() && SwiftErrorVal)
  5412. isTailCall = false;
  5413. TargetLowering::CallLoweringInfo CLI(DAG);
  5414. CLI.setDebugLoc(getCurSDLoc())
  5415. .setChain(getRoot())
  5416. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  5417. .setTailCall(isTailCall)
  5418. .setConvergent(CS.isConvergent());
  5419. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  5420. if (Result.first.getNode()) {
  5421. const Instruction *Inst = CS.getInstruction();
  5422. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  5423. setValue(Inst, Result.first);
  5424. }
  5425. // The last element of CLI.InVals has the SDValue for swifterror return.
  5426. // Here we copy it to a virtual register and update SwiftErrorMap for
  5427. // book-keeping.
  5428. if (SwiftErrorVal && TLI.supportSwiftError()) {
  5429. // Get the last element of InVals.
  5430. SDValue Src = CLI.InVals.back();
  5431. unsigned VReg; bool CreatedVReg;
  5432. std::tie(VReg, CreatedVReg) =
  5433. FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
  5434. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  5435. // We update the virtual register for the actual swifterror argument.
  5436. if (CreatedVReg)
  5437. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  5438. DAG.setRoot(CopyNode);
  5439. }
  5440. }
  5441. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  5442. SelectionDAGBuilder &Builder) {
  5443. // Check to see if this load can be trivially constant folded, e.g. if the
  5444. // input is from a string literal.
  5445. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  5446. // Cast pointer to the type we really want to load.
  5447. Type *LoadTy =
  5448. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  5449. if (LoadVT.isVector())
  5450. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  5451. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  5452. PointerType::getUnqual(LoadTy));
  5453. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  5454. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  5455. return Builder.getValue(LoadCst);
  5456. }
  5457. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  5458. // still constant memory, the input chain can be the entry node.
  5459. SDValue Root;
  5460. bool ConstantMemory = false;
  5461. // Do not serialize (non-volatile) loads of constant memory with anything.
  5462. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  5463. Root = Builder.DAG.getEntryNode();
  5464. ConstantMemory = true;
  5465. } else {
  5466. // Do not serialize non-volatile loads against each other.
  5467. Root = Builder.DAG.getRoot();
  5468. }
  5469. SDValue Ptr = Builder.getValue(PtrVal);
  5470. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  5471. Ptr, MachinePointerInfo(PtrVal),
  5472. /* Alignment = */ 1);
  5473. if (!ConstantMemory)
  5474. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  5475. return LoadVal;
  5476. }
  5477. /// Record the value for an instruction that produces an integer result,
  5478. /// converting the type where necessary.
  5479. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  5480. SDValue Value,
  5481. bool IsSigned) {
  5482. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5483. I.getType(), true);
  5484. if (IsSigned)
  5485. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  5486. else
  5487. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  5488. setValue(&I, Value);
  5489. }
  5490. /// See if we can lower a memcmp call into an optimized form. If so, return
  5491. /// true and lower it. Otherwise return false, and it will be lowered like a
  5492. /// normal call.
  5493. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5494. /// correct prototype.
  5495. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  5496. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  5497. const Value *Size = I.getArgOperand(2);
  5498. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  5499. if (CSize && CSize->getZExtValue() == 0) {
  5500. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5501. I.getType(), true);
  5502. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  5503. return true;
  5504. }
  5505. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5506. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  5507. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  5508. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  5509. if (Res.first.getNode()) {
  5510. processIntegerCallValue(I, Res.first, true);
  5511. PendingLoads.push_back(Res.second);
  5512. return true;
  5513. }
  5514. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5515. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5516. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  5517. return false;
  5518. // If the target has a fast compare for the given size, it will return a
  5519. // preferred load type for that size. Require that the load VT is legal and
  5520. // that the target supports unaligned loads of that type. Otherwise, return
  5521. // INVALID.
  5522. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  5523. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5524. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  5525. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  5526. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5527. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5528. // TODO: Check alignment of src and dest ptrs.
  5529. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5530. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5531. if (!TLI.isTypeLegal(LVT) ||
  5532. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  5533. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  5534. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  5535. }
  5536. return LVT;
  5537. };
  5538. // This turns into unaligned loads. We only do this if the target natively
  5539. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5540. // we'll only produce a small number of byte loads.
  5541. MVT LoadVT;
  5542. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  5543. switch (NumBitsToCompare) {
  5544. default:
  5545. return false;
  5546. case 16:
  5547. LoadVT = MVT::i16;
  5548. break;
  5549. case 32:
  5550. LoadVT = MVT::i32;
  5551. break;
  5552. case 64:
  5553. case 128:
  5554. case 256:
  5555. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  5556. break;
  5557. }
  5558. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  5559. return false;
  5560. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  5561. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  5562. // Bitcast to a wide integer type if the loads are vectors.
  5563. if (LoadVT.isVector()) {
  5564. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  5565. LoadL = DAG.getBitcast(CmpVT, LoadL);
  5566. LoadR = DAG.getBitcast(CmpVT, LoadR);
  5567. }
  5568. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  5569. processIntegerCallValue(I, Cmp, false);
  5570. return true;
  5571. }
  5572. /// See if we can lower a memchr call into an optimized form. If so, return
  5573. /// true and lower it. Otherwise return false, and it will be lowered like a
  5574. /// normal call.
  5575. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5576. /// correct prototype.
  5577. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5578. const Value *Src = I.getArgOperand(0);
  5579. const Value *Char = I.getArgOperand(1);
  5580. const Value *Length = I.getArgOperand(2);
  5581. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5582. std::pair<SDValue, SDValue> Res =
  5583. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5584. getValue(Src), getValue(Char), getValue(Length),
  5585. MachinePointerInfo(Src));
  5586. if (Res.first.getNode()) {
  5587. setValue(&I, Res.first);
  5588. PendingLoads.push_back(Res.second);
  5589. return true;
  5590. }
  5591. return false;
  5592. }
  5593. /// See if we can lower a mempcpy call into an optimized form. If so, return
  5594. /// true and lower it. Otherwise return false, and it will be lowered like a
  5595. /// normal call.
  5596. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5597. /// correct prototype.
  5598. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  5599. SDValue Dst = getValue(I.getArgOperand(0));
  5600. SDValue Src = getValue(I.getArgOperand(1));
  5601. SDValue Size = getValue(I.getArgOperand(2));
  5602. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  5603. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5604. unsigned Align = std::min(DstAlign, SrcAlign);
  5605. if (Align == 0) // Alignment of one or both could not be inferred.
  5606. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  5607. bool isVol = false;
  5608. SDLoc sdl = getCurSDLoc();
  5609. // In the mempcpy context we need to pass in a false value for isTailCall
  5610. // because the return pointer needs to be adjusted by the size of
  5611. // the copied memory.
  5612. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  5613. false, /*isTailCall=*/false,
  5614. MachinePointerInfo(I.getArgOperand(0)),
  5615. MachinePointerInfo(I.getArgOperand(1)));
  5616. assert(MC.getNode() != nullptr &&
  5617. "** memcpy should not be lowered as TailCall in mempcpy context **");
  5618. DAG.setRoot(MC);
  5619. // Check if Size needs to be truncated or extended.
  5620. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  5621. // Adjust return pointer to point just past the last dst byte.
  5622. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  5623. Dst, Size);
  5624. setValue(&I, DstPlusSize);
  5625. return true;
  5626. }
  5627. /// See if we can lower a strcpy call into an optimized form. If so, return
  5628. /// true and lower it, otherwise return false and it will be lowered like a
  5629. /// normal call.
  5630. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5631. /// correct prototype.
  5632. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5633. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5634. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5635. std::pair<SDValue, SDValue> Res =
  5636. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5637. getValue(Arg0), getValue(Arg1),
  5638. MachinePointerInfo(Arg0),
  5639. MachinePointerInfo(Arg1), isStpcpy);
  5640. if (Res.first.getNode()) {
  5641. setValue(&I, Res.first);
  5642. DAG.setRoot(Res.second);
  5643. return true;
  5644. }
  5645. return false;
  5646. }
  5647. /// See if we can lower a strcmp call into an optimized form. If so, return
  5648. /// true and lower it, otherwise return false and it will be lowered like a
  5649. /// normal call.
  5650. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5651. /// correct prototype.
  5652. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5653. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5654. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5655. std::pair<SDValue, SDValue> Res =
  5656. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5657. getValue(Arg0), getValue(Arg1),
  5658. MachinePointerInfo(Arg0),
  5659. MachinePointerInfo(Arg1));
  5660. if (Res.first.getNode()) {
  5661. processIntegerCallValue(I, Res.first, true);
  5662. PendingLoads.push_back(Res.second);
  5663. return true;
  5664. }
  5665. return false;
  5666. }
  5667. /// See if we can lower a strlen call into an optimized form. If so, return
  5668. /// true and lower it, otherwise return false and it will be lowered like a
  5669. /// normal call.
  5670. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5671. /// correct prototype.
  5672. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5673. const Value *Arg0 = I.getArgOperand(0);
  5674. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5675. std::pair<SDValue, SDValue> Res =
  5676. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5677. getValue(Arg0), MachinePointerInfo(Arg0));
  5678. if (Res.first.getNode()) {
  5679. processIntegerCallValue(I, Res.first, false);
  5680. PendingLoads.push_back(Res.second);
  5681. return true;
  5682. }
  5683. return false;
  5684. }
  5685. /// See if we can lower a strnlen call into an optimized form. If so, return
  5686. /// true and lower it, otherwise return false and it will be lowered like a
  5687. /// normal call.
  5688. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5689. /// correct prototype.
  5690. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5691. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5692. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5693. std::pair<SDValue, SDValue> Res =
  5694. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5695. getValue(Arg0), getValue(Arg1),
  5696. MachinePointerInfo(Arg0));
  5697. if (Res.first.getNode()) {
  5698. processIntegerCallValue(I, Res.first, false);
  5699. PendingLoads.push_back(Res.second);
  5700. return true;
  5701. }
  5702. return false;
  5703. }
  5704. /// See if we can lower a unary floating-point operation into an SDNode with
  5705. /// the specified Opcode. If so, return true and lower it, otherwise return
  5706. /// false and it will be lowered like a normal call.
  5707. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5708. /// correct prototype.
  5709. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5710. unsigned Opcode) {
  5711. // We already checked this call's prototype; verify it doesn't modify errno.
  5712. if (!I.onlyReadsMemory())
  5713. return false;
  5714. SDValue Tmp = getValue(I.getArgOperand(0));
  5715. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5716. return true;
  5717. }
  5718. /// See if we can lower a binary floating-point operation into an SDNode with
  5719. /// the specified Opcode. If so, return true and lower it. Otherwise return
  5720. /// false, and it will be lowered like a normal call.
  5721. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5722. /// correct prototype.
  5723. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  5724. unsigned Opcode) {
  5725. // We already checked this call's prototype; verify it doesn't modify errno.
  5726. if (!I.onlyReadsMemory())
  5727. return false;
  5728. SDValue Tmp0 = getValue(I.getArgOperand(0));
  5729. SDValue Tmp1 = getValue(I.getArgOperand(1));
  5730. EVT VT = Tmp0.getValueType();
  5731. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  5732. return true;
  5733. }
  5734. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5735. // Handle inline assembly differently.
  5736. if (isa<InlineAsm>(I.getCalledValue())) {
  5737. visitInlineAsm(&I);
  5738. return;
  5739. }
  5740. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5741. computeUsesVAFloatArgument(I, MMI);
  5742. const char *RenameFn = nullptr;
  5743. if (Function *F = I.getCalledFunction()) {
  5744. if (F->isDeclaration()) {
  5745. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  5746. if (unsigned IID = II->getIntrinsicID(F)) {
  5747. RenameFn = visitIntrinsicCall(I, IID);
  5748. if (!RenameFn)
  5749. return;
  5750. }
  5751. }
  5752. if (Intrinsic::ID IID = F->getIntrinsicID()) {
  5753. RenameFn = visitIntrinsicCall(I, IID);
  5754. if (!RenameFn)
  5755. return;
  5756. }
  5757. }
  5758. // Check for well-known libc/libm calls. If the function is internal, it
  5759. // can't be a library call. Don't do the check if marked as nobuiltin for
  5760. // some reason.
  5761. LibFunc Func;
  5762. if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
  5763. LibInfo->getLibFunc(*F, Func) &&
  5764. LibInfo->hasOptimizedCodeGen(Func)) {
  5765. switch (Func) {
  5766. default: break;
  5767. case LibFunc_copysign:
  5768. case LibFunc_copysignf:
  5769. case LibFunc_copysignl:
  5770. // We already checked this call's prototype; verify it doesn't modify
  5771. // errno.
  5772. if (I.onlyReadsMemory()) {
  5773. SDValue LHS = getValue(I.getArgOperand(0));
  5774. SDValue RHS = getValue(I.getArgOperand(1));
  5775. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  5776. LHS.getValueType(), LHS, RHS));
  5777. return;
  5778. }
  5779. break;
  5780. case LibFunc_fabs:
  5781. case LibFunc_fabsf:
  5782. case LibFunc_fabsl:
  5783. if (visitUnaryFloatCall(I, ISD::FABS))
  5784. return;
  5785. break;
  5786. case LibFunc_fmin:
  5787. case LibFunc_fminf:
  5788. case LibFunc_fminl:
  5789. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  5790. return;
  5791. break;
  5792. case LibFunc_fmax:
  5793. case LibFunc_fmaxf:
  5794. case LibFunc_fmaxl:
  5795. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  5796. return;
  5797. break;
  5798. case LibFunc_sin:
  5799. case LibFunc_sinf:
  5800. case LibFunc_sinl:
  5801. if (visitUnaryFloatCall(I, ISD::FSIN))
  5802. return;
  5803. break;
  5804. case LibFunc_cos:
  5805. case LibFunc_cosf:
  5806. case LibFunc_cosl:
  5807. if (visitUnaryFloatCall(I, ISD::FCOS))
  5808. return;
  5809. break;
  5810. case LibFunc_sqrt:
  5811. case LibFunc_sqrtf:
  5812. case LibFunc_sqrtl:
  5813. case LibFunc_sqrt_finite:
  5814. case LibFunc_sqrtf_finite:
  5815. case LibFunc_sqrtl_finite:
  5816. if (visitUnaryFloatCall(I, ISD::FSQRT))
  5817. return;
  5818. break;
  5819. case LibFunc_floor:
  5820. case LibFunc_floorf:
  5821. case LibFunc_floorl:
  5822. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  5823. return;
  5824. break;
  5825. case LibFunc_nearbyint:
  5826. case LibFunc_nearbyintf:
  5827. case LibFunc_nearbyintl:
  5828. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  5829. return;
  5830. break;
  5831. case LibFunc_ceil:
  5832. case LibFunc_ceilf:
  5833. case LibFunc_ceill:
  5834. if (visitUnaryFloatCall(I, ISD::FCEIL))
  5835. return;
  5836. break;
  5837. case LibFunc_rint:
  5838. case LibFunc_rintf:
  5839. case LibFunc_rintl:
  5840. if (visitUnaryFloatCall(I, ISD::FRINT))
  5841. return;
  5842. break;
  5843. case LibFunc_round:
  5844. case LibFunc_roundf:
  5845. case LibFunc_roundl:
  5846. if (visitUnaryFloatCall(I, ISD::FROUND))
  5847. return;
  5848. break;
  5849. case LibFunc_trunc:
  5850. case LibFunc_truncf:
  5851. case LibFunc_truncl:
  5852. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  5853. return;
  5854. break;
  5855. case LibFunc_log2:
  5856. case LibFunc_log2f:
  5857. case LibFunc_log2l:
  5858. if (visitUnaryFloatCall(I, ISD::FLOG2))
  5859. return;
  5860. break;
  5861. case LibFunc_exp2:
  5862. case LibFunc_exp2f:
  5863. case LibFunc_exp2l:
  5864. if (visitUnaryFloatCall(I, ISD::FEXP2))
  5865. return;
  5866. break;
  5867. case LibFunc_memcmp:
  5868. if (visitMemCmpCall(I))
  5869. return;
  5870. break;
  5871. case LibFunc_mempcpy:
  5872. if (visitMemPCpyCall(I))
  5873. return;
  5874. break;
  5875. case LibFunc_memchr:
  5876. if (visitMemChrCall(I))
  5877. return;
  5878. break;
  5879. case LibFunc_strcpy:
  5880. if (visitStrCpyCall(I, false))
  5881. return;
  5882. break;
  5883. case LibFunc_stpcpy:
  5884. if (visitStrCpyCall(I, true))
  5885. return;
  5886. break;
  5887. case LibFunc_strcmp:
  5888. if (visitStrCmpCall(I))
  5889. return;
  5890. break;
  5891. case LibFunc_strlen:
  5892. if (visitStrLenCall(I))
  5893. return;
  5894. break;
  5895. case LibFunc_strnlen:
  5896. if (visitStrNLenCall(I))
  5897. return;
  5898. break;
  5899. }
  5900. }
  5901. }
  5902. SDValue Callee;
  5903. if (!RenameFn)
  5904. Callee = getValue(I.getCalledValue());
  5905. else
  5906. Callee = DAG.getExternalSymbol(
  5907. RenameFn,
  5908. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  5909. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  5910. // have to do anything here to lower funclet bundles.
  5911. assert(!I.hasOperandBundlesOtherThan(
  5912. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  5913. "Cannot lower calls with arbitrary operand bundles!");
  5914. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  5915. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  5916. else
  5917. // Check if we can potentially perform a tail call. More detailed checking
  5918. // is be done within LowerCallTo, after more information about the call is
  5919. // known.
  5920. LowerCallTo(&I, Callee, I.isTailCall());
  5921. }
  5922. namespace {
  5923. /// AsmOperandInfo - This contains information for each constraint that we are
  5924. /// lowering.
  5925. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  5926. public:
  5927. /// CallOperand - If this is the result output operand or a clobber
  5928. /// this is null, otherwise it is the incoming operand to the CallInst.
  5929. /// This gets modified as the asm is processed.
  5930. SDValue CallOperand;
  5931. /// AssignedRegs - If this is a register or register class operand, this
  5932. /// contains the set of register corresponding to the operand.
  5933. RegsForValue AssignedRegs;
  5934. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  5935. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
  5936. }
  5937. /// Whether or not this operand accesses memory
  5938. bool hasMemory(const TargetLowering &TLI) const {
  5939. // Indirect operand accesses access memory.
  5940. if (isIndirect)
  5941. return true;
  5942. for (const auto &Code : Codes)
  5943. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  5944. return true;
  5945. return false;
  5946. }
  5947. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  5948. /// corresponds to. If there is no Value* for this operand, it returns
  5949. /// MVT::Other.
  5950. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  5951. const DataLayout &DL) const {
  5952. if (!CallOperandVal) return MVT::Other;
  5953. if (isa<BasicBlock>(CallOperandVal))
  5954. return TLI.getPointerTy(DL);
  5955. llvm::Type *OpTy = CallOperandVal->getType();
  5956. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  5957. // If this is an indirect operand, the operand is a pointer to the
  5958. // accessed type.
  5959. if (isIndirect) {
  5960. llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  5961. if (!PtrTy)
  5962. report_fatal_error("Indirect operand for inline asm not a pointer!");
  5963. OpTy = PtrTy->getElementType();
  5964. }
  5965. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  5966. if (StructType *STy = dyn_cast<StructType>(OpTy))
  5967. if (STy->getNumElements() == 1)
  5968. OpTy = STy->getElementType(0);
  5969. // If OpTy is not a single value, it may be a struct/union that we
  5970. // can tile with integers.
  5971. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  5972. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  5973. switch (BitSize) {
  5974. default: break;
  5975. case 1:
  5976. case 8:
  5977. case 16:
  5978. case 32:
  5979. case 64:
  5980. case 128:
  5981. OpTy = IntegerType::get(Context, BitSize);
  5982. break;
  5983. }
  5984. }
  5985. return TLI.getValueType(DL, OpTy, true);
  5986. }
  5987. };
  5988. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  5989. } // end anonymous namespace
  5990. /// Make sure that the output operand \p OpInfo and its corresponding input
  5991. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  5992. /// out).
  5993. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  5994. SDISelAsmOperandInfo &MatchingOpInfo,
  5995. SelectionDAG &DAG) {
  5996. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  5997. return;
  5998. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  5999. const auto &TLI = DAG.getTargetLoweringInfo();
  6000. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6001. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6002. OpInfo.ConstraintVT);
  6003. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6004. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6005. MatchingOpInfo.ConstraintVT);
  6006. if ((OpInfo.ConstraintVT.isInteger() !=
  6007. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6008. (MatchRC.second != InputRC.second)) {
  6009. // FIXME: error out in a more elegant fashion
  6010. report_fatal_error("Unsupported asm: input constraint"
  6011. " with a matching output constraint of"
  6012. " incompatible type!");
  6013. }
  6014. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6015. }
  6016. /// Get a direct memory input to behave well as an indirect operand.
  6017. /// This may introduce stores, hence the need for a \p Chain.
  6018. /// \return The (possibly updated) chain.
  6019. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6020. SDISelAsmOperandInfo &OpInfo,
  6021. SelectionDAG &DAG) {
  6022. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6023. // If we don't have an indirect input, put it in the constpool if we can,
  6024. // otherwise spill it to a stack slot.
  6025. // TODO: This isn't quite right. We need to handle these according to
  6026. // the addressing mode that the constraint wants. Also, this may take
  6027. // an additional register for the computation and we don't want that
  6028. // either.
  6029. // If the operand is a float, integer, or vector constant, spill to a
  6030. // constant pool entry to get its address.
  6031. const Value *OpVal = OpInfo.CallOperandVal;
  6032. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6033. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6034. OpInfo.CallOperand = DAG.getConstantPool(
  6035. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6036. return Chain;
  6037. }
  6038. // Otherwise, create a stack slot and emit a store to it before the asm.
  6039. Type *Ty = OpVal->getType();
  6040. auto &DL = DAG.getDataLayout();
  6041. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6042. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6043. MachineFunction &MF = DAG.getMachineFunction();
  6044. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6045. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6046. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6047. MachinePointerInfo::getFixedStack(MF, SSFI));
  6048. OpInfo.CallOperand = StackSlot;
  6049. return Chain;
  6050. }
  6051. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6052. /// specified operand. We prefer to assign virtual registers, to allow the
  6053. /// register allocator to handle the assignment process. However, if the asm
  6054. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6055. /// allocation. This produces generally horrible, but correct, code.
  6056. ///
  6057. /// OpInfo describes the operand.
  6058. ///
  6059. static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
  6060. const SDLoc &DL,
  6061. SDISelAsmOperandInfo &OpInfo) {
  6062. LLVMContext &Context = *DAG.getContext();
  6063. MachineFunction &MF = DAG.getMachineFunction();
  6064. SmallVector<unsigned, 4> Regs;
  6065. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6066. // If this is a constraint for a single physreg, or a constraint for a
  6067. // register class, find it.
  6068. std::pair<unsigned, const TargetRegisterClass *> PhysReg =
  6069. TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
  6070. OpInfo.ConstraintVT);
  6071. unsigned NumRegs = 1;
  6072. if (OpInfo.ConstraintVT != MVT::Other) {
  6073. // If this is a FP input in an integer register (or visa versa) insert a bit
  6074. // cast of the input value. More generally, handle any case where the input
  6075. // value disagrees with the register class we plan to stick this in.
  6076. if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
  6077. !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
  6078. // Try to convert to the first EVT that the reg class contains. If the
  6079. // types are identical size, use a bitcast to convert (e.g. two differing
  6080. // vector types).
  6081. MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
  6082. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  6083. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  6084. RegVT, OpInfo.CallOperand);
  6085. OpInfo.ConstraintVT = RegVT;
  6086. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6087. // If the input is a FP value and we want it in FP registers, do a
  6088. // bitcast to the corresponding integer type. This turns an f64 value
  6089. // into i64, which can be passed with two i32 values on a 32-bit
  6090. // machine.
  6091. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6092. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  6093. RegVT, OpInfo.CallOperand);
  6094. OpInfo.ConstraintVT = RegVT;
  6095. }
  6096. }
  6097. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6098. }
  6099. MVT RegVT;
  6100. EVT ValueVT = OpInfo.ConstraintVT;
  6101. // If this is a constraint for a specific physical register, like {r17},
  6102. // assign it now.
  6103. if (unsigned AssignedReg = PhysReg.first) {
  6104. const TargetRegisterClass *RC = PhysReg.second;
  6105. if (OpInfo.ConstraintVT == MVT::Other)
  6106. ValueVT = *TRI.legalclasstypes_begin(*RC);
  6107. // Get the actual register value type. This is important, because the user
  6108. // may have asked for (e.g.) the AX register in i32 type. We need to
  6109. // remember that AX is actually i16 to get the right extension.
  6110. RegVT = *TRI.legalclasstypes_begin(*RC);
  6111. // This is a explicit reference to a physical register.
  6112. Regs.push_back(AssignedReg);
  6113. // If this is an expanded reference, add the rest of the regs to Regs.
  6114. if (NumRegs != 1) {
  6115. TargetRegisterClass::iterator I = RC->begin();
  6116. for (; *I != AssignedReg; ++I)
  6117. assert(I != RC->end() && "Didn't find reg!");
  6118. // Already added the first reg.
  6119. --NumRegs; ++I;
  6120. for (; NumRegs; --NumRegs, ++I) {
  6121. assert(I != RC->end() && "Ran out of registers to allocate!");
  6122. Regs.push_back(*I);
  6123. }
  6124. }
  6125. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6126. return;
  6127. }
  6128. // Otherwise, if this was a reference to an LLVM register class, create vregs
  6129. // for this reference.
  6130. if (const TargetRegisterClass *RC = PhysReg.second) {
  6131. RegVT = *TRI.legalclasstypes_begin(*RC);
  6132. if (OpInfo.ConstraintVT == MVT::Other)
  6133. ValueVT = RegVT;
  6134. // Create the appropriate number of virtual registers.
  6135. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6136. for (; NumRegs; --NumRegs)
  6137. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6138. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6139. return;
  6140. }
  6141. // Otherwise, we couldn't allocate enough registers for this.
  6142. }
  6143. static unsigned
  6144. findMatchingInlineAsmOperand(unsigned OperandNo,
  6145. const std::vector<SDValue> &AsmNodeOperands) {
  6146. // Scan until we find the definition we already emitted of this operand.
  6147. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6148. for (; OperandNo; --OperandNo) {
  6149. // Advance to the next operand.
  6150. unsigned OpFlag =
  6151. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6152. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6153. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6154. InlineAsm::isMemKind(OpFlag)) &&
  6155. "Skipped past definitions?");
  6156. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6157. }
  6158. return CurOp;
  6159. }
  6160. /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
  6161. /// \return true if it has succeeded, false otherwise
  6162. static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
  6163. MVT RegVT, SelectionDAG &DAG) {
  6164. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6165. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  6166. for (unsigned i = 0, e = NumRegs; i != e; ++i) {
  6167. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  6168. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6169. else
  6170. return false;
  6171. }
  6172. return true;
  6173. }
  6174. class ExtraFlags {
  6175. unsigned Flags = 0;
  6176. public:
  6177. explicit ExtraFlags(ImmutableCallSite CS) {
  6178. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6179. if (IA->hasSideEffects())
  6180. Flags |= InlineAsm::Extra_HasSideEffects;
  6181. if (IA->isAlignStack())
  6182. Flags |= InlineAsm::Extra_IsAlignStack;
  6183. if (CS.isConvergent())
  6184. Flags |= InlineAsm::Extra_IsConvergent;
  6185. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  6186. }
  6187. void update(const llvm::TargetLowering::AsmOperandInfo &OpInfo) {
  6188. // Ideally, we would only check against memory constraints. However, the
  6189. // meaning of an Other constraint can be target-specific and we can't easily
  6190. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  6191. // for Other constraints as well.
  6192. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6193. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6194. if (OpInfo.Type == InlineAsm::isInput)
  6195. Flags |= InlineAsm::Extra_MayLoad;
  6196. else if (OpInfo.Type == InlineAsm::isOutput)
  6197. Flags |= InlineAsm::Extra_MayStore;
  6198. else if (OpInfo.Type == InlineAsm::isClobber)
  6199. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6200. }
  6201. }
  6202. unsigned get() const { return Flags; }
  6203. };
  6204. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6205. ///
  6206. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6207. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6208. /// ConstraintOperands - Information about all of the constraints.
  6209. SDISelAsmOperandInfoVector ConstraintOperands;
  6210. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6211. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6212. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6213. bool hasMemory = false;
  6214. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6215. ExtraFlags ExtraInfo(CS);
  6216. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6217. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6218. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  6219. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  6220. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6221. MVT OpVT = MVT::Other;
  6222. // Compute the value type for each operand.
  6223. if (OpInfo.Type == InlineAsm::isInput ||
  6224. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6225. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6226. // Process the call argument. BasicBlocks are labels, currently appearing
  6227. // only in asm's.
  6228. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  6229. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  6230. } else {
  6231. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  6232. }
  6233. OpVT =
  6234. OpInfo
  6235. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  6236. .getSimpleVT();
  6237. }
  6238. if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  6239. // The return value of the call is this value. As such, there is no
  6240. // corresponding argument.
  6241. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6242. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  6243. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
  6244. STy->getElementType(ResNo));
  6245. } else {
  6246. assert(ResNo == 0 && "Asm only has one result!");
  6247. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  6248. }
  6249. ++ResNo;
  6250. }
  6251. OpInfo.ConstraintVT = OpVT;
  6252. if (!hasMemory)
  6253. hasMemory = OpInfo.hasMemory(TLI);
  6254. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  6255. // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
  6256. auto TargetConstraint = TargetConstraints[i];
  6257. // Compute the constraint code and ConstraintType to use.
  6258. TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
  6259. ExtraInfo.update(TargetConstraint);
  6260. }
  6261. SDValue Chain, Flag;
  6262. // We won't need to flush pending loads if this asm doesn't touch
  6263. // memory and is nonvolatile.
  6264. if (hasMemory || IA->hasSideEffects())
  6265. Chain = getRoot();
  6266. else
  6267. Chain = DAG.getRoot();
  6268. // Second pass over the constraints: compute which constraint option to use
  6269. // and assign registers to constraints that want a specific physreg.
  6270. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6271. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6272. // If this is an output operand with a matching input operand, look up the
  6273. // matching input. If their types mismatch, e.g. one is an integer, the
  6274. // other is floating point, or their sizes are different, flag it as an
  6275. // error.
  6276. if (OpInfo.hasMatchingInput()) {
  6277. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  6278. patchMatchingInput(OpInfo, Input, DAG);
  6279. }
  6280. // Compute the constraint code and ConstraintType to use.
  6281. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  6282. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6283. OpInfo.Type == InlineAsm::isClobber)
  6284. continue;
  6285. // If this is a memory input, and if the operand is not indirect, do what we
  6286. // need to to provide an address for the memory input.
  6287. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6288. !OpInfo.isIndirect) {
  6289. assert((OpInfo.isMultipleAlternative ||
  6290. (OpInfo.Type == InlineAsm::isInput)) &&
  6291. "Can only indirectify direct input operands!");
  6292. // Memory operands really want the address of the value.
  6293. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  6294. // There is no longer a Value* corresponding to this operand.
  6295. OpInfo.CallOperandVal = nullptr;
  6296. // It is now an indirect operand.
  6297. OpInfo.isIndirect = true;
  6298. }
  6299. // If this constraint is for a specific register, allocate it before
  6300. // anything else.
  6301. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  6302. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6303. }
  6304. // Third pass - Loop over all of the operands, assigning virtual or physregs
  6305. // to register class operands.
  6306. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6307. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6308. // C_Register operands have already been allocated, Other/Memory don't need
  6309. // to be.
  6310. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  6311. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6312. }
  6313. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  6314. std::vector<SDValue> AsmNodeOperands;
  6315. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  6316. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  6317. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  6318. // If we have a !srcloc metadata node associated with it, we want to attach
  6319. // this to the ultimately generated inline asm machineinstr. To do this, we
  6320. // pass in the third operand as this (potentially null) inline asm MDNode.
  6321. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  6322. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  6323. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6324. // bits as operand 3.
  6325. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6326. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6327. // Loop over all of the inputs, copying the operand values into the
  6328. // appropriate registers and processing the output regs.
  6329. RegsForValue RetValRegs;
  6330. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  6331. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  6332. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6333. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6334. switch (OpInfo.Type) {
  6335. case InlineAsm::isOutput: {
  6336. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  6337. OpInfo.ConstraintType != TargetLowering::C_Register) {
  6338. // Memory output, or 'other' output (e.g. 'X' constraint).
  6339. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  6340. unsigned ConstraintID =
  6341. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6342. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6343. "Failed to convert memory constraint code to constraint id.");
  6344. // Add information to the INLINEASM node to know about this output.
  6345. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6346. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  6347. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  6348. MVT::i32));
  6349. AsmNodeOperands.push_back(OpInfo.CallOperand);
  6350. break;
  6351. }
  6352. // Otherwise, this is a register or register class output.
  6353. // Copy the output from the appropriate register. Find a register that
  6354. // we can use.
  6355. if (OpInfo.AssignedRegs.Regs.empty()) {
  6356. emitInlineAsmError(
  6357. CS, "couldn't allocate output register for constraint '" +
  6358. Twine(OpInfo.ConstraintCode) + "'");
  6359. return;
  6360. }
  6361. // If this is an indirect operand, store through the pointer after the
  6362. // asm.
  6363. if (OpInfo.isIndirect) {
  6364. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  6365. OpInfo.CallOperandVal));
  6366. } else {
  6367. // This is the result value of the call.
  6368. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6369. // Concatenate this output onto the outputs list.
  6370. RetValRegs.append(OpInfo.AssignedRegs);
  6371. }
  6372. // Add information to the INLINEASM node to know that this register is
  6373. // set.
  6374. OpInfo.AssignedRegs
  6375. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  6376. ? InlineAsm::Kind_RegDefEarlyClobber
  6377. : InlineAsm::Kind_RegDef,
  6378. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  6379. break;
  6380. }
  6381. case InlineAsm::isInput: {
  6382. SDValue InOperandVal = OpInfo.CallOperand;
  6383. if (OpInfo.isMatchingInputConstraint()) {
  6384. // If this is required to match an output register we have already set,
  6385. // just use its register.
  6386. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  6387. AsmNodeOperands);
  6388. unsigned OpFlag =
  6389. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6390. if (InlineAsm::isRegDefKind(OpFlag) ||
  6391. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  6392. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  6393. if (OpInfo.isIndirect) {
  6394. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  6395. emitInlineAsmError(CS, "inline asm not supported yet:"
  6396. " don't know how to handle tied "
  6397. "indirect register inputs");
  6398. return;
  6399. }
  6400. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  6401. SmallVector<unsigned, 4> Regs;
  6402. if (!createVirtualRegs(Regs,
  6403. InlineAsm::getNumOperandRegisters(OpFlag),
  6404. RegVT, DAG)) {
  6405. emitInlineAsmError(CS, "inline asm error: This value type register "
  6406. "class is not natively supported!");
  6407. return;
  6408. }
  6409. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  6410. SDLoc dl = getCurSDLoc();
  6411. // Use the produced MatchedRegs object to
  6412. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  6413. CS.getInstruction());
  6414. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  6415. true, OpInfo.getMatchedOperand(), dl,
  6416. DAG, AsmNodeOperands);
  6417. break;
  6418. }
  6419. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  6420. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  6421. "Unexpected number of operands");
  6422. // Add information to the INLINEASM node to know about this input.
  6423. // See InlineAsm.h isUseOperandTiedToDef.
  6424. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  6425. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  6426. OpInfo.getMatchedOperand());
  6427. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6428. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6429. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  6430. break;
  6431. }
  6432. // Treat indirect 'X' constraint as memory.
  6433. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  6434. OpInfo.isIndirect)
  6435. OpInfo.ConstraintType = TargetLowering::C_Memory;
  6436. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  6437. std::vector<SDValue> Ops;
  6438. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  6439. Ops, DAG);
  6440. if (Ops.empty()) {
  6441. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  6442. Twine(OpInfo.ConstraintCode) + "'");
  6443. return;
  6444. }
  6445. // Add information to the INLINEASM node to know about this input.
  6446. unsigned ResOpType =
  6447. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  6448. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6449. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6450. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  6451. break;
  6452. }
  6453. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  6454. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  6455. assert(InOperandVal.getValueType() ==
  6456. TLI.getPointerTy(DAG.getDataLayout()) &&
  6457. "Memory operands expect pointer values");
  6458. unsigned ConstraintID =
  6459. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6460. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6461. "Failed to convert memory constraint code to constraint id.");
  6462. // Add information to the INLINEASM node to know about this input.
  6463. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6464. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  6465. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  6466. getCurSDLoc(),
  6467. MVT::i32));
  6468. AsmNodeOperands.push_back(InOperandVal);
  6469. break;
  6470. }
  6471. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  6472. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  6473. "Unknown constraint type!");
  6474. // TODO: Support this.
  6475. if (OpInfo.isIndirect) {
  6476. emitInlineAsmError(
  6477. CS, "Don't know how to handle indirect register inputs yet "
  6478. "for constraint '" +
  6479. Twine(OpInfo.ConstraintCode) + "'");
  6480. return;
  6481. }
  6482. // Copy the input into the appropriate registers.
  6483. if (OpInfo.AssignedRegs.Regs.empty()) {
  6484. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  6485. Twine(OpInfo.ConstraintCode) + "'");
  6486. return;
  6487. }
  6488. SDLoc dl = getCurSDLoc();
  6489. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  6490. Chain, &Flag, CS.getInstruction());
  6491. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  6492. dl, DAG, AsmNodeOperands);
  6493. break;
  6494. }
  6495. case InlineAsm::isClobber: {
  6496. // Add the clobbered value to the operand list, so that the register
  6497. // allocator is aware that the physreg got clobbered.
  6498. if (!OpInfo.AssignedRegs.Regs.empty())
  6499. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  6500. false, 0, getCurSDLoc(), DAG,
  6501. AsmNodeOperands);
  6502. break;
  6503. }
  6504. }
  6505. }
  6506. // Finish up input operands. Set the input chain and add the flag last.
  6507. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  6508. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  6509. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  6510. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  6511. Flag = Chain.getValue(1);
  6512. // If this asm returns a register value, copy the result from that register
  6513. // and set it as the value of the call.
  6514. if (!RetValRegs.Regs.empty()) {
  6515. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6516. Chain, &Flag, CS.getInstruction());
  6517. // FIXME: Why don't we do this for inline asms with MRVs?
  6518. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  6519. EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6520. // If any of the results of the inline asm is a vector, it may have the
  6521. // wrong width/num elts. This can happen for register classes that can
  6522. // contain multiple different value types. The preg or vreg allocated may
  6523. // not have the same VT as was expected. Convert it to the right type
  6524. // with bit_convert.
  6525. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  6526. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  6527. ResultType, Val);
  6528. } else if (ResultType != Val.getValueType() &&
  6529. ResultType.isInteger() && Val.getValueType().isInteger()) {
  6530. // If a result value was tied to an input value, the computed result may
  6531. // have a wider width than the expected result. Extract the relevant
  6532. // portion.
  6533. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  6534. }
  6535. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  6536. }
  6537. setValue(CS.getInstruction(), Val);
  6538. // Don't need to use this as a chain in this case.
  6539. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  6540. return;
  6541. }
  6542. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  6543. // Process indirect outputs, first output all of the flagged copies out of
  6544. // physregs.
  6545. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  6546. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  6547. const Value *Ptr = IndirectStoresToEmit[i].second;
  6548. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6549. Chain, &Flag, IA);
  6550. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  6551. }
  6552. // Emit the non-flagged stores from the physregs.
  6553. SmallVector<SDValue, 8> OutChains;
  6554. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  6555. SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
  6556. getValue(StoresToEmit[i].second),
  6557. MachinePointerInfo(StoresToEmit[i].second));
  6558. OutChains.push_back(Val);
  6559. }
  6560. if (!OutChains.empty())
  6561. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  6562. DAG.setRoot(Chain);
  6563. }
  6564. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  6565. const Twine &Message) {
  6566. LLVMContext &Ctx = *DAG.getContext();
  6567. Ctx.emitError(CS.getInstruction(), Message);
  6568. // Make sure we leave the DAG in a valid state
  6569. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6570. auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6571. setValue(CS.getInstruction(), DAG.getUNDEF(VT));
  6572. }
  6573. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  6574. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  6575. MVT::Other, getRoot(),
  6576. getValue(I.getArgOperand(0)),
  6577. DAG.getSrcValue(I.getArgOperand(0))));
  6578. }
  6579. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  6580. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6581. const DataLayout &DL = DAG.getDataLayout();
  6582. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  6583. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  6584. DAG.getSrcValue(I.getOperand(0)),
  6585. DL.getABITypeAlignment(I.getType()));
  6586. setValue(&I, V);
  6587. DAG.setRoot(V.getValue(1));
  6588. }
  6589. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  6590. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  6591. MVT::Other, getRoot(),
  6592. getValue(I.getArgOperand(0)),
  6593. DAG.getSrcValue(I.getArgOperand(0))));
  6594. }
  6595. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  6596. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  6597. MVT::Other, getRoot(),
  6598. getValue(I.getArgOperand(0)),
  6599. getValue(I.getArgOperand(1)),
  6600. DAG.getSrcValue(I.getArgOperand(0)),
  6601. DAG.getSrcValue(I.getArgOperand(1))));
  6602. }
  6603. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  6604. const Instruction &I,
  6605. SDValue Op) {
  6606. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  6607. if (!Range)
  6608. return Op;
  6609. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  6610. if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
  6611. return Op;
  6612. APInt Lo = CR.getUnsignedMin();
  6613. if (!Lo.isMinValue())
  6614. return Op;
  6615. APInt Hi = CR.getUnsignedMax();
  6616. unsigned Bits = Hi.getActiveBits();
  6617. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  6618. SDLoc SL = getCurSDLoc();
  6619. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  6620. DAG.getValueType(SmallVT));
  6621. unsigned NumVals = Op.getNode()->getNumValues();
  6622. if (NumVals == 1)
  6623. return ZExt;
  6624. SmallVector<SDValue, 4> Ops;
  6625. Ops.push_back(ZExt);
  6626. for (unsigned I = 1; I != NumVals; ++I)
  6627. Ops.push_back(Op.getValue(I));
  6628. return DAG.getMergeValues(Ops, SL);
  6629. }
  6630. /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
  6631. /// the call being lowered.
  6632. ///
  6633. /// This is a helper for lowering intrinsics that follow a target calling
  6634. /// convention or require stack pointer adjustment. Only a subset of the
  6635. /// intrinsic's operands need to participate in the calling convention.
  6636. void SelectionDAGBuilder::populateCallLoweringInfo(
  6637. TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
  6638. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  6639. bool IsPatchPoint) {
  6640. TargetLowering::ArgListTy Args;
  6641. Args.reserve(NumArgs);
  6642. // Populate the argument list.
  6643. // Attributes for args start at offset 1, after the return attribute.
  6644. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  6645. ArgI != ArgE; ++ArgI) {
  6646. const Value *V = CS->getOperand(ArgI);
  6647. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  6648. TargetLowering::ArgListEntry Entry;
  6649. Entry.Node = getValue(V);
  6650. Entry.Ty = V->getType();
  6651. Entry.setAttributes(&CS, ArgIdx);
  6652. Args.push_back(Entry);
  6653. }
  6654. CLI.setDebugLoc(getCurSDLoc())
  6655. .setChain(getRoot())
  6656. .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
  6657. .setDiscardResult(CS->use_empty())
  6658. .setIsPatchPoint(IsPatchPoint);
  6659. }
  6660. /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
  6661. /// or patchpoint target node's operand list.
  6662. ///
  6663. /// Constants are converted to TargetConstants purely as an optimization to
  6664. /// avoid constant materialization and register allocation.
  6665. ///
  6666. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  6667. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  6668. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  6669. /// address materialization and register allocation, but may also be required
  6670. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  6671. /// alloca in the entry block, then the runtime may assume that the alloca's
  6672. /// StackMap location can be read immediately after compilation and that the
  6673. /// location is valid at any point during execution (this is similar to the
  6674. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  6675. /// only available in a register, then the runtime would need to trap when
  6676. /// execution reaches the StackMap in order to read the alloca's location.
  6677. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  6678. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  6679. SelectionDAGBuilder &Builder) {
  6680. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  6681. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  6682. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6683. Ops.push_back(
  6684. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  6685. Ops.push_back(
  6686. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  6687. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  6688. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  6689. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  6690. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  6691. } else
  6692. Ops.push_back(OpVal);
  6693. }
  6694. }
  6695. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  6696. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  6697. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  6698. // [live variables...])
  6699. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  6700. SDValue Chain, InFlag, Callee, NullPtr;
  6701. SmallVector<SDValue, 32> Ops;
  6702. SDLoc DL = getCurSDLoc();
  6703. Callee = getValue(CI.getCalledValue());
  6704. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  6705. // The stackmap intrinsic only records the live variables (the arguemnts
  6706. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  6707. // intrinsic, this won't be lowered to a function call. This means we don't
  6708. // have to worry about calling conventions and target specific lowering code.
  6709. // Instead we perform the call lowering right here.
  6710. //
  6711. // chain, flag = CALLSEQ_START(chain, 0, 0)
  6712. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  6713. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  6714. //
  6715. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  6716. InFlag = Chain.getValue(1);
  6717. // Add the <id> and <numBytes> constants.
  6718. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6719. Ops.push_back(DAG.getTargetConstant(
  6720. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  6721. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6722. Ops.push_back(DAG.getTargetConstant(
  6723. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  6724. MVT::i32));
  6725. // Push live variables for the stack map.
  6726. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  6727. // We are not pushing any register mask info here on the operands list,
  6728. // because the stackmap doesn't clobber anything.
  6729. // Push the chain and the glue flag.
  6730. Ops.push_back(Chain);
  6731. Ops.push_back(InFlag);
  6732. // Create the STACKMAP node.
  6733. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6734. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  6735. Chain = SDValue(SM, 0);
  6736. InFlag = Chain.getValue(1);
  6737. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  6738. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  6739. // Set the root to the target-lowered call chain.
  6740. DAG.setRoot(Chain);
  6741. // Inform the Frame Information that we have a stackmap in this function.
  6742. FuncInfo.MF->getFrameInfo().setHasStackMap();
  6743. }
  6744. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  6745. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  6746. const BasicBlock *EHPadBB) {
  6747. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  6748. // i32 <numBytes>,
  6749. // i8* <target>,
  6750. // i32 <numArgs>,
  6751. // [Args...],
  6752. // [live variables...])
  6753. CallingConv::ID CC = CS.getCallingConv();
  6754. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  6755. bool HasDef = !CS->getType()->isVoidTy();
  6756. SDLoc dl = getCurSDLoc();
  6757. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  6758. // Handle immediate and symbolic callees.
  6759. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  6760. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  6761. /*isTarget=*/true);
  6762. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  6763. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  6764. SDLoc(SymbolicCallee),
  6765. SymbolicCallee->getValueType(0));
  6766. // Get the real number of arguments participating in the call <numArgs>
  6767. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  6768. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  6769. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  6770. // Intrinsics include all meta-operands up to but not including CC.
  6771. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  6772. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  6773. "Not enough arguments provided to the patchpoint intrinsic");
  6774. // For AnyRegCC the arguments are lowered later on manually.
  6775. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  6776. Type *ReturnTy =
  6777. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  6778. TargetLowering::CallLoweringInfo CLI(DAG);
  6779. populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
  6780. true);
  6781. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6782. SDNode *CallEnd = Result.second.getNode();
  6783. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  6784. CallEnd = CallEnd->getOperand(0).getNode();
  6785. /// Get a call instruction from the call sequence chain.
  6786. /// Tail calls are not allowed.
  6787. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  6788. "Expected a callseq node.");
  6789. SDNode *Call = CallEnd->getOperand(0).getNode();
  6790. bool HasGlue = Call->getGluedNode();
  6791. // Replace the target specific call node with the patchable intrinsic.
  6792. SmallVector<SDValue, 8> Ops;
  6793. // Add the <id> and <numBytes> constants.
  6794. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  6795. Ops.push_back(DAG.getTargetConstant(
  6796. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  6797. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  6798. Ops.push_back(DAG.getTargetConstant(
  6799. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  6800. MVT::i32));
  6801. // Add the callee.
  6802. Ops.push_back(Callee);
  6803. // Adjust <numArgs> to account for any arguments that have been passed on the
  6804. // stack instead.
  6805. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  6806. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  6807. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  6808. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  6809. // Add the calling convention
  6810. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  6811. // Add the arguments we omitted previously. The register allocator should
  6812. // place these in any free register.
  6813. if (IsAnyRegCC)
  6814. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  6815. Ops.push_back(getValue(CS.getArgument(i)));
  6816. // Push the arguments from the call instruction up to the register mask.
  6817. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  6818. Ops.append(Call->op_begin() + 2, e);
  6819. // Push live variables for the stack map.
  6820. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  6821. // Push the register mask info.
  6822. if (HasGlue)
  6823. Ops.push_back(*(Call->op_end()-2));
  6824. else
  6825. Ops.push_back(*(Call->op_end()-1));
  6826. // Push the chain (this is originally the first operand of the call, but
  6827. // becomes now the last or second to last operand).
  6828. Ops.push_back(*(Call->op_begin()));
  6829. // Push the glue flag (last operand).
  6830. if (HasGlue)
  6831. Ops.push_back(*(Call->op_end()-1));
  6832. SDVTList NodeTys;
  6833. if (IsAnyRegCC && HasDef) {
  6834. // Create the return types based on the intrinsic definition
  6835. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6836. SmallVector<EVT, 3> ValueVTs;
  6837. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  6838. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  6839. // There is always a chain and a glue type at the end
  6840. ValueVTs.push_back(MVT::Other);
  6841. ValueVTs.push_back(MVT::Glue);
  6842. NodeTys = DAG.getVTList(ValueVTs);
  6843. } else
  6844. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6845. // Replace the target specific call node with a PATCHPOINT node.
  6846. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  6847. dl, NodeTys, Ops);
  6848. // Update the NodeMap.
  6849. if (HasDef) {
  6850. if (IsAnyRegCC)
  6851. setValue(CS.getInstruction(), SDValue(MN, 0));
  6852. else
  6853. setValue(CS.getInstruction(), Result.first);
  6854. }
  6855. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  6856. // call sequence. Furthermore the location of the chain and glue can change
  6857. // when the AnyReg calling convention is used and the intrinsic returns a
  6858. // value.
  6859. if (IsAnyRegCC && HasDef) {
  6860. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  6861. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  6862. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  6863. } else
  6864. DAG.ReplaceAllUsesWith(Call, MN);
  6865. DAG.DeleteNode(Call);
  6866. // Inform the Frame Information that we have a patchpoint in this function.
  6867. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  6868. }
  6869. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  6870. unsigned Intrinsic) {
  6871. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6872. SDValue Op1 = getValue(I.getArgOperand(0));
  6873. SDValue Op2;
  6874. if (I.getNumArgOperands() > 1)
  6875. Op2 = getValue(I.getArgOperand(1));
  6876. SDLoc dl = getCurSDLoc();
  6877. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6878. SDValue Res;
  6879. FastMathFlags FMF;
  6880. if (isa<FPMathOperator>(I))
  6881. FMF = I.getFastMathFlags();
  6882. SDNodeFlags SDFlags;
  6883. SDFlags.setNoNaNs(FMF.noNaNs());
  6884. switch (Intrinsic) {
  6885. case Intrinsic::experimental_vector_reduce_fadd:
  6886. if (FMF.unsafeAlgebra())
  6887. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  6888. else
  6889. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  6890. break;
  6891. case Intrinsic::experimental_vector_reduce_fmul:
  6892. if (FMF.unsafeAlgebra())
  6893. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  6894. else
  6895. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  6896. break;
  6897. case Intrinsic::experimental_vector_reduce_add:
  6898. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  6899. break;
  6900. case Intrinsic::experimental_vector_reduce_mul:
  6901. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  6902. break;
  6903. case Intrinsic::experimental_vector_reduce_and:
  6904. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  6905. break;
  6906. case Intrinsic::experimental_vector_reduce_or:
  6907. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  6908. break;
  6909. case Intrinsic::experimental_vector_reduce_xor:
  6910. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  6911. break;
  6912. case Intrinsic::experimental_vector_reduce_smax:
  6913. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  6914. break;
  6915. case Intrinsic::experimental_vector_reduce_smin:
  6916. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  6917. break;
  6918. case Intrinsic::experimental_vector_reduce_umax:
  6919. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  6920. break;
  6921. case Intrinsic::experimental_vector_reduce_umin:
  6922. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  6923. break;
  6924. case Intrinsic::experimental_vector_reduce_fmax: {
  6925. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
  6926. break;
  6927. }
  6928. case Intrinsic::experimental_vector_reduce_fmin: {
  6929. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
  6930. break;
  6931. }
  6932. default:
  6933. llvm_unreachable("Unhandled vector reduce intrinsic");
  6934. }
  6935. setValue(&I, Res);
  6936. }
  6937. /// Returns an AttributeList representing the attributes applied to the return
  6938. /// value of the given call.
  6939. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  6940. SmallVector<Attribute::AttrKind, 2> Attrs;
  6941. if (CLI.RetSExt)
  6942. Attrs.push_back(Attribute::SExt);
  6943. if (CLI.RetZExt)
  6944. Attrs.push_back(Attribute::ZExt);
  6945. if (CLI.IsInReg)
  6946. Attrs.push_back(Attribute::InReg);
  6947. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  6948. Attrs);
  6949. }
  6950. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  6951. /// implementation, which just calls LowerCall.
  6952. /// FIXME: When all targets are
  6953. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  6954. std::pair<SDValue, SDValue>
  6955. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  6956. // Handle the incoming return values from the call.
  6957. CLI.Ins.clear();
  6958. Type *OrigRetTy = CLI.RetTy;
  6959. SmallVector<EVT, 4> RetTys;
  6960. SmallVector<uint64_t, 4> Offsets;
  6961. auto &DL = CLI.DAG.getDataLayout();
  6962. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  6963. if (CLI.IsPostTypeLegalization) {
  6964. // If we are lowering a libcall after legalization, split the return type.
  6965. SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
  6966. SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
  6967. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  6968. EVT RetVT = OldRetTys[i];
  6969. uint64_t Offset = OldOffsets[i];
  6970. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  6971. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  6972. unsigned RegisterVTSize = RegisterVT.getSizeInBits();
  6973. RetTys.append(NumRegs, RegisterVT);
  6974. for (unsigned j = 0; j != NumRegs; ++j)
  6975. Offsets.push_back(Offset + j * RegisterVTSize);
  6976. }
  6977. }
  6978. SmallVector<ISD::OutputArg, 4> Outs;
  6979. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  6980. bool CanLowerReturn =
  6981. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  6982. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  6983. SDValue DemoteStackSlot;
  6984. int DemoteStackIdx = -100;
  6985. if (!CanLowerReturn) {
  6986. // FIXME: equivalent assert?
  6987. // assert(!CS.hasInAllocaArgument() &&
  6988. // "sret demotion is incompatible with inalloca");
  6989. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  6990. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  6991. MachineFunction &MF = CLI.DAG.getMachineFunction();
  6992. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6993. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  6994. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  6995. ArgListEntry Entry;
  6996. Entry.Node = DemoteStackSlot;
  6997. Entry.Ty = StackSlotPtrType;
  6998. Entry.IsSExt = false;
  6999. Entry.IsZExt = false;
  7000. Entry.IsInReg = false;
  7001. Entry.IsSRet = true;
  7002. Entry.IsNest = false;
  7003. Entry.IsByVal = false;
  7004. Entry.IsReturned = false;
  7005. Entry.IsSwiftSelf = false;
  7006. Entry.IsSwiftError = false;
  7007. Entry.Alignment = Align;
  7008. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7009. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7010. // sret demotion isn't compatible with tail-calls, since the sret argument
  7011. // points into the callers stack frame.
  7012. CLI.IsTailCall = false;
  7013. } else {
  7014. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7015. EVT VT = RetTys[I];
  7016. MVT RegisterVT =
  7017. getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7018. unsigned NumRegs =
  7019. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7020. for (unsigned i = 0; i != NumRegs; ++i) {
  7021. ISD::InputArg MyFlags;
  7022. MyFlags.VT = RegisterVT;
  7023. MyFlags.ArgVT = VT;
  7024. MyFlags.Used = CLI.IsReturnValueUsed;
  7025. if (CLI.RetSExt)
  7026. MyFlags.Flags.setSExt();
  7027. if (CLI.RetZExt)
  7028. MyFlags.Flags.setZExt();
  7029. if (CLI.IsInReg)
  7030. MyFlags.Flags.setInReg();
  7031. CLI.Ins.push_back(MyFlags);
  7032. }
  7033. }
  7034. }
  7035. // We push in swifterror return as the last element of CLI.Ins.
  7036. ArgListTy &Args = CLI.getArgs();
  7037. if (supportSwiftError()) {
  7038. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7039. if (Args[i].IsSwiftError) {
  7040. ISD::InputArg MyFlags;
  7041. MyFlags.VT = getPointerTy(DL);
  7042. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7043. MyFlags.Flags.setSwiftError();
  7044. CLI.Ins.push_back(MyFlags);
  7045. }
  7046. }
  7047. }
  7048. // Handle all of the outgoing arguments.
  7049. CLI.Outs.clear();
  7050. CLI.OutVals.clear();
  7051. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7052. SmallVector<EVT, 4> ValueVTs;
  7053. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7054. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7055. Type *FinalType = Args[i].Ty;
  7056. if (Args[i].IsByVal)
  7057. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7058. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7059. FinalType, CLI.CallConv, CLI.IsVarArg);
  7060. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7061. ++Value) {
  7062. EVT VT = ValueVTs[Value];
  7063. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7064. SDValue Op = SDValue(Args[i].Node.getNode(),
  7065. Args[i].Node.getResNo() + Value);
  7066. ISD::ArgFlagsTy Flags;
  7067. // Certain targets (such as MIPS), may have a different ABI alignment
  7068. // for a type depending on the context. Give the target a chance to
  7069. // specify the alignment it wants.
  7070. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7071. if (Args[i].IsZExt)
  7072. Flags.setZExt();
  7073. if (Args[i].IsSExt)
  7074. Flags.setSExt();
  7075. if (Args[i].IsInReg) {
  7076. // If we are using vectorcall calling convention, a structure that is
  7077. // passed InReg - is surely an HVA
  7078. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7079. isa<StructType>(FinalType)) {
  7080. // The first value of a structure is marked
  7081. if (0 == Value)
  7082. Flags.setHvaStart();
  7083. Flags.setHva();
  7084. }
  7085. // Set InReg Flag
  7086. Flags.setInReg();
  7087. }
  7088. if (Args[i].IsSRet)
  7089. Flags.setSRet();
  7090. if (Args[i].IsSwiftSelf)
  7091. Flags.setSwiftSelf();
  7092. if (Args[i].IsSwiftError)
  7093. Flags.setSwiftError();
  7094. if (Args[i].IsByVal)
  7095. Flags.setByVal();
  7096. if (Args[i].IsInAlloca) {
  7097. Flags.setInAlloca();
  7098. // Set the byval flag for CCAssignFn callbacks that don't know about
  7099. // inalloca. This way we can know how many bytes we should've allocated
  7100. // and how many bytes a callee cleanup function will pop. If we port
  7101. // inalloca to more targets, we'll have to add custom inalloca handling
  7102. // in the various CC lowering callbacks.
  7103. Flags.setByVal();
  7104. }
  7105. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  7106. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  7107. Type *ElementTy = Ty->getElementType();
  7108. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7109. // For ByVal, alignment should come from FE. BE will guess if this
  7110. // info is not there but there are cases it cannot get right.
  7111. unsigned FrameAlign;
  7112. if (Args[i].Alignment)
  7113. FrameAlign = Args[i].Alignment;
  7114. else
  7115. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  7116. Flags.setByValAlign(FrameAlign);
  7117. }
  7118. if (Args[i].IsNest)
  7119. Flags.setNest();
  7120. if (NeedsRegBlock)
  7121. Flags.setInConsecutiveRegs();
  7122. Flags.setOrigAlign(OriginalAlignment);
  7123. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7124. unsigned NumParts =
  7125. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7126. SmallVector<SDValue, 4> Parts(NumParts);
  7127. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  7128. if (Args[i].IsSExt)
  7129. ExtendKind = ISD::SIGN_EXTEND;
  7130. else if (Args[i].IsZExt)
  7131. ExtendKind = ISD::ZERO_EXTEND;
  7132. // Conservatively only handle 'returned' on non-vectors for now
  7133. if (Args[i].IsReturned && !Op.getValueType().isVector()) {
  7134. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  7135. "unexpected use of 'returned'");
  7136. // Before passing 'returned' to the target lowering code, ensure that
  7137. // either the register MVT and the actual EVT are the same size or that
  7138. // the return value and argument are extended in the same way; in these
  7139. // cases it's safe to pass the argument register value unchanged as the
  7140. // return register value (although it's at the target's option whether
  7141. // to do so)
  7142. // TODO: allow code generation to take advantage of partially preserved
  7143. // registers rather than clobbering the entire register when the
  7144. // parameter extension method is not compatible with the return
  7145. // extension method
  7146. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  7147. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  7148. CLI.RetZExt == Args[i].IsZExt))
  7149. Flags.setReturned();
  7150. }
  7151. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  7152. CLI.CS.getInstruction(), ExtendKind, true);
  7153. for (unsigned j = 0; j != NumParts; ++j) {
  7154. // if it isn't first piece, alignment must be 1
  7155. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  7156. i < CLI.NumFixedArgs,
  7157. i, j*Parts[j].getValueType().getStoreSize());
  7158. if (NumParts > 1 && j == 0)
  7159. MyFlags.Flags.setSplit();
  7160. else if (j != 0) {
  7161. MyFlags.Flags.setOrigAlign(1);
  7162. if (j == NumParts - 1)
  7163. MyFlags.Flags.setSplitEnd();
  7164. }
  7165. CLI.Outs.push_back(MyFlags);
  7166. CLI.OutVals.push_back(Parts[j]);
  7167. }
  7168. if (NeedsRegBlock && Value == NumValues - 1)
  7169. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  7170. }
  7171. }
  7172. SmallVector<SDValue, 4> InVals;
  7173. CLI.Chain = LowerCall(CLI, InVals);
  7174. // Update CLI.InVals to use outside of this function.
  7175. CLI.InVals = InVals;
  7176. // Verify that the target's LowerCall behaved as expected.
  7177. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  7178. "LowerCall didn't return a valid chain!");
  7179. assert((!CLI.IsTailCall || InVals.empty()) &&
  7180. "LowerCall emitted a return value for a tail call!");
  7181. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  7182. "LowerCall didn't emit the correct number of values!");
  7183. // For a tail call, the return value is merely live-out and there aren't
  7184. // any nodes in the DAG representing it. Return a special value to
  7185. // indicate that a tail call has been emitted and no more Instructions
  7186. // should be processed in the current block.
  7187. if (CLI.IsTailCall) {
  7188. CLI.DAG.setRoot(CLI.Chain);
  7189. return std::make_pair(SDValue(), SDValue());
  7190. }
  7191. #ifndef NDEBUG
  7192. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  7193. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  7194. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  7195. "LowerCall emitted a value with the wrong type!");
  7196. }
  7197. #endif
  7198. SmallVector<SDValue, 4> ReturnValues;
  7199. if (!CanLowerReturn) {
  7200. // The instruction result is the result of loading from the
  7201. // hidden sret parameter.
  7202. SmallVector<EVT, 1> PVTs;
  7203. Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
  7204. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  7205. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  7206. EVT PtrVT = PVTs[0];
  7207. unsigned NumValues = RetTys.size();
  7208. ReturnValues.resize(NumValues);
  7209. SmallVector<SDValue, 4> Chains(NumValues);
  7210. // An aggregate return value cannot wrap around the address space, so
  7211. // offsets to its parts don't wrap either.
  7212. SDNodeFlags Flags;
  7213. Flags.setNoUnsignedWrap(true);
  7214. for (unsigned i = 0; i < NumValues; ++i) {
  7215. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  7216. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  7217. PtrVT), Flags);
  7218. SDValue L = CLI.DAG.getLoad(
  7219. RetTys[i], CLI.DL, CLI.Chain, Add,
  7220. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  7221. DemoteStackIdx, Offsets[i]),
  7222. /* Alignment = */ 1);
  7223. ReturnValues[i] = L;
  7224. Chains[i] = L.getValue(1);
  7225. }
  7226. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  7227. } else {
  7228. // Collect the legal value parts into potentially illegal values
  7229. // that correspond to the original function's return values.
  7230. Optional<ISD::NodeType> AssertOp;
  7231. if (CLI.RetSExt)
  7232. AssertOp = ISD::AssertSext;
  7233. else if (CLI.RetZExt)
  7234. AssertOp = ISD::AssertZext;
  7235. unsigned CurReg = 0;
  7236. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7237. EVT VT = RetTys[I];
  7238. MVT RegisterVT =
  7239. getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7240. unsigned NumRegs =
  7241. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7242. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  7243. NumRegs, RegisterVT, VT, nullptr,
  7244. AssertOp, true));
  7245. CurReg += NumRegs;
  7246. }
  7247. // For a function returning void, there is no return value. We can't create
  7248. // such a node, so we just return a null return value in that case. In
  7249. // that case, nothing will actually look at the value.
  7250. if (ReturnValues.empty())
  7251. return std::make_pair(SDValue(), CLI.Chain);
  7252. }
  7253. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  7254. CLI.DAG.getVTList(RetTys), ReturnValues);
  7255. return std::make_pair(Res, CLI.Chain);
  7256. }
  7257. void TargetLowering::LowerOperationWrapper(SDNode *N,
  7258. SmallVectorImpl<SDValue> &Results,
  7259. SelectionDAG &DAG) const {
  7260. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  7261. Results.push_back(Res);
  7262. }
  7263. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  7264. llvm_unreachable("LowerOperation not implemented for this target!");
  7265. }
  7266. void
  7267. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  7268. SDValue Op = getNonRegisterValue(V);
  7269. assert((Op.getOpcode() != ISD::CopyFromReg ||
  7270. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  7271. "Copy from a reg to the same reg!");
  7272. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  7273. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7274. // If this is an InlineAsm we have to match the registers required, not the
  7275. // notional registers required by the type.
  7276. bool IsABIRegCopy =
  7277. V && ((isa<CallInst>(V) &&
  7278. !(static_cast<const CallInst *>(V))->isInlineAsm()) ||
  7279. isa<ReturnInst>(V));
  7280. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  7281. V->getType(), IsABIRegCopy);
  7282. SDValue Chain = DAG.getEntryNode();
  7283. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  7284. FuncInfo.PreferredExtendType.end())
  7285. ? ISD::ANY_EXTEND
  7286. : FuncInfo.PreferredExtendType[V];
  7287. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  7288. PendingExports.push_back(Chain);
  7289. }
  7290. #include "llvm/CodeGen/SelectionDAGISel.h"
  7291. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  7292. /// entry block, return true. This includes arguments used by switches, since
  7293. /// the switch may expand into multiple basic blocks.
  7294. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  7295. // With FastISel active, we may be splitting blocks, so force creation
  7296. // of virtual registers for all non-dead arguments.
  7297. if (FastISel)
  7298. return A->use_empty();
  7299. const BasicBlock &Entry = A->getParent()->front();
  7300. for (const User *U : A->users())
  7301. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  7302. return false; // Use not in entry block.
  7303. return true;
  7304. }
  7305. typedef DenseMap<const Argument *,
  7306. std::pair<const AllocaInst *, const StoreInst *>>
  7307. ArgCopyElisionMapTy;
  7308. /// Scan the entry block of the function in FuncInfo for arguments that look
  7309. /// like copies into a local alloca. Record any copied arguments in
  7310. /// ArgCopyElisionCandidates.
  7311. static void
  7312. findArgumentCopyElisionCandidates(const DataLayout &DL,
  7313. FunctionLoweringInfo *FuncInfo,
  7314. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  7315. // Record the state of every static alloca used in the entry block. Argument
  7316. // allocas are all used in the entry block, so we need approximately as many
  7317. // entries as we have arguments.
  7318. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  7319. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  7320. unsigned NumArgs = FuncInfo->Fn->arg_size();
  7321. StaticAllocas.reserve(NumArgs * 2);
  7322. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  7323. if (!V)
  7324. return nullptr;
  7325. V = V->stripPointerCasts();
  7326. const auto *AI = dyn_cast<AllocaInst>(V);
  7327. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  7328. return nullptr;
  7329. auto Iter = StaticAllocas.insert({AI, Unknown});
  7330. return &Iter.first->second;
  7331. };
  7332. // Look for stores of arguments to static allocas. Look through bitcasts and
  7333. // GEPs to handle type coercions, as long as the alloca is fully initialized
  7334. // by the store. Any non-store use of an alloca escapes it and any subsequent
  7335. // unanalyzed store might write it.
  7336. // FIXME: Handle structs initialized with multiple stores.
  7337. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  7338. // Look for stores, and handle non-store uses conservatively.
  7339. const auto *SI = dyn_cast<StoreInst>(&I);
  7340. if (!SI) {
  7341. // We will look through cast uses, so ignore them completely.
  7342. if (I.isCast())
  7343. continue;
  7344. // Ignore debug info intrinsics, they don't escape or store to allocas.
  7345. if (isa<DbgInfoIntrinsic>(I))
  7346. continue;
  7347. // This is an unknown instruction. Assume it escapes or writes to all
  7348. // static alloca operands.
  7349. for (const Use &U : I.operands()) {
  7350. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  7351. *Info = StaticAllocaInfo::Clobbered;
  7352. }
  7353. continue;
  7354. }
  7355. // If the stored value is a static alloca, mark it as escaped.
  7356. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  7357. *Info = StaticAllocaInfo::Clobbered;
  7358. // Check if the destination is a static alloca.
  7359. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  7360. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  7361. if (!Info)
  7362. continue;
  7363. const AllocaInst *AI = cast<AllocaInst>(Dst);
  7364. // Skip allocas that have been initialized or clobbered.
  7365. if (*Info != StaticAllocaInfo::Unknown)
  7366. continue;
  7367. // Check if the stored value is an argument, and that this store fully
  7368. // initializes the alloca. Don't elide copies from the same argument twice.
  7369. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  7370. const auto *Arg = dyn_cast<Argument>(Val);
  7371. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  7372. Arg->getType()->isEmptyTy() ||
  7373. DL.getTypeStoreSize(Arg->getType()) !=
  7374. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  7375. ArgCopyElisionCandidates.count(Arg)) {
  7376. *Info = StaticAllocaInfo::Clobbered;
  7377. continue;
  7378. }
  7379. DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
  7380. // Mark this alloca and store for argument copy elision.
  7381. *Info = StaticAllocaInfo::Elidable;
  7382. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  7383. // Stop scanning if we've seen all arguments. This will happen early in -O0
  7384. // builds, which is useful, because -O0 builds have large entry blocks and
  7385. // many allocas.
  7386. if (ArgCopyElisionCandidates.size() == NumArgs)
  7387. break;
  7388. }
  7389. }
  7390. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  7391. /// ArgVal is a load from a suitable fixed stack object.
  7392. static void tryToElideArgumentCopy(
  7393. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  7394. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  7395. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  7396. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  7397. SDValue ArgVal, bool &ArgHasUses) {
  7398. // Check if this is a load from a fixed stack object.
  7399. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  7400. if (!LNode)
  7401. return;
  7402. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  7403. if (!FINode)
  7404. return;
  7405. // Check that the fixed stack object is the right size and alignment.
  7406. // Look at the alignment that the user wrote on the alloca instead of looking
  7407. // at the stack object.
  7408. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  7409. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  7410. const AllocaInst *AI = ArgCopyIter->second.first;
  7411. int FixedIndex = FINode->getIndex();
  7412. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  7413. int OldIndex = AllocaIndex;
  7414. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  7415. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  7416. DEBUG(dbgs() << " argument copy elision failed due to bad fixed stack "
  7417. "object size\n");
  7418. return;
  7419. }
  7420. unsigned RequiredAlignment = AI->getAlignment();
  7421. if (!RequiredAlignment) {
  7422. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  7423. AI->getAllocatedType());
  7424. }
  7425. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  7426. DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  7427. "greater than stack argument alignment ("
  7428. << RequiredAlignment << " vs "
  7429. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  7430. return;
  7431. }
  7432. // Perform the elision. Delete the old stack object and replace its only use
  7433. // in the variable info map. Mark the stack object as mutable.
  7434. DEBUG({
  7435. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  7436. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  7437. << '\n';
  7438. });
  7439. MFI.RemoveStackObject(OldIndex);
  7440. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  7441. AllocaIndex = FixedIndex;
  7442. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  7443. Chains.push_back(ArgVal.getValue(1));
  7444. // Avoid emitting code for the store implementing the copy.
  7445. const StoreInst *SI = ArgCopyIter->second.second;
  7446. ElidedArgCopyInstrs.insert(SI);
  7447. // Check for uses of the argument again so that we can avoid exporting ArgVal
  7448. // if it is't used by anything other than the store.
  7449. for (const Value *U : Arg.users()) {
  7450. if (U != SI) {
  7451. ArgHasUses = true;
  7452. break;
  7453. }
  7454. }
  7455. }
  7456. void SelectionDAGISel::LowerArguments(const Function &F) {
  7457. SelectionDAG &DAG = SDB->DAG;
  7458. SDLoc dl = SDB->getCurSDLoc();
  7459. const DataLayout &DL = DAG.getDataLayout();
  7460. SmallVector<ISD::InputArg, 16> Ins;
  7461. if (!FuncInfo->CanLowerReturn) {
  7462. // Put in an sret pointer parameter before all the other parameters.
  7463. SmallVector<EVT, 1> ValueVTs;
  7464. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7465. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  7466. // NOTE: Assuming that a pointer will never break down to more than one VT
  7467. // or one register.
  7468. ISD::ArgFlagsTy Flags;
  7469. Flags.setSRet();
  7470. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  7471. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  7472. ISD::InputArg::NoArgIndex, 0);
  7473. Ins.push_back(RetArg);
  7474. }
  7475. // Look for stores of arguments to static allocas. Mark such arguments with a
  7476. // flag to ask the target to give us the memory location of that argument if
  7477. // available.
  7478. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  7479. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  7480. // Set up the incoming argument description vector.
  7481. for (const Argument &Arg : F.args()) {
  7482. unsigned ArgNo = Arg.getArgNo();
  7483. SmallVector<EVT, 4> ValueVTs;
  7484. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7485. bool isArgValueUsed = !Arg.use_empty();
  7486. unsigned PartBase = 0;
  7487. Type *FinalType = Arg.getType();
  7488. if (Arg.hasAttribute(Attribute::ByVal))
  7489. FinalType = cast<PointerType>(FinalType)->getElementType();
  7490. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  7491. FinalType, F.getCallingConv(), F.isVarArg());
  7492. for (unsigned Value = 0, NumValues = ValueVTs.size();
  7493. Value != NumValues; ++Value) {
  7494. EVT VT = ValueVTs[Value];
  7495. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  7496. ISD::ArgFlagsTy Flags;
  7497. // Certain targets (such as MIPS), may have a different ABI alignment
  7498. // for a type depending on the context. Give the target a chance to
  7499. // specify the alignment it wants.
  7500. unsigned OriginalAlignment =
  7501. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  7502. if (Arg.hasAttribute(Attribute::ZExt))
  7503. Flags.setZExt();
  7504. if (Arg.hasAttribute(Attribute::SExt))
  7505. Flags.setSExt();
  7506. if (Arg.hasAttribute(Attribute::InReg)) {
  7507. // If we are using vectorcall calling convention, a structure that is
  7508. // passed InReg - is surely an HVA
  7509. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  7510. isa<StructType>(Arg.getType())) {
  7511. // The first value of a structure is marked
  7512. if (0 == Value)
  7513. Flags.setHvaStart();
  7514. Flags.setHva();
  7515. }
  7516. // Set InReg Flag
  7517. Flags.setInReg();
  7518. }
  7519. if (Arg.hasAttribute(Attribute::StructRet))
  7520. Flags.setSRet();
  7521. if (Arg.hasAttribute(Attribute::SwiftSelf))
  7522. Flags.setSwiftSelf();
  7523. if (Arg.hasAttribute(Attribute::SwiftError))
  7524. Flags.setSwiftError();
  7525. if (Arg.hasAttribute(Attribute::ByVal))
  7526. Flags.setByVal();
  7527. if (Arg.hasAttribute(Attribute::InAlloca)) {
  7528. Flags.setInAlloca();
  7529. // Set the byval flag for CCAssignFn callbacks that don't know about
  7530. // inalloca. This way we can know how many bytes we should've allocated
  7531. // and how many bytes a callee cleanup function will pop. If we port
  7532. // inalloca to more targets, we'll have to add custom inalloca handling
  7533. // in the various CC lowering callbacks.
  7534. Flags.setByVal();
  7535. }
  7536. if (F.getCallingConv() == CallingConv::X86_INTR) {
  7537. // IA Interrupt passes frame (1st parameter) by value in the stack.
  7538. if (ArgNo == 0)
  7539. Flags.setByVal();
  7540. }
  7541. if (Flags.isByVal() || Flags.isInAlloca()) {
  7542. PointerType *Ty = cast<PointerType>(Arg.getType());
  7543. Type *ElementTy = Ty->getElementType();
  7544. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7545. // For ByVal, alignment should be passed from FE. BE will guess if
  7546. // this info is not there but there are cases it cannot get right.
  7547. unsigned FrameAlign;
  7548. if (Arg.getParamAlignment())
  7549. FrameAlign = Arg.getParamAlignment();
  7550. else
  7551. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  7552. Flags.setByValAlign(FrameAlign);
  7553. }
  7554. if (Arg.hasAttribute(Attribute::Nest))
  7555. Flags.setNest();
  7556. if (NeedsRegBlock)
  7557. Flags.setInConsecutiveRegs();
  7558. Flags.setOrigAlign(OriginalAlignment);
  7559. if (ArgCopyElisionCandidates.count(&Arg))
  7560. Flags.setCopyElisionCandidate();
  7561. MVT RegisterVT =
  7562. TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
  7563. unsigned NumRegs =
  7564. TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
  7565. for (unsigned i = 0; i != NumRegs; ++i) {
  7566. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  7567. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  7568. if (NumRegs > 1 && i == 0)
  7569. MyFlags.Flags.setSplit();
  7570. // if it isn't first piece, alignment must be 1
  7571. else if (i > 0) {
  7572. MyFlags.Flags.setOrigAlign(1);
  7573. if (i == NumRegs - 1)
  7574. MyFlags.Flags.setSplitEnd();
  7575. }
  7576. Ins.push_back(MyFlags);
  7577. }
  7578. if (NeedsRegBlock && Value == NumValues - 1)
  7579. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  7580. PartBase += VT.getStoreSize();
  7581. }
  7582. }
  7583. // Call the target to set up the argument values.
  7584. SmallVector<SDValue, 8> InVals;
  7585. SDValue NewRoot = TLI->LowerFormalArguments(
  7586. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  7587. // Verify that the target's LowerFormalArguments behaved as expected.
  7588. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  7589. "LowerFormalArguments didn't return a valid chain!");
  7590. assert(InVals.size() == Ins.size() &&
  7591. "LowerFormalArguments didn't emit the correct number of values!");
  7592. DEBUG({
  7593. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  7594. assert(InVals[i].getNode() &&
  7595. "LowerFormalArguments emitted a null value!");
  7596. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  7597. "LowerFormalArguments emitted a value with the wrong type!");
  7598. }
  7599. });
  7600. // Update the DAG with the new chain value resulting from argument lowering.
  7601. DAG.setRoot(NewRoot);
  7602. // Set up the argument values.
  7603. unsigned i = 0;
  7604. if (!FuncInfo->CanLowerReturn) {
  7605. // Create a virtual register for the sret pointer, and put in a copy
  7606. // from the sret argument into it.
  7607. SmallVector<EVT, 1> ValueVTs;
  7608. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7609. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  7610. MVT VT = ValueVTs[0].getSimpleVT();
  7611. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  7612. Optional<ISD::NodeType> AssertOp = None;
  7613. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  7614. RegVT, VT, nullptr, AssertOp);
  7615. MachineFunction& MF = SDB->DAG.getMachineFunction();
  7616. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  7617. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  7618. FuncInfo->DemoteRegister = SRetReg;
  7619. NewRoot =
  7620. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  7621. DAG.setRoot(NewRoot);
  7622. // i indexes lowered arguments. Bump it past the hidden sret argument.
  7623. ++i;
  7624. }
  7625. SmallVector<SDValue, 4> Chains;
  7626. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  7627. for (const Argument &Arg : F.args()) {
  7628. SmallVector<SDValue, 4> ArgValues;
  7629. SmallVector<EVT, 4> ValueVTs;
  7630. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7631. unsigned NumValues = ValueVTs.size();
  7632. if (NumValues == 0)
  7633. continue;
  7634. bool ArgHasUses = !Arg.use_empty();
  7635. // Elide the copying store if the target loaded this argument from a
  7636. // suitable fixed stack object.
  7637. if (Ins[i].Flags.isCopyElisionCandidate()) {
  7638. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  7639. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  7640. InVals[i], ArgHasUses);
  7641. }
  7642. // If this argument is unused then remember its value. It is used to generate
  7643. // debugging information.
  7644. bool isSwiftErrorArg =
  7645. TLI->supportSwiftError() &&
  7646. Arg.hasAttribute(Attribute::SwiftError);
  7647. if (!ArgHasUses && !isSwiftErrorArg) {
  7648. SDB->setUnusedArgValue(&Arg, InVals[i]);
  7649. // Also remember any frame index for use in FastISel.
  7650. if (FrameIndexSDNode *FI =
  7651. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  7652. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7653. }
  7654. for (unsigned Val = 0; Val != NumValues; ++Val) {
  7655. EVT VT = ValueVTs[Val];
  7656. MVT PartVT =
  7657. TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
  7658. unsigned NumParts =
  7659. TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
  7660. // Even an apparant 'unused' swifterror argument needs to be returned. So
  7661. // we do generate a copy for it that can be used on return from the
  7662. // function.
  7663. if (ArgHasUses || isSwiftErrorArg) {
  7664. Optional<ISD::NodeType> AssertOp;
  7665. if (Arg.hasAttribute(Attribute::SExt))
  7666. AssertOp = ISD::AssertSext;
  7667. else if (Arg.hasAttribute(Attribute::ZExt))
  7668. AssertOp = ISD::AssertZext;
  7669. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  7670. PartVT, VT, nullptr, AssertOp,
  7671. true));
  7672. }
  7673. i += NumParts;
  7674. }
  7675. // We don't need to do anything else for unused arguments.
  7676. if (ArgValues.empty())
  7677. continue;
  7678. // Note down frame index.
  7679. if (FrameIndexSDNode *FI =
  7680. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  7681. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7682. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  7683. SDB->getCurSDLoc());
  7684. SDB->setValue(&Arg, Res);
  7685. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  7686. if (LoadSDNode *LNode =
  7687. dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
  7688. if (FrameIndexSDNode *FI =
  7689. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  7690. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7691. }
  7692. // Update the SwiftErrorVRegDefMap.
  7693. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  7694. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7695. if (TargetRegisterInfo::isVirtualRegister(Reg))
  7696. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  7697. FuncInfo->SwiftErrorArg, Reg);
  7698. }
  7699. // If this argument is live outside of the entry block, insert a copy from
  7700. // wherever we got it to the vreg that other BB's will reference it as.
  7701. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  7702. // If we can, though, try to skip creating an unnecessary vreg.
  7703. // FIXME: This isn't very clean... it would be nice to make this more
  7704. // general. It's also subtly incompatible with the hacks FastISel
  7705. // uses with vregs.
  7706. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7707. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  7708. FuncInfo->ValueMap[&Arg] = Reg;
  7709. continue;
  7710. }
  7711. }
  7712. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  7713. FuncInfo->InitializeRegForValue(&Arg);
  7714. SDB->CopyToExportRegsIfNeeded(&Arg);
  7715. }
  7716. }
  7717. if (!Chains.empty()) {
  7718. Chains.push_back(NewRoot);
  7719. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  7720. }
  7721. DAG.setRoot(NewRoot);
  7722. assert(i == InVals.size() && "Argument register count mismatch!");
  7723. // If any argument copy elisions occurred and we have debug info, update the
  7724. // stale frame indices used in the dbg.declare variable info table.
  7725. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  7726. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  7727. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  7728. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  7729. if (I != ArgCopyElisionFrameIndexMap.end())
  7730. VI.Slot = I->second;
  7731. }
  7732. }
  7733. // Finally, if the target has anything special to do, allow it to do so.
  7734. EmitFunctionEntryCode();
  7735. }
  7736. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  7737. /// ensure constants are generated when needed. Remember the virtual registers
  7738. /// that need to be added to the Machine PHI nodes as input. We cannot just
  7739. /// directly add them, because expansion might result in multiple MBB's for one
  7740. /// BB. As such, the start of the BB might correspond to a different MBB than
  7741. /// the end.
  7742. ///
  7743. void
  7744. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  7745. const TerminatorInst *TI = LLVMBB->getTerminator();
  7746. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  7747. // Check PHI nodes in successors that expect a value to be available from this
  7748. // block.
  7749. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  7750. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  7751. if (!isa<PHINode>(SuccBB->begin())) continue;
  7752. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  7753. // If this terminator has multiple identical successors (common for
  7754. // switches), only handle each succ once.
  7755. if (!SuccsHandled.insert(SuccMBB).second)
  7756. continue;
  7757. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  7758. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  7759. // nodes and Machine PHI nodes, but the incoming operands have not been
  7760. // emitted yet.
  7761. for (BasicBlock::const_iterator I = SuccBB->begin();
  7762. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  7763. // Ignore dead phi's.
  7764. if (PN->use_empty()) continue;
  7765. // Skip empty types
  7766. if (PN->getType()->isEmptyTy())
  7767. continue;
  7768. unsigned Reg;
  7769. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  7770. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  7771. unsigned &RegOut = ConstantsOut[C];
  7772. if (RegOut == 0) {
  7773. RegOut = FuncInfo.CreateRegs(C->getType());
  7774. CopyValueToVirtualRegister(C, RegOut);
  7775. }
  7776. Reg = RegOut;
  7777. } else {
  7778. DenseMap<const Value *, unsigned>::iterator I =
  7779. FuncInfo.ValueMap.find(PHIOp);
  7780. if (I != FuncInfo.ValueMap.end())
  7781. Reg = I->second;
  7782. else {
  7783. assert(isa<AllocaInst>(PHIOp) &&
  7784. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  7785. "Didn't codegen value into a register!??");
  7786. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  7787. CopyValueToVirtualRegister(PHIOp, Reg);
  7788. }
  7789. }
  7790. // Remember that this register needs to added to the machine PHI node as
  7791. // the input for this MBB.
  7792. SmallVector<EVT, 4> ValueVTs;
  7793. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7794. ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
  7795. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  7796. EVT VT = ValueVTs[vti];
  7797. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  7798. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  7799. FuncInfo.PHINodesToUpdate.push_back(
  7800. std::make_pair(&*MBBI++, Reg + i));
  7801. Reg += NumRegisters;
  7802. }
  7803. }
  7804. }
  7805. ConstantsOut.clear();
  7806. }
  7807. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  7808. /// is 0.
  7809. MachineBasicBlock *
  7810. SelectionDAGBuilder::StackProtectorDescriptor::
  7811. AddSuccessorMBB(const BasicBlock *BB,
  7812. MachineBasicBlock *ParentMBB,
  7813. bool IsLikely,
  7814. MachineBasicBlock *SuccMBB) {
  7815. // If SuccBB has not been created yet, create it.
  7816. if (!SuccMBB) {
  7817. MachineFunction *MF = ParentMBB->getParent();
  7818. MachineFunction::iterator BBI(ParentMBB);
  7819. SuccMBB = MF->CreateMachineBasicBlock(BB);
  7820. MF->insert(++BBI, SuccMBB);
  7821. }
  7822. // Add it as a successor of ParentMBB.
  7823. ParentMBB->addSuccessor(
  7824. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  7825. return SuccMBB;
  7826. }
  7827. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  7828. MachineFunction::iterator I(MBB);
  7829. if (++I == FuncInfo.MF->end())
  7830. return nullptr;
  7831. return &*I;
  7832. }
  7833. /// During lowering new call nodes can be created (such as memset, etc.).
  7834. /// Those will become new roots of the current DAG, but complications arise
  7835. /// when they are tail calls. In such cases, the call lowering will update
  7836. /// the root, but the builder still needs to know that a tail call has been
  7837. /// lowered in order to avoid generating an additional return.
  7838. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  7839. // If the node is null, we do have a tail call.
  7840. if (MaybeTC.getNode() != nullptr)
  7841. DAG.setRoot(MaybeTC);
  7842. else
  7843. HasTailCall = true;
  7844. }
  7845. uint64_t
  7846. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  7847. unsigned First, unsigned Last) const {
  7848. assert(Last >= First);
  7849. const APInt &LowCase = Clusters[First].Low->getValue();
  7850. const APInt &HighCase = Clusters[Last].High->getValue();
  7851. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  7852. // FIXME: A range of consecutive cases has 100% density, but only requires one
  7853. // comparison to lower. We should discriminate against such consecutive ranges
  7854. // in jump tables.
  7855. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  7856. }
  7857. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  7858. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  7859. unsigned Last) const {
  7860. assert(Last >= First);
  7861. assert(TotalCases[Last] >= TotalCases[First]);
  7862. uint64_t NumCases =
  7863. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  7864. return NumCases;
  7865. }
  7866. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  7867. unsigned First, unsigned Last,
  7868. const SwitchInst *SI,
  7869. MachineBasicBlock *DefaultMBB,
  7870. CaseCluster &JTCluster) {
  7871. assert(First <= Last);
  7872. auto Prob = BranchProbability::getZero();
  7873. unsigned NumCmps = 0;
  7874. std::vector<MachineBasicBlock*> Table;
  7875. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  7876. // Initialize probabilities in JTProbs.
  7877. for (unsigned I = First; I <= Last; ++I)
  7878. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  7879. for (unsigned I = First; I <= Last; ++I) {
  7880. assert(Clusters[I].Kind == CC_Range);
  7881. Prob += Clusters[I].Prob;
  7882. const APInt &Low = Clusters[I].Low->getValue();
  7883. const APInt &High = Clusters[I].High->getValue();
  7884. NumCmps += (Low == High) ? 1 : 2;
  7885. if (I != First) {
  7886. // Fill the gap between this and the previous cluster.
  7887. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  7888. assert(PreviousHigh.slt(Low));
  7889. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  7890. for (uint64_t J = 0; J < Gap; J++)
  7891. Table.push_back(DefaultMBB);
  7892. }
  7893. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  7894. for (uint64_t J = 0; J < ClusterSize; ++J)
  7895. Table.push_back(Clusters[I].MBB);
  7896. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  7897. }
  7898. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7899. unsigned NumDests = JTProbs.size();
  7900. if (TLI.isSuitableForBitTests(
  7901. NumDests, NumCmps, Clusters[First].Low->getValue(),
  7902. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  7903. // Clusters[First..Last] should be lowered as bit tests instead.
  7904. return false;
  7905. }
  7906. // Create the MBB that will load from and jump through the table.
  7907. // Note: We create it here, but it's not inserted into the function yet.
  7908. MachineFunction *CurMF = FuncInfo.MF;
  7909. MachineBasicBlock *JumpTableMBB =
  7910. CurMF->CreateMachineBasicBlock(SI->getParent());
  7911. // Add successors. Note: use table order for determinism.
  7912. SmallPtrSet<MachineBasicBlock *, 8> Done;
  7913. for (MachineBasicBlock *Succ : Table) {
  7914. if (Done.count(Succ))
  7915. continue;
  7916. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  7917. Done.insert(Succ);
  7918. }
  7919. JumpTableMBB->normalizeSuccProbs();
  7920. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  7921. ->createJumpTableIndex(Table);
  7922. // Set up the jump table info.
  7923. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  7924. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  7925. Clusters[Last].High->getValue(), SI->getCondition(),
  7926. nullptr, false);
  7927. JTCases.emplace_back(std::move(JTH), std::move(JT));
  7928. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  7929. JTCases.size() - 1, Prob);
  7930. return true;
  7931. }
  7932. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  7933. const SwitchInst *SI,
  7934. MachineBasicBlock *DefaultMBB) {
  7935. #ifndef NDEBUG
  7936. // Clusters must be non-empty, sorted, and only contain Range clusters.
  7937. assert(!Clusters.empty());
  7938. for (CaseCluster &C : Clusters)
  7939. assert(C.Kind == CC_Range);
  7940. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  7941. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  7942. #endif
  7943. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7944. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  7945. return;
  7946. const int64_t N = Clusters.size();
  7947. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  7948. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  7949. if (N < 2 || N < MinJumpTableEntries)
  7950. return;
  7951. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  7952. SmallVector<unsigned, 8> TotalCases(N);
  7953. for (unsigned i = 0; i < N; ++i) {
  7954. const APInt &Hi = Clusters[i].High->getValue();
  7955. const APInt &Lo = Clusters[i].Low->getValue();
  7956. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  7957. if (i != 0)
  7958. TotalCases[i] += TotalCases[i - 1];
  7959. }
  7960. // Cheap case: the whole range may be suitable for jump table.
  7961. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  7962. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  7963. assert(NumCases < UINT64_MAX / 100);
  7964. assert(Range >= NumCases);
  7965. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  7966. CaseCluster JTCluster;
  7967. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  7968. Clusters[0] = JTCluster;
  7969. Clusters.resize(1);
  7970. return;
  7971. }
  7972. }
  7973. // The algorithm below is not suitable for -O0.
  7974. if (TM.getOptLevel() == CodeGenOpt::None)
  7975. return;
  7976. // Split Clusters into minimum number of dense partitions. The algorithm uses
  7977. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  7978. // for the Case Statement'" (1994), but builds the MinPartitions array in
  7979. // reverse order to make it easier to reconstruct the partitions in ascending
  7980. // order. In the choice between two optimal partitionings, it picks the one
  7981. // which yields more jump tables.
  7982. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  7983. SmallVector<unsigned, 8> MinPartitions(N);
  7984. // LastElement[i] is the last element of the partition starting at i.
  7985. SmallVector<unsigned, 8> LastElement(N);
  7986. // PartitionsScore[i] is used to break ties when choosing between two
  7987. // partitionings resulting in the same number of partitions.
  7988. SmallVector<unsigned, 8> PartitionsScore(N);
  7989. // For PartitionsScore, a small number of comparisons is considered as good as
  7990. // a jump table and a single comparison is considered better than a jump
  7991. // table.
  7992. enum PartitionScores : unsigned {
  7993. NoTable = 0,
  7994. Table = 1,
  7995. FewCases = 1,
  7996. SingleCase = 2
  7997. };
  7998. // Base case: There is only one way to partition Clusters[N-1].
  7999. MinPartitions[N - 1] = 1;
  8000. LastElement[N - 1] = N - 1;
  8001. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8002. // Note: loop indexes are signed to avoid underflow.
  8003. for (int64_t i = N - 2; i >= 0; i--) {
  8004. // Find optimal partitioning of Clusters[i..N-1].
  8005. // Baseline: Put Clusters[i] into a partition on its own.
  8006. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8007. LastElement[i] = i;
  8008. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8009. // Search for a solution that results in fewer partitions.
  8010. for (int64_t j = N - 1; j > i; j--) {
  8011. // Try building a partition from Clusters[i..j].
  8012. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8013. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8014. assert(NumCases < UINT64_MAX / 100);
  8015. assert(Range >= NumCases);
  8016. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8017. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8018. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8019. int64_t NumEntries = j - i + 1;
  8020. if (NumEntries == 1)
  8021. Score += PartitionScores::SingleCase;
  8022. else if (NumEntries <= SmallNumberOfEntries)
  8023. Score += PartitionScores::FewCases;
  8024. else if (NumEntries >= MinJumpTableEntries)
  8025. Score += PartitionScores::Table;
  8026. // If this leads to fewer partitions, or to the same number of
  8027. // partitions with better score, it is a better partitioning.
  8028. if (NumPartitions < MinPartitions[i] ||
  8029. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8030. MinPartitions[i] = NumPartitions;
  8031. LastElement[i] = j;
  8032. PartitionsScore[i] = Score;
  8033. }
  8034. }
  8035. }
  8036. }
  8037. // Iterate over the partitions, replacing some with jump tables in-place.
  8038. unsigned DstIndex = 0;
  8039. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8040. Last = LastElement[First];
  8041. assert(Last >= First);
  8042. assert(DstIndex <= First);
  8043. unsigned NumClusters = Last - First + 1;
  8044. CaseCluster JTCluster;
  8045. if (NumClusters >= MinJumpTableEntries &&
  8046. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8047. Clusters[DstIndex++] = JTCluster;
  8048. } else {
  8049. for (unsigned I = First; I <= Last; ++I)
  8050. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8051. }
  8052. }
  8053. Clusters.resize(DstIndex);
  8054. }
  8055. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8056. unsigned First, unsigned Last,
  8057. const SwitchInst *SI,
  8058. CaseCluster &BTCluster) {
  8059. assert(First <= Last);
  8060. if (First == Last)
  8061. return false;
  8062. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8063. unsigned NumCmps = 0;
  8064. for (int64_t I = First; I <= Last; ++I) {
  8065. assert(Clusters[I].Kind == CC_Range);
  8066. Dests.set(Clusters[I].MBB->getNumber());
  8067. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  8068. }
  8069. unsigned NumDests = Dests.count();
  8070. APInt Low = Clusters[First].Low->getValue();
  8071. APInt High = Clusters[Last].High->getValue();
  8072. assert(Low.slt(High));
  8073. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8074. const DataLayout &DL = DAG.getDataLayout();
  8075. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  8076. return false;
  8077. APInt LowBound;
  8078. APInt CmpRange;
  8079. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  8080. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  8081. "Case range must fit in bit mask!");
  8082. // Check if the clusters cover a contiguous range such that no value in the
  8083. // range will jump to the default statement.
  8084. bool ContiguousRange = true;
  8085. for (int64_t I = First + 1; I <= Last; ++I) {
  8086. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  8087. ContiguousRange = false;
  8088. break;
  8089. }
  8090. }
  8091. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  8092. // Optimize the case where all the case values fit in a word without having
  8093. // to subtract minValue. In this case, we can optimize away the subtraction.
  8094. LowBound = APInt::getNullValue(Low.getBitWidth());
  8095. CmpRange = High;
  8096. ContiguousRange = false;
  8097. } else {
  8098. LowBound = Low;
  8099. CmpRange = High - Low;
  8100. }
  8101. CaseBitsVector CBV;
  8102. auto TotalProb = BranchProbability::getZero();
  8103. for (unsigned i = First; i <= Last; ++i) {
  8104. // Find the CaseBits for this destination.
  8105. unsigned j;
  8106. for (j = 0; j < CBV.size(); ++j)
  8107. if (CBV[j].BB == Clusters[i].MBB)
  8108. break;
  8109. if (j == CBV.size())
  8110. CBV.push_back(
  8111. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  8112. CaseBits *CB = &CBV[j];
  8113. // Update Mask, Bits and ExtraProb.
  8114. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  8115. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  8116. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  8117. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  8118. CB->Bits += Hi - Lo + 1;
  8119. CB->ExtraProb += Clusters[i].Prob;
  8120. TotalProb += Clusters[i].Prob;
  8121. }
  8122. BitTestInfo BTI;
  8123. std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
  8124. // Sort by probability first, number of bits second.
  8125. if (a.ExtraProb != b.ExtraProb)
  8126. return a.ExtraProb > b.ExtraProb;
  8127. return a.Bits > b.Bits;
  8128. });
  8129. for (auto &CB : CBV) {
  8130. MachineBasicBlock *BitTestBB =
  8131. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  8132. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  8133. }
  8134. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  8135. SI->getCondition(), -1U, MVT::Other, false,
  8136. ContiguousRange, nullptr, nullptr, std::move(BTI),
  8137. TotalProb);
  8138. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  8139. BitTestCases.size() - 1, TotalProb);
  8140. return true;
  8141. }
  8142. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  8143. const SwitchInst *SI) {
  8144. // Partition Clusters into as few subsets as possible, where each subset has a
  8145. // range that fits in a machine word and has <= 3 unique destinations.
  8146. #ifndef NDEBUG
  8147. // Clusters must be sorted and contain Range or JumpTable clusters.
  8148. assert(!Clusters.empty());
  8149. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  8150. for (const CaseCluster &C : Clusters)
  8151. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  8152. for (unsigned i = 1; i < Clusters.size(); ++i)
  8153. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  8154. #endif
  8155. // The algorithm below is not suitable for -O0.
  8156. if (TM.getOptLevel() == CodeGenOpt::None)
  8157. return;
  8158. // If target does not have legal shift left, do not emit bit tests at all.
  8159. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8160. const DataLayout &DL = DAG.getDataLayout();
  8161. EVT PTy = TLI.getPointerTy(DL);
  8162. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  8163. return;
  8164. int BitWidth = PTy.getSizeInBits();
  8165. const int64_t N = Clusters.size();
  8166. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8167. SmallVector<unsigned, 8> MinPartitions(N);
  8168. // LastElement[i] is the last element of the partition starting at i.
  8169. SmallVector<unsigned, 8> LastElement(N);
  8170. // FIXME: This might not be the best algorithm for finding bit test clusters.
  8171. // Base case: There is only one way to partition Clusters[N-1].
  8172. MinPartitions[N - 1] = 1;
  8173. LastElement[N - 1] = N - 1;
  8174. // Note: loop indexes are signed to avoid underflow.
  8175. for (int64_t i = N - 2; i >= 0; --i) {
  8176. // Find optimal partitioning of Clusters[i..N-1].
  8177. // Baseline: Put Clusters[i] into a partition on its own.
  8178. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8179. LastElement[i] = i;
  8180. // Search for a solution that results in fewer partitions.
  8181. // Note: the search is limited by BitWidth, reducing time complexity.
  8182. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  8183. // Try building a partition from Clusters[i..j].
  8184. // Check the range.
  8185. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  8186. Clusters[j].High->getValue(), DL))
  8187. continue;
  8188. // Check nbr of destinations and cluster types.
  8189. // FIXME: This works, but doesn't seem very efficient.
  8190. bool RangesOnly = true;
  8191. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8192. for (int64_t k = i; k <= j; k++) {
  8193. if (Clusters[k].Kind != CC_Range) {
  8194. RangesOnly = false;
  8195. break;
  8196. }
  8197. Dests.set(Clusters[k].MBB->getNumber());
  8198. }
  8199. if (!RangesOnly || Dests.count() > 3)
  8200. break;
  8201. // Check if it's a better partition.
  8202. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8203. if (NumPartitions < MinPartitions[i]) {
  8204. // Found a better partition.
  8205. MinPartitions[i] = NumPartitions;
  8206. LastElement[i] = j;
  8207. }
  8208. }
  8209. }
  8210. // Iterate over the partitions, replacing with bit-test clusters in-place.
  8211. unsigned DstIndex = 0;
  8212. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8213. Last = LastElement[First];
  8214. assert(First <= Last);
  8215. assert(DstIndex <= First);
  8216. CaseCluster BitTestCluster;
  8217. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  8218. Clusters[DstIndex++] = BitTestCluster;
  8219. } else {
  8220. size_t NumClusters = Last - First + 1;
  8221. std::memmove(&Clusters[DstIndex], &Clusters[First],
  8222. sizeof(Clusters[0]) * NumClusters);
  8223. DstIndex += NumClusters;
  8224. }
  8225. }
  8226. Clusters.resize(DstIndex);
  8227. }
  8228. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8229. MachineBasicBlock *SwitchMBB,
  8230. MachineBasicBlock *DefaultMBB) {
  8231. MachineFunction *CurMF = FuncInfo.MF;
  8232. MachineBasicBlock *NextMBB = nullptr;
  8233. MachineFunction::iterator BBI(W.MBB);
  8234. if (++BBI != FuncInfo.MF->end())
  8235. NextMBB = &*BBI;
  8236. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8237. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8238. if (Size == 2 && W.MBB == SwitchMBB) {
  8239. // If any two of the cases has the same destination, and if one value
  8240. // is the same as the other, but has one bit unset that the other has set,
  8241. // use bit manipulation to do two compares at once. For example:
  8242. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8243. // TODO: This could be extended to merge any 2 cases in switches with 3
  8244. // cases.
  8245. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8246. CaseCluster &Small = *W.FirstCluster;
  8247. CaseCluster &Big = *W.LastCluster;
  8248. if (Small.Low == Small.High && Big.Low == Big.High &&
  8249. Small.MBB == Big.MBB) {
  8250. const APInt &SmallValue = Small.Low->getValue();
  8251. const APInt &BigValue = Big.Low->getValue();
  8252. // Check that there is only one bit different.
  8253. APInt CommonBit = BigValue ^ SmallValue;
  8254. if (CommonBit.isPowerOf2()) {
  8255. SDValue CondLHS = getValue(Cond);
  8256. EVT VT = CondLHS.getValueType();
  8257. SDLoc DL = getCurSDLoc();
  8258. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8259. DAG.getConstant(CommonBit, DL, VT));
  8260. SDValue Cond = DAG.getSetCC(
  8261. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8262. ISD::SETEQ);
  8263. // Update successor info.
  8264. // Both Small and Big will jump to Small.BB, so we sum up the
  8265. // probabilities.
  8266. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8267. if (BPI)
  8268. addSuccessorWithProb(
  8269. SwitchMBB, DefaultMBB,
  8270. // The default destination is the first successor in IR.
  8271. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8272. else
  8273. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8274. // Insert the true branch.
  8275. SDValue BrCond =
  8276. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8277. DAG.getBasicBlock(Small.MBB));
  8278. // Insert the false branch.
  8279. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8280. DAG.getBasicBlock(DefaultMBB));
  8281. DAG.setRoot(BrCond);
  8282. return;
  8283. }
  8284. }
  8285. }
  8286. if (TM.getOptLevel() != CodeGenOpt::None) {
  8287. // Order cases by probability so the most likely case will be checked first.
  8288. std::sort(W.FirstCluster, W.LastCluster + 1,
  8289. [](const CaseCluster &a, const CaseCluster &b) {
  8290. return a.Prob > b.Prob;
  8291. });
  8292. // Rearrange the case blocks so that the last one falls through if possible
  8293. // without without changing the order of probabilities.
  8294. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8295. --I;
  8296. if (I->Prob > W.LastCluster->Prob)
  8297. break;
  8298. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8299. std::swap(*I, *W.LastCluster);
  8300. break;
  8301. }
  8302. }
  8303. }
  8304. // Compute total probability.
  8305. BranchProbability DefaultProb = W.DefaultProb;
  8306. BranchProbability UnhandledProbs = DefaultProb;
  8307. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8308. UnhandledProbs += I->Prob;
  8309. MachineBasicBlock *CurMBB = W.MBB;
  8310. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8311. MachineBasicBlock *Fallthrough;
  8312. if (I == W.LastCluster) {
  8313. // For the last cluster, fall through to the default destination.
  8314. Fallthrough = DefaultMBB;
  8315. } else {
  8316. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8317. CurMF->insert(BBI, Fallthrough);
  8318. // Put Cond in a virtual register to make it available from the new blocks.
  8319. ExportFromCurrentBlock(Cond);
  8320. }
  8321. UnhandledProbs -= I->Prob;
  8322. switch (I->Kind) {
  8323. case CC_JumpTable: {
  8324. // FIXME: Optimize away range check based on pivot comparisons.
  8325. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  8326. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  8327. // The jump block hasn't been inserted yet; insert it here.
  8328. MachineBasicBlock *JumpMBB = JT->MBB;
  8329. CurMF->insert(BBI, JumpMBB);
  8330. auto JumpProb = I->Prob;
  8331. auto FallthroughProb = UnhandledProbs;
  8332. // If the default statement is a target of the jump table, we evenly
  8333. // distribute the default probability to successors of CurMBB. Also
  8334. // update the probability on the edge from JumpMBB to Fallthrough.
  8335. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8336. SE = JumpMBB->succ_end();
  8337. SI != SE; ++SI) {
  8338. if (*SI == DefaultMBB) {
  8339. JumpProb += DefaultProb / 2;
  8340. FallthroughProb -= DefaultProb / 2;
  8341. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8342. JumpMBB->normalizeSuccProbs();
  8343. break;
  8344. }
  8345. }
  8346. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8347. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8348. CurMBB->normalizeSuccProbs();
  8349. // The jump table header will be inserted in our current block, do the
  8350. // range check, and fall through to our fallthrough block.
  8351. JTH->HeaderBB = CurMBB;
  8352. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8353. // If we're in the right place, emit the jump table header right now.
  8354. if (CurMBB == SwitchMBB) {
  8355. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8356. JTH->Emitted = true;
  8357. }
  8358. break;
  8359. }
  8360. case CC_BitTests: {
  8361. // FIXME: Optimize away range check based on pivot comparisons.
  8362. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  8363. // The bit test blocks haven't been inserted yet; insert them here.
  8364. for (BitTestCase &BTC : BTB->Cases)
  8365. CurMF->insert(BBI, BTC.ThisBB);
  8366. // Fill in fields of the BitTestBlock.
  8367. BTB->Parent = CurMBB;
  8368. BTB->Default = Fallthrough;
  8369. BTB->DefaultProb = UnhandledProbs;
  8370. // If the cases in bit test don't form a contiguous range, we evenly
  8371. // distribute the probability on the edge to Fallthrough to two
  8372. // successors of CurMBB.
  8373. if (!BTB->ContiguousRange) {
  8374. BTB->Prob += DefaultProb / 2;
  8375. BTB->DefaultProb -= DefaultProb / 2;
  8376. }
  8377. // If we're in the right place, emit the bit test header right now.
  8378. if (CurMBB == SwitchMBB) {
  8379. visitBitTestHeader(*BTB, SwitchMBB);
  8380. BTB->Emitted = true;
  8381. }
  8382. break;
  8383. }
  8384. case CC_Range: {
  8385. const Value *RHS, *LHS, *MHS;
  8386. ISD::CondCode CC;
  8387. if (I->Low == I->High) {
  8388. // Check Cond == I->Low.
  8389. CC = ISD::SETEQ;
  8390. LHS = Cond;
  8391. RHS=I->Low;
  8392. MHS = nullptr;
  8393. } else {
  8394. // Check I->Low <= Cond <= I->High.
  8395. CC = ISD::SETLE;
  8396. LHS = I->Low;
  8397. MHS = Cond;
  8398. RHS = I->High;
  8399. }
  8400. // The false probability is the sum of all unhandled cases.
  8401. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
  8402. UnhandledProbs);
  8403. if (CurMBB == SwitchMBB)
  8404. visitSwitchCase(CB, SwitchMBB);
  8405. else
  8406. SwitchCases.push_back(CB);
  8407. break;
  8408. }
  8409. }
  8410. CurMBB = Fallthrough;
  8411. }
  8412. }
  8413. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  8414. CaseClusterIt First,
  8415. CaseClusterIt Last) {
  8416. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  8417. if (X.Prob != CC.Prob)
  8418. return X.Prob > CC.Prob;
  8419. // Ties are broken by comparing the case value.
  8420. return X.Low->getValue().slt(CC.Low->getValue());
  8421. });
  8422. }
  8423. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  8424. const SwitchWorkListItem &W,
  8425. Value *Cond,
  8426. MachineBasicBlock *SwitchMBB) {
  8427. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  8428. "Clusters not sorted?");
  8429. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  8430. // Balance the tree based on branch probabilities to create a near-optimal (in
  8431. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  8432. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  8433. CaseClusterIt LastLeft = W.FirstCluster;
  8434. CaseClusterIt FirstRight = W.LastCluster;
  8435. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  8436. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  8437. // Move LastLeft and FirstRight towards each other from opposite directions to
  8438. // find a partitioning of the clusters which balances the probability on both
  8439. // sides. If LeftProb and RightProb are equal, alternate which side is
  8440. // taken to ensure 0-probability nodes are distributed evenly.
  8441. unsigned I = 0;
  8442. while (LastLeft + 1 < FirstRight) {
  8443. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  8444. LeftProb += (++LastLeft)->Prob;
  8445. else
  8446. RightProb += (--FirstRight)->Prob;
  8447. I++;
  8448. }
  8449. for (;;) {
  8450. // Our binary search tree differs from a typical BST in that ours can have up
  8451. // to three values in each leaf. The pivot selection above doesn't take that
  8452. // into account, which means the tree might require more nodes and be less
  8453. // efficient. We compensate for this here.
  8454. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  8455. unsigned NumRight = W.LastCluster - FirstRight + 1;
  8456. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  8457. // If one side has less than 3 clusters, and the other has more than 3,
  8458. // consider taking a cluster from the other side.
  8459. if (NumLeft < NumRight) {
  8460. // Consider moving the first cluster on the right to the left side.
  8461. CaseCluster &CC = *FirstRight;
  8462. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8463. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8464. if (LeftSideRank <= RightSideRank) {
  8465. // Moving the cluster to the left does not demote it.
  8466. ++LastLeft;
  8467. ++FirstRight;
  8468. continue;
  8469. }
  8470. } else {
  8471. assert(NumRight < NumLeft);
  8472. // Consider moving the last element on the left to the right side.
  8473. CaseCluster &CC = *LastLeft;
  8474. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8475. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8476. if (RightSideRank <= LeftSideRank) {
  8477. // Moving the cluster to the right does not demot it.
  8478. --LastLeft;
  8479. --FirstRight;
  8480. continue;
  8481. }
  8482. }
  8483. }
  8484. break;
  8485. }
  8486. assert(LastLeft + 1 == FirstRight);
  8487. assert(LastLeft >= W.FirstCluster);
  8488. assert(FirstRight <= W.LastCluster);
  8489. // Use the first element on the right as pivot since we will make less-than
  8490. // comparisons against it.
  8491. CaseClusterIt PivotCluster = FirstRight;
  8492. assert(PivotCluster > W.FirstCluster);
  8493. assert(PivotCluster <= W.LastCluster);
  8494. CaseClusterIt FirstLeft = W.FirstCluster;
  8495. CaseClusterIt LastRight = W.LastCluster;
  8496. const ConstantInt *Pivot = PivotCluster->Low;
  8497. // New blocks will be inserted immediately after the current one.
  8498. MachineFunction::iterator BBI(W.MBB);
  8499. ++BBI;
  8500. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  8501. // we can branch to its destination directly if it's squeezed exactly in
  8502. // between the known lower bound and Pivot - 1.
  8503. MachineBasicBlock *LeftMBB;
  8504. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  8505. FirstLeft->Low == W.GE &&
  8506. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  8507. LeftMBB = FirstLeft->MBB;
  8508. } else {
  8509. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8510. FuncInfo.MF->insert(BBI, LeftMBB);
  8511. WorkList.push_back(
  8512. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  8513. // Put Cond in a virtual register to make it available from the new blocks.
  8514. ExportFromCurrentBlock(Cond);
  8515. }
  8516. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  8517. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  8518. // directly if RHS.High equals the current upper bound.
  8519. MachineBasicBlock *RightMBB;
  8520. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  8521. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  8522. RightMBB = FirstRight->MBB;
  8523. } else {
  8524. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8525. FuncInfo.MF->insert(BBI, RightMBB);
  8526. WorkList.push_back(
  8527. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  8528. // Put Cond in a virtual register to make it available from the new blocks.
  8529. ExportFromCurrentBlock(Cond);
  8530. }
  8531. // Create the CaseBlock record that will be used to lower the branch.
  8532. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  8533. LeftProb, RightProb);
  8534. if (W.MBB == SwitchMBB)
  8535. visitSwitchCase(CB, SwitchMBB);
  8536. else
  8537. SwitchCases.push_back(CB);
  8538. }
  8539. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  8540. // Extract cases from the switch.
  8541. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8542. CaseClusterVector Clusters;
  8543. Clusters.reserve(SI.getNumCases());
  8544. for (auto I : SI.cases()) {
  8545. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  8546. const ConstantInt *CaseVal = I.getCaseValue();
  8547. BranchProbability Prob =
  8548. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  8549. : BranchProbability(1, SI.getNumCases() + 1);
  8550. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  8551. }
  8552. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  8553. // Cluster adjacent cases with the same destination. We do this at all
  8554. // optimization levels because it's cheap to do and will make codegen faster
  8555. // if there are many clusters.
  8556. sortAndRangeify(Clusters);
  8557. if (TM.getOptLevel() != CodeGenOpt::None) {
  8558. // Replace an unreachable default with the most popular destination.
  8559. // FIXME: Exploit unreachable default more aggressively.
  8560. bool UnreachableDefault =
  8561. isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
  8562. if (UnreachableDefault && !Clusters.empty()) {
  8563. DenseMap<const BasicBlock *, unsigned> Popularity;
  8564. unsigned MaxPop = 0;
  8565. const BasicBlock *MaxBB = nullptr;
  8566. for (auto I : SI.cases()) {
  8567. const BasicBlock *BB = I.getCaseSuccessor();
  8568. if (++Popularity[BB] > MaxPop) {
  8569. MaxPop = Popularity[BB];
  8570. MaxBB = BB;
  8571. }
  8572. }
  8573. // Set new default.
  8574. assert(MaxPop > 0 && MaxBB);
  8575. DefaultMBB = FuncInfo.MBBMap[MaxBB];
  8576. // Remove cases that were pointing to the destination that is now the
  8577. // default.
  8578. CaseClusterVector New;
  8579. New.reserve(Clusters.size());
  8580. for (CaseCluster &CC : Clusters) {
  8581. if (CC.MBB != DefaultMBB)
  8582. New.push_back(CC);
  8583. }
  8584. Clusters = std::move(New);
  8585. }
  8586. }
  8587. // If there is only the default destination, jump there directly.
  8588. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8589. if (Clusters.empty()) {
  8590. SwitchMBB->addSuccessor(DefaultMBB);
  8591. if (DefaultMBB != NextBlock(SwitchMBB)) {
  8592. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  8593. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  8594. }
  8595. return;
  8596. }
  8597. findJumpTables(Clusters, &SI, DefaultMBB);
  8598. findBitTestClusters(Clusters, &SI);
  8599. DEBUG({
  8600. dbgs() << "Case clusters: ";
  8601. for (const CaseCluster &C : Clusters) {
  8602. if (C.Kind == CC_JumpTable) dbgs() << "JT:";
  8603. if (C.Kind == CC_BitTests) dbgs() << "BT:";
  8604. C.Low->getValue().print(dbgs(), true);
  8605. if (C.Low != C.High) {
  8606. dbgs() << '-';
  8607. C.High->getValue().print(dbgs(), true);
  8608. }
  8609. dbgs() << ' ';
  8610. }
  8611. dbgs() << '\n';
  8612. });
  8613. assert(!Clusters.empty());
  8614. SwitchWorkList WorkList;
  8615. CaseClusterIt First = Clusters.begin();
  8616. CaseClusterIt Last = Clusters.end() - 1;
  8617. auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
  8618. WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  8619. while (!WorkList.empty()) {
  8620. SwitchWorkListItem W = WorkList.back();
  8621. WorkList.pop_back();
  8622. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  8623. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  8624. !DefaultMBB->getParent()->getFunction()->optForMinSize()) {
  8625. // For optimized builds, lower large range as a balanced binary tree.
  8626. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  8627. continue;
  8628. }
  8629. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  8630. }
  8631. }