2
0

SelectionDAGBuilder.cpp 322 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294
  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/TargetLibraryInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/CodeGen/FastISel.h"
  25. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  26. #include "llvm/CodeGen/GCMetadata.h"
  27. #include "llvm/CodeGen/GCStrategy.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineFunction.h"
  30. #include "llvm/CodeGen/MachineInstrBuilder.h"
  31. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/SelectionDAG.h"
  35. #include "llvm/CodeGen/StackMaps.h"
  36. #include "llvm/CodeGen/WinEHFuncInfo.h"
  37. #include "llvm/IR/CallingConv.h"
  38. #include "llvm/IR/Constants.h"
  39. #include "llvm/IR/DataLayout.h"
  40. #include "llvm/IR/DebugInfo.h"
  41. #include "llvm/IR/DerivedTypes.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/GlobalVariable.h"
  44. #include "llvm/IR/InlineAsm.h"
  45. #include "llvm/IR/Instructions.h"
  46. #include "llvm/IR/IntrinsicInst.h"
  47. #include "llvm/IR/Intrinsics.h"
  48. #include "llvm/IR/LLVMContext.h"
  49. #include "llvm/IR/Module.h"
  50. #include "llvm/IR/Statepoint.h"
  51. #include "llvm/MC/MCSymbol.h"
  52. #include "llvm/Support/CommandLine.h"
  53. #include "llvm/Support/Debug.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "llvm/Support/MathExtras.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include "llvm/Target/TargetFrameLowering.h"
  58. #include "llvm/Target/TargetInstrInfo.h"
  59. #include "llvm/Target/TargetIntrinsicInfo.h"
  60. #include "llvm/Target/TargetLowering.h"
  61. #include "llvm/Target/TargetOptions.h"
  62. #include "llvm/Target/TargetSelectionDAGInfo.h"
  63. #include "llvm/Target/TargetSubtargetInfo.h"
  64. #include <algorithm>
  65. using namespace llvm;
  66. #define DEBUG_TYPE "isel"
  67. /// LimitFloatPrecision - Generate low-precision inline sequences for
  68. /// some float libcalls (6, 8 or 12 bits).
  69. static unsigned LimitFloatPrecision;
  70. static cl::opt<unsigned, true>
  71. LimitFPPrecision("limit-float-precision",
  72. cl::desc("Generate low-precision inline sequences "
  73. "for some float libcalls"),
  74. cl::location(LimitFloatPrecision),
  75. cl::init(0));
  76. static cl::opt<bool>
  77. EnableFMFInDAG("enable-fmf-dag", cl::init(false), cl::Hidden,
  78. cl::desc("Enable fast-math-flags for DAG nodes"));
  79. // Limit the width of DAG chains. This is important in general to prevent
  80. // DAG-based analysis from blowing up. For example, alias analysis and
  81. // load clustering may not complete in reasonable time. It is difficult to
  82. // recognize and avoid this situation within each individual analysis, and
  83. // future analyses are likely to have the same behavior. Limiting DAG width is
  84. // the safe approach and will be especially important with global DAGs.
  85. //
  86. // MaxParallelChains default is arbitrarily high to avoid affecting
  87. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  88. // sequence over this should have been converted to llvm.memcpy by the
  89. // frontend. It easy to induce this behavior with .ll code such as:
  90. // %buffer = alloca [4096 x i8]
  91. // %data = load [4096 x i8]* %argPtr
  92. // store [4096 x i8] %data, [4096 x i8]* %buffer
  93. static const unsigned MaxParallelChains = 64;
  94. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  95. const SDValue *Parts, unsigned NumParts,
  96. MVT PartVT, EVT ValueVT, const Value *V);
  97. /// getCopyFromParts - Create a value that contains the specified legal parts
  98. /// combined into the value they represent. If the parts combine to a type
  99. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  100. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  101. /// (ISD::AssertSext).
  102. static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
  103. const SDValue *Parts,
  104. unsigned NumParts, MVT PartVT, EVT ValueVT,
  105. const Value *V,
  106. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  107. if (ValueVT.isVector())
  108. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  109. PartVT, ValueVT, V);
  110. assert(NumParts > 0 && "No parts to assemble!");
  111. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  112. SDValue Val = Parts[0];
  113. if (NumParts > 1) {
  114. // Assemble the value from multiple parts.
  115. if (ValueVT.isInteger()) {
  116. unsigned PartBits = PartVT.getSizeInBits();
  117. unsigned ValueBits = ValueVT.getSizeInBits();
  118. // Assemble the power of 2 part.
  119. unsigned RoundParts = NumParts & (NumParts - 1) ?
  120. 1 << Log2_32(NumParts) : NumParts;
  121. unsigned RoundBits = PartBits * RoundParts;
  122. EVT RoundVT = RoundBits == ValueBits ?
  123. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  124. SDValue Lo, Hi;
  125. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  126. if (RoundParts > 2) {
  127. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  128. PartVT, HalfVT, V);
  129. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  130. RoundParts / 2, PartVT, HalfVT, V);
  131. } else {
  132. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  133. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  134. }
  135. if (DAG.getDataLayout().isBigEndian())
  136. std::swap(Lo, Hi);
  137. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  138. if (RoundParts < NumParts) {
  139. // Assemble the trailing non-power-of-2 part.
  140. unsigned OddParts = NumParts - RoundParts;
  141. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  142. Hi = getCopyFromParts(DAG, DL,
  143. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  144. // Combine the round and odd parts.
  145. Lo = Val;
  146. if (DAG.getDataLayout().isBigEndian())
  147. std::swap(Lo, Hi);
  148. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  149. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  150. Hi =
  151. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  152. DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
  153. TLI.getPointerTy(DAG.getDataLayout())));
  154. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  155. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  156. }
  157. } else if (PartVT.isFloatingPoint()) {
  158. // FP split into multiple FP parts (for ppcf128)
  159. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  160. "Unexpected split");
  161. SDValue Lo, Hi;
  162. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  163. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  164. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  165. std::swap(Lo, Hi);
  166. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  167. } else {
  168. // FP split into integer parts (soft fp)
  169. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  170. !PartVT.isVector() && "Unexpected split");
  171. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  172. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  173. }
  174. }
  175. // There is now one part, held in Val. Correct it to match ValueVT.
  176. EVT PartEVT = Val.getValueType();
  177. if (PartEVT == ValueVT)
  178. return Val;
  179. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  180. if (ValueVT.bitsLT(PartEVT)) {
  181. // For a truncate, see if we have any information to
  182. // indicate whether the truncated bits will always be
  183. // zero or sign-extension.
  184. if (AssertOp != ISD::DELETED_NODE)
  185. Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
  186. DAG.getValueType(ValueVT));
  187. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  188. }
  189. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  190. }
  191. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  192. // FP_ROUND's are always exact here.
  193. if (ValueVT.bitsLT(Val.getValueType()))
  194. return DAG.getNode(
  195. ISD::FP_ROUND, DL, ValueVT, Val,
  196. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  197. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  198. }
  199. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  200. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  201. llvm_unreachable("Unknown mismatch!");
  202. }
  203. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  204. const Twine &ErrMsg) {
  205. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  206. if (!V)
  207. return Ctx.emitError(ErrMsg);
  208. const char *AsmError = ", possible invalid constraint for vector type";
  209. if (const CallInst *CI = dyn_cast<CallInst>(I))
  210. if (isa<InlineAsm>(CI->getCalledValue()))
  211. return Ctx.emitError(I, ErrMsg + AsmError);
  212. return Ctx.emitError(I, ErrMsg);
  213. }
  214. /// getCopyFromPartsVector - Create a value that contains the specified legal
  215. /// parts combined into the value they represent. If the parts combine to a
  216. /// type larger then ValueVT then AssertOp can be used to specify whether the
  217. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  218. /// ValueVT (ISD::AssertSext).
  219. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  220. const SDValue *Parts, unsigned NumParts,
  221. MVT PartVT, EVT ValueVT, const Value *V) {
  222. assert(ValueVT.isVector() && "Not a vector value");
  223. assert(NumParts > 0 && "No parts to assemble!");
  224. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  225. SDValue Val = Parts[0];
  226. // Handle a multi-element vector.
  227. if (NumParts > 1) {
  228. EVT IntermediateVT;
  229. MVT RegisterVT;
  230. unsigned NumIntermediates;
  231. unsigned NumRegs =
  232. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  233. NumIntermediates, RegisterVT);
  234. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  235. NumParts = NumRegs; // Silence a compiler warning.
  236. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  237. assert(RegisterVT.getSizeInBits() ==
  238. Parts[0].getSimpleValueType().getSizeInBits() &&
  239. "Part type sizes don't match!");
  240. // Assemble the parts into intermediate operands.
  241. SmallVector<SDValue, 8> Ops(NumIntermediates);
  242. if (NumIntermediates == NumParts) {
  243. // If the register was not expanded, truncate or copy the value,
  244. // as appropriate.
  245. for (unsigned i = 0; i != NumParts; ++i)
  246. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  247. PartVT, IntermediateVT, V);
  248. } else if (NumParts > 0) {
  249. // If the intermediate type was expanded, build the intermediate
  250. // operands from the parts.
  251. assert(NumParts % NumIntermediates == 0 &&
  252. "Must expand into a divisible number of parts!");
  253. unsigned Factor = NumParts / NumIntermediates;
  254. for (unsigned i = 0; i != NumIntermediates; ++i)
  255. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  256. PartVT, IntermediateVT, V);
  257. }
  258. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  259. // intermediate operands.
  260. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  261. : ISD::BUILD_VECTOR,
  262. DL, ValueVT, Ops);
  263. }
  264. // There is now one part, held in Val. Correct it to match ValueVT.
  265. EVT PartEVT = Val.getValueType();
  266. if (PartEVT == ValueVT)
  267. return Val;
  268. if (PartEVT.isVector()) {
  269. // If the element type of the source/dest vectors are the same, but the
  270. // parts vector has more elements than the value vector, then we have a
  271. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  272. // elements we want.
  273. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  274. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  275. "Cannot narrow, it would be a lossy transformation");
  276. return DAG.getNode(
  277. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  278. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  279. }
  280. // Vector/Vector bitcast.
  281. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  282. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  283. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  284. "Cannot handle this kind of promotion");
  285. // Promoted vector extract
  286. bool Smaller = ValueVT.bitsLE(PartEVT);
  287. return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  288. DL, ValueVT, Val);
  289. }
  290. // Trivial bitcast if the types are the same size and the destination
  291. // vector type is legal.
  292. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  293. TLI.isTypeLegal(ValueVT))
  294. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  295. // Handle cases such as i8 -> <1 x i1>
  296. if (ValueVT.getVectorNumElements() != 1) {
  297. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  298. "non-trivial scalar-to-vector conversion");
  299. return DAG.getUNDEF(ValueVT);
  300. }
  301. if (ValueVT.getVectorNumElements() == 1 &&
  302. ValueVT.getVectorElementType() != PartEVT) {
  303. bool Smaller = ValueVT.bitsLE(PartEVT);
  304. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  305. DL, ValueVT.getScalarType(), Val);
  306. }
  307. return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
  308. }
  309. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
  310. SDValue Val, SDValue *Parts, unsigned NumParts,
  311. MVT PartVT, const Value *V);
  312. /// getCopyToParts - Create a series of nodes that contain the specified value
  313. /// split into legal parts. If the parts contain more bits than Val, then, for
  314. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  315. static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
  316. SDValue Val, SDValue *Parts, unsigned NumParts,
  317. MVT PartVT, const Value *V,
  318. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  319. EVT ValueVT = Val.getValueType();
  320. // Handle the vector case separately.
  321. if (ValueVT.isVector())
  322. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
  323. unsigned PartBits = PartVT.getSizeInBits();
  324. unsigned OrigNumParts = NumParts;
  325. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  326. "Copying to an illegal type!");
  327. if (NumParts == 0)
  328. return;
  329. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  330. EVT PartEVT = PartVT;
  331. if (PartEVT == ValueVT) {
  332. assert(NumParts == 1 && "No-op copy with multiple parts!");
  333. Parts[0] = Val;
  334. return;
  335. }
  336. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  337. // If the parts cover more bits than the value has, promote the value.
  338. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  339. assert(NumParts == 1 && "Do not know what to promote to!");
  340. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  341. } else {
  342. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  343. ValueVT.isInteger() &&
  344. "Unknown mismatch!");
  345. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  346. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  347. if (PartVT == MVT::x86mmx)
  348. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  349. }
  350. } else if (PartBits == ValueVT.getSizeInBits()) {
  351. // Different types of the same size.
  352. assert(NumParts == 1 && PartEVT != ValueVT);
  353. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  354. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  355. // If the parts cover less bits than value has, truncate the value.
  356. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  357. ValueVT.isInteger() &&
  358. "Unknown mismatch!");
  359. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  360. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  361. if (PartVT == MVT::x86mmx)
  362. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  363. }
  364. // The value may have changed - recompute ValueVT.
  365. ValueVT = Val.getValueType();
  366. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  367. "Failed to tile the value with PartVT!");
  368. if (NumParts == 1) {
  369. if (PartEVT != ValueVT)
  370. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  371. "scalar-to-vector conversion failed");
  372. Parts[0] = Val;
  373. return;
  374. }
  375. // Expand the value into multiple parts.
  376. if (NumParts & (NumParts - 1)) {
  377. // The number of parts is not a power of 2. Split off and copy the tail.
  378. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  379. "Do not know what to expand to!");
  380. unsigned RoundParts = 1 << Log2_32(NumParts);
  381. unsigned RoundBits = RoundParts * PartBits;
  382. unsigned OddParts = NumParts - RoundParts;
  383. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  384. DAG.getIntPtrConstant(RoundBits, DL));
  385. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  386. if (DAG.getDataLayout().isBigEndian())
  387. // The odd parts were reversed by getCopyToParts - unreverse them.
  388. std::reverse(Parts + RoundParts, Parts + NumParts);
  389. NumParts = RoundParts;
  390. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  391. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  392. }
  393. // The number of parts is a power of 2. Repeatedly bisect the value using
  394. // EXTRACT_ELEMENT.
  395. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  396. EVT::getIntegerVT(*DAG.getContext(),
  397. ValueVT.getSizeInBits()),
  398. Val);
  399. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  400. for (unsigned i = 0; i < NumParts; i += StepSize) {
  401. unsigned ThisBits = StepSize * PartBits / 2;
  402. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  403. SDValue &Part0 = Parts[i];
  404. SDValue &Part1 = Parts[i+StepSize/2];
  405. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  406. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  407. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  408. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  409. if (ThisBits == PartBits && ThisVT != PartVT) {
  410. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  411. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  412. }
  413. }
  414. }
  415. if (DAG.getDataLayout().isBigEndian())
  416. std::reverse(Parts, Parts + OrigNumParts);
  417. }
  418. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  419. /// value split into legal parts.
  420. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
  421. SDValue Val, SDValue *Parts, unsigned NumParts,
  422. MVT PartVT, const Value *V) {
  423. EVT ValueVT = Val.getValueType();
  424. assert(ValueVT.isVector() && "Not a vector");
  425. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  426. if (NumParts == 1) {
  427. EVT PartEVT = PartVT;
  428. if (PartEVT == ValueVT) {
  429. // Nothing to do.
  430. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  431. // Bitconvert vector->vector case.
  432. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  433. } else if (PartVT.isVector() &&
  434. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  435. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  436. EVT ElementVT = PartVT.getVectorElementType();
  437. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  438. // undef elements.
  439. SmallVector<SDValue, 16> Ops;
  440. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  441. Ops.push_back(DAG.getNode(
  442. ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
  443. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
  444. for (unsigned i = ValueVT.getVectorNumElements(),
  445. e = PartVT.getVectorNumElements(); i != e; ++i)
  446. Ops.push_back(DAG.getUNDEF(ElementVT));
  447. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
  448. // FIXME: Use CONCAT for 2x -> 4x.
  449. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  450. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  451. } else if (PartVT.isVector() &&
  452. PartEVT.getVectorElementType().bitsGE(
  453. ValueVT.getVectorElementType()) &&
  454. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  455. // Promoted vector extract
  456. bool Smaller = PartEVT.bitsLE(ValueVT);
  457. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  458. DL, PartVT, Val);
  459. } else{
  460. // Vector -> scalar conversion.
  461. assert(ValueVT.getVectorNumElements() == 1 &&
  462. "Only trivial vector-to-scalar conversions should get here!");
  463. Val = DAG.getNode(
  464. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  465. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  466. bool Smaller = ValueVT.bitsLE(PartVT);
  467. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  468. DL, PartVT, Val);
  469. }
  470. Parts[0] = Val;
  471. return;
  472. }
  473. // Handle a multi-element vector.
  474. EVT IntermediateVT;
  475. MVT RegisterVT;
  476. unsigned NumIntermediates;
  477. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  478. IntermediateVT,
  479. NumIntermediates, RegisterVT);
  480. unsigned NumElements = ValueVT.getVectorNumElements();
  481. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  482. NumParts = NumRegs; // Silence a compiler warning.
  483. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  484. // Split the vector into intermediate operands.
  485. SmallVector<SDValue, 8> Ops(NumIntermediates);
  486. for (unsigned i = 0; i != NumIntermediates; ++i) {
  487. if (IntermediateVT.isVector())
  488. Ops[i] =
  489. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  490. DAG.getConstant(i * (NumElements / NumIntermediates), DL,
  491. TLI.getVectorIdxTy(DAG.getDataLayout())));
  492. else
  493. Ops[i] = DAG.getNode(
  494. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  495. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  496. }
  497. // Split the intermediate operands into legal parts.
  498. if (NumParts == NumIntermediates) {
  499. // If the register was not expanded, promote or copy the value,
  500. // as appropriate.
  501. for (unsigned i = 0; i != NumParts; ++i)
  502. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  503. } else if (NumParts > 0) {
  504. // If the intermediate type was expanded, split each the value into
  505. // legal parts.
  506. assert(NumIntermediates != 0 && "division by zero");
  507. assert(NumParts % NumIntermediates == 0 &&
  508. "Must expand into a divisible number of parts!");
  509. unsigned Factor = NumParts / NumIntermediates;
  510. for (unsigned i = 0; i != NumIntermediates; ++i)
  511. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  512. }
  513. }
  514. RegsForValue::RegsForValue() {}
  515. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  516. EVT valuevt)
  517. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  518. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  519. const DataLayout &DL, unsigned Reg, Type *Ty) {
  520. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  521. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  522. EVT ValueVT = ValueVTs[Value];
  523. unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
  524. MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
  525. for (unsigned i = 0; i != NumRegs; ++i)
  526. Regs.push_back(Reg + i);
  527. RegVTs.push_back(RegisterVT);
  528. Reg += NumRegs;
  529. }
  530. }
  531. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  532. /// this value and returns the result as a ValueVT value. This uses
  533. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  534. /// If the Flag pointer is NULL, no flag is used.
  535. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  536. FunctionLoweringInfo &FuncInfo,
  537. SDLoc dl,
  538. SDValue &Chain, SDValue *Flag,
  539. const Value *V) const {
  540. // A Value with type {} or [0 x %t] needs no registers.
  541. if (ValueVTs.empty())
  542. return SDValue();
  543. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  544. // Assemble the legal parts into the final values.
  545. SmallVector<SDValue, 4> Values(ValueVTs.size());
  546. SmallVector<SDValue, 8> Parts;
  547. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  548. // Copy the legal parts from the registers.
  549. EVT ValueVT = ValueVTs[Value];
  550. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  551. MVT RegisterVT = RegVTs[Value];
  552. Parts.resize(NumRegs);
  553. for (unsigned i = 0; i != NumRegs; ++i) {
  554. SDValue P;
  555. if (!Flag) {
  556. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  557. } else {
  558. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  559. *Flag = P.getValue(2);
  560. }
  561. Chain = P.getValue(1);
  562. Parts[i] = P;
  563. // If the source register was virtual and if we know something about it,
  564. // add an assert node.
  565. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  566. !RegisterVT.isInteger() || RegisterVT.isVector())
  567. continue;
  568. const FunctionLoweringInfo::LiveOutInfo *LOI =
  569. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  570. if (!LOI)
  571. continue;
  572. unsigned RegSize = RegisterVT.getSizeInBits();
  573. unsigned NumSignBits = LOI->NumSignBits;
  574. unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
  575. if (NumZeroBits == RegSize) {
  576. // The current value is a zero.
  577. // Explicitly express that as it would be easier for
  578. // optimizations to kick in.
  579. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  580. continue;
  581. }
  582. // FIXME: We capture more information than the dag can represent. For
  583. // now, just use the tightest assertzext/assertsext possible.
  584. bool isSExt = true;
  585. EVT FromVT(MVT::Other);
  586. if (NumSignBits == RegSize)
  587. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  588. else if (NumZeroBits >= RegSize-1)
  589. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  590. else if (NumSignBits > RegSize-8)
  591. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  592. else if (NumZeroBits >= RegSize-8)
  593. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  594. else if (NumSignBits > RegSize-16)
  595. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  596. else if (NumZeroBits >= RegSize-16)
  597. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  598. else if (NumSignBits > RegSize-32)
  599. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  600. else if (NumZeroBits >= RegSize-32)
  601. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  602. else
  603. continue;
  604. // Add an assertion node.
  605. assert(FromVT != MVT::Other);
  606. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  607. RegisterVT, P, DAG.getValueType(FromVT));
  608. }
  609. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  610. NumRegs, RegisterVT, ValueVT, V);
  611. Part += NumRegs;
  612. Parts.clear();
  613. }
  614. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  615. }
  616. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  617. /// specified value into the registers specified by this object. This uses
  618. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  619. /// If the Flag pointer is NULL, no flag is used.
  620. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
  621. SDValue &Chain, SDValue *Flag, const Value *V,
  622. ISD::NodeType PreferredExtendType) const {
  623. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  624. ISD::NodeType ExtendKind = PreferredExtendType;
  625. // Get the list of the values's legal parts.
  626. unsigned NumRegs = Regs.size();
  627. SmallVector<SDValue, 8> Parts(NumRegs);
  628. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  629. EVT ValueVT = ValueVTs[Value];
  630. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  631. MVT RegisterVT = RegVTs[Value];
  632. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  633. ExtendKind = ISD::ZERO_EXTEND;
  634. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  635. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  636. Part += NumParts;
  637. }
  638. // Copy the parts into the registers.
  639. SmallVector<SDValue, 8> Chains(NumRegs);
  640. for (unsigned i = 0; i != NumRegs; ++i) {
  641. SDValue Part;
  642. if (!Flag) {
  643. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  644. } else {
  645. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  646. *Flag = Part.getValue(1);
  647. }
  648. Chains[i] = Part.getValue(0);
  649. }
  650. if (NumRegs == 1 || Flag)
  651. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  652. // flagged to it. That is the CopyToReg nodes and the user are considered
  653. // a single scheduling unit. If we create a TokenFactor and return it as
  654. // chain, then the TokenFactor is both a predecessor (operand) of the
  655. // user as well as a successor (the TF operands are flagged to the user).
  656. // c1, f1 = CopyToReg
  657. // c2, f2 = CopyToReg
  658. // c3 = TokenFactor c1, c2
  659. // ...
  660. // = op c3, ..., f2
  661. Chain = Chains[NumRegs-1];
  662. else
  663. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  664. }
  665. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  666. /// operand list. This adds the code marker and includes the number of
  667. /// values added into it.
  668. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  669. unsigned MatchingIdx, SDLoc dl,
  670. SelectionDAG &DAG,
  671. std::vector<SDValue> &Ops) const {
  672. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  673. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  674. if (HasMatching)
  675. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  676. else if (!Regs.empty() &&
  677. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  678. // Put the register class of the virtual registers in the flag word. That
  679. // way, later passes can recompute register class constraints for inline
  680. // assembly as well as normal instructions.
  681. // Don't do this for tied operands that can use the regclass information
  682. // from the def.
  683. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  684. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  685. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  686. }
  687. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  688. Ops.push_back(Res);
  689. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  690. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  691. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  692. MVT RegisterVT = RegVTs[Value];
  693. for (unsigned i = 0; i != NumRegs; ++i) {
  694. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  695. unsigned TheReg = Regs[Reg++];
  696. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  697. if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
  698. // If we clobbered the stack pointer, MFI should know about it.
  699. assert(DAG.getMachineFunction().getFrameInfo()->
  700. hasOpaqueSPAdjustment());
  701. }
  702. }
  703. }
  704. }
  705. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
  706. const TargetLibraryInfo *li) {
  707. AA = &aa;
  708. GFI = gfi;
  709. LibInfo = li;
  710. DL = &DAG.getDataLayout();
  711. Context = DAG.getContext();
  712. LPadToCallSiteMap.clear();
  713. }
  714. /// clear - Clear out the current SelectionDAG and the associated
  715. /// state and prepare this SelectionDAGBuilder object to be used
  716. /// for a new block. This doesn't clear out information about
  717. /// additional blocks that are needed to complete switch lowering
  718. /// or PHI node updating; that information is cleared out as it is
  719. /// consumed.
  720. void SelectionDAGBuilder::clear() {
  721. NodeMap.clear();
  722. UnusedArgNodeMap.clear();
  723. PendingLoads.clear();
  724. PendingExports.clear();
  725. CurInst = nullptr;
  726. HasTailCall = false;
  727. SDNodeOrder = LowestSDNodeOrder;
  728. StatepointLowering.clear();
  729. }
  730. /// clearDanglingDebugInfo - Clear the dangling debug information
  731. /// map. This function is separated from the clear so that debug
  732. /// information that is dangling in a basic block can be properly
  733. /// resolved in a different basic block. This allows the
  734. /// SelectionDAG to resolve dangling debug information attached
  735. /// to PHI nodes.
  736. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  737. DanglingDebugInfoMap.clear();
  738. }
  739. /// getRoot - Return the current virtual root of the Selection DAG,
  740. /// flushing any PendingLoad items. This must be done before emitting
  741. /// a store or any other node that may need to be ordered after any
  742. /// prior load instructions.
  743. ///
  744. SDValue SelectionDAGBuilder::getRoot() {
  745. if (PendingLoads.empty())
  746. return DAG.getRoot();
  747. if (PendingLoads.size() == 1) {
  748. SDValue Root = PendingLoads[0];
  749. DAG.setRoot(Root);
  750. PendingLoads.clear();
  751. return Root;
  752. }
  753. // Otherwise, we have to make a token factor node.
  754. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  755. PendingLoads);
  756. PendingLoads.clear();
  757. DAG.setRoot(Root);
  758. return Root;
  759. }
  760. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  761. /// PendingLoad items, flush all the PendingExports items. It is necessary
  762. /// to do this before emitting a terminator instruction.
  763. ///
  764. SDValue SelectionDAGBuilder::getControlRoot() {
  765. SDValue Root = DAG.getRoot();
  766. if (PendingExports.empty())
  767. return Root;
  768. // Turn all of the CopyToReg chains into one factored node.
  769. if (Root.getOpcode() != ISD::EntryToken) {
  770. unsigned i = 0, e = PendingExports.size();
  771. for (; i != e; ++i) {
  772. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  773. if (PendingExports[i].getNode()->getOperand(0) == Root)
  774. break; // Don't add the root if we already indirectly depend on it.
  775. }
  776. if (i == e)
  777. PendingExports.push_back(Root);
  778. }
  779. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  780. PendingExports);
  781. PendingExports.clear();
  782. DAG.setRoot(Root);
  783. return Root;
  784. }
  785. void SelectionDAGBuilder::visit(const Instruction &I) {
  786. // Set up outgoing PHI node register values before emitting the terminator.
  787. if (isa<TerminatorInst>(&I))
  788. HandlePHINodesInSuccessorBlocks(I.getParent());
  789. ++SDNodeOrder;
  790. CurInst = &I;
  791. visit(I.getOpcode(), I);
  792. if (!isa<TerminatorInst>(&I) && !HasTailCall)
  793. CopyToExportRegsIfNeeded(&I);
  794. CurInst = nullptr;
  795. }
  796. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  797. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  798. }
  799. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  800. // Note: this doesn't use InstVisitor, because it has to work with
  801. // ConstantExpr's in addition to instructions.
  802. switch (Opcode) {
  803. default: llvm_unreachable("Unknown instruction type encountered!");
  804. // Build the switch statement using the Instruction.def file.
  805. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  806. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  807. #include "llvm/IR/Instruction.def"
  808. }
  809. }
  810. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  811. // generate the debug data structures now that we've seen its definition.
  812. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  813. SDValue Val) {
  814. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  815. if (DDI.getDI()) {
  816. const DbgValueInst *DI = DDI.getDI();
  817. DebugLoc dl = DDI.getdl();
  818. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  819. DILocalVariable *Variable = DI->getVariable();
  820. DIExpression *Expr = DI->getExpression();
  821. assert(Variable->isValidLocationForIntrinsic(dl) &&
  822. "Expected inlined-at fields to agree");
  823. uint64_t Offset = DI->getOffset();
  824. // A dbg.value for an alloca is always indirect.
  825. bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
  826. SDDbgValue *SDV;
  827. if (Val.getNode()) {
  828. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect,
  829. Val)) {
  830. SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
  831. IsIndirect, Offset, dl, DbgSDNodeOrder);
  832. DAG.AddDbgValue(SDV, Val.getNode(), false);
  833. }
  834. } else
  835. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  836. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  837. }
  838. }
  839. /// getCopyFromRegs - If there was virtual register allocated for the value V
  840. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  841. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  842. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  843. SDValue Result;
  844. if (It != FuncInfo.ValueMap.end()) {
  845. unsigned InReg = It->second;
  846. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  847. DAG.getDataLayout(), InReg, Ty);
  848. SDValue Chain = DAG.getEntryNode();
  849. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  850. resolveDanglingDebugInfo(V, Result);
  851. }
  852. return Result;
  853. }
  854. /// getValue - Return an SDValue for the given Value.
  855. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  856. // If we already have an SDValue for this value, use it. It's important
  857. // to do this first, so that we don't create a CopyFromReg if we already
  858. // have a regular SDValue.
  859. SDValue &N = NodeMap[V];
  860. if (N.getNode()) return N;
  861. // If there's a virtual register allocated and initialized for this
  862. // value, use it.
  863. SDValue copyFromReg = getCopyFromRegs(V, V->getType());
  864. if (copyFromReg.getNode()) {
  865. return copyFromReg;
  866. }
  867. // Otherwise create a new SDValue and remember it.
  868. SDValue Val = getValueImpl(V);
  869. NodeMap[V] = Val;
  870. resolveDanglingDebugInfo(V, Val);
  871. return Val;
  872. }
  873. // Return true if SDValue exists for the given Value
  874. bool SelectionDAGBuilder::findValue(const Value *V) const {
  875. return (NodeMap.find(V) != NodeMap.end()) ||
  876. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  877. }
  878. /// getNonRegisterValue - Return an SDValue for the given Value, but
  879. /// don't look in FuncInfo.ValueMap for a virtual register.
  880. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  881. // If we already have an SDValue for this value, use it.
  882. SDValue &N = NodeMap[V];
  883. if (N.getNode()) {
  884. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  885. // Remove the debug location from the node as the node is about to be used
  886. // in a location which may differ from the original debug location. This
  887. // is relevant to Constant and ConstantFP nodes because they can appear
  888. // as constant expressions inside PHI nodes.
  889. N->setDebugLoc(DebugLoc());
  890. }
  891. return N;
  892. }
  893. // Otherwise create a new SDValue and remember it.
  894. SDValue Val = getValueImpl(V);
  895. NodeMap[V] = Val;
  896. resolveDanglingDebugInfo(V, Val);
  897. return Val;
  898. }
  899. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  900. /// Create an SDValue for the given value.
  901. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  902. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  903. if (const Constant *C = dyn_cast<Constant>(V)) {
  904. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  905. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  906. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  907. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  908. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  909. if (isa<ConstantPointerNull>(C)) {
  910. unsigned AS = V->getType()->getPointerAddressSpace();
  911. return DAG.getConstant(0, getCurSDLoc(),
  912. TLI.getPointerTy(DAG.getDataLayout(), AS));
  913. }
  914. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  915. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  916. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  917. return DAG.getUNDEF(VT);
  918. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  919. visit(CE->getOpcode(), *CE);
  920. SDValue N1 = NodeMap[V];
  921. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  922. return N1;
  923. }
  924. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  925. SmallVector<SDValue, 4> Constants;
  926. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  927. OI != OE; ++OI) {
  928. SDNode *Val = getValue(*OI).getNode();
  929. // If the operand is an empty aggregate, there are no values.
  930. if (!Val) continue;
  931. // Add each leaf value from the operand to the Constants list
  932. // to form a flattened list of all the values.
  933. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  934. Constants.push_back(SDValue(Val, i));
  935. }
  936. return DAG.getMergeValues(Constants, getCurSDLoc());
  937. }
  938. if (const ConstantDataSequential *CDS =
  939. dyn_cast<ConstantDataSequential>(C)) {
  940. SmallVector<SDValue, 4> Ops;
  941. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  942. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  943. // Add each leaf value from the operand to the Constants list
  944. // to form a flattened list of all the values.
  945. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  946. Ops.push_back(SDValue(Val, i));
  947. }
  948. if (isa<ArrayType>(CDS->getType()))
  949. return DAG.getMergeValues(Ops, getCurSDLoc());
  950. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  951. VT, Ops);
  952. }
  953. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  954. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  955. "Unknown struct or array constant!");
  956. SmallVector<EVT, 4> ValueVTs;
  957. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  958. unsigned NumElts = ValueVTs.size();
  959. if (NumElts == 0)
  960. return SDValue(); // empty struct
  961. SmallVector<SDValue, 4> Constants(NumElts);
  962. for (unsigned i = 0; i != NumElts; ++i) {
  963. EVT EltVT = ValueVTs[i];
  964. if (isa<UndefValue>(C))
  965. Constants[i] = DAG.getUNDEF(EltVT);
  966. else if (EltVT.isFloatingPoint())
  967. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  968. else
  969. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  970. }
  971. return DAG.getMergeValues(Constants, getCurSDLoc());
  972. }
  973. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  974. return DAG.getBlockAddress(BA, VT);
  975. VectorType *VecTy = cast<VectorType>(V->getType());
  976. unsigned NumElements = VecTy->getNumElements();
  977. // Now that we know the number and type of the elements, get that number of
  978. // elements into the Ops array based on what kind of constant it is.
  979. SmallVector<SDValue, 16> Ops;
  980. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  981. for (unsigned i = 0; i != NumElements; ++i)
  982. Ops.push_back(getValue(CV->getOperand(i)));
  983. } else {
  984. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  985. EVT EltVT =
  986. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  987. SDValue Op;
  988. if (EltVT.isFloatingPoint())
  989. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  990. else
  991. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  992. Ops.assign(NumElements, Op);
  993. }
  994. // Create a BUILD_VECTOR node.
  995. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
  996. }
  997. // If this is a static alloca, generate it as the frameindex instead of
  998. // computation.
  999. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1000. DenseMap<const AllocaInst*, int>::iterator SI =
  1001. FuncInfo.StaticAllocaMap.find(AI);
  1002. if (SI != FuncInfo.StaticAllocaMap.end())
  1003. return DAG.getFrameIndex(SI->second,
  1004. TLI.getPointerTy(DAG.getDataLayout()));
  1005. }
  1006. // If this is an instruction which fast-isel has deferred, select it now.
  1007. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1008. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1009. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1010. Inst->getType());
  1011. SDValue Chain = DAG.getEntryNode();
  1012. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1013. }
  1014. llvm_unreachable("Can't get register for value!");
  1015. }
  1016. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1017. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1018. auto &DL = DAG.getDataLayout();
  1019. SDValue Chain = getControlRoot();
  1020. SmallVector<ISD::OutputArg, 8> Outs;
  1021. SmallVector<SDValue, 8> OutVals;
  1022. if (!FuncInfo.CanLowerReturn) {
  1023. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1024. const Function *F = I.getParent()->getParent();
  1025. // Emit a store of the return value through the virtual register.
  1026. // Leave Outs empty so that LowerReturn won't try to load return
  1027. // registers the usual way.
  1028. SmallVector<EVT, 1> PtrValueVTs;
  1029. ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
  1030. PtrValueVTs);
  1031. SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
  1032. SDValue RetOp = getValue(I.getOperand(0));
  1033. SmallVector<EVT, 4> ValueVTs;
  1034. SmallVector<uint64_t, 4> Offsets;
  1035. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1036. unsigned NumValues = ValueVTs.size();
  1037. SmallVector<SDValue, 4> Chains(NumValues);
  1038. for (unsigned i = 0; i != NumValues; ++i) {
  1039. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
  1040. RetPtr.getValueType(), RetPtr,
  1041. DAG.getIntPtrConstant(Offsets[i],
  1042. getCurSDLoc()));
  1043. Chains[i] =
  1044. DAG.getStore(Chain, getCurSDLoc(),
  1045. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1046. // FIXME: better loc info would be nice.
  1047. Add, MachinePointerInfo(), false, false, 0);
  1048. }
  1049. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1050. MVT::Other, Chains);
  1051. } else if (I.getNumOperands() != 0) {
  1052. SmallVector<EVT, 4> ValueVTs;
  1053. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1054. unsigned NumValues = ValueVTs.size();
  1055. if (NumValues) {
  1056. SDValue RetOp = getValue(I.getOperand(0));
  1057. const Function *F = I.getParent()->getParent();
  1058. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1059. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1060. Attribute::SExt))
  1061. ExtendKind = ISD::SIGN_EXTEND;
  1062. else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1063. Attribute::ZExt))
  1064. ExtendKind = ISD::ZERO_EXTEND;
  1065. LLVMContext &Context = F->getContext();
  1066. bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1067. Attribute::InReg);
  1068. for (unsigned j = 0; j != NumValues; ++j) {
  1069. EVT VT = ValueVTs[j];
  1070. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1071. VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
  1072. unsigned NumParts = TLI.getNumRegisters(Context, VT);
  1073. MVT PartVT = TLI.getRegisterType(Context, VT);
  1074. SmallVector<SDValue, 4> Parts(NumParts);
  1075. getCopyToParts(DAG, getCurSDLoc(),
  1076. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1077. &Parts[0], NumParts, PartVT, &I, ExtendKind);
  1078. // 'inreg' on function refers to return value
  1079. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1080. if (RetInReg)
  1081. Flags.setInReg();
  1082. // Propagate extension type if any
  1083. if (ExtendKind == ISD::SIGN_EXTEND)
  1084. Flags.setSExt();
  1085. else if (ExtendKind == ISD::ZERO_EXTEND)
  1086. Flags.setZExt();
  1087. for (unsigned i = 0; i < NumParts; ++i) {
  1088. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1089. VT, /*isfixed=*/true, 0, 0));
  1090. OutVals.push_back(Parts[i]);
  1091. }
  1092. }
  1093. }
  1094. }
  1095. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1096. CallingConv::ID CallConv =
  1097. DAG.getMachineFunction().getFunction()->getCallingConv();
  1098. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1099. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1100. // Verify that the target's LowerReturn behaved as expected.
  1101. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1102. "LowerReturn didn't return a valid chain!");
  1103. // Update the DAG with the new chain value resulting from return lowering.
  1104. DAG.setRoot(Chain);
  1105. }
  1106. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1107. /// created for it, emit nodes to copy the value into the virtual
  1108. /// registers.
  1109. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1110. // Skip empty types
  1111. if (V->getType()->isEmptyTy())
  1112. return;
  1113. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1114. if (VMI != FuncInfo.ValueMap.end()) {
  1115. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1116. CopyValueToVirtualRegister(V, VMI->second);
  1117. }
  1118. }
  1119. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1120. /// the current basic block, add it to ValueMap now so that we'll get a
  1121. /// CopyTo/FromReg.
  1122. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1123. // No need to export constants.
  1124. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1125. // Already exported?
  1126. if (FuncInfo.isExportedInst(V)) return;
  1127. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1128. CopyValueToVirtualRegister(V, Reg);
  1129. }
  1130. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1131. const BasicBlock *FromBB) {
  1132. // The operands of the setcc have to be in this block. We don't know
  1133. // how to export them from some other block.
  1134. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1135. // Can export from current BB.
  1136. if (VI->getParent() == FromBB)
  1137. return true;
  1138. // Is already exported, noop.
  1139. return FuncInfo.isExportedInst(V);
  1140. }
  1141. // If this is an argument, we can export it if the BB is the entry block or
  1142. // if it is already exported.
  1143. if (isa<Argument>(V)) {
  1144. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1145. return true;
  1146. // Otherwise, can only export this if it is already exported.
  1147. return FuncInfo.isExportedInst(V);
  1148. }
  1149. // Otherwise, constants can always be exported.
  1150. return true;
  1151. }
  1152. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1153. uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
  1154. const MachineBasicBlock *Dst) const {
  1155. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1156. if (!BPI)
  1157. return 0;
  1158. const BasicBlock *SrcBB = Src->getBasicBlock();
  1159. const BasicBlock *DstBB = Dst->getBasicBlock();
  1160. return BPI->getEdgeWeight(SrcBB, DstBB);
  1161. }
  1162. void SelectionDAGBuilder::
  1163. addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
  1164. uint32_t Weight /* = 0 */) {
  1165. if (!Weight)
  1166. Weight = getEdgeWeight(Src, Dst);
  1167. Src->addSuccessor(Dst, Weight);
  1168. }
  1169. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1170. if (const Instruction *I = dyn_cast<Instruction>(V))
  1171. return I->getParent() == BB;
  1172. return true;
  1173. }
  1174. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1175. /// This function emits a branch and is used at the leaves of an OR or an
  1176. /// AND operator tree.
  1177. ///
  1178. void
  1179. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1180. MachineBasicBlock *TBB,
  1181. MachineBasicBlock *FBB,
  1182. MachineBasicBlock *CurBB,
  1183. MachineBasicBlock *SwitchBB,
  1184. uint32_t TWeight,
  1185. uint32_t FWeight) {
  1186. const BasicBlock *BB = CurBB->getBasicBlock();
  1187. // If the leaf of the tree is a comparison, merge the condition into
  1188. // the caseblock.
  1189. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1190. // The operands of the cmp have to be in this block. We don't know
  1191. // how to export them from some other block. If this is the first block
  1192. // of the sequence, no exporting is needed.
  1193. if (CurBB == SwitchBB ||
  1194. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1195. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1196. ISD::CondCode Condition;
  1197. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1198. Condition = getICmpCondCode(IC->getPredicate());
  1199. } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  1200. Condition = getFCmpCondCode(FC->getPredicate());
  1201. if (TM.Options.NoNaNsFPMath)
  1202. Condition = getFCmpCodeWithoutNaN(Condition);
  1203. } else {
  1204. (void)Condition; // silence warning.
  1205. llvm_unreachable("Unknown compare instruction");
  1206. }
  1207. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1208. TBB, FBB, CurBB, TWeight, FWeight);
  1209. SwitchCases.push_back(CB);
  1210. return;
  1211. }
  1212. }
  1213. // Create a CaseBlock record representing this branch.
  1214. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1215. nullptr, TBB, FBB, CurBB, TWeight, FWeight);
  1216. SwitchCases.push_back(CB);
  1217. }
  1218. /// Scale down both weights to fit into uint32_t.
  1219. static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  1220. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  1221. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  1222. NewTrue = NewTrue / Scale;
  1223. NewFalse = NewFalse / Scale;
  1224. }
  1225. /// FindMergedConditions - If Cond is an expression like
  1226. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1227. MachineBasicBlock *TBB,
  1228. MachineBasicBlock *FBB,
  1229. MachineBasicBlock *CurBB,
  1230. MachineBasicBlock *SwitchBB,
  1231. unsigned Opc, uint32_t TWeight,
  1232. uint32_t FWeight) {
  1233. // If this node is not part of the or/and tree, emit it as a branch.
  1234. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1235. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1236. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1237. BOp->getParent() != CurBB->getBasicBlock() ||
  1238. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1239. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1240. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1241. TWeight, FWeight);
  1242. return;
  1243. }
  1244. // Create TmpBB after CurBB.
  1245. MachineFunction::iterator BBI = CurBB;
  1246. MachineFunction &MF = DAG.getMachineFunction();
  1247. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1248. CurBB->getParent()->insert(++BBI, TmpBB);
  1249. if (Opc == Instruction::Or) {
  1250. // Codegen X | Y as:
  1251. // BB1:
  1252. // jmp_if_X TBB
  1253. // jmp TmpBB
  1254. // TmpBB:
  1255. // jmp_if_Y TBB
  1256. // jmp FBB
  1257. //
  1258. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1259. // The requirement is that
  1260. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1261. // = TrueProb for original BB.
  1262. // Assuming the original weights are A and B, one choice is to set BB1's
  1263. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  1264. // assumes that
  1265. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1266. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1267. // TmpBB, but the math is more complicated.
  1268. uint64_t NewTrueWeight = TWeight;
  1269. uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
  1270. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1271. // Emit the LHS condition.
  1272. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1273. NewTrueWeight, NewFalseWeight);
  1274. NewTrueWeight = TWeight;
  1275. NewFalseWeight = 2 * (uint64_t)FWeight;
  1276. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1277. // Emit the RHS condition into TmpBB.
  1278. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1279. NewTrueWeight, NewFalseWeight);
  1280. } else {
  1281. assert(Opc == Instruction::And && "Unknown merge op!");
  1282. // Codegen X & Y as:
  1283. // BB1:
  1284. // jmp_if_X TmpBB
  1285. // jmp FBB
  1286. // TmpBB:
  1287. // jmp_if_Y TBB
  1288. // jmp FBB
  1289. //
  1290. // This requires creation of TmpBB after CurBB.
  1291. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1292. // The requirement is that
  1293. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1294. // = FalseProb for original BB.
  1295. // Assuming the original weights are A and B, one choice is to set BB1's
  1296. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  1297. // assumes that
  1298. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  1299. uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
  1300. uint64_t NewFalseWeight = FWeight;
  1301. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1302. // Emit the LHS condition.
  1303. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1304. NewTrueWeight, NewFalseWeight);
  1305. NewTrueWeight = 2 * (uint64_t)TWeight;
  1306. NewFalseWeight = FWeight;
  1307. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1308. // Emit the RHS condition into TmpBB.
  1309. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1310. NewTrueWeight, NewFalseWeight);
  1311. }
  1312. }
  1313. /// If the set of cases should be emitted as a series of branches, return true.
  1314. /// If we should emit this as a bunch of and/or'd together conditions, return
  1315. /// false.
  1316. bool
  1317. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1318. if (Cases.size() != 2) return true;
  1319. // If this is two comparisons of the same values or'd or and'd together, they
  1320. // will get folded into a single comparison, so don't emit two blocks.
  1321. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1322. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1323. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1324. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1325. return false;
  1326. }
  1327. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1328. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1329. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1330. Cases[0].CC == Cases[1].CC &&
  1331. isa<Constant>(Cases[0].CmpRHS) &&
  1332. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1333. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1334. return false;
  1335. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1336. return false;
  1337. }
  1338. return true;
  1339. }
  1340. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1341. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1342. // Update machine-CFG edges.
  1343. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1344. if (I.isUnconditional()) {
  1345. // Update machine-CFG edges.
  1346. BrMBB->addSuccessor(Succ0MBB);
  1347. // If this is not a fall-through branch or optimizations are switched off,
  1348. // emit the branch.
  1349. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1350. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1351. MVT::Other, getControlRoot(),
  1352. DAG.getBasicBlock(Succ0MBB)));
  1353. return;
  1354. }
  1355. // If this condition is one of the special cases we handle, do special stuff
  1356. // now.
  1357. const Value *CondVal = I.getCondition();
  1358. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1359. // If this is a series of conditions that are or'd or and'd together, emit
  1360. // this as a sequence of branches instead of setcc's with and/or operations.
  1361. // As long as jumps are not expensive, this should improve performance.
  1362. // For example, instead of something like:
  1363. // cmp A, B
  1364. // C = seteq
  1365. // cmp D, E
  1366. // F = setle
  1367. // or C, F
  1368. // jnz foo
  1369. // Emit:
  1370. // cmp A, B
  1371. // je foo
  1372. // cmp D, E
  1373. // jle foo
  1374. //
  1375. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1376. if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
  1377. BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
  1378. BOp->getOpcode() == Instruction::Or)) {
  1379. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1380. BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
  1381. getEdgeWeight(BrMBB, Succ1MBB));
  1382. // If the compares in later blocks need to use values not currently
  1383. // exported from this block, export them now. This block should always
  1384. // be the first entry.
  1385. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1386. // Allow some cases to be rejected.
  1387. if (ShouldEmitAsBranches(SwitchCases)) {
  1388. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1389. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1390. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1391. }
  1392. // Emit the branch for this block.
  1393. visitSwitchCase(SwitchCases[0], BrMBB);
  1394. SwitchCases.erase(SwitchCases.begin());
  1395. return;
  1396. }
  1397. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1398. // SwitchCases.
  1399. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1400. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1401. SwitchCases.clear();
  1402. }
  1403. }
  1404. // Create a CaseBlock record representing this branch.
  1405. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1406. nullptr, Succ0MBB, Succ1MBB, BrMBB);
  1407. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1408. // cond branch.
  1409. visitSwitchCase(CB, BrMBB);
  1410. }
  1411. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1412. /// the binary search tree resulting from lowering a switch instruction.
  1413. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1414. MachineBasicBlock *SwitchBB) {
  1415. SDValue Cond;
  1416. SDValue CondLHS = getValue(CB.CmpLHS);
  1417. SDLoc dl = getCurSDLoc();
  1418. // Build the setcc now.
  1419. if (!CB.CmpMHS) {
  1420. // Fold "(X == true)" to X and "(X == false)" to !X to
  1421. // handle common cases produced by branch lowering.
  1422. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1423. CB.CC == ISD::SETEQ)
  1424. Cond = CondLHS;
  1425. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1426. CB.CC == ISD::SETEQ) {
  1427. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  1428. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1429. } else
  1430. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1431. } else {
  1432. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1433. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1434. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1435. SDValue CmpOp = getValue(CB.CmpMHS);
  1436. EVT VT = CmpOp.getValueType();
  1437. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1438. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  1439. ISD::SETLE);
  1440. } else {
  1441. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1442. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  1443. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1444. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  1445. }
  1446. }
  1447. // Update successor info
  1448. addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
  1449. // TrueBB and FalseBB are always different unless the incoming IR is
  1450. // degenerate. This only happens when running llc on weird IR.
  1451. if (CB.TrueBB != CB.FalseBB)
  1452. addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
  1453. // If the lhs block is the next block, invert the condition so that we can
  1454. // fall through to the lhs instead of the rhs block.
  1455. if (CB.TrueBB == NextBlock(SwitchBB)) {
  1456. std::swap(CB.TrueBB, CB.FalseBB);
  1457. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  1458. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1459. }
  1460. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1461. MVT::Other, getControlRoot(), Cond,
  1462. DAG.getBasicBlock(CB.TrueBB));
  1463. // Insert the false branch. Do this even if it's a fall through branch,
  1464. // this makes it easier to do DAG optimizations which require inverting
  1465. // the branch condition.
  1466. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1467. DAG.getBasicBlock(CB.FalseBB));
  1468. DAG.setRoot(BrCond);
  1469. }
  1470. /// visitJumpTable - Emit JumpTable node in the current MBB
  1471. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1472. // Emit the code for the jump table
  1473. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1474. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  1475. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1476. JT.Reg, PTy);
  1477. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1478. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1479. MVT::Other, Index.getValue(1),
  1480. Table, Index);
  1481. DAG.setRoot(BrJumpTable);
  1482. }
  1483. /// visitJumpTableHeader - This function emits necessary code to produce index
  1484. /// in the JumpTable from switch case.
  1485. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1486. JumpTableHeader &JTH,
  1487. MachineBasicBlock *SwitchBB) {
  1488. SDLoc dl = getCurSDLoc();
  1489. // Subtract the lowest switch case value from the value being switched on and
  1490. // conditional branch to default mbb if the result is greater than the
  1491. // difference between smallest and largest cases.
  1492. SDValue SwitchOp = getValue(JTH.SValue);
  1493. EVT VT = SwitchOp.getValueType();
  1494. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1495. DAG.getConstant(JTH.First, dl, VT));
  1496. // The SDNode we just created, which holds the value being switched on minus
  1497. // the smallest case value, needs to be copied to a virtual register so it
  1498. // can be used as an index into the jump table in a subsequent basic block.
  1499. // This value may be smaller or larger than the target's pointer type, and
  1500. // therefore require extension or truncating.
  1501. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1502. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1503. unsigned JumpTableReg =
  1504. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  1505. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  1506. JumpTableReg, SwitchOp);
  1507. JT.Reg = JumpTableReg;
  1508. // Emit the range check for the jump table, and branch to the default block
  1509. // for the switch statement if the value being switched on exceeds the largest
  1510. // case in the switch.
  1511. SDValue CMP = DAG.getSetCC(
  1512. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1513. Sub.getValueType()),
  1514. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  1515. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1516. MVT::Other, CopyTo, CMP,
  1517. DAG.getBasicBlock(JT.Default));
  1518. // Avoid emitting unnecessary branches to the next block.
  1519. if (JT.MBB != NextBlock(SwitchBB))
  1520. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1521. DAG.getBasicBlock(JT.MBB));
  1522. DAG.setRoot(BrCond);
  1523. }
  1524. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1525. /// tail spliced into a stack protector check success bb.
  1526. ///
  1527. /// For a high level explanation of how this fits into the stack protector
  1528. /// generation see the comment on the declaration of class
  1529. /// StackProtectorDescriptor.
  1530. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1531. MachineBasicBlock *ParentBB) {
  1532. // First create the loads to the guard/stack slot for the comparison.
  1533. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1534. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1535. MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
  1536. int FI = MFI->getStackProtectorIndex();
  1537. const Value *IRGuard = SPD.getGuard();
  1538. SDValue GuardPtr = getValue(IRGuard);
  1539. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1540. unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType());
  1541. SDValue Guard;
  1542. SDLoc dl = getCurSDLoc();
  1543. // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
  1544. // guard value from the virtual register holding the value. Otherwise, emit a
  1545. // volatile load to retrieve the stack guard value.
  1546. unsigned GuardReg = SPD.getGuardReg();
  1547. if (GuardReg && TLI.useLoadStackGuardNode())
  1548. Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
  1549. PtrTy);
  1550. else
  1551. Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
  1552. GuardPtr, MachinePointerInfo(IRGuard, 0),
  1553. true, false, false, Align);
  1554. SDValue StackSlot = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
  1555. StackSlotPtr,
  1556. MachinePointerInfo::getFixedStack(FI),
  1557. true, false, false, Align);
  1558. // Perform the comparison via a subtract/getsetcc.
  1559. EVT VT = Guard.getValueType();
  1560. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
  1561. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  1562. *DAG.getContext(),
  1563. Sub.getValueType()),
  1564. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1565. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1566. // branch to failure MBB.
  1567. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1568. MVT::Other, StackSlot.getOperand(0),
  1569. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1570. // Otherwise branch to success MBB.
  1571. SDValue Br = DAG.getNode(ISD::BR, dl,
  1572. MVT::Other, BrCond,
  1573. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1574. DAG.setRoot(Br);
  1575. }
  1576. /// Codegen the failure basic block for a stack protector check.
  1577. ///
  1578. /// A failure stack protector machine basic block consists simply of a call to
  1579. /// __stack_chk_fail().
  1580. ///
  1581. /// For a high level explanation of how this fits into the stack protector
  1582. /// generation see the comment on the declaration of class
  1583. /// StackProtectorDescriptor.
  1584. void
  1585. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1586. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1587. SDValue Chain =
  1588. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  1589. nullptr, 0, false, getCurSDLoc(), false, false).second;
  1590. DAG.setRoot(Chain);
  1591. }
  1592. /// visitBitTestHeader - This function emits necessary code to produce value
  1593. /// suitable for "bit tests"
  1594. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1595. MachineBasicBlock *SwitchBB) {
  1596. SDLoc dl = getCurSDLoc();
  1597. // Subtract the minimum value
  1598. SDValue SwitchOp = getValue(B.SValue);
  1599. EVT VT = SwitchOp.getValueType();
  1600. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1601. DAG.getConstant(B.First, dl, VT));
  1602. // Check range
  1603. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1604. SDValue RangeCmp = DAG.getSetCC(
  1605. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1606. Sub.getValueType()),
  1607. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  1608. // Determine the type of the test operands.
  1609. bool UsePtrType = false;
  1610. if (!TLI.isTypeLegal(VT))
  1611. UsePtrType = true;
  1612. else {
  1613. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1614. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1615. // Switch table case range are encoded into series of masks.
  1616. // Just use pointer type, it's guaranteed to fit.
  1617. UsePtrType = true;
  1618. break;
  1619. }
  1620. }
  1621. if (UsePtrType) {
  1622. VT = TLI.getPointerTy(DAG.getDataLayout());
  1623. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  1624. }
  1625. B.RegVT = VT.getSimpleVT();
  1626. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1627. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  1628. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1629. addSuccessorWithWeight(SwitchBB, B.Default);
  1630. addSuccessorWithWeight(SwitchBB, MBB);
  1631. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  1632. MVT::Other, CopyTo, RangeCmp,
  1633. DAG.getBasicBlock(B.Default));
  1634. // Avoid emitting unnecessary branches to the next block.
  1635. if (MBB != NextBlock(SwitchBB))
  1636. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  1637. DAG.getBasicBlock(MBB));
  1638. DAG.setRoot(BrRange);
  1639. }
  1640. /// visitBitTestCase - this function produces one "bit test"
  1641. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1642. MachineBasicBlock* NextMBB,
  1643. uint32_t BranchWeightToNext,
  1644. unsigned Reg,
  1645. BitTestCase &B,
  1646. MachineBasicBlock *SwitchBB) {
  1647. SDLoc dl = getCurSDLoc();
  1648. MVT VT = BB.RegVT;
  1649. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  1650. SDValue Cmp;
  1651. unsigned PopCount = countPopulation(B.Mask);
  1652. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1653. if (PopCount == 1) {
  1654. // Testing for a single bit; just compare the shift count with what it
  1655. // would need to be to shift a 1 bit in that position.
  1656. Cmp = DAG.getSetCC(
  1657. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1658. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  1659. ISD::SETEQ);
  1660. } else if (PopCount == BB.Range) {
  1661. // There is only one zero bit in the range, test for it directly.
  1662. Cmp = DAG.getSetCC(
  1663. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1664. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  1665. ISD::SETNE);
  1666. } else {
  1667. // Make desired shift
  1668. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  1669. DAG.getConstant(1, dl, VT), ShiftOp);
  1670. // Emit bit tests and jumps
  1671. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  1672. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  1673. Cmp = DAG.getSetCC(
  1674. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1675. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1676. }
  1677. // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
  1678. addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
  1679. // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
  1680. addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
  1681. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  1682. MVT::Other, getControlRoot(),
  1683. Cmp, DAG.getBasicBlock(B.TargetBB));
  1684. // Avoid emitting unnecessary branches to the next block.
  1685. if (NextMBB != NextBlock(SwitchBB))
  1686. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  1687. DAG.getBasicBlock(NextMBB));
  1688. DAG.setRoot(BrAnd);
  1689. }
  1690. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1691. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1692. // Retrieve successors.
  1693. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1694. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1695. const Value *Callee(I.getCalledValue());
  1696. const Function *Fn = dyn_cast<Function>(Callee);
  1697. if (isa<InlineAsm>(Callee))
  1698. visitInlineAsm(&I);
  1699. else if (Fn && Fn->isIntrinsic()) {
  1700. switch (Fn->getIntrinsicID()) {
  1701. default:
  1702. llvm_unreachable("Cannot invoke this intrinsic");
  1703. case Intrinsic::donothing:
  1704. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  1705. break;
  1706. case Intrinsic::experimental_patchpoint_void:
  1707. case Intrinsic::experimental_patchpoint_i64:
  1708. visitPatchpoint(&I, LandingPad);
  1709. break;
  1710. case Intrinsic::experimental_gc_statepoint:
  1711. LowerStatepoint(ImmutableStatepoint(&I), LandingPad);
  1712. break;
  1713. }
  1714. } else
  1715. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1716. // If the value of the invoke is used outside of its defining block, make it
  1717. // available as a virtual register.
  1718. // We already took care of the exported value for the statepoint instruction
  1719. // during call to the LowerStatepoint.
  1720. if (!isStatepoint(I)) {
  1721. CopyToExportRegsIfNeeded(&I);
  1722. }
  1723. // Update successor info
  1724. addSuccessorWithWeight(InvokeMBB, Return);
  1725. addSuccessorWithWeight(InvokeMBB, LandingPad);
  1726. // Drop into normal successor.
  1727. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1728. MVT::Other, getControlRoot(),
  1729. DAG.getBasicBlock(Return)));
  1730. }
  1731. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  1732. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  1733. }
  1734. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  1735. assert(FuncInfo.MBB->isLandingPad() &&
  1736. "Call to landingpad not in landing pad!");
  1737. MachineBasicBlock *MBB = FuncInfo.MBB;
  1738. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  1739. AddLandingPadInfo(LP, MMI, MBB);
  1740. // If there aren't registers to copy the values into (e.g., during SjLj
  1741. // exceptions), then don't bother to create these DAG nodes.
  1742. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1743. if (TLI.getExceptionPointerRegister() == 0 &&
  1744. TLI.getExceptionSelectorRegister() == 0)
  1745. return;
  1746. SmallVector<EVT, 2> ValueVTs;
  1747. SDLoc dl = getCurSDLoc();
  1748. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  1749. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  1750. // Get the two live-in registers as SDValues. The physregs have already been
  1751. // copied into virtual registers.
  1752. SDValue Ops[2];
  1753. if (FuncInfo.ExceptionPointerVirtReg) {
  1754. Ops[0] = DAG.getZExtOrTrunc(
  1755. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  1756. FuncInfo.ExceptionPointerVirtReg,
  1757. TLI.getPointerTy(DAG.getDataLayout())),
  1758. dl, ValueVTs[0]);
  1759. } else {
  1760. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1761. }
  1762. Ops[1] = DAG.getZExtOrTrunc(
  1763. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  1764. FuncInfo.ExceptionSelectorVirtReg,
  1765. TLI.getPointerTy(DAG.getDataLayout())),
  1766. dl, ValueVTs[1]);
  1767. // Merge into one.
  1768. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  1769. DAG.getVTList(ValueVTs), Ops);
  1770. setValue(&LP, Res);
  1771. }
  1772. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  1773. #ifndef NDEBUG
  1774. for (const CaseCluster &CC : Clusters)
  1775. assert(CC.Low == CC.High && "Input clusters must be single-case");
  1776. #endif
  1777. std::sort(Clusters.begin(), Clusters.end(),
  1778. [](const CaseCluster &a, const CaseCluster &b) {
  1779. return a.Low->getValue().slt(b.Low->getValue());
  1780. });
  1781. // Merge adjacent clusters with the same destination.
  1782. const unsigned N = Clusters.size();
  1783. unsigned DstIndex = 0;
  1784. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  1785. CaseCluster &CC = Clusters[SrcIndex];
  1786. const ConstantInt *CaseVal = CC.Low;
  1787. MachineBasicBlock *Succ = CC.MBB;
  1788. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  1789. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  1790. // If this case has the same successor and is a neighbour, merge it into
  1791. // the previous cluster.
  1792. Clusters[DstIndex - 1].High = CaseVal;
  1793. Clusters[DstIndex - 1].Weight += CC.Weight;
  1794. assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!");
  1795. } else {
  1796. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  1797. sizeof(Clusters[SrcIndex]));
  1798. }
  1799. }
  1800. Clusters.resize(DstIndex);
  1801. }
  1802. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  1803. MachineBasicBlock *Last) {
  1804. // Update JTCases.
  1805. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  1806. if (JTCases[i].first.HeaderBB == First)
  1807. JTCases[i].first.HeaderBB = Last;
  1808. // Update BitTestCases.
  1809. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  1810. if (BitTestCases[i].Parent == First)
  1811. BitTestCases[i].Parent = Last;
  1812. }
  1813. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  1814. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  1815. // Update machine-CFG edges with unique successors.
  1816. SmallSet<BasicBlock*, 32> Done;
  1817. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  1818. BasicBlock *BB = I.getSuccessor(i);
  1819. bool Inserted = Done.insert(BB).second;
  1820. if (!Inserted)
  1821. continue;
  1822. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  1823. addSuccessorWithWeight(IndirectBrMBB, Succ);
  1824. }
  1825. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  1826. MVT::Other, getControlRoot(),
  1827. getValue(I.getAddress())));
  1828. }
  1829. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  1830. if (DAG.getTarget().Options.TrapUnreachable)
  1831. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  1832. }
  1833. void SelectionDAGBuilder::visitFSub(const User &I) {
  1834. // -0.0 - X --> fneg
  1835. Type *Ty = I.getType();
  1836. if (isa<Constant>(I.getOperand(0)) &&
  1837. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  1838. SDValue Op2 = getValue(I.getOperand(1));
  1839. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  1840. Op2.getValueType(), Op2));
  1841. return;
  1842. }
  1843. visitBinary(I, ISD::FSUB);
  1844. }
  1845. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  1846. SDValue Op1 = getValue(I.getOperand(0));
  1847. SDValue Op2 = getValue(I.getOperand(1));
  1848. bool nuw = false;
  1849. bool nsw = false;
  1850. bool exact = false;
  1851. FastMathFlags FMF;
  1852. if (const OverflowingBinaryOperator *OFBinOp =
  1853. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  1854. nuw = OFBinOp->hasNoUnsignedWrap();
  1855. nsw = OFBinOp->hasNoSignedWrap();
  1856. }
  1857. if (const PossiblyExactOperator *ExactOp =
  1858. dyn_cast<const PossiblyExactOperator>(&I))
  1859. exact = ExactOp->isExact();
  1860. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
  1861. FMF = FPOp->getFastMathFlags();
  1862. SDNodeFlags Flags;
  1863. Flags.setExact(exact);
  1864. Flags.setNoSignedWrap(nsw);
  1865. Flags.setNoUnsignedWrap(nuw);
  1866. if (EnableFMFInDAG) {
  1867. Flags.setAllowReciprocal(FMF.allowReciprocal());
  1868. Flags.setNoInfs(FMF.noInfs());
  1869. Flags.setNoNaNs(FMF.noNaNs());
  1870. Flags.setNoSignedZeros(FMF.noSignedZeros());
  1871. Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
  1872. }
  1873. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  1874. Op1, Op2, &Flags);
  1875. setValue(&I, BinNodeValue);
  1876. }
  1877. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  1878. SDValue Op1 = getValue(I.getOperand(0));
  1879. SDValue Op2 = getValue(I.getOperand(1));
  1880. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  1881. Op2.getValueType(), DAG.getDataLayout());
  1882. // Coerce the shift amount to the right type if we can.
  1883. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  1884. unsigned ShiftSize = ShiftTy.getSizeInBits();
  1885. unsigned Op2Size = Op2.getValueType().getSizeInBits();
  1886. SDLoc DL = getCurSDLoc();
  1887. // If the operand is smaller than the shift count type, promote it.
  1888. if (ShiftSize > Op2Size)
  1889. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  1890. // If the operand is larger than the shift count type but the shift
  1891. // count type has enough bits to represent any shift value, truncate
  1892. // it now. This is a common case and it exposes the truncate to
  1893. // optimization early.
  1894. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  1895. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  1896. // Otherwise we'll need to temporarily settle for some other convenient
  1897. // type. Type legalization will make adjustments once the shiftee is split.
  1898. else
  1899. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  1900. }
  1901. bool nuw = false;
  1902. bool nsw = false;
  1903. bool exact = false;
  1904. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  1905. if (const OverflowingBinaryOperator *OFBinOp =
  1906. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  1907. nuw = OFBinOp->hasNoUnsignedWrap();
  1908. nsw = OFBinOp->hasNoSignedWrap();
  1909. }
  1910. if (const PossiblyExactOperator *ExactOp =
  1911. dyn_cast<const PossiblyExactOperator>(&I))
  1912. exact = ExactOp->isExact();
  1913. }
  1914. SDNodeFlags Flags;
  1915. Flags.setExact(exact);
  1916. Flags.setNoSignedWrap(nsw);
  1917. Flags.setNoUnsignedWrap(nuw);
  1918. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  1919. &Flags);
  1920. setValue(&I, Res);
  1921. }
  1922. void SelectionDAGBuilder::visitSDiv(const User &I) {
  1923. SDValue Op1 = getValue(I.getOperand(0));
  1924. SDValue Op2 = getValue(I.getOperand(1));
  1925. SDNodeFlags Flags;
  1926. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  1927. cast<PossiblyExactOperator>(&I)->isExact());
  1928. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  1929. Op2, &Flags));
  1930. }
  1931. void SelectionDAGBuilder::visitICmp(const User &I) {
  1932. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  1933. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  1934. predicate = IC->getPredicate();
  1935. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  1936. predicate = ICmpInst::Predicate(IC->getPredicate());
  1937. SDValue Op1 = getValue(I.getOperand(0));
  1938. SDValue Op2 = getValue(I.getOperand(1));
  1939. ISD::CondCode Opcode = getICmpCondCode(predicate);
  1940. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  1941. I.getType());
  1942. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  1943. }
  1944. void SelectionDAGBuilder::visitFCmp(const User &I) {
  1945. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  1946. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  1947. predicate = FC->getPredicate();
  1948. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  1949. predicate = FCmpInst::Predicate(FC->getPredicate());
  1950. SDValue Op1 = getValue(I.getOperand(0));
  1951. SDValue Op2 = getValue(I.getOperand(1));
  1952. ISD::CondCode Condition = getFCmpCondCode(predicate);
  1953. if (TM.Options.NoNaNsFPMath)
  1954. Condition = getFCmpCodeWithoutNaN(Condition);
  1955. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  1956. I.getType());
  1957. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  1958. }
  1959. void SelectionDAGBuilder::visitSelect(const User &I) {
  1960. SmallVector<EVT, 4> ValueVTs;
  1961. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  1962. ValueVTs);
  1963. unsigned NumValues = ValueVTs.size();
  1964. if (NumValues == 0) return;
  1965. SmallVector<SDValue, 4> Values(NumValues);
  1966. SDValue Cond = getValue(I.getOperand(0));
  1967. SDValue LHSVal = getValue(I.getOperand(1));
  1968. SDValue RHSVal = getValue(I.getOperand(2));
  1969. auto BaseOps = {Cond};
  1970. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  1971. ISD::VSELECT : ISD::SELECT;
  1972. // Min/max matching is only viable if all output VTs are the same.
  1973. if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
  1974. Value *LHS, *RHS;
  1975. SelectPatternFlavor SPF = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  1976. ISD::NodeType Opc = ISD::DELETED_NODE;
  1977. switch (SPF) {
  1978. case SPF_UMAX: Opc = ISD::UMAX; break;
  1979. case SPF_UMIN: Opc = ISD::UMIN; break;
  1980. case SPF_SMAX: Opc = ISD::SMAX; break;
  1981. case SPF_SMIN: Opc = ISD::SMIN; break;
  1982. default: break;
  1983. }
  1984. EVT VT = ValueVTs[0];
  1985. LLVMContext &Ctx = *DAG.getContext();
  1986. auto &TLI = DAG.getTargetLoweringInfo();
  1987. while (TLI.getTypeAction(Ctx, VT) == TargetLoweringBase::TypeSplitVector)
  1988. VT = TLI.getTypeToTransformTo(Ctx, VT);
  1989. if (Opc != ISD::DELETED_NODE && TLI.isOperationLegalOrCustom(Opc, VT) &&
  1990. // If the underlying comparison instruction is used by any other instruction,
  1991. // the consumed instructions won't be destroyed, so it is not profitable
  1992. // to convert to a min/max.
  1993. cast<SelectInst>(&I)->getCondition()->hasOneUse()) {
  1994. OpCode = Opc;
  1995. LHSVal = getValue(LHS);
  1996. RHSVal = getValue(RHS);
  1997. BaseOps = {};
  1998. }
  1999. }
  2000. for (unsigned i = 0; i != NumValues; ++i) {
  2001. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2002. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2003. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2004. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2005. LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
  2006. Ops);
  2007. }
  2008. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2009. DAG.getVTList(ValueVTs), Values));
  2010. }
  2011. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2012. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2013. SDValue N = getValue(I.getOperand(0));
  2014. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2015. I.getType());
  2016. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2017. }
  2018. void SelectionDAGBuilder::visitZExt(const User &I) {
  2019. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2020. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2021. SDValue N = getValue(I.getOperand(0));
  2022. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2023. I.getType());
  2024. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2025. }
  2026. void SelectionDAGBuilder::visitSExt(const User &I) {
  2027. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2028. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2029. SDValue N = getValue(I.getOperand(0));
  2030. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2031. I.getType());
  2032. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2033. }
  2034. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2035. // FPTrunc is never a no-op cast, no need to check
  2036. SDValue N = getValue(I.getOperand(0));
  2037. SDLoc dl = getCurSDLoc();
  2038. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2039. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2040. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2041. DAG.getTargetConstant(
  2042. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2043. }
  2044. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2045. // FPExt is never a no-op cast, no need to check
  2046. SDValue N = getValue(I.getOperand(0));
  2047. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2048. I.getType());
  2049. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2050. }
  2051. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2052. // FPToUI is never a no-op cast, no need to check
  2053. SDValue N = getValue(I.getOperand(0));
  2054. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2055. I.getType());
  2056. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2057. }
  2058. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2059. // FPToSI is never a no-op cast, no need to check
  2060. SDValue N = getValue(I.getOperand(0));
  2061. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2062. I.getType());
  2063. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2064. }
  2065. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2066. // UIToFP is never a no-op cast, no need to check
  2067. SDValue N = getValue(I.getOperand(0));
  2068. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2069. I.getType());
  2070. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2071. }
  2072. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2073. // SIToFP is never a no-op cast, no need to check
  2074. SDValue N = getValue(I.getOperand(0));
  2075. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2076. I.getType());
  2077. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2078. }
  2079. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2080. // What to do depends on the size of the integer and the size of the pointer.
  2081. // We can either truncate, zero extend, or no-op, accordingly.
  2082. SDValue N = getValue(I.getOperand(0));
  2083. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2084. I.getType());
  2085. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2086. }
  2087. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2088. // What to do depends on the size of the integer and the size of the pointer.
  2089. // We can either truncate, zero extend, or no-op, accordingly.
  2090. SDValue N = getValue(I.getOperand(0));
  2091. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2092. I.getType());
  2093. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2094. }
  2095. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2096. SDValue N = getValue(I.getOperand(0));
  2097. SDLoc dl = getCurSDLoc();
  2098. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2099. I.getType());
  2100. // BitCast assures us that source and destination are the same size so this is
  2101. // either a BITCAST or a no-op.
  2102. if (DestVT != N.getValueType())
  2103. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2104. DestVT, N)); // convert types.
  2105. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2106. // might fold any kind of constant expression to an integer constant and that
  2107. // is not what we are looking for. Only regcognize a bitcast of a genuine
  2108. // constant integer as an opaque constant.
  2109. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2110. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2111. /*isOpaque*/true));
  2112. else
  2113. setValue(&I, N); // noop cast.
  2114. }
  2115. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2116. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2117. const Value *SV = I.getOperand(0);
  2118. SDValue N = getValue(SV);
  2119. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2120. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2121. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2122. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2123. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2124. setValue(&I, N);
  2125. }
  2126. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2127. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2128. SDValue InVec = getValue(I.getOperand(0));
  2129. SDValue InVal = getValue(I.getOperand(1));
  2130. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  2131. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2132. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2133. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2134. InVec, InVal, InIdx));
  2135. }
  2136. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2137. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2138. SDValue InVec = getValue(I.getOperand(0));
  2139. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  2140. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2141. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2142. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2143. InVec, InIdx));
  2144. }
  2145. // Utility for visitShuffleVector - Return true if every element in Mask,
  2146. // beginning from position Pos and ending in Pos+Size, falls within the
  2147. // specified sequential range [L, L+Pos). or is undef.
  2148. static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
  2149. unsigned Pos, unsigned Size, int Low) {
  2150. for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
  2151. if (Mask[i] >= 0 && Mask[i] != Low)
  2152. return false;
  2153. return true;
  2154. }
  2155. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2156. SDValue Src1 = getValue(I.getOperand(0));
  2157. SDValue Src2 = getValue(I.getOperand(1));
  2158. SmallVector<int, 8> Mask;
  2159. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2160. unsigned MaskNumElts = Mask.size();
  2161. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2162. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2163. EVT SrcVT = Src1.getValueType();
  2164. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2165. if (SrcNumElts == MaskNumElts) {
  2166. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2167. &Mask[0]));
  2168. return;
  2169. }
  2170. // Normalize the shuffle vector since mask and vector length don't match.
  2171. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2172. // Mask is longer than the source vectors and is a multiple of the source
  2173. // vectors. We can use concatenate vector to make the mask and vectors
  2174. // lengths match.
  2175. if (SrcNumElts*2 == MaskNumElts) {
  2176. // First check for Src1 in low and Src2 in high
  2177. if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
  2178. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
  2179. // The shuffle is concatenating two vectors together.
  2180. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2181. VT, Src1, Src2));
  2182. return;
  2183. }
  2184. // Then check for Src2 in low and Src1 in high
  2185. if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
  2186. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
  2187. // The shuffle is concatenating two vectors together.
  2188. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2189. VT, Src2, Src1));
  2190. return;
  2191. }
  2192. }
  2193. // Pad both vectors with undefs to make them the same length as the mask.
  2194. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2195. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2196. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2197. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2198. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2199. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2200. MOps1[0] = Src1;
  2201. MOps2[0] = Src2;
  2202. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2203. getCurSDLoc(), VT, MOps1);
  2204. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2205. getCurSDLoc(), VT, MOps2);
  2206. // Readjust mask for new input vector length.
  2207. SmallVector<int, 8> MappedOps;
  2208. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2209. int Idx = Mask[i];
  2210. if (Idx >= (int)SrcNumElts)
  2211. Idx -= SrcNumElts - MaskNumElts;
  2212. MappedOps.push_back(Idx);
  2213. }
  2214. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2215. &MappedOps[0]));
  2216. return;
  2217. }
  2218. if (SrcNumElts > MaskNumElts) {
  2219. // Analyze the access pattern of the vector to see if we can extract
  2220. // two subvectors and do the shuffle. The analysis is done by calculating
  2221. // the range of elements the mask access on both vectors.
  2222. int MinRange[2] = { static_cast<int>(SrcNumElts),
  2223. static_cast<int>(SrcNumElts)};
  2224. int MaxRange[2] = {-1, -1};
  2225. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2226. int Idx = Mask[i];
  2227. unsigned Input = 0;
  2228. if (Idx < 0)
  2229. continue;
  2230. if (Idx >= (int)SrcNumElts) {
  2231. Input = 1;
  2232. Idx -= SrcNumElts;
  2233. }
  2234. if (Idx > MaxRange[Input])
  2235. MaxRange[Input] = Idx;
  2236. if (Idx < MinRange[Input])
  2237. MinRange[Input] = Idx;
  2238. }
  2239. // Check if the access is smaller than the vector size and can we find
  2240. // a reasonable extract index.
  2241. int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
  2242. // Extract.
  2243. int StartIdx[2]; // StartIdx to extract from
  2244. for (unsigned Input = 0; Input < 2; ++Input) {
  2245. if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
  2246. RangeUse[Input] = 0; // Unused
  2247. StartIdx[Input] = 0;
  2248. continue;
  2249. }
  2250. // Find a good start index that is a multiple of the mask length. Then
  2251. // see if the rest of the elements are in range.
  2252. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2253. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2254. StartIdx[Input] + MaskNumElts <= SrcNumElts)
  2255. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2256. }
  2257. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2258. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2259. return;
  2260. }
  2261. if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
  2262. // Extract appropriate subvector and generate a vector shuffle
  2263. for (unsigned Input = 0; Input < 2; ++Input) {
  2264. SDValue &Src = Input == 0 ? Src1 : Src2;
  2265. if (RangeUse[Input] == 0)
  2266. Src = DAG.getUNDEF(VT);
  2267. else {
  2268. SDLoc dl = getCurSDLoc();
  2269. Src = DAG.getNode(
  2270. ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
  2271. DAG.getConstant(StartIdx[Input], dl,
  2272. TLI.getVectorIdxTy(DAG.getDataLayout())));
  2273. }
  2274. }
  2275. // Calculate new mask.
  2276. SmallVector<int, 8> MappedOps;
  2277. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2278. int Idx = Mask[i];
  2279. if (Idx >= 0) {
  2280. if (Idx < (int)SrcNumElts)
  2281. Idx -= StartIdx[0];
  2282. else
  2283. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2284. }
  2285. MappedOps.push_back(Idx);
  2286. }
  2287. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2288. &MappedOps[0]));
  2289. return;
  2290. }
  2291. }
  2292. // We can't use either concat vectors or extract subvectors so fall back to
  2293. // replacing the shuffle with extract and build vector.
  2294. // to insert and build vector.
  2295. EVT EltVT = VT.getVectorElementType();
  2296. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  2297. SDLoc dl = getCurSDLoc();
  2298. SmallVector<SDValue,8> Ops;
  2299. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2300. int Idx = Mask[i];
  2301. SDValue Res;
  2302. if (Idx < 0) {
  2303. Res = DAG.getUNDEF(EltVT);
  2304. } else {
  2305. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2306. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2307. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
  2308. EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
  2309. }
  2310. Ops.push_back(Res);
  2311. }
  2312. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
  2313. }
  2314. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  2315. const Value *Op0 = I.getOperand(0);
  2316. const Value *Op1 = I.getOperand(1);
  2317. Type *AggTy = I.getType();
  2318. Type *ValTy = Op1->getType();
  2319. bool IntoUndef = isa<UndefValue>(Op0);
  2320. bool FromUndef = isa<UndefValue>(Op1);
  2321. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2322. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2323. SmallVector<EVT, 4> AggValueVTs;
  2324. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  2325. SmallVector<EVT, 4> ValValueVTs;
  2326. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2327. unsigned NumAggValues = AggValueVTs.size();
  2328. unsigned NumValValues = ValValueVTs.size();
  2329. SmallVector<SDValue, 4> Values(NumAggValues);
  2330. // Ignore an insertvalue that produces an empty object
  2331. if (!NumAggValues) {
  2332. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2333. return;
  2334. }
  2335. SDValue Agg = getValue(Op0);
  2336. unsigned i = 0;
  2337. // Copy the beginning value(s) from the original aggregate.
  2338. for (; i != LinearIndex; ++i)
  2339. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2340. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2341. // Copy values from the inserted value(s).
  2342. if (NumValValues) {
  2343. SDValue Val = getValue(Op1);
  2344. for (; i != LinearIndex + NumValValues; ++i)
  2345. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2346. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2347. }
  2348. // Copy remaining value(s) from the original aggregate.
  2349. for (; i != NumAggValues; ++i)
  2350. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2351. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2352. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2353. DAG.getVTList(AggValueVTs), Values));
  2354. }
  2355. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  2356. const Value *Op0 = I.getOperand(0);
  2357. Type *AggTy = Op0->getType();
  2358. Type *ValTy = I.getType();
  2359. bool OutOfUndef = isa<UndefValue>(Op0);
  2360. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2361. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2362. SmallVector<EVT, 4> ValValueVTs;
  2363. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2364. unsigned NumValValues = ValValueVTs.size();
  2365. // Ignore a extractvalue that produces an empty object
  2366. if (!NumValValues) {
  2367. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2368. return;
  2369. }
  2370. SmallVector<SDValue, 4> Values(NumValValues);
  2371. SDValue Agg = getValue(Op0);
  2372. // Copy out the selected value(s).
  2373. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2374. Values[i - LinearIndex] =
  2375. OutOfUndef ?
  2376. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2377. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2378. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2379. DAG.getVTList(ValValueVTs), Values));
  2380. }
  2381. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2382. Value *Op0 = I.getOperand(0);
  2383. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2384. // element which holds a pointer.
  2385. Type *Ty = Op0->getType()->getScalarType();
  2386. unsigned AS = Ty->getPointerAddressSpace();
  2387. SDValue N = getValue(Op0);
  2388. SDLoc dl = getCurSDLoc();
  2389. // Normalize Vector GEP - all scalar operands should be converted to the
  2390. // splat vector.
  2391. unsigned VectorWidth = I.getType()->isVectorTy() ?
  2392. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  2393. if (VectorWidth && !N.getValueType().isVector()) {
  2394. MVT VT = MVT::getVectorVT(N.getValueType().getSimpleVT(), VectorWidth);
  2395. SmallVector<SDValue, 16> Ops(VectorWidth, N);
  2396. N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
  2397. }
  2398. for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
  2399. OI != E; ++OI) {
  2400. const Value *Idx = *OI;
  2401. if (StructType *StTy = dyn_cast<StructType>(Ty)) {
  2402. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2403. if (Field) {
  2404. // N = N + Offset
  2405. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  2406. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  2407. DAG.getConstant(Offset, dl, N.getValueType()));
  2408. }
  2409. Ty = StTy->getElementType(Field);
  2410. } else {
  2411. Ty = cast<SequentialType>(Ty)->getElementType();
  2412. MVT PtrTy =
  2413. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
  2414. unsigned PtrSize = PtrTy.getSizeInBits();
  2415. APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty));
  2416. // If this is a scalar constant or a splat vector of constants,
  2417. // handle it quickly.
  2418. const auto *CI = dyn_cast<ConstantInt>(Idx);
  2419. if (!CI && isa<ConstantDataVector>(Idx) &&
  2420. cast<ConstantDataVector>(Idx)->getSplatValue())
  2421. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  2422. if (CI) {
  2423. if (CI->isZero())
  2424. continue;
  2425. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
  2426. SDValue OffsVal = VectorWidth ?
  2427. DAG.getConstant(Offs, dl, MVT::getVectorVT(PtrTy, VectorWidth)) :
  2428. DAG.getConstant(Offs, dl, PtrTy);
  2429. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal);
  2430. continue;
  2431. }
  2432. // N = N + Idx * ElementSize;
  2433. SDValue IdxN = getValue(Idx);
  2434. if (!IdxN.getValueType().isVector() && VectorWidth) {
  2435. MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth);
  2436. SmallVector<SDValue, 16> Ops(VectorWidth, IdxN);
  2437. IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
  2438. }
  2439. // If the index is smaller or larger than intptr_t, truncate or extend
  2440. // it.
  2441. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  2442. // If this is a multiply by a power of two, turn it into a shl
  2443. // immediately. This is a very common case.
  2444. if (ElementSize != 1) {
  2445. if (ElementSize.isPowerOf2()) {
  2446. unsigned Amt = ElementSize.logBase2();
  2447. IdxN = DAG.getNode(ISD::SHL, dl,
  2448. N.getValueType(), IdxN,
  2449. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  2450. } else {
  2451. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  2452. IdxN = DAG.getNode(ISD::MUL, dl,
  2453. N.getValueType(), IdxN, Scale);
  2454. }
  2455. }
  2456. N = DAG.getNode(ISD::ADD, dl,
  2457. N.getValueType(), N, IdxN);
  2458. }
  2459. }
  2460. setValue(&I, N);
  2461. }
  2462. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2463. // If this is a fixed sized alloca in the entry block of the function,
  2464. // allocate it statically on the stack.
  2465. if (FuncInfo.StaticAllocaMap.count(&I))
  2466. return; // getValue will auto-populate this.
  2467. SDLoc dl = getCurSDLoc();
  2468. Type *Ty = I.getAllocatedType();
  2469. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2470. auto &DL = DAG.getDataLayout();
  2471. uint64_t TySize = DL.getTypeAllocSize(Ty);
  2472. unsigned Align =
  2473. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  2474. SDValue AllocSize = getValue(I.getArraySize());
  2475. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
  2476. if (AllocSize.getValueType() != IntPtr)
  2477. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  2478. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  2479. AllocSize,
  2480. DAG.getConstant(TySize, dl, IntPtr));
  2481. // Handle alignment. If the requested alignment is less than or equal to
  2482. // the stack alignment, ignore it. If the size is greater than or equal to
  2483. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2484. unsigned StackAlign =
  2485. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  2486. if (Align <= StackAlign)
  2487. Align = 0;
  2488. // Round the size of the allocation up to the stack alignment size
  2489. // by add SA-1 to the size.
  2490. AllocSize = DAG.getNode(ISD::ADD, dl,
  2491. AllocSize.getValueType(), AllocSize,
  2492. DAG.getIntPtrConstant(StackAlign - 1, dl));
  2493. // Mask out the low bits for alignment purposes.
  2494. AllocSize = DAG.getNode(ISD::AND, dl,
  2495. AllocSize.getValueType(), AllocSize,
  2496. DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
  2497. dl));
  2498. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
  2499. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2500. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  2501. setValue(&I, DSA);
  2502. DAG.setRoot(DSA.getValue(1));
  2503. assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
  2504. }
  2505. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  2506. if (I.isAtomic())
  2507. return visitAtomicLoad(I);
  2508. const Value *SV = I.getOperand(0);
  2509. SDValue Ptr = getValue(SV);
  2510. Type *Ty = I.getType();
  2511. bool isVolatile = I.isVolatile();
  2512. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  2513. // The IR notion of invariant_load only guarantees that all *non-faulting*
  2514. // invariant loads result in the same value. The MI notion of invariant load
  2515. // guarantees that the load can be legally moved to any location within its
  2516. // containing function. The MI notion of invariant_load is stronger than the
  2517. // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load
  2518. // with a guarantee that the location being loaded from is dereferenceable
  2519. // throughout the function's lifetime.
  2520. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr &&
  2521. isDereferenceablePointer(SV, *DAG.getTarget().getDataLayout());
  2522. unsigned Alignment = I.getAlignment();
  2523. AAMDNodes AAInfo;
  2524. I.getAAMetadata(AAInfo);
  2525. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  2526. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2527. SmallVector<EVT, 4> ValueVTs;
  2528. SmallVector<uint64_t, 4> Offsets;
  2529. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  2530. unsigned NumValues = ValueVTs.size();
  2531. if (NumValues == 0)
  2532. return;
  2533. SDValue Root;
  2534. bool ConstantMemory = false;
  2535. if (isVolatile || NumValues > MaxParallelChains)
  2536. // Serialize volatile loads with other side effects.
  2537. Root = getRoot();
  2538. else if (AA->pointsToConstantMemory(
  2539. MemoryLocation(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
  2540. // Do not serialize (non-volatile) loads of constant memory with anything.
  2541. Root = DAG.getEntryNode();
  2542. ConstantMemory = true;
  2543. } else {
  2544. // Do not serialize non-volatile loads against each other.
  2545. Root = DAG.getRoot();
  2546. }
  2547. SDLoc dl = getCurSDLoc();
  2548. if (isVolatile)
  2549. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  2550. SmallVector<SDValue, 4> Values(NumValues);
  2551. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  2552. EVT PtrVT = Ptr.getValueType();
  2553. unsigned ChainI = 0;
  2554. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  2555. // Serializing loads here may result in excessive register pressure, and
  2556. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  2557. // could recover a bit by hoisting nodes upward in the chain by recognizing
  2558. // they are side-effect free or do not alias. The optimizer should really
  2559. // avoid this case by converting large object/array copies to llvm.memcpy
  2560. // (MaxParallelChains should always remain as failsafe).
  2561. if (ChainI == MaxParallelChains) {
  2562. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  2563. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2564. makeArrayRef(Chains.data(), ChainI));
  2565. Root = Chain;
  2566. ChainI = 0;
  2567. }
  2568. SDValue A = DAG.getNode(ISD::ADD, dl,
  2569. PtrVT, Ptr,
  2570. DAG.getConstant(Offsets[i], dl, PtrVT));
  2571. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
  2572. A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
  2573. isNonTemporal, isInvariant, Alignment, AAInfo,
  2574. Ranges);
  2575. Values[i] = L;
  2576. Chains[ChainI] = L.getValue(1);
  2577. }
  2578. if (!ConstantMemory) {
  2579. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2580. makeArrayRef(Chains.data(), ChainI));
  2581. if (isVolatile)
  2582. DAG.setRoot(Chain);
  2583. else
  2584. PendingLoads.push_back(Chain);
  2585. }
  2586. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  2587. DAG.getVTList(ValueVTs), Values));
  2588. }
  2589. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  2590. if (I.isAtomic())
  2591. return visitAtomicStore(I);
  2592. const Value *SrcV = I.getOperand(0);
  2593. const Value *PtrV = I.getOperand(1);
  2594. SmallVector<EVT, 4> ValueVTs;
  2595. SmallVector<uint64_t, 4> Offsets;
  2596. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  2597. SrcV->getType(), ValueVTs, &Offsets);
  2598. unsigned NumValues = ValueVTs.size();
  2599. if (NumValues == 0)
  2600. return;
  2601. // Get the lowered operands. Note that we do this after
  2602. // checking if NumResults is zero, because with zero results
  2603. // the operands won't have values in the map.
  2604. SDValue Src = getValue(SrcV);
  2605. SDValue Ptr = getValue(PtrV);
  2606. SDValue Root = getRoot();
  2607. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  2608. EVT PtrVT = Ptr.getValueType();
  2609. bool isVolatile = I.isVolatile();
  2610. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  2611. unsigned Alignment = I.getAlignment();
  2612. SDLoc dl = getCurSDLoc();
  2613. AAMDNodes AAInfo;
  2614. I.getAAMetadata(AAInfo);
  2615. unsigned ChainI = 0;
  2616. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  2617. // See visitLoad comments.
  2618. if (ChainI == MaxParallelChains) {
  2619. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2620. makeArrayRef(Chains.data(), ChainI));
  2621. Root = Chain;
  2622. ChainI = 0;
  2623. }
  2624. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  2625. DAG.getConstant(Offsets[i], dl, PtrVT));
  2626. SDValue St = DAG.getStore(Root, dl,
  2627. SDValue(Src.getNode(), Src.getResNo() + i),
  2628. Add, MachinePointerInfo(PtrV, Offsets[i]),
  2629. isVolatile, isNonTemporal, Alignment, AAInfo);
  2630. Chains[ChainI] = St;
  2631. }
  2632. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2633. makeArrayRef(Chains.data(), ChainI));
  2634. DAG.setRoot(StoreNode);
  2635. }
  2636. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
  2637. SDLoc sdl = getCurSDLoc();
  2638. // llvm.masked.store.*(Src0, Ptr, alignemt, Mask)
  2639. Value *PtrOperand = I.getArgOperand(1);
  2640. SDValue Ptr = getValue(PtrOperand);
  2641. SDValue Src0 = getValue(I.getArgOperand(0));
  2642. SDValue Mask = getValue(I.getArgOperand(3));
  2643. EVT VT = Src0.getValueType();
  2644. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  2645. if (!Alignment)
  2646. Alignment = DAG.getEVTAlignment(VT);
  2647. AAMDNodes AAInfo;
  2648. I.getAAMetadata(AAInfo);
  2649. MachineMemOperand *MMO =
  2650. DAG.getMachineFunction().
  2651. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  2652. MachineMemOperand::MOStore, VT.getStoreSize(),
  2653. Alignment, AAInfo);
  2654. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  2655. MMO, false);
  2656. DAG.setRoot(StoreNode);
  2657. setValue(&I, StoreNode);
  2658. }
  2659. // Gather/scatter receive a vector of pointers.
  2660. // This vector of pointers may be represented as a base pointer + vector of
  2661. // indices, it depends on GEP and instruction preceeding GEP
  2662. // that calculates indices
  2663. static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index,
  2664. SelectionDAGBuilder* SDB) {
  2665. assert (Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  2666. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  2667. if (!Gep || Gep->getNumOperands() > 2)
  2668. return false;
  2669. ShuffleVectorInst *ShuffleInst =
  2670. dyn_cast<ShuffleVectorInst>(Gep->getPointerOperand());
  2671. if (!ShuffleInst || !ShuffleInst->getMask()->isNullValue() ||
  2672. cast<Instruction>(ShuffleInst->getOperand(0))->getOpcode() !=
  2673. Instruction::InsertElement)
  2674. return false;
  2675. Ptr = cast<InsertElementInst>(ShuffleInst->getOperand(0))->getOperand(1);
  2676. SelectionDAG& DAG = SDB->DAG;
  2677. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2678. // Check is the Ptr is inside current basic block
  2679. // If not, look for the shuffle instruction
  2680. if (SDB->findValue(Ptr))
  2681. Base = SDB->getValue(Ptr);
  2682. else if (SDB->findValue(ShuffleInst)) {
  2683. SDValue ShuffleNode = SDB->getValue(ShuffleInst);
  2684. SDLoc sdl = ShuffleNode;
  2685. Base = DAG.getNode(
  2686. ISD::EXTRACT_VECTOR_ELT, sdl,
  2687. ShuffleNode.getValueType().getScalarType(), ShuffleNode,
  2688. DAG.getConstant(0, sdl, TLI.getVectorIdxTy(DAG.getDataLayout())));
  2689. SDB->setValue(Ptr, Base);
  2690. }
  2691. else
  2692. return false;
  2693. Value *IndexVal = Gep->getOperand(1);
  2694. if (SDB->findValue(IndexVal)) {
  2695. Index = SDB->getValue(IndexVal);
  2696. if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
  2697. IndexVal = Sext->getOperand(0);
  2698. if (SDB->findValue(IndexVal))
  2699. Index = SDB->getValue(IndexVal);
  2700. }
  2701. return true;
  2702. }
  2703. return false;
  2704. }
  2705. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  2706. SDLoc sdl = getCurSDLoc();
  2707. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  2708. Value *Ptr = I.getArgOperand(1);
  2709. SDValue Src0 = getValue(I.getArgOperand(0));
  2710. SDValue Mask = getValue(I.getArgOperand(3));
  2711. EVT VT = Src0.getValueType();
  2712. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  2713. if (!Alignment)
  2714. Alignment = DAG.getEVTAlignment(VT);
  2715. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2716. AAMDNodes AAInfo;
  2717. I.getAAMetadata(AAInfo);
  2718. SDValue Base;
  2719. SDValue Index;
  2720. Value *BasePtr = Ptr;
  2721. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  2722. Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  2723. MachineMemOperand *MMO = DAG.getMachineFunction().
  2724. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  2725. MachineMemOperand::MOStore, VT.getStoreSize(),
  2726. Alignment, AAInfo);
  2727. if (!UniformBase) {
  2728. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  2729. Index = getValue(Ptr);
  2730. }
  2731. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
  2732. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  2733. Ops, MMO);
  2734. DAG.setRoot(Scatter);
  2735. setValue(&I, Scatter);
  2736. }
  2737. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
  2738. SDLoc sdl = getCurSDLoc();
  2739. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  2740. Value *PtrOperand = I.getArgOperand(0);
  2741. SDValue Ptr = getValue(PtrOperand);
  2742. SDValue Src0 = getValue(I.getArgOperand(3));
  2743. SDValue Mask = getValue(I.getArgOperand(2));
  2744. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2745. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2746. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  2747. if (!Alignment)
  2748. Alignment = DAG.getEVTAlignment(VT);
  2749. AAMDNodes AAInfo;
  2750. I.getAAMetadata(AAInfo);
  2751. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  2752. SDValue InChain = DAG.getRoot();
  2753. if (AA->pointsToConstantMemory(MemoryLocation(
  2754. PtrOperand, AA->getTypeStoreSize(I.getType()), AAInfo))) {
  2755. // Do not serialize (non-volatile) loads of constant memory with anything.
  2756. InChain = DAG.getEntryNode();
  2757. }
  2758. MachineMemOperand *MMO =
  2759. DAG.getMachineFunction().
  2760. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  2761. MachineMemOperand::MOLoad, VT.getStoreSize(),
  2762. Alignment, AAInfo, Ranges);
  2763. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  2764. ISD::NON_EXTLOAD);
  2765. SDValue OutChain = Load.getValue(1);
  2766. DAG.setRoot(OutChain);
  2767. setValue(&I, Load);
  2768. }
  2769. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  2770. SDLoc sdl = getCurSDLoc();
  2771. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  2772. Value *Ptr = I.getArgOperand(0);
  2773. SDValue Src0 = getValue(I.getArgOperand(3));
  2774. SDValue Mask = getValue(I.getArgOperand(2));
  2775. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2776. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2777. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  2778. if (!Alignment)
  2779. Alignment = DAG.getEVTAlignment(VT);
  2780. AAMDNodes AAInfo;
  2781. I.getAAMetadata(AAInfo);
  2782. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  2783. SDValue Root = DAG.getRoot();
  2784. SDValue Base;
  2785. SDValue Index;
  2786. Value *BasePtr = Ptr;
  2787. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  2788. bool ConstantMemory = false;
  2789. if (UniformBase &&
  2790. AA->pointsToConstantMemory(
  2791. MemoryLocation(BasePtr, AA->getTypeStoreSize(I.getType()), AAInfo))) {
  2792. // Do not serialize (non-volatile) loads of constant memory with anything.
  2793. Root = DAG.getEntryNode();
  2794. ConstantMemory = true;
  2795. }
  2796. MachineMemOperand *MMO =
  2797. DAG.getMachineFunction().
  2798. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  2799. MachineMemOperand::MOLoad, VT.getStoreSize(),
  2800. Alignment, AAInfo, Ranges);
  2801. if (!UniformBase) {
  2802. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  2803. Index = getValue(Ptr);
  2804. }
  2805. SDValue Ops[] = { Root, Src0, Mask, Base, Index };
  2806. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  2807. Ops, MMO);
  2808. SDValue OutChain = Gather.getValue(1);
  2809. if (!ConstantMemory)
  2810. PendingLoads.push_back(OutChain);
  2811. setValue(&I, Gather);
  2812. }
  2813. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  2814. SDLoc dl = getCurSDLoc();
  2815. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  2816. AtomicOrdering FailureOrder = I.getFailureOrdering();
  2817. SynchronizationScope Scope = I.getSynchScope();
  2818. SDValue InChain = getRoot();
  2819. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  2820. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  2821. SDValue L = DAG.getAtomicCmpSwap(
  2822. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  2823. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  2824. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  2825. /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
  2826. SDValue OutChain = L.getValue(2);
  2827. setValue(&I, L);
  2828. DAG.setRoot(OutChain);
  2829. }
  2830. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  2831. SDLoc dl = getCurSDLoc();
  2832. ISD::NodeType NT;
  2833. switch (I.getOperation()) {
  2834. default: llvm_unreachable("Unknown atomicrmw operation");
  2835. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  2836. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  2837. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  2838. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  2839. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  2840. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  2841. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  2842. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  2843. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  2844. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  2845. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  2846. }
  2847. AtomicOrdering Order = I.getOrdering();
  2848. SynchronizationScope Scope = I.getSynchScope();
  2849. SDValue InChain = getRoot();
  2850. SDValue L =
  2851. DAG.getAtomic(NT, dl,
  2852. getValue(I.getValOperand()).getSimpleValueType(),
  2853. InChain,
  2854. getValue(I.getPointerOperand()),
  2855. getValue(I.getValOperand()),
  2856. I.getPointerOperand(),
  2857. /* Alignment=*/ 0, Order, Scope);
  2858. SDValue OutChain = L.getValue(1);
  2859. setValue(&I, L);
  2860. DAG.setRoot(OutChain);
  2861. }
  2862. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  2863. SDLoc dl = getCurSDLoc();
  2864. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2865. SDValue Ops[3];
  2866. Ops[0] = getRoot();
  2867. Ops[1] = DAG.getConstant(I.getOrdering(), dl,
  2868. TLI.getPointerTy(DAG.getDataLayout()));
  2869. Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
  2870. TLI.getPointerTy(DAG.getDataLayout()));
  2871. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  2872. }
  2873. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  2874. SDLoc dl = getCurSDLoc();
  2875. AtomicOrdering Order = I.getOrdering();
  2876. SynchronizationScope Scope = I.getSynchScope();
  2877. SDValue InChain = getRoot();
  2878. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2879. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2880. if (I.getAlignment() < VT.getSizeInBits() / 8)
  2881. report_fatal_error("Cannot generate unaligned atomic load");
  2882. MachineMemOperand *MMO =
  2883. DAG.getMachineFunction().
  2884. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  2885. MachineMemOperand::MOVolatile |
  2886. MachineMemOperand::MOLoad,
  2887. VT.getStoreSize(),
  2888. I.getAlignment() ? I.getAlignment() :
  2889. DAG.getEVTAlignment(VT));
  2890. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  2891. SDValue L =
  2892. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  2893. getValue(I.getPointerOperand()), MMO,
  2894. Order, Scope);
  2895. SDValue OutChain = L.getValue(1);
  2896. setValue(&I, L);
  2897. DAG.setRoot(OutChain);
  2898. }
  2899. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  2900. SDLoc dl = getCurSDLoc();
  2901. AtomicOrdering Order = I.getOrdering();
  2902. SynchronizationScope Scope = I.getSynchScope();
  2903. SDValue InChain = getRoot();
  2904. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2905. EVT VT =
  2906. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  2907. if (I.getAlignment() < VT.getSizeInBits() / 8)
  2908. report_fatal_error("Cannot generate unaligned atomic store");
  2909. SDValue OutChain =
  2910. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  2911. InChain,
  2912. getValue(I.getPointerOperand()),
  2913. getValue(I.getValueOperand()),
  2914. I.getPointerOperand(), I.getAlignment(),
  2915. Order, Scope);
  2916. DAG.setRoot(OutChain);
  2917. }
  2918. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  2919. /// node.
  2920. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  2921. unsigned Intrinsic) {
  2922. bool HasChain = !I.doesNotAccessMemory();
  2923. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  2924. // Build the operand list.
  2925. SmallVector<SDValue, 8> Ops;
  2926. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  2927. if (OnlyLoad) {
  2928. // We don't need to serialize loads against other loads.
  2929. Ops.push_back(DAG.getRoot());
  2930. } else {
  2931. Ops.push_back(getRoot());
  2932. }
  2933. }
  2934. // Info is set by getTgtMemInstrinsic
  2935. TargetLowering::IntrinsicInfo Info;
  2936. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2937. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  2938. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  2939. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  2940. Info.opc == ISD::INTRINSIC_W_CHAIN)
  2941. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  2942. TLI.getPointerTy(DAG.getDataLayout())));
  2943. // Add all operands of the call to the operand list.
  2944. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  2945. SDValue Op = getValue(I.getArgOperand(i));
  2946. Ops.push_back(Op);
  2947. }
  2948. SmallVector<EVT, 4> ValueVTs;
  2949. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  2950. if (HasChain)
  2951. ValueVTs.push_back(MVT::Other);
  2952. SDVTList VTs = DAG.getVTList(ValueVTs);
  2953. // Create the node.
  2954. SDValue Result;
  2955. if (IsTgtIntrinsic) {
  2956. // This is target intrinsic that touches memory
  2957. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
  2958. VTs, Ops, Info.memVT,
  2959. MachinePointerInfo(Info.ptrVal, Info.offset),
  2960. Info.align, Info.vol,
  2961. Info.readMem, Info.writeMem, Info.size);
  2962. } else if (!HasChain) {
  2963. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  2964. } else if (!I.getType()->isVoidTy()) {
  2965. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  2966. } else {
  2967. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  2968. }
  2969. if (HasChain) {
  2970. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  2971. if (OnlyLoad)
  2972. PendingLoads.push_back(Chain);
  2973. else
  2974. DAG.setRoot(Chain);
  2975. }
  2976. if (!I.getType()->isVoidTy()) {
  2977. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  2978. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  2979. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  2980. }
  2981. setValue(&I, Result);
  2982. }
  2983. }
  2984. /// GetSignificand - Get the significand and build it into a floating-point
  2985. /// number with exponent of 1:
  2986. ///
  2987. /// Op = (Op & 0x007fffff) | 0x3f800000;
  2988. ///
  2989. /// where Op is the hexadecimal representation of floating point value.
  2990. static SDValue
  2991. GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
  2992. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2993. DAG.getConstant(0x007fffff, dl, MVT::i32));
  2994. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  2995. DAG.getConstant(0x3f800000, dl, MVT::i32));
  2996. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  2997. }
  2998. /// GetExponent - Get the exponent:
  2999. ///
  3000. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3001. ///
  3002. /// where Op is the hexadecimal representation of floating point value.
  3003. static SDValue
  3004. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  3005. SDLoc dl) {
  3006. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3007. DAG.getConstant(0x7f800000, dl, MVT::i32));
  3008. SDValue t1 = DAG.getNode(
  3009. ISD::SRL, dl, MVT::i32, t0,
  3010. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  3011. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3012. DAG.getConstant(127, dl, MVT::i32));
  3013. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3014. }
  3015. /// getF32Constant - Get 32-bit floating point constant.
  3016. static SDValue
  3017. getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
  3018. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
  3019. MVT::f32);
  3020. }
  3021. static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
  3022. SelectionDAG &DAG) {
  3023. // IntegerPartOfX = ((int32_t)(t0);
  3024. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3025. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  3026. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3027. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3028. // IntegerPartOfX <<= 23;
  3029. IntegerPartOfX = DAG.getNode(
  3030. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3031. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  3032. DAG.getDataLayout())));
  3033. SDValue TwoToFractionalPartOfX;
  3034. if (LimitFloatPrecision <= 6) {
  3035. // For floating-point precision of 6:
  3036. //
  3037. // TwoToFractionalPartOfX =
  3038. // 0.997535578f +
  3039. // (0.735607626f + 0.252464424f * x) * x;
  3040. //
  3041. // error 0.0144103317, which is 6 bits
  3042. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3043. getF32Constant(DAG, 0x3e814304, dl));
  3044. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3045. getF32Constant(DAG, 0x3f3c50c8, dl));
  3046. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3047. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3048. getF32Constant(DAG, 0x3f7f5e7e, dl));
  3049. } else if (LimitFloatPrecision <= 12) {
  3050. // For floating-point precision of 12:
  3051. //
  3052. // TwoToFractionalPartOfX =
  3053. // 0.999892986f +
  3054. // (0.696457318f +
  3055. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3056. //
  3057. // error 0.000107046256, which is 13 to 14 bits
  3058. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3059. getF32Constant(DAG, 0x3da235e3, dl));
  3060. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3061. getF32Constant(DAG, 0x3e65b8f3, dl));
  3062. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3063. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3064. getF32Constant(DAG, 0x3f324b07, dl));
  3065. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3066. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3067. getF32Constant(DAG, 0x3f7ff8fd, dl));
  3068. } else { // LimitFloatPrecision <= 18
  3069. // For floating-point precision of 18:
  3070. //
  3071. // TwoToFractionalPartOfX =
  3072. // 0.999999982f +
  3073. // (0.693148872f +
  3074. // (0.240227044f +
  3075. // (0.554906021e-1f +
  3076. // (0.961591928e-2f +
  3077. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3078. // error 2.47208000*10^(-7), which is better than 18 bits
  3079. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3080. getF32Constant(DAG, 0x3924b03e, dl));
  3081. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3082. getF32Constant(DAG, 0x3ab24b87, dl));
  3083. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3084. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3085. getF32Constant(DAG, 0x3c1d8c17, dl));
  3086. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3087. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3088. getF32Constant(DAG, 0x3d634a1d, dl));
  3089. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3090. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3091. getF32Constant(DAG, 0x3e75fe14, dl));
  3092. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3093. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3094. getF32Constant(DAG, 0x3f317234, dl));
  3095. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3096. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3097. getF32Constant(DAG, 0x3f800000, dl));
  3098. }
  3099. // Add the exponent into the result in integer domain.
  3100. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  3101. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3102. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  3103. }
  3104. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3105. /// limited-precision mode.
  3106. static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3107. const TargetLowering &TLI) {
  3108. if (Op.getValueType() == MVT::f32 &&
  3109. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3110. // Put the exponent in the right bit position for later addition to the
  3111. // final result:
  3112. //
  3113. // #define LOG2OFe 1.4426950f
  3114. // t0 = Op * LOG2OFe
  3115. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3116. getF32Constant(DAG, 0x3fb8aa3b, dl));
  3117. return getLimitedPrecisionExp2(t0, dl, DAG);
  3118. }
  3119. // No special expansion.
  3120. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3121. }
  3122. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3123. /// limited-precision mode.
  3124. static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3125. const TargetLowering &TLI) {
  3126. if (Op.getValueType() == MVT::f32 &&
  3127. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3128. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3129. // Scale the exponent by log(2) [0.69314718f].
  3130. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3131. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3132. getF32Constant(DAG, 0x3f317218, dl));
  3133. // Get the significand and build it into a floating-point number with
  3134. // exponent of 1.
  3135. SDValue X = GetSignificand(DAG, Op1, dl);
  3136. SDValue LogOfMantissa;
  3137. if (LimitFloatPrecision <= 6) {
  3138. // For floating-point precision of 6:
  3139. //
  3140. // LogofMantissa =
  3141. // -1.1609546f +
  3142. // (1.4034025f - 0.23903021f * x) * x;
  3143. //
  3144. // error 0.0034276066, which is better than 8 bits
  3145. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3146. getF32Constant(DAG, 0xbe74c456, dl));
  3147. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3148. getF32Constant(DAG, 0x3fb3a2b1, dl));
  3149. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3150. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3151. getF32Constant(DAG, 0x3f949a29, dl));
  3152. } else if (LimitFloatPrecision <= 12) {
  3153. // For floating-point precision of 12:
  3154. //
  3155. // LogOfMantissa =
  3156. // -1.7417939f +
  3157. // (2.8212026f +
  3158. // (-1.4699568f +
  3159. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3160. //
  3161. // error 0.000061011436, which is 14 bits
  3162. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3163. getF32Constant(DAG, 0xbd67b6d6, dl));
  3164. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3165. getF32Constant(DAG, 0x3ee4f4b8, dl));
  3166. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3167. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3168. getF32Constant(DAG, 0x3fbc278b, dl));
  3169. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3170. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3171. getF32Constant(DAG, 0x40348e95, dl));
  3172. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3173. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3174. getF32Constant(DAG, 0x3fdef31a, dl));
  3175. } else { // LimitFloatPrecision <= 18
  3176. // For floating-point precision of 18:
  3177. //
  3178. // LogOfMantissa =
  3179. // -2.1072184f +
  3180. // (4.2372794f +
  3181. // (-3.7029485f +
  3182. // (2.2781945f +
  3183. // (-0.87823314f +
  3184. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3185. //
  3186. // error 0.0000023660568, which is better than 18 bits
  3187. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3188. getF32Constant(DAG, 0xbc91e5ac, dl));
  3189. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3190. getF32Constant(DAG, 0x3e4350aa, dl));
  3191. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3192. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3193. getF32Constant(DAG, 0x3f60d3e3, dl));
  3194. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3195. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3196. getF32Constant(DAG, 0x4011cdf0, dl));
  3197. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3198. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3199. getF32Constant(DAG, 0x406cfd1c, dl));
  3200. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3201. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3202. getF32Constant(DAG, 0x408797cb, dl));
  3203. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3204. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3205. getF32Constant(DAG, 0x4006dcab, dl));
  3206. }
  3207. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3208. }
  3209. // No special expansion.
  3210. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3211. }
  3212. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3213. /// limited-precision mode.
  3214. static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3215. const TargetLowering &TLI) {
  3216. if (Op.getValueType() == MVT::f32 &&
  3217. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3218. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3219. // Get the exponent.
  3220. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3221. // Get the significand and build it into a floating-point number with
  3222. // exponent of 1.
  3223. SDValue X = GetSignificand(DAG, Op1, dl);
  3224. // Different possible minimax approximations of significand in
  3225. // floating-point for various degrees of accuracy over [1,2].
  3226. SDValue Log2ofMantissa;
  3227. if (LimitFloatPrecision <= 6) {
  3228. // For floating-point precision of 6:
  3229. //
  3230. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3231. //
  3232. // error 0.0049451742, which is more than 7 bits
  3233. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3234. getF32Constant(DAG, 0xbeb08fe0, dl));
  3235. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3236. getF32Constant(DAG, 0x40019463, dl));
  3237. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3238. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3239. getF32Constant(DAG, 0x3fd6633d, dl));
  3240. } else if (LimitFloatPrecision <= 12) {
  3241. // For floating-point precision of 12:
  3242. //
  3243. // Log2ofMantissa =
  3244. // -2.51285454f +
  3245. // (4.07009056f +
  3246. // (-2.12067489f +
  3247. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3248. //
  3249. // error 0.0000876136000, which is better than 13 bits
  3250. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3251. getF32Constant(DAG, 0xbda7262e, dl));
  3252. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3253. getF32Constant(DAG, 0x3f25280b, dl));
  3254. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3255. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3256. getF32Constant(DAG, 0x4007b923, dl));
  3257. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3258. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3259. getF32Constant(DAG, 0x40823e2f, dl));
  3260. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3261. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3262. getF32Constant(DAG, 0x4020d29c, dl));
  3263. } else { // LimitFloatPrecision <= 18
  3264. // For floating-point precision of 18:
  3265. //
  3266. // Log2ofMantissa =
  3267. // -3.0400495f +
  3268. // (6.1129976f +
  3269. // (-5.3420409f +
  3270. // (3.2865683f +
  3271. // (-1.2669343f +
  3272. // (0.27515199f -
  3273. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3274. //
  3275. // error 0.0000018516, which is better than 18 bits
  3276. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3277. getF32Constant(DAG, 0xbcd2769e, dl));
  3278. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3279. getF32Constant(DAG, 0x3e8ce0b9, dl));
  3280. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3281. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3282. getF32Constant(DAG, 0x3fa22ae7, dl));
  3283. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3284. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3285. getF32Constant(DAG, 0x40525723, dl));
  3286. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3287. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3288. getF32Constant(DAG, 0x40aaf200, dl));
  3289. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3290. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3291. getF32Constant(DAG, 0x40c39dad, dl));
  3292. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3293. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3294. getF32Constant(DAG, 0x4042902c, dl));
  3295. }
  3296. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  3297. }
  3298. // No special expansion.
  3299. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  3300. }
  3301. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3302. /// limited-precision mode.
  3303. static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3304. const TargetLowering &TLI) {
  3305. if (Op.getValueType() == MVT::f32 &&
  3306. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3307. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3308. // Scale the exponent by log10(2) [0.30102999f].
  3309. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3310. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3311. getF32Constant(DAG, 0x3e9a209a, dl));
  3312. // Get the significand and build it into a floating-point number with
  3313. // exponent of 1.
  3314. SDValue X = GetSignificand(DAG, Op1, dl);
  3315. SDValue Log10ofMantissa;
  3316. if (LimitFloatPrecision <= 6) {
  3317. // For floating-point precision of 6:
  3318. //
  3319. // Log10ofMantissa =
  3320. // -0.50419619f +
  3321. // (0.60948995f - 0.10380950f * x) * x;
  3322. //
  3323. // error 0.0014886165, which is 6 bits
  3324. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3325. getF32Constant(DAG, 0xbdd49a13, dl));
  3326. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3327. getF32Constant(DAG, 0x3f1c0789, dl));
  3328. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3329. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3330. getF32Constant(DAG, 0x3f011300, dl));
  3331. } else if (LimitFloatPrecision <= 12) {
  3332. // For floating-point precision of 12:
  3333. //
  3334. // Log10ofMantissa =
  3335. // -0.64831180f +
  3336. // (0.91751397f +
  3337. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3338. //
  3339. // error 0.00019228036, which is better than 12 bits
  3340. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3341. getF32Constant(DAG, 0x3d431f31, dl));
  3342. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3343. getF32Constant(DAG, 0x3ea21fb2, dl));
  3344. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3345. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3346. getF32Constant(DAG, 0x3f6ae232, dl));
  3347. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3348. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3349. getF32Constant(DAG, 0x3f25f7c3, dl));
  3350. } else { // LimitFloatPrecision <= 18
  3351. // For floating-point precision of 18:
  3352. //
  3353. // Log10ofMantissa =
  3354. // -0.84299375f +
  3355. // (1.5327582f +
  3356. // (-1.0688956f +
  3357. // (0.49102474f +
  3358. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3359. //
  3360. // error 0.0000037995730, which is better than 18 bits
  3361. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3362. getF32Constant(DAG, 0x3c5d51ce, dl));
  3363. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3364. getF32Constant(DAG, 0x3e00685a, dl));
  3365. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3366. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3367. getF32Constant(DAG, 0x3efb6798, dl));
  3368. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3369. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3370. getF32Constant(DAG, 0x3f88d192, dl));
  3371. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3372. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3373. getF32Constant(DAG, 0x3fc4316c, dl));
  3374. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3375. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3376. getF32Constant(DAG, 0x3f57ce70, dl));
  3377. }
  3378. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  3379. }
  3380. // No special expansion.
  3381. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  3382. }
  3383. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3384. /// limited-precision mode.
  3385. static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3386. const TargetLowering &TLI) {
  3387. if (Op.getValueType() == MVT::f32 &&
  3388. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  3389. return getLimitedPrecisionExp2(Op, dl, DAG);
  3390. // No special expansion.
  3391. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  3392. }
  3393. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3394. /// limited-precision mode with x == 10.0f.
  3395. static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
  3396. SelectionDAG &DAG, const TargetLowering &TLI) {
  3397. bool IsExp10 = false;
  3398. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  3399. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3400. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  3401. APFloat Ten(10.0f);
  3402. IsExp10 = LHSC->isExactlyValue(Ten);
  3403. }
  3404. }
  3405. if (IsExp10) {
  3406. // Put the exponent in the right bit position for later addition to the
  3407. // final result:
  3408. //
  3409. // #define LOG2OF10 3.3219281f
  3410. // t0 = Op * LOG2OF10;
  3411. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  3412. getF32Constant(DAG, 0x40549a78, dl));
  3413. return getLimitedPrecisionExp2(t0, dl, DAG);
  3414. }
  3415. // No special expansion.
  3416. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  3417. }
  3418. /// ExpandPowI - Expand a llvm.powi intrinsic.
  3419. static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
  3420. SelectionDAG &DAG) {
  3421. // If RHS is a constant, we can expand this out to a multiplication tree,
  3422. // otherwise we end up lowering to a call to __powidf2 (for example). When
  3423. // optimizing for size, we only want to do this if the expansion would produce
  3424. // a small number of multiplies, otherwise we do the full expansion.
  3425. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  3426. // Get the exponent as a positive value.
  3427. unsigned Val = RHSC->getSExtValue();
  3428. if ((int)Val < 0) Val = -Val;
  3429. // powi(x, 0) -> 1.0
  3430. if (Val == 0)
  3431. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  3432. const Function *F = DAG.getMachineFunction().getFunction();
  3433. if (!F->hasFnAttribute(Attribute::OptimizeForSize) ||
  3434. // If optimizing for size, don't insert too many multiplies. This
  3435. // inserts up to 5 multiplies.
  3436. countPopulation(Val) + Log2_32(Val) < 7) {
  3437. // We use the simple binary decomposition method to generate the multiply
  3438. // sequence. There are more optimal ways to do this (for example,
  3439. // powi(x,15) generates one more multiply than it should), but this has
  3440. // the benefit of being both really simple and much better than a libcall.
  3441. SDValue Res; // Logically starts equal to 1.0
  3442. SDValue CurSquare = LHS;
  3443. while (Val) {
  3444. if (Val & 1) {
  3445. if (Res.getNode())
  3446. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  3447. else
  3448. Res = CurSquare; // 1.0*CurSquare.
  3449. }
  3450. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  3451. CurSquare, CurSquare);
  3452. Val >>= 1;
  3453. }
  3454. // If the original was negative, invert the result, producing 1/(x*x*x).
  3455. if (RHSC->getSExtValue() < 0)
  3456. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  3457. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  3458. return Res;
  3459. }
  3460. }
  3461. // Otherwise, expand to a libcall.
  3462. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  3463. }
  3464. // getTruncatedArgReg - Find underlying register used for an truncated
  3465. // argument.
  3466. static unsigned getTruncatedArgReg(const SDValue &N) {
  3467. if (N.getOpcode() != ISD::TRUNCATE)
  3468. return 0;
  3469. const SDValue &Ext = N.getOperand(0);
  3470. if (Ext.getOpcode() == ISD::AssertZext ||
  3471. Ext.getOpcode() == ISD::AssertSext) {
  3472. const SDValue &CFR = Ext.getOperand(0);
  3473. if (CFR.getOpcode() == ISD::CopyFromReg)
  3474. return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
  3475. if (CFR.getOpcode() == ISD::TRUNCATE)
  3476. return getTruncatedArgReg(CFR);
  3477. }
  3478. return 0;
  3479. }
  3480. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  3481. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  3482. /// At the end of instruction selection, they will be inserted to the entry BB.
  3483. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  3484. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  3485. DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
  3486. const Argument *Arg = dyn_cast<Argument>(V);
  3487. if (!Arg)
  3488. return false;
  3489. MachineFunction &MF = DAG.getMachineFunction();
  3490. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  3491. // Ignore inlined function arguments here.
  3492. //
  3493. // FIXME: Should we be checking DL->inlinedAt() to determine this?
  3494. if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
  3495. return false;
  3496. Optional<MachineOperand> Op;
  3497. // Some arguments' frame index is recorded during argument lowering.
  3498. if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
  3499. Op = MachineOperand::CreateFI(FI);
  3500. if (!Op && N.getNode()) {
  3501. unsigned Reg;
  3502. if (N.getOpcode() == ISD::CopyFromReg)
  3503. Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
  3504. else
  3505. Reg = getTruncatedArgReg(N);
  3506. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  3507. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  3508. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  3509. if (PR)
  3510. Reg = PR;
  3511. }
  3512. if (Reg)
  3513. Op = MachineOperand::CreateReg(Reg, false);
  3514. }
  3515. if (!Op) {
  3516. // Check if ValueMap has reg number.
  3517. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  3518. if (VMI != FuncInfo.ValueMap.end())
  3519. Op = MachineOperand::CreateReg(VMI->second, false);
  3520. }
  3521. if (!Op && N.getNode())
  3522. // Check if frame index is available.
  3523. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  3524. if (FrameIndexSDNode *FINode =
  3525. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  3526. Op = MachineOperand::CreateFI(FINode->getIndex());
  3527. if (!Op)
  3528. return false;
  3529. assert(Variable->isValidLocationForIntrinsic(DL) &&
  3530. "Expected inlined-at fields to agree");
  3531. if (Op->isReg())
  3532. FuncInfo.ArgDbgValues.push_back(
  3533. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  3534. Op->getReg(), Offset, Variable, Expr));
  3535. else
  3536. FuncInfo.ArgDbgValues.push_back(
  3537. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
  3538. .addOperand(*Op)
  3539. .addImm(Offset)
  3540. .addMetadata(Variable)
  3541. .addMetadata(Expr));
  3542. return true;
  3543. }
  3544. // VisualStudio defines setjmp as _setjmp
  3545. #if defined(_MSC_VER) && defined(setjmp) && \
  3546. !defined(setjmp_undefined_for_msvc)
  3547. # pragma push_macro("setjmp")
  3548. # undef setjmp
  3549. # define setjmp_undefined_for_msvc
  3550. #endif
  3551. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  3552. /// we want to emit this as a call to a named external function, return the name
  3553. /// otherwise lower it and return null.
  3554. const char *
  3555. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  3556. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3557. SDLoc sdl = getCurSDLoc();
  3558. DebugLoc dl = getCurDebugLoc();
  3559. SDValue Res;
  3560. switch (Intrinsic) {
  3561. default:
  3562. // By default, turn this into a target intrinsic node.
  3563. visitTargetIntrinsic(I, Intrinsic);
  3564. return nullptr;
  3565. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  3566. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  3567. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  3568. case Intrinsic::returnaddress:
  3569. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  3570. TLI.getPointerTy(DAG.getDataLayout()),
  3571. getValue(I.getArgOperand(0))));
  3572. return nullptr;
  3573. case Intrinsic::frameaddress:
  3574. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  3575. TLI.getPointerTy(DAG.getDataLayout()),
  3576. getValue(I.getArgOperand(0))));
  3577. return nullptr;
  3578. case Intrinsic::read_register: {
  3579. Value *Reg = I.getArgOperand(0);
  3580. SDValue Chain = getRoot();
  3581. SDValue RegName =
  3582. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  3583. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3584. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  3585. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  3586. setValue(&I, Res);
  3587. DAG.setRoot(Res.getValue(1));
  3588. return nullptr;
  3589. }
  3590. case Intrinsic::write_register: {
  3591. Value *Reg = I.getArgOperand(0);
  3592. Value *RegValue = I.getArgOperand(1);
  3593. SDValue Chain = getRoot();
  3594. SDValue RegName =
  3595. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  3596. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  3597. RegName, getValue(RegValue)));
  3598. return nullptr;
  3599. }
  3600. case Intrinsic::setjmp:
  3601. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  3602. case Intrinsic::longjmp:
  3603. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  3604. case Intrinsic::memcpy: {
  3605. // FIXME: this definition of "user defined address space" is x86-specific
  3606. // Assert for address < 256 since we support only user defined address
  3607. // spaces.
  3608. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3609. < 256 &&
  3610. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  3611. < 256 &&
  3612. "Unknown address space");
  3613. SDValue Op1 = getValue(I.getArgOperand(0));
  3614. SDValue Op2 = getValue(I.getArgOperand(1));
  3615. SDValue Op3 = getValue(I.getArgOperand(2));
  3616. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3617. if (!Align)
  3618. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  3619. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3620. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  3621. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  3622. false, isTC,
  3623. MachinePointerInfo(I.getArgOperand(0)),
  3624. MachinePointerInfo(I.getArgOperand(1)));
  3625. updateDAGForMaybeTailCall(MC);
  3626. return nullptr;
  3627. }
  3628. case Intrinsic::memset: {
  3629. // FIXME: this definition of "user defined address space" is x86-specific
  3630. // Assert for address < 256 since we support only user defined address
  3631. // spaces.
  3632. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3633. < 256 &&
  3634. "Unknown address space");
  3635. SDValue Op1 = getValue(I.getArgOperand(0));
  3636. SDValue Op2 = getValue(I.getArgOperand(1));
  3637. SDValue Op3 = getValue(I.getArgOperand(2));
  3638. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3639. if (!Align)
  3640. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  3641. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3642. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  3643. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  3644. isTC, MachinePointerInfo(I.getArgOperand(0)));
  3645. updateDAGForMaybeTailCall(MS);
  3646. return nullptr;
  3647. }
  3648. case Intrinsic::memmove: {
  3649. // FIXME: this definition of "user defined address space" is x86-specific
  3650. // Assert for address < 256 since we support only user defined address
  3651. // spaces.
  3652. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3653. < 256 &&
  3654. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  3655. < 256 &&
  3656. "Unknown address space");
  3657. SDValue Op1 = getValue(I.getArgOperand(0));
  3658. SDValue Op2 = getValue(I.getArgOperand(1));
  3659. SDValue Op3 = getValue(I.getArgOperand(2));
  3660. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3661. if (!Align)
  3662. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  3663. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3664. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  3665. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  3666. isTC, MachinePointerInfo(I.getArgOperand(0)),
  3667. MachinePointerInfo(I.getArgOperand(1)));
  3668. updateDAGForMaybeTailCall(MM);
  3669. return nullptr;
  3670. }
  3671. case Intrinsic::dbg_declare: {
  3672. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  3673. DILocalVariable *Variable = DI.getVariable();
  3674. DIExpression *Expression = DI.getExpression();
  3675. const Value *Address = DI.getAddress();
  3676. assert(Variable && "Missing variable");
  3677. if (!Address) {
  3678. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  3679. return nullptr;
  3680. }
  3681. // Check if address has undef value.
  3682. if (isa<UndefValue>(Address) ||
  3683. (Address->use_empty() && !isa<Argument>(Address))) {
  3684. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  3685. return nullptr;
  3686. }
  3687. SDValue &N = NodeMap[Address];
  3688. if (!N.getNode() && isa<Argument>(Address))
  3689. // Check unused arguments map.
  3690. N = UnusedArgNodeMap[Address];
  3691. SDDbgValue *SDV;
  3692. if (N.getNode()) {
  3693. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  3694. Address = BCI->getOperand(0);
  3695. // Parameters are handled specially.
  3696. bool isParameter = Variable->getTag() == dwarf::DW_TAG_arg_variable ||
  3697. isa<Argument>(Address);
  3698. const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
  3699. if (isParameter && !AI) {
  3700. FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  3701. if (FINode)
  3702. // Byval parameter. We have a frame index at this point.
  3703. SDV = DAG.getFrameIndexDbgValue(
  3704. Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
  3705. else {
  3706. // Address is an argument, so try to emit its dbg value using
  3707. // virtual register info from the FuncInfo.ValueMap.
  3708. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
  3709. N);
  3710. return nullptr;
  3711. }
  3712. } else if (AI)
  3713. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  3714. true, 0, dl, SDNodeOrder);
  3715. else {
  3716. // Can't do anything with other non-AI cases yet.
  3717. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  3718. DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
  3719. DEBUG(Address->dump());
  3720. return nullptr;
  3721. }
  3722. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  3723. } else {
  3724. // If Address is an argument then try to emit its dbg value using
  3725. // virtual register info from the FuncInfo.ValueMap.
  3726. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
  3727. N)) {
  3728. // If variable is pinned by a alloca in dominating bb then
  3729. // use StaticAllocaMap.
  3730. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  3731. if (AI->getParent() != DI.getParent()) {
  3732. DenseMap<const AllocaInst*, int>::iterator SI =
  3733. FuncInfo.StaticAllocaMap.find(AI);
  3734. if (SI != FuncInfo.StaticAllocaMap.end()) {
  3735. SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
  3736. 0, dl, SDNodeOrder);
  3737. DAG.AddDbgValue(SDV, nullptr, false);
  3738. return nullptr;
  3739. }
  3740. }
  3741. }
  3742. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  3743. }
  3744. }
  3745. return nullptr;
  3746. }
  3747. case Intrinsic::dbg_value: {
  3748. const DbgValueInst &DI = cast<DbgValueInst>(I);
  3749. assert(DI.getVariable() && "Missing variable");
  3750. DILocalVariable *Variable = DI.getVariable();
  3751. DIExpression *Expression = DI.getExpression();
  3752. uint64_t Offset = DI.getOffset();
  3753. const Value *V = DI.getValue();
  3754. if (!V)
  3755. return nullptr;
  3756. SDDbgValue *SDV;
  3757. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  3758. SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
  3759. SDNodeOrder);
  3760. DAG.AddDbgValue(SDV, nullptr, false);
  3761. } else {
  3762. // Do not use getValue() in here; we don't want to generate code at
  3763. // this point if it hasn't been done yet.
  3764. SDValue N = NodeMap[V];
  3765. if (!N.getNode() && isa<Argument>(V))
  3766. // Check unused arguments map.
  3767. N = UnusedArgNodeMap[V];
  3768. if (N.getNode()) {
  3769. // A dbg.value for an alloca is always indirect.
  3770. bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
  3771. if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
  3772. IsIndirect, N)) {
  3773. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  3774. IsIndirect, Offset, dl, SDNodeOrder);
  3775. DAG.AddDbgValue(SDV, N.getNode(), false);
  3776. }
  3777. } else if (!V->use_empty() ) {
  3778. // Do not call getValue(V) yet, as we don't want to generate code.
  3779. // Remember it for later.
  3780. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  3781. DanglingDebugInfoMap[V] = DDI;
  3782. } else {
  3783. // We may expand this to cover more cases. One case where we have no
  3784. // data available is an unreferenced parameter.
  3785. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  3786. }
  3787. }
  3788. // Build a debug info table entry.
  3789. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  3790. V = BCI->getOperand(0);
  3791. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  3792. // Don't handle byval struct arguments or VLAs, for example.
  3793. if (!AI) {
  3794. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  3795. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  3796. return nullptr;
  3797. }
  3798. DenseMap<const AllocaInst*, int>::iterator SI =
  3799. FuncInfo.StaticAllocaMap.find(AI);
  3800. if (SI == FuncInfo.StaticAllocaMap.end())
  3801. return nullptr; // VLAs.
  3802. return nullptr;
  3803. }
  3804. case Intrinsic::eh_typeid_for: {
  3805. // Find the type id for the given typeinfo.
  3806. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  3807. unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
  3808. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  3809. setValue(&I, Res);
  3810. return nullptr;
  3811. }
  3812. case Intrinsic::eh_return_i32:
  3813. case Intrinsic::eh_return_i64:
  3814. DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
  3815. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  3816. MVT::Other,
  3817. getControlRoot(),
  3818. getValue(I.getArgOperand(0)),
  3819. getValue(I.getArgOperand(1))));
  3820. return nullptr;
  3821. case Intrinsic::eh_unwind_init:
  3822. DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
  3823. return nullptr;
  3824. case Intrinsic::eh_dwarf_cfa: {
  3825. SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
  3826. TLI.getPointerTy(DAG.getDataLayout()));
  3827. SDValue Offset = DAG.getNode(ISD::ADD, sdl,
  3828. CfaArg.getValueType(),
  3829. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
  3830. CfaArg.getValueType()),
  3831. CfaArg);
  3832. SDValue FA = DAG.getNode(
  3833. ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()),
  3834. DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
  3835. setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
  3836. FA, Offset));
  3837. return nullptr;
  3838. }
  3839. case Intrinsic::eh_sjlj_callsite: {
  3840. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  3841. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  3842. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  3843. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  3844. MMI.setCurrentCallSite(CI->getZExtValue());
  3845. return nullptr;
  3846. }
  3847. case Intrinsic::eh_sjlj_functioncontext: {
  3848. // Get and store the index of the function context.
  3849. MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
  3850. AllocaInst *FnCtx =
  3851. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  3852. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  3853. MFI->setFunctionContextIndex(FI);
  3854. return nullptr;
  3855. }
  3856. case Intrinsic::eh_sjlj_setjmp: {
  3857. SDValue Ops[2];
  3858. Ops[0] = getRoot();
  3859. Ops[1] = getValue(I.getArgOperand(0));
  3860. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  3861. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  3862. setValue(&I, Op.getValue(0));
  3863. DAG.setRoot(Op.getValue(1));
  3864. return nullptr;
  3865. }
  3866. case Intrinsic::eh_sjlj_longjmp: {
  3867. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  3868. getRoot(), getValue(I.getArgOperand(0))));
  3869. return nullptr;
  3870. }
  3871. case Intrinsic::masked_gather:
  3872. visitMaskedGather(I);
  3873. return nullptr;
  3874. case Intrinsic::masked_load:
  3875. visitMaskedLoad(I);
  3876. return nullptr;
  3877. case Intrinsic::masked_scatter:
  3878. visitMaskedScatter(I);
  3879. return nullptr;
  3880. case Intrinsic::masked_store:
  3881. visitMaskedStore(I);
  3882. return nullptr;
  3883. #if 0 // HLSL Change - remove platform intrinsics
  3884. case Intrinsic::x86_mmx_pslli_w:
  3885. case Intrinsic::x86_mmx_pslli_d:
  3886. case Intrinsic::x86_mmx_pslli_q:
  3887. case Intrinsic::x86_mmx_psrli_w:
  3888. case Intrinsic::x86_mmx_psrli_d:
  3889. case Intrinsic::x86_mmx_psrli_q:
  3890. case Intrinsic::x86_mmx_psrai_w:
  3891. case Intrinsic::x86_mmx_psrai_d: {
  3892. SDValue ShAmt = getValue(I.getArgOperand(1));
  3893. if (isa<ConstantSDNode>(ShAmt)) {
  3894. visitTargetIntrinsic(I, Intrinsic);
  3895. return nullptr;
  3896. }
  3897. unsigned NewIntrinsic = 0;
  3898. EVT ShAmtVT = MVT::v2i32;
  3899. switch (Intrinsic) {
  3900. case Intrinsic::x86_mmx_pslli_w:
  3901. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  3902. break;
  3903. case Intrinsic::x86_mmx_pslli_d:
  3904. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  3905. break;
  3906. case Intrinsic::x86_mmx_pslli_q:
  3907. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  3908. break;
  3909. case Intrinsic::x86_mmx_psrli_w:
  3910. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  3911. break;
  3912. case Intrinsic::x86_mmx_psrli_d:
  3913. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  3914. break;
  3915. case Intrinsic::x86_mmx_psrli_q:
  3916. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  3917. break;
  3918. case Intrinsic::x86_mmx_psrai_w:
  3919. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  3920. break;
  3921. case Intrinsic::x86_mmx_psrai_d:
  3922. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  3923. break;
  3924. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  3925. }
  3926. // The vector shift intrinsics with scalars uses 32b shift amounts but
  3927. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  3928. // to be zero.
  3929. // We must do this early because v2i32 is not a legal type.
  3930. SDValue ShOps[2];
  3931. ShOps[0] = ShAmt;
  3932. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  3933. ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
  3934. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3935. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  3936. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  3937. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  3938. getValue(I.getArgOperand(0)), ShAmt);
  3939. setValue(&I, Res);
  3940. return nullptr;
  3941. }
  3942. #endif // HLSL Change - remove platform intrinsics
  3943. case Intrinsic::convertff:
  3944. case Intrinsic::convertfsi:
  3945. case Intrinsic::convertfui:
  3946. case Intrinsic::convertsif:
  3947. case Intrinsic::convertuif:
  3948. case Intrinsic::convertss:
  3949. case Intrinsic::convertsu:
  3950. case Intrinsic::convertus:
  3951. case Intrinsic::convertuu: {
  3952. ISD::CvtCode Code = ISD::CVT_INVALID;
  3953. switch (Intrinsic) {
  3954. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  3955. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  3956. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  3957. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  3958. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  3959. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  3960. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  3961. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  3962. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  3963. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  3964. }
  3965. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3966. const Value *Op1 = I.getArgOperand(0);
  3967. Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
  3968. DAG.getValueType(DestVT),
  3969. DAG.getValueType(getValue(Op1).getValueType()),
  3970. getValue(I.getArgOperand(1)),
  3971. getValue(I.getArgOperand(2)),
  3972. Code);
  3973. setValue(&I, Res);
  3974. return nullptr;
  3975. }
  3976. case Intrinsic::powi:
  3977. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  3978. getValue(I.getArgOperand(1)), DAG));
  3979. return nullptr;
  3980. case Intrinsic::log:
  3981. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  3982. return nullptr;
  3983. case Intrinsic::log2:
  3984. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  3985. return nullptr;
  3986. case Intrinsic::log10:
  3987. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  3988. return nullptr;
  3989. case Intrinsic::exp:
  3990. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  3991. return nullptr;
  3992. case Intrinsic::exp2:
  3993. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  3994. return nullptr;
  3995. case Intrinsic::pow:
  3996. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  3997. getValue(I.getArgOperand(1)), DAG, TLI));
  3998. return nullptr;
  3999. case Intrinsic::sqrt:
  4000. case Intrinsic::fabs:
  4001. case Intrinsic::sin:
  4002. case Intrinsic::cos:
  4003. case Intrinsic::floor:
  4004. case Intrinsic::ceil:
  4005. case Intrinsic::trunc:
  4006. case Intrinsic::rint:
  4007. case Intrinsic::nearbyint:
  4008. case Intrinsic::round: {
  4009. unsigned Opcode;
  4010. switch (Intrinsic) {
  4011. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4012. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4013. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4014. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4015. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4016. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4017. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4018. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4019. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4020. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4021. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4022. }
  4023. setValue(&I, DAG.getNode(Opcode, sdl,
  4024. getValue(I.getArgOperand(0)).getValueType(),
  4025. getValue(I.getArgOperand(0))));
  4026. return nullptr;
  4027. }
  4028. case Intrinsic::minnum:
  4029. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  4030. getValue(I.getArgOperand(0)).getValueType(),
  4031. getValue(I.getArgOperand(0)),
  4032. getValue(I.getArgOperand(1))));
  4033. return nullptr;
  4034. case Intrinsic::maxnum:
  4035. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  4036. getValue(I.getArgOperand(0)).getValueType(),
  4037. getValue(I.getArgOperand(0)),
  4038. getValue(I.getArgOperand(1))));
  4039. return nullptr;
  4040. case Intrinsic::copysign:
  4041. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4042. getValue(I.getArgOperand(0)).getValueType(),
  4043. getValue(I.getArgOperand(0)),
  4044. getValue(I.getArgOperand(1))));
  4045. return nullptr;
  4046. case Intrinsic::fma:
  4047. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4048. getValue(I.getArgOperand(0)).getValueType(),
  4049. getValue(I.getArgOperand(0)),
  4050. getValue(I.getArgOperand(1)),
  4051. getValue(I.getArgOperand(2))));
  4052. return nullptr;
  4053. case Intrinsic::fmuladd: {
  4054. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4055. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4056. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4057. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4058. getValue(I.getArgOperand(0)).getValueType(),
  4059. getValue(I.getArgOperand(0)),
  4060. getValue(I.getArgOperand(1)),
  4061. getValue(I.getArgOperand(2))));
  4062. } else {
  4063. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4064. getValue(I.getArgOperand(0)).getValueType(),
  4065. getValue(I.getArgOperand(0)),
  4066. getValue(I.getArgOperand(1)));
  4067. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4068. getValue(I.getArgOperand(0)).getValueType(),
  4069. Mul,
  4070. getValue(I.getArgOperand(2)));
  4071. setValue(&I, Add);
  4072. }
  4073. return nullptr;
  4074. }
  4075. case Intrinsic::convert_to_fp16:
  4076. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4077. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4078. getValue(I.getArgOperand(0)),
  4079. DAG.getTargetConstant(0, sdl,
  4080. MVT::i32))));
  4081. return nullptr;
  4082. case Intrinsic::convert_from_fp16:
  4083. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  4084. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  4085. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4086. getValue(I.getArgOperand(0)))));
  4087. return nullptr;
  4088. case Intrinsic::pcmarker: {
  4089. SDValue Tmp = getValue(I.getArgOperand(0));
  4090. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4091. return nullptr;
  4092. }
  4093. case Intrinsic::readcyclecounter: {
  4094. SDValue Op = getRoot();
  4095. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4096. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4097. setValue(&I, Res);
  4098. DAG.setRoot(Res.getValue(1));
  4099. return nullptr;
  4100. }
  4101. case Intrinsic::bswap:
  4102. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4103. getValue(I.getArgOperand(0)).getValueType(),
  4104. getValue(I.getArgOperand(0))));
  4105. return nullptr;
  4106. case Intrinsic::cttz: {
  4107. SDValue Arg = getValue(I.getArgOperand(0));
  4108. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4109. EVT Ty = Arg.getValueType();
  4110. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4111. sdl, Ty, Arg));
  4112. return nullptr;
  4113. }
  4114. case Intrinsic::ctlz: {
  4115. SDValue Arg = getValue(I.getArgOperand(0));
  4116. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4117. EVT Ty = Arg.getValueType();
  4118. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4119. sdl, Ty, Arg));
  4120. return nullptr;
  4121. }
  4122. case Intrinsic::ctpop: {
  4123. SDValue Arg = getValue(I.getArgOperand(0));
  4124. EVT Ty = Arg.getValueType();
  4125. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4126. return nullptr;
  4127. }
  4128. case Intrinsic::stacksave: {
  4129. SDValue Op = getRoot();
  4130. Res = DAG.getNode(
  4131. ISD::STACKSAVE, sdl,
  4132. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  4133. setValue(&I, Res);
  4134. DAG.setRoot(Res.getValue(1));
  4135. return nullptr;
  4136. }
  4137. case Intrinsic::stackrestore: {
  4138. Res = getValue(I.getArgOperand(0));
  4139. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4140. return nullptr;
  4141. }
  4142. case Intrinsic::stackprotector: {
  4143. // Emit code into the DAG to store the stack guard onto the stack.
  4144. MachineFunction &MF = DAG.getMachineFunction();
  4145. MachineFrameInfo *MFI = MF.getFrameInfo();
  4146. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4147. SDValue Src, Chain = getRoot();
  4148. const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
  4149. const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
  4150. // See if Ptr is a bitcast. If it is, look through it and see if we can get
  4151. // global variable __stack_chk_guard.
  4152. if (!GV)
  4153. if (const Operator *BC = dyn_cast<Operator>(Ptr))
  4154. if (BC->getOpcode() == Instruction::BitCast)
  4155. GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
  4156. if (GV && TLI.useLoadStackGuardNode()) {
  4157. // Emit a LOAD_STACK_GUARD node.
  4158. MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
  4159. sdl, PtrTy, Chain);
  4160. MachinePointerInfo MPInfo(GV);
  4161. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  4162. unsigned Flags = MachineMemOperand::MOLoad |
  4163. MachineMemOperand::MOInvariant;
  4164. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
  4165. PtrTy.getSizeInBits() / 8,
  4166. DAG.getEVTAlignment(PtrTy));
  4167. Node->setMemRefs(MemRefs, MemRefs + 1);
  4168. // Copy the guard value to a virtual register so that it can be
  4169. // retrieved in the epilogue.
  4170. Src = SDValue(Node, 0);
  4171. const TargetRegisterClass *RC =
  4172. TLI.getRegClassFor(Src.getSimpleValueType());
  4173. unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
  4174. SPDescriptor.setGuardReg(Reg);
  4175. Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
  4176. } else {
  4177. Src = getValue(I.getArgOperand(0)); // The guard's value.
  4178. }
  4179. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4180. int FI = FuncInfo.StaticAllocaMap[Slot];
  4181. MFI->setStackProtectorIndex(FI);
  4182. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4183. // Store the stack protector onto the stack.
  4184. Res = DAG.getStore(Chain, sdl, Src, FIN,
  4185. MachinePointerInfo::getFixedStack(FI),
  4186. true, false, 0);
  4187. setValue(&I, Res);
  4188. DAG.setRoot(Res);
  4189. return nullptr;
  4190. }
  4191. case Intrinsic::objectsize: {
  4192. // If we don't know by now, we're never going to know.
  4193. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4194. assert(CI && "Non-constant type in __builtin_object_size?");
  4195. SDValue Arg = getValue(I.getCalledValue());
  4196. EVT Ty = Arg.getValueType();
  4197. if (CI->isZero())
  4198. Res = DAG.getConstant(-1ULL, sdl, Ty);
  4199. else
  4200. Res = DAG.getConstant(0, sdl, Ty);
  4201. setValue(&I, Res);
  4202. return nullptr;
  4203. }
  4204. case Intrinsic::annotation:
  4205. case Intrinsic::ptr_annotation:
  4206. // Drop the intrinsic, but forward the value
  4207. setValue(&I, getValue(I.getOperand(0)));
  4208. return nullptr;
  4209. case Intrinsic::assume:
  4210. case Intrinsic::var_annotation:
  4211. // Discard annotate attributes and assumptions
  4212. return nullptr;
  4213. case Intrinsic::init_trampoline: {
  4214. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4215. SDValue Ops[6];
  4216. Ops[0] = getRoot();
  4217. Ops[1] = getValue(I.getArgOperand(0));
  4218. Ops[2] = getValue(I.getArgOperand(1));
  4219. Ops[3] = getValue(I.getArgOperand(2));
  4220. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4221. Ops[5] = DAG.getSrcValue(F);
  4222. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  4223. DAG.setRoot(Res);
  4224. return nullptr;
  4225. }
  4226. case Intrinsic::adjust_trampoline: {
  4227. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  4228. TLI.getPointerTy(DAG.getDataLayout()),
  4229. getValue(I.getArgOperand(0))));
  4230. return nullptr;
  4231. }
  4232. case Intrinsic::gcroot:
  4233. if (GFI) {
  4234. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  4235. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4236. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4237. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4238. }
  4239. return nullptr;
  4240. case Intrinsic::gcread:
  4241. case Intrinsic::gcwrite:
  4242. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4243. case Intrinsic::flt_rounds:
  4244. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  4245. return nullptr;
  4246. case Intrinsic::expect: {
  4247. // Just replace __builtin_expect(exp, c) with EXP.
  4248. setValue(&I, getValue(I.getArgOperand(0)));
  4249. return nullptr;
  4250. }
  4251. case Intrinsic::debugtrap:
  4252. case Intrinsic::trap: {
  4253. StringRef TrapFuncName =
  4254. I.getAttributes()
  4255. .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
  4256. .getValueAsString();
  4257. if (TrapFuncName.empty()) {
  4258. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  4259. ISD::TRAP : ISD::DEBUGTRAP;
  4260. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  4261. return nullptr;
  4262. }
  4263. TargetLowering::ArgListTy Args;
  4264. TargetLowering::CallLoweringInfo CLI(DAG);
  4265. CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
  4266. CallingConv::C, I.getType(),
  4267. DAG.getExternalSymbol(TrapFuncName.data(),
  4268. TLI.getPointerTy(DAG.getDataLayout())),
  4269. std::move(Args), 0);
  4270. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  4271. DAG.setRoot(Result.second);
  4272. return nullptr;
  4273. }
  4274. case Intrinsic::uadd_with_overflow:
  4275. case Intrinsic::sadd_with_overflow:
  4276. case Intrinsic::usub_with_overflow:
  4277. case Intrinsic::ssub_with_overflow:
  4278. case Intrinsic::umul_with_overflow:
  4279. case Intrinsic::smul_with_overflow: {
  4280. ISD::NodeType Op;
  4281. switch (Intrinsic) {
  4282. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4283. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  4284. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  4285. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  4286. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  4287. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  4288. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  4289. }
  4290. SDValue Op1 = getValue(I.getArgOperand(0));
  4291. SDValue Op2 = getValue(I.getArgOperand(1));
  4292. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  4293. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  4294. return nullptr;
  4295. }
  4296. case Intrinsic::prefetch: {
  4297. SDValue Ops[5];
  4298. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  4299. Ops[0] = getRoot();
  4300. Ops[1] = getValue(I.getArgOperand(0));
  4301. Ops[2] = getValue(I.getArgOperand(1));
  4302. Ops[3] = getValue(I.getArgOperand(2));
  4303. Ops[4] = getValue(I.getArgOperand(3));
  4304. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  4305. DAG.getVTList(MVT::Other), Ops,
  4306. EVT::getIntegerVT(*Context, 8),
  4307. MachinePointerInfo(I.getArgOperand(0)),
  4308. 0, /* align */
  4309. false, /* volatile */
  4310. rw==0, /* read */
  4311. rw==1)); /* write */
  4312. return nullptr;
  4313. }
  4314. case Intrinsic::lifetime_start:
  4315. case Intrinsic::lifetime_end: {
  4316. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  4317. // Stack coloring is not enabled in O0, discard region information.
  4318. if (TM.getOptLevel() == CodeGenOpt::None)
  4319. return nullptr;
  4320. SmallVector<Value *, 4> Allocas;
  4321. GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
  4322. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  4323. E = Allocas.end(); Object != E; ++Object) {
  4324. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  4325. // Could not find an Alloca.
  4326. if (!LifetimeObject)
  4327. continue;
  4328. // First check that the Alloca is static, otherwise it won't have a
  4329. // valid frame index.
  4330. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  4331. if (SI == FuncInfo.StaticAllocaMap.end())
  4332. return nullptr;
  4333. int FI = SI->second;
  4334. SDValue Ops[2];
  4335. Ops[0] = getRoot();
  4336. Ops[1] =
  4337. DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
  4338. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  4339. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  4340. DAG.setRoot(Res);
  4341. }
  4342. return nullptr;
  4343. }
  4344. case Intrinsic::invariant_start:
  4345. // Discard region information.
  4346. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  4347. return nullptr;
  4348. case Intrinsic::invariant_end:
  4349. // Discard region information.
  4350. return nullptr;
  4351. case Intrinsic::stackprotectorcheck: {
  4352. // Do not actually emit anything for this basic block. Instead we initialize
  4353. // the stack protector descriptor and export the guard variable so we can
  4354. // access it in FinishBasicBlock.
  4355. const BasicBlock *BB = I.getParent();
  4356. SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
  4357. ExportFromCurrentBlock(SPDescriptor.getGuard());
  4358. // Flush our exports since we are going to process a terminator.
  4359. (void)getControlRoot();
  4360. return nullptr;
  4361. }
  4362. case Intrinsic::clear_cache:
  4363. return TLI.getClearCacheBuiltinName();
  4364. case Intrinsic::eh_actions:
  4365. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  4366. return nullptr;
  4367. case Intrinsic::donothing:
  4368. // ignore
  4369. return nullptr;
  4370. case Intrinsic::experimental_stackmap: {
  4371. visitStackmap(I);
  4372. return nullptr;
  4373. }
  4374. case Intrinsic::experimental_patchpoint_void:
  4375. case Intrinsic::experimental_patchpoint_i64: {
  4376. visitPatchpoint(&I);
  4377. return nullptr;
  4378. }
  4379. case Intrinsic::experimental_gc_statepoint: {
  4380. visitStatepoint(I);
  4381. return nullptr;
  4382. }
  4383. case Intrinsic::experimental_gc_result_int:
  4384. case Intrinsic::experimental_gc_result_float:
  4385. case Intrinsic::experimental_gc_result_ptr:
  4386. case Intrinsic::experimental_gc_result: {
  4387. visitGCResult(I);
  4388. return nullptr;
  4389. }
  4390. case Intrinsic::experimental_gc_relocate: {
  4391. visitGCRelocate(I);
  4392. return nullptr;
  4393. }
  4394. case Intrinsic::instrprof_increment:
  4395. llvm_unreachable("instrprof failed to lower an increment");
  4396. case Intrinsic::localescape: {
  4397. MachineFunction &MF = DAG.getMachineFunction();
  4398. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4399. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  4400. // is the same on all targets.
  4401. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  4402. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  4403. if (isa<ConstantPointerNull>(Arg))
  4404. continue; // Skip null pointers. They represent a hole in index space.
  4405. AllocaInst *Slot = cast<AllocaInst>(Arg);
  4406. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  4407. "can only escape static allocas");
  4408. int FI = FuncInfo.StaticAllocaMap[Slot];
  4409. MCSymbol *FrameAllocSym =
  4410. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  4411. GlobalValue::getRealLinkageName(MF.getName()), Idx);
  4412. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  4413. TII->get(TargetOpcode::LOCAL_ESCAPE))
  4414. .addSym(FrameAllocSym)
  4415. .addFrameIndex(FI);
  4416. }
  4417. return nullptr;
  4418. }
  4419. case Intrinsic::localrecover: {
  4420. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  4421. MachineFunction &MF = DAG.getMachineFunction();
  4422. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  4423. // Get the symbol that defines the frame offset.
  4424. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  4425. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  4426. unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
  4427. MCSymbol *FrameAllocSym =
  4428. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  4429. GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
  4430. // Create a MCSymbol for the label to avoid any target lowering
  4431. // that would make this PC relative.
  4432. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  4433. SDValue OffsetVal =
  4434. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  4435. // Add the offset to the FP.
  4436. Value *FP = I.getArgOperand(1);
  4437. SDValue FPVal = getValue(FP);
  4438. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  4439. setValue(&I, Add);
  4440. return nullptr;
  4441. }
  4442. case Intrinsic::eh_begincatch:
  4443. case Intrinsic::eh_endcatch:
  4444. llvm_unreachable("begin/end catch intrinsics not lowered in codegen");
  4445. case Intrinsic::eh_exceptioncode: {
  4446. unsigned Reg = TLI.getExceptionPointerRegister();
  4447. assert(Reg && "cannot get exception code on this platform");
  4448. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  4449. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  4450. assert(FuncInfo.MBB->isLandingPad() && "eh.exceptioncode in non-lpad");
  4451. unsigned VReg = FuncInfo.MBB->addLiveIn(Reg, PtrRC);
  4452. SDValue N =
  4453. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  4454. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  4455. setValue(&I, N);
  4456. return nullptr;
  4457. }
  4458. }
  4459. }
  4460. std::pair<SDValue, SDValue>
  4461. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  4462. MachineBasicBlock *LandingPad) {
  4463. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4464. MCSymbol *BeginLabel = nullptr;
  4465. if (LandingPad) {
  4466. // Insert a label before the invoke call to mark the try range. This can be
  4467. // used to detect deletion of the invoke via the MachineModuleInfo.
  4468. BeginLabel = MMI.getContext().createTempSymbol();
  4469. // For SjLj, keep track of which landing pads go with which invokes
  4470. // so as to maintain the ordering of pads in the LSDA.
  4471. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  4472. if (CallSiteIndex) {
  4473. MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  4474. LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
  4475. // Now that the call site is handled, stop tracking it.
  4476. MMI.setCurrentCallSite(0);
  4477. }
  4478. // Both PendingLoads and PendingExports must be flushed here;
  4479. // this call might not return.
  4480. (void)getRoot();
  4481. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  4482. CLI.setChain(getRoot());
  4483. }
  4484. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4485. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  4486. assert((CLI.IsTailCall || Result.second.getNode()) &&
  4487. "Non-null chain expected with non-tail call!");
  4488. assert((Result.second.getNode() || !Result.first.getNode()) &&
  4489. "Null value expected with tail call!");
  4490. if (!Result.second.getNode()) {
  4491. // As a special case, a null chain means that a tail call has been emitted
  4492. // and the DAG root is already updated.
  4493. HasTailCall = true;
  4494. // Since there's no actual continuation from this block, nothing can be
  4495. // relying on us setting vregs for them.
  4496. PendingExports.clear();
  4497. } else {
  4498. DAG.setRoot(Result.second);
  4499. }
  4500. if (LandingPad) {
  4501. // Insert a label at the end of the invoke call to mark the try range. This
  4502. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  4503. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  4504. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  4505. // Inform MachineModuleInfo of range.
  4506. MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
  4507. }
  4508. return Result;
  4509. }
  4510. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  4511. bool isTailCall,
  4512. MachineBasicBlock *LandingPad) {
  4513. PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  4514. FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  4515. Type *RetTy = FTy->getReturnType();
  4516. TargetLowering::ArgListTy Args;
  4517. TargetLowering::ArgListEntry Entry;
  4518. Args.reserve(CS.arg_size());
  4519. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  4520. i != e; ++i) {
  4521. const Value *V = *i;
  4522. // Skip empty types
  4523. if (V->getType()->isEmptyTy())
  4524. continue;
  4525. SDValue ArgNode = getValue(V);
  4526. Entry.Node = ArgNode; Entry.Ty = V->getType();
  4527. // Skip the first return-type Attribute to get to params.
  4528. Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
  4529. Args.push_back(Entry);
  4530. // If we have an explicit sret argument that is an Instruction, (i.e., it
  4531. // might point to function-local memory), we can't meaningfully tail-call.
  4532. if (Entry.isSRet && isa<Instruction>(V))
  4533. isTailCall = false;
  4534. }
  4535. // Check if target-independent constraints permit a tail call here.
  4536. // Target-dependent constraints are checked within TLI->LowerCallTo.
  4537. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  4538. isTailCall = false;
  4539. TargetLowering::CallLoweringInfo CLI(DAG);
  4540. CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
  4541. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  4542. .setTailCall(isTailCall);
  4543. std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
  4544. if (Result.first.getNode())
  4545. setValue(CS.getInstruction(), Result.first);
  4546. }
  4547. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  4548. /// value is equal or not-equal to zero.
  4549. static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
  4550. for (const User *U : V->users()) {
  4551. if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
  4552. if (IC->isEquality())
  4553. if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  4554. if (C->isNullValue())
  4555. continue;
  4556. // Unknown instruction.
  4557. return false;
  4558. }
  4559. return true;
  4560. }
  4561. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  4562. Type *LoadTy,
  4563. SelectionDAGBuilder &Builder) {
  4564. // Check to see if this load can be trivially constant folded, e.g. if the
  4565. // input is from a string literal.
  4566. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  4567. // Cast pointer to the type we really want to load.
  4568. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  4569. PointerType::getUnqual(LoadTy));
  4570. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  4571. const_cast<Constant *>(LoadInput), *Builder.DL))
  4572. return Builder.getValue(LoadCst);
  4573. }
  4574. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  4575. // still constant memory, the input chain can be the entry node.
  4576. SDValue Root;
  4577. bool ConstantMemory = false;
  4578. // Do not serialize (non-volatile) loads of constant memory with anything.
  4579. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  4580. Root = Builder.DAG.getEntryNode();
  4581. ConstantMemory = true;
  4582. } else {
  4583. // Do not serialize non-volatile loads against each other.
  4584. Root = Builder.DAG.getRoot();
  4585. }
  4586. SDValue Ptr = Builder.getValue(PtrVal);
  4587. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  4588. Ptr, MachinePointerInfo(PtrVal),
  4589. false /*volatile*/,
  4590. false /*nontemporal*/,
  4591. false /*isinvariant*/, 1 /* align=1 */);
  4592. if (!ConstantMemory)
  4593. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  4594. return LoadVal;
  4595. }
  4596. /// processIntegerCallValue - Record the value for an instruction that
  4597. /// produces an integer result, converting the type where necessary.
  4598. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  4599. SDValue Value,
  4600. bool IsSigned) {
  4601. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  4602. I.getType(), true);
  4603. if (IsSigned)
  4604. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  4605. else
  4606. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  4607. setValue(&I, Value);
  4608. }
  4609. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  4610. /// If so, return true and lower it, otherwise return false and it will be
  4611. /// lowered like a normal call.
  4612. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  4613. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  4614. if (I.getNumArgOperands() != 3)
  4615. return false;
  4616. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  4617. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  4618. !I.getArgOperand(2)->getType()->isIntegerTy() ||
  4619. !I.getType()->isIntegerTy())
  4620. return false;
  4621. const Value *Size = I.getArgOperand(2);
  4622. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  4623. if (CSize && CSize->getZExtValue() == 0) {
  4624. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  4625. I.getType(), true);
  4626. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  4627. return true;
  4628. }
  4629. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4630. std::pair<SDValue, SDValue> Res =
  4631. TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  4632. getValue(LHS), getValue(RHS), getValue(Size),
  4633. MachinePointerInfo(LHS),
  4634. MachinePointerInfo(RHS));
  4635. if (Res.first.getNode()) {
  4636. processIntegerCallValue(I, Res.first, true);
  4637. PendingLoads.push_back(Res.second);
  4638. return true;
  4639. }
  4640. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  4641. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  4642. if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
  4643. bool ActuallyDoIt = true;
  4644. MVT LoadVT;
  4645. Type *LoadTy;
  4646. switch (CSize->getZExtValue()) {
  4647. default:
  4648. LoadVT = MVT::Other;
  4649. LoadTy = nullptr;
  4650. ActuallyDoIt = false;
  4651. break;
  4652. case 2:
  4653. LoadVT = MVT::i16;
  4654. LoadTy = Type::getInt16Ty(CSize->getContext());
  4655. break;
  4656. case 4:
  4657. LoadVT = MVT::i32;
  4658. LoadTy = Type::getInt32Ty(CSize->getContext());
  4659. break;
  4660. case 8:
  4661. LoadVT = MVT::i64;
  4662. LoadTy = Type::getInt64Ty(CSize->getContext());
  4663. break;
  4664. /*
  4665. case 16:
  4666. LoadVT = MVT::v4i32;
  4667. LoadTy = Type::getInt32Ty(CSize->getContext());
  4668. LoadTy = VectorType::get(LoadTy, 4);
  4669. break;
  4670. */
  4671. }
  4672. // This turns into unaligned loads. We only do this if the target natively
  4673. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  4674. // we'll only produce a small number of byte loads.
  4675. // Require that we can find a legal MVT, and only do this if the target
  4676. // supports unaligned loads of that type. Expanding into byte loads would
  4677. // bloat the code.
  4678. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4679. if (ActuallyDoIt && CSize->getZExtValue() > 4) {
  4680. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  4681. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  4682. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  4683. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  4684. // TODO: Check alignment of src and dest ptrs.
  4685. if (!TLI.isTypeLegal(LoadVT) ||
  4686. !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
  4687. !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
  4688. ActuallyDoIt = false;
  4689. }
  4690. if (ActuallyDoIt) {
  4691. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  4692. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  4693. SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
  4694. ISD::SETNE);
  4695. processIntegerCallValue(I, Res, false);
  4696. return true;
  4697. }
  4698. }
  4699. return false;
  4700. }
  4701. /// visitMemChrCall -- See if we can lower a memchr call into an optimized
  4702. /// form. If so, return true and lower it, otherwise return false and it
  4703. /// will be lowered like a normal call.
  4704. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  4705. // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
  4706. if (I.getNumArgOperands() != 3)
  4707. return false;
  4708. const Value *Src = I.getArgOperand(0);
  4709. const Value *Char = I.getArgOperand(1);
  4710. const Value *Length = I.getArgOperand(2);
  4711. if (!Src->getType()->isPointerTy() ||
  4712. !Char->getType()->isIntegerTy() ||
  4713. !Length->getType()->isIntegerTy() ||
  4714. !I.getType()->isPointerTy())
  4715. return false;
  4716. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4717. std::pair<SDValue, SDValue> Res =
  4718. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  4719. getValue(Src), getValue(Char), getValue(Length),
  4720. MachinePointerInfo(Src));
  4721. if (Res.first.getNode()) {
  4722. setValue(&I, Res.first);
  4723. PendingLoads.push_back(Res.second);
  4724. return true;
  4725. }
  4726. return false;
  4727. }
  4728. /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
  4729. /// optimized form. If so, return true and lower it, otherwise return false
  4730. /// and it will be lowered like a normal call.
  4731. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  4732. // Verify that the prototype makes sense. char *strcpy(char *, char *)
  4733. if (I.getNumArgOperands() != 2)
  4734. return false;
  4735. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  4736. if (!Arg0->getType()->isPointerTy() ||
  4737. !Arg1->getType()->isPointerTy() ||
  4738. !I.getType()->isPointerTy())
  4739. return false;
  4740. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4741. std::pair<SDValue, SDValue> Res =
  4742. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  4743. getValue(Arg0), getValue(Arg1),
  4744. MachinePointerInfo(Arg0),
  4745. MachinePointerInfo(Arg1), isStpcpy);
  4746. if (Res.first.getNode()) {
  4747. setValue(&I, Res.first);
  4748. DAG.setRoot(Res.second);
  4749. return true;
  4750. }
  4751. return false;
  4752. }
  4753. /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
  4754. /// If so, return true and lower it, otherwise return false and it will be
  4755. /// lowered like a normal call.
  4756. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  4757. // Verify that the prototype makes sense. int strcmp(void*,void*)
  4758. if (I.getNumArgOperands() != 2)
  4759. return false;
  4760. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  4761. if (!Arg0->getType()->isPointerTy() ||
  4762. !Arg1->getType()->isPointerTy() ||
  4763. !I.getType()->isIntegerTy())
  4764. return false;
  4765. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4766. std::pair<SDValue, SDValue> Res =
  4767. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  4768. getValue(Arg0), getValue(Arg1),
  4769. MachinePointerInfo(Arg0),
  4770. MachinePointerInfo(Arg1));
  4771. if (Res.first.getNode()) {
  4772. processIntegerCallValue(I, Res.first, true);
  4773. PendingLoads.push_back(Res.second);
  4774. return true;
  4775. }
  4776. return false;
  4777. }
  4778. /// visitStrLenCall -- See if we can lower a strlen call into an optimized
  4779. /// form. If so, return true and lower it, otherwise return false and it
  4780. /// will be lowered like a normal call.
  4781. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  4782. // Verify that the prototype makes sense. size_t strlen(char *)
  4783. if (I.getNumArgOperands() != 1)
  4784. return false;
  4785. const Value *Arg0 = I.getArgOperand(0);
  4786. if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
  4787. return false;
  4788. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4789. std::pair<SDValue, SDValue> Res =
  4790. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  4791. getValue(Arg0), MachinePointerInfo(Arg0));
  4792. if (Res.first.getNode()) {
  4793. processIntegerCallValue(I, Res.first, false);
  4794. PendingLoads.push_back(Res.second);
  4795. return true;
  4796. }
  4797. return false;
  4798. }
  4799. /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
  4800. /// form. If so, return true and lower it, otherwise return false and it
  4801. /// will be lowered like a normal call.
  4802. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  4803. // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
  4804. if (I.getNumArgOperands() != 2)
  4805. return false;
  4806. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  4807. if (!Arg0->getType()->isPointerTy() ||
  4808. !Arg1->getType()->isIntegerTy() ||
  4809. !I.getType()->isIntegerTy())
  4810. return false;
  4811. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4812. std::pair<SDValue, SDValue> Res =
  4813. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  4814. getValue(Arg0), getValue(Arg1),
  4815. MachinePointerInfo(Arg0));
  4816. if (Res.first.getNode()) {
  4817. processIntegerCallValue(I, Res.first, false);
  4818. PendingLoads.push_back(Res.second);
  4819. return true;
  4820. }
  4821. return false;
  4822. }
  4823. /// visitUnaryFloatCall - If a call instruction is a unary floating-point
  4824. /// operation (as expected), translate it to an SDNode with the specified opcode
  4825. /// and return true.
  4826. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  4827. unsigned Opcode) {
  4828. // Sanity check that it really is a unary floating-point call.
  4829. if (I.getNumArgOperands() != 1 ||
  4830. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  4831. I.getType() != I.getArgOperand(0)->getType() ||
  4832. !I.onlyReadsMemory())
  4833. return false;
  4834. SDValue Tmp = getValue(I.getArgOperand(0));
  4835. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  4836. return true;
  4837. }
  4838. /// visitBinaryFloatCall - If a call instruction is a binary floating-point
  4839. /// operation (as expected), translate it to an SDNode with the specified opcode
  4840. /// and return true.
  4841. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  4842. unsigned Opcode) {
  4843. // Sanity check that it really is a binary floating-point call.
  4844. if (I.getNumArgOperands() != 2 ||
  4845. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  4846. I.getType() != I.getArgOperand(0)->getType() ||
  4847. I.getType() != I.getArgOperand(1)->getType() ||
  4848. !I.onlyReadsMemory())
  4849. return false;
  4850. SDValue Tmp0 = getValue(I.getArgOperand(0));
  4851. SDValue Tmp1 = getValue(I.getArgOperand(1));
  4852. EVT VT = Tmp0.getValueType();
  4853. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  4854. return true;
  4855. }
  4856. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  4857. // Handle inline assembly differently.
  4858. if (isa<InlineAsm>(I.getCalledValue())) {
  4859. visitInlineAsm(&I);
  4860. return;
  4861. }
  4862. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4863. ComputeUsesVAFloatArgument(I, &MMI);
  4864. const char *RenameFn = nullptr;
  4865. if (Function *F = I.getCalledFunction()) {
  4866. if (F->isDeclaration()) {
  4867. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  4868. if (unsigned IID = II->getIntrinsicID(F)) {
  4869. RenameFn = visitIntrinsicCall(I, IID);
  4870. if (!RenameFn)
  4871. return;
  4872. }
  4873. }
  4874. if (Intrinsic::ID IID = F->getIntrinsicID()) {
  4875. RenameFn = visitIntrinsicCall(I, IID);
  4876. if (!RenameFn)
  4877. return;
  4878. }
  4879. }
  4880. // Check for well-known libc/libm calls. If the function is internal, it
  4881. // can't be a library call.
  4882. LibFunc::Func Func;
  4883. if (!F->hasLocalLinkage() && F->hasName() &&
  4884. LibInfo->getLibFunc(F->getName(), Func) &&
  4885. LibInfo->hasOptimizedCodeGen(Func)) {
  4886. switch (Func) {
  4887. default: break;
  4888. case LibFunc::copysign:
  4889. case LibFunc::copysignf:
  4890. case LibFunc::copysignl:
  4891. if (I.getNumArgOperands() == 2 && // Basic sanity checks.
  4892. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  4893. I.getType() == I.getArgOperand(0)->getType() &&
  4894. I.getType() == I.getArgOperand(1)->getType() &&
  4895. I.onlyReadsMemory()) {
  4896. SDValue LHS = getValue(I.getArgOperand(0));
  4897. SDValue RHS = getValue(I.getArgOperand(1));
  4898. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  4899. LHS.getValueType(), LHS, RHS));
  4900. return;
  4901. }
  4902. break;
  4903. case LibFunc::fabs:
  4904. case LibFunc::fabsf:
  4905. case LibFunc::fabsl:
  4906. if (visitUnaryFloatCall(I, ISD::FABS))
  4907. return;
  4908. break;
  4909. case LibFunc::fmin:
  4910. case LibFunc::fminf:
  4911. case LibFunc::fminl:
  4912. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  4913. return;
  4914. break;
  4915. case LibFunc::fmax:
  4916. case LibFunc::fmaxf:
  4917. case LibFunc::fmaxl:
  4918. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  4919. return;
  4920. break;
  4921. case LibFunc::sin:
  4922. case LibFunc::sinf:
  4923. case LibFunc::sinl:
  4924. if (visitUnaryFloatCall(I, ISD::FSIN))
  4925. return;
  4926. break;
  4927. case LibFunc::cos:
  4928. case LibFunc::cosf:
  4929. case LibFunc::cosl:
  4930. if (visitUnaryFloatCall(I, ISD::FCOS))
  4931. return;
  4932. break;
  4933. case LibFunc::sqrt:
  4934. case LibFunc::sqrtf:
  4935. case LibFunc::sqrtl:
  4936. case LibFunc::sqrt_finite:
  4937. case LibFunc::sqrtf_finite:
  4938. case LibFunc::sqrtl_finite:
  4939. if (visitUnaryFloatCall(I, ISD::FSQRT))
  4940. return;
  4941. break;
  4942. case LibFunc::floor:
  4943. case LibFunc::floorf:
  4944. case LibFunc::floorl:
  4945. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  4946. return;
  4947. break;
  4948. case LibFunc::nearbyint:
  4949. case LibFunc::nearbyintf:
  4950. case LibFunc::nearbyintl:
  4951. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  4952. return;
  4953. break;
  4954. case LibFunc::ceil:
  4955. case LibFunc::ceilf:
  4956. case LibFunc::ceill:
  4957. if (visitUnaryFloatCall(I, ISD::FCEIL))
  4958. return;
  4959. break;
  4960. case LibFunc::rint:
  4961. case LibFunc::rintf:
  4962. case LibFunc::rintl:
  4963. if (visitUnaryFloatCall(I, ISD::FRINT))
  4964. return;
  4965. break;
  4966. case LibFunc::round:
  4967. case LibFunc::roundf:
  4968. case LibFunc::roundl:
  4969. if (visitUnaryFloatCall(I, ISD::FROUND))
  4970. return;
  4971. break;
  4972. case LibFunc::trunc:
  4973. case LibFunc::truncf:
  4974. case LibFunc::truncl:
  4975. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  4976. return;
  4977. break;
  4978. case LibFunc::log2:
  4979. case LibFunc::log2f:
  4980. case LibFunc::log2l:
  4981. if (visitUnaryFloatCall(I, ISD::FLOG2))
  4982. return;
  4983. break;
  4984. case LibFunc::exp2:
  4985. case LibFunc::exp2f:
  4986. case LibFunc::exp2l:
  4987. if (visitUnaryFloatCall(I, ISD::FEXP2))
  4988. return;
  4989. break;
  4990. case LibFunc::memcmp:
  4991. if (visitMemCmpCall(I))
  4992. return;
  4993. break;
  4994. case LibFunc::memchr:
  4995. if (visitMemChrCall(I))
  4996. return;
  4997. break;
  4998. case LibFunc::strcpy:
  4999. if (visitStrCpyCall(I, false))
  5000. return;
  5001. break;
  5002. case LibFunc::stpcpy:
  5003. if (visitStrCpyCall(I, true))
  5004. return;
  5005. break;
  5006. case LibFunc::strcmp:
  5007. if (visitStrCmpCall(I))
  5008. return;
  5009. break;
  5010. case LibFunc::strlen:
  5011. if (visitStrLenCall(I))
  5012. return;
  5013. break;
  5014. case LibFunc::strnlen:
  5015. if (visitStrNLenCall(I))
  5016. return;
  5017. break;
  5018. }
  5019. }
  5020. }
  5021. SDValue Callee;
  5022. if (!RenameFn)
  5023. Callee = getValue(I.getCalledValue());
  5024. else
  5025. Callee = DAG.getExternalSymbol(
  5026. RenameFn,
  5027. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  5028. // Check if we can potentially perform a tail call. More detailed checking is
  5029. // be done within LowerCallTo, after more information about the call is known.
  5030. LowerCallTo(&I, Callee, I.isTailCall());
  5031. }
  5032. namespace {
  5033. /// AsmOperandInfo - This contains information for each constraint that we are
  5034. /// lowering.
  5035. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  5036. public:
  5037. /// CallOperand - If this is the result output operand or a clobber
  5038. /// this is null, otherwise it is the incoming operand to the CallInst.
  5039. /// This gets modified as the asm is processed.
  5040. SDValue CallOperand;
  5041. /// AssignedRegs - If this is a register or register class operand, this
  5042. /// contains the set of register corresponding to the operand.
  5043. RegsForValue AssignedRegs;
  5044. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  5045. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
  5046. }
  5047. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  5048. /// corresponds to. If there is no Value* for this operand, it returns
  5049. /// MVT::Other.
  5050. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  5051. const DataLayout &DL) const {
  5052. if (!CallOperandVal) return MVT::Other;
  5053. if (isa<BasicBlock>(CallOperandVal))
  5054. return TLI.getPointerTy(DL);
  5055. llvm::Type *OpTy = CallOperandVal->getType();
  5056. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  5057. // If this is an indirect operand, the operand is a pointer to the
  5058. // accessed type.
  5059. if (isIndirect) {
  5060. llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  5061. if (!PtrTy)
  5062. report_fatal_error("Indirect operand for inline asm not a pointer!");
  5063. OpTy = PtrTy->getElementType();
  5064. }
  5065. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  5066. if (StructType *STy = dyn_cast<StructType>(OpTy))
  5067. if (STy->getNumElements() == 1)
  5068. OpTy = STy->getElementType(0);
  5069. // If OpTy is not a single value, it may be a struct/union that we
  5070. // can tile with integers.
  5071. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  5072. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  5073. switch (BitSize) {
  5074. default: break;
  5075. case 1:
  5076. case 8:
  5077. case 16:
  5078. case 32:
  5079. case 64:
  5080. case 128:
  5081. OpTy = IntegerType::get(Context, BitSize);
  5082. break;
  5083. }
  5084. }
  5085. return TLI.getValueType(DL, OpTy, true);
  5086. }
  5087. };
  5088. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  5089. } // end anonymous namespace
  5090. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  5091. /// specified operand. We prefer to assign virtual registers, to allow the
  5092. /// register allocator to handle the assignment process. However, if the asm
  5093. /// uses features that we can't model on machineinstrs, we have SDISel do the
  5094. /// allocation. This produces generally horrible, but correct, code.
  5095. ///
  5096. /// OpInfo describes the operand.
  5097. ///
  5098. static void GetRegistersForValue(SelectionDAG &DAG,
  5099. const TargetLowering &TLI,
  5100. SDLoc DL,
  5101. SDISelAsmOperandInfo &OpInfo) {
  5102. LLVMContext &Context = *DAG.getContext();
  5103. MachineFunction &MF = DAG.getMachineFunction();
  5104. SmallVector<unsigned, 4> Regs;
  5105. // If this is a constraint for a single physreg, or a constraint for a
  5106. // register class, find it.
  5107. std::pair<unsigned, const TargetRegisterClass *> PhysReg =
  5108. TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
  5109. OpInfo.ConstraintCode,
  5110. OpInfo.ConstraintVT);
  5111. unsigned NumRegs = 1;
  5112. if (OpInfo.ConstraintVT != MVT::Other) {
  5113. // If this is a FP input in an integer register (or visa versa) insert a bit
  5114. // cast of the input value. More generally, handle any case where the input
  5115. // value disagrees with the register class we plan to stick this in.
  5116. if (OpInfo.Type == InlineAsm::isInput &&
  5117. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  5118. // Try to convert to the first EVT that the reg class contains. If the
  5119. // types are identical size, use a bitcast to convert (e.g. two differing
  5120. // vector types).
  5121. MVT RegVT = *PhysReg.second->vt_begin();
  5122. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  5123. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5124. RegVT, OpInfo.CallOperand);
  5125. OpInfo.ConstraintVT = RegVT;
  5126. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  5127. // If the input is a FP value and we want it in FP registers, do a
  5128. // bitcast to the corresponding integer type. This turns an f64 value
  5129. // into i64, which can be passed with two i32 values on a 32-bit
  5130. // machine.
  5131. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  5132. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5133. RegVT, OpInfo.CallOperand);
  5134. OpInfo.ConstraintVT = RegVT;
  5135. }
  5136. }
  5137. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  5138. }
  5139. MVT RegVT;
  5140. EVT ValueVT = OpInfo.ConstraintVT;
  5141. // If this is a constraint for a specific physical register, like {r17},
  5142. // assign it now.
  5143. if (unsigned AssignedReg = PhysReg.first) {
  5144. const TargetRegisterClass *RC = PhysReg.second;
  5145. if (OpInfo.ConstraintVT == MVT::Other)
  5146. ValueVT = *RC->vt_begin();
  5147. // Get the actual register value type. This is important, because the user
  5148. // may have asked for (e.g.) the AX register in i32 type. We need to
  5149. // remember that AX is actually i16 to get the right extension.
  5150. RegVT = *RC->vt_begin();
  5151. // This is a explicit reference to a physical register.
  5152. Regs.push_back(AssignedReg);
  5153. // If this is an expanded reference, add the rest of the regs to Regs.
  5154. if (NumRegs != 1) {
  5155. TargetRegisterClass::iterator I = RC->begin();
  5156. for (; *I != AssignedReg; ++I)
  5157. assert(I != RC->end() && "Didn't find reg!");
  5158. // Already added the first reg.
  5159. --NumRegs; ++I;
  5160. for (; NumRegs; --NumRegs, ++I) {
  5161. assert(I != RC->end() && "Ran out of registers to allocate!");
  5162. Regs.push_back(*I);
  5163. }
  5164. }
  5165. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5166. return;
  5167. }
  5168. // Otherwise, if this was a reference to an LLVM register class, create vregs
  5169. // for this reference.
  5170. if (const TargetRegisterClass *RC = PhysReg.second) {
  5171. RegVT = *RC->vt_begin();
  5172. if (OpInfo.ConstraintVT == MVT::Other)
  5173. ValueVT = RegVT;
  5174. // Create the appropriate number of virtual registers.
  5175. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  5176. for (; NumRegs; --NumRegs)
  5177. Regs.push_back(RegInfo.createVirtualRegister(RC));
  5178. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5179. return;
  5180. }
  5181. // Otherwise, we couldn't allocate enough registers for this.
  5182. }
  5183. /// visitInlineAsm - Handle a call to an InlineAsm object.
  5184. ///
  5185. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  5186. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  5187. /// ConstraintOperands - Information about all of the constraints.
  5188. SDISelAsmOperandInfoVector ConstraintOperands;
  5189. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5190. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  5191. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  5192. bool hasMemory = false;
  5193. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  5194. unsigned ResNo = 0; // ResNo - The result number of the next output.
  5195. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5196. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  5197. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  5198. MVT OpVT = MVT::Other;
  5199. // Compute the value type for each operand.
  5200. switch (OpInfo.Type) {
  5201. case InlineAsm::isOutput:
  5202. // Indirect outputs just consume an argument.
  5203. if (OpInfo.isIndirect) {
  5204. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5205. break;
  5206. }
  5207. // The return value of the call is this value. As such, there is no
  5208. // corresponding argument.
  5209. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5210. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  5211. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
  5212. STy->getElementType(ResNo));
  5213. } else {
  5214. assert(ResNo == 0 && "Asm only has one result!");
  5215. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  5216. }
  5217. ++ResNo;
  5218. break;
  5219. case InlineAsm::isInput:
  5220. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5221. break;
  5222. case InlineAsm::isClobber:
  5223. // Nothing to do.
  5224. break;
  5225. }
  5226. // If this is an input or an indirect output, process the call argument.
  5227. // BasicBlocks are labels, currently appearing only in asm's.
  5228. if (OpInfo.CallOperandVal) {
  5229. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  5230. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  5231. } else {
  5232. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  5233. }
  5234. OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
  5235. DAG.getDataLayout()).getSimpleVT();
  5236. }
  5237. OpInfo.ConstraintVT = OpVT;
  5238. // Indirect operand accesses access memory.
  5239. if (OpInfo.isIndirect)
  5240. hasMemory = true;
  5241. else {
  5242. for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
  5243. TargetLowering::ConstraintType
  5244. CType = TLI.getConstraintType(OpInfo.Codes[j]);
  5245. if (CType == TargetLowering::C_Memory) {
  5246. hasMemory = true;
  5247. break;
  5248. }
  5249. }
  5250. }
  5251. }
  5252. SDValue Chain, Flag;
  5253. // We won't need to flush pending loads if this asm doesn't touch
  5254. // memory and is nonvolatile.
  5255. if (hasMemory || IA->hasSideEffects())
  5256. Chain = getRoot();
  5257. else
  5258. Chain = DAG.getRoot();
  5259. // Second pass over the constraints: compute which constraint option to use
  5260. // and assign registers to constraints that want a specific physreg.
  5261. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5262. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5263. // If this is an output operand with a matching input operand, look up the
  5264. // matching input. If their types mismatch, e.g. one is an integer, the
  5265. // other is floating point, or their sizes are different, flag it as an
  5266. // error.
  5267. if (OpInfo.hasMatchingInput()) {
  5268. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  5269. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  5270. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  5271. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  5272. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  5273. OpInfo.ConstraintVT);
  5274. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  5275. TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
  5276. Input.ConstraintVT);
  5277. if ((OpInfo.ConstraintVT.isInteger() !=
  5278. Input.ConstraintVT.isInteger()) ||
  5279. (MatchRC.second != InputRC.second)) {
  5280. report_fatal_error("Unsupported asm: input constraint"
  5281. " with a matching output constraint of"
  5282. " incompatible type!");
  5283. }
  5284. Input.ConstraintVT = OpInfo.ConstraintVT;
  5285. }
  5286. }
  5287. // Compute the constraint code and ConstraintType to use.
  5288. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  5289. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5290. OpInfo.Type == InlineAsm::isClobber)
  5291. continue;
  5292. // If this is a memory input, and if the operand is not indirect, do what we
  5293. // need to to provide an address for the memory input.
  5294. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5295. !OpInfo.isIndirect) {
  5296. assert((OpInfo.isMultipleAlternative ||
  5297. (OpInfo.Type == InlineAsm::isInput)) &&
  5298. "Can only indirectify direct input operands!");
  5299. // Memory operands really want the address of the value. If we don't have
  5300. // an indirect input, put it in the constpool if we can, otherwise spill
  5301. // it to a stack slot.
  5302. // TODO: This isn't quite right. We need to handle these according to
  5303. // the addressing mode that the constraint wants. Also, this may take
  5304. // an additional register for the computation and we don't want that
  5305. // either.
  5306. // If the operand is a float, integer, or vector constant, spill to a
  5307. // constant pool entry to get its address.
  5308. const Value *OpVal = OpInfo.CallOperandVal;
  5309. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  5310. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  5311. OpInfo.CallOperand = DAG.getConstantPool(
  5312. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  5313. } else {
  5314. // Otherwise, create a stack slot and emit a store to it before the
  5315. // asm.
  5316. Type *Ty = OpVal->getType();
  5317. auto &DL = DAG.getDataLayout();
  5318. uint64_t TySize = DL.getTypeAllocSize(Ty);
  5319. unsigned Align = DL.getPrefTypeAlignment(Ty);
  5320. MachineFunction &MF = DAG.getMachineFunction();
  5321. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  5322. SDValue StackSlot =
  5323. DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout()));
  5324. Chain = DAG.getStore(Chain, getCurSDLoc(),
  5325. OpInfo.CallOperand, StackSlot,
  5326. MachinePointerInfo::getFixedStack(SSFI),
  5327. false, false, 0);
  5328. OpInfo.CallOperand = StackSlot;
  5329. }
  5330. // There is no longer a Value* corresponding to this operand.
  5331. OpInfo.CallOperandVal = nullptr;
  5332. // It is now an indirect operand.
  5333. OpInfo.isIndirect = true;
  5334. }
  5335. // If this constraint is for a specific register, allocate it before
  5336. // anything else.
  5337. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  5338. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  5339. }
  5340. // Second pass - Loop over all of the operands, assigning virtual or physregs
  5341. // to register class operands.
  5342. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5343. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5344. // C_Register operands have already been allocated, Other/Memory don't need
  5345. // to be.
  5346. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  5347. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  5348. }
  5349. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  5350. std::vector<SDValue> AsmNodeOperands;
  5351. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  5352. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  5353. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  5354. // If we have a !srcloc metadata node associated with it, we want to attach
  5355. // this to the ultimately generated inline asm machineinstr. To do this, we
  5356. // pass in the third operand as this (potentially null) inline asm MDNode.
  5357. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  5358. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  5359. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  5360. // bits as operand 3.
  5361. unsigned ExtraInfo = 0;
  5362. if (IA->hasSideEffects())
  5363. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  5364. if (IA->isAlignStack())
  5365. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  5366. // Set the asm dialect.
  5367. ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  5368. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  5369. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5370. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  5371. // Compute the constraint code and ConstraintType to use.
  5372. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  5373. // Ideally, we would only check against memory constraints. However, the
  5374. // meaning of an other constraint can be target-specific and we can't easily
  5375. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  5376. // for other constriants as well.
  5377. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  5378. OpInfo.ConstraintType == TargetLowering::C_Other) {
  5379. if (OpInfo.Type == InlineAsm::isInput)
  5380. ExtraInfo |= InlineAsm::Extra_MayLoad;
  5381. else if (OpInfo.Type == InlineAsm::isOutput)
  5382. ExtraInfo |= InlineAsm::Extra_MayStore;
  5383. else if (OpInfo.Type == InlineAsm::isClobber)
  5384. ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  5385. }
  5386. }
  5387. AsmNodeOperands.push_back(DAG.getTargetConstant(
  5388. ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  5389. // Loop over all of the inputs, copying the operand values into the
  5390. // appropriate registers and processing the output regs.
  5391. RegsForValue RetValRegs;
  5392. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  5393. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  5394. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5395. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5396. switch (OpInfo.Type) {
  5397. case InlineAsm::isOutput: {
  5398. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  5399. OpInfo.ConstraintType != TargetLowering::C_Register) {
  5400. // Memory output, or 'other' output (e.g. 'X' constraint).
  5401. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  5402. unsigned ConstraintID =
  5403. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  5404. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  5405. "Failed to convert memory constraint code to constraint id.");
  5406. // Add information to the INLINEASM node to know about this output.
  5407. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5408. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  5409. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  5410. MVT::i32));
  5411. AsmNodeOperands.push_back(OpInfo.CallOperand);
  5412. break;
  5413. }
  5414. // Otherwise, this is a register or register class output.
  5415. // Copy the output from the appropriate register. Find a register that
  5416. // we can use.
  5417. if (OpInfo.AssignedRegs.Regs.empty()) {
  5418. LLVMContext &Ctx = *DAG.getContext();
  5419. Ctx.emitError(CS.getInstruction(),
  5420. "couldn't allocate output register for constraint '" +
  5421. Twine(OpInfo.ConstraintCode) + "'");
  5422. return;
  5423. }
  5424. // If this is an indirect operand, store through the pointer after the
  5425. // asm.
  5426. if (OpInfo.isIndirect) {
  5427. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  5428. OpInfo.CallOperandVal));
  5429. } else {
  5430. // This is the result value of the call.
  5431. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5432. // Concatenate this output onto the outputs list.
  5433. RetValRegs.append(OpInfo.AssignedRegs);
  5434. }
  5435. // Add information to the INLINEASM node to know that this register is
  5436. // set.
  5437. OpInfo.AssignedRegs
  5438. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  5439. ? InlineAsm::Kind_RegDefEarlyClobber
  5440. : InlineAsm::Kind_RegDef,
  5441. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  5442. break;
  5443. }
  5444. case InlineAsm::isInput: {
  5445. SDValue InOperandVal = OpInfo.CallOperand;
  5446. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  5447. // If this is required to match an output register we have already set,
  5448. // just use its register.
  5449. unsigned OperandNo = OpInfo.getMatchedOperand();
  5450. // Scan until we find the definition we already emitted of this operand.
  5451. // When we find it, create a RegsForValue operand.
  5452. unsigned CurOp = InlineAsm::Op_FirstOperand;
  5453. for (; OperandNo; --OperandNo) {
  5454. // Advance to the next operand.
  5455. unsigned OpFlag =
  5456. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5457. assert((InlineAsm::isRegDefKind(OpFlag) ||
  5458. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  5459. InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
  5460. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  5461. }
  5462. unsigned OpFlag =
  5463. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5464. if (InlineAsm::isRegDefKind(OpFlag) ||
  5465. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  5466. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  5467. if (OpInfo.isIndirect) {
  5468. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  5469. LLVMContext &Ctx = *DAG.getContext();
  5470. Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
  5471. " don't know how to handle tied "
  5472. "indirect register inputs");
  5473. return;
  5474. }
  5475. RegsForValue MatchedRegs;
  5476. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  5477. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  5478. MatchedRegs.RegVTs.push_back(RegVT);
  5479. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  5480. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  5481. i != e; ++i) {
  5482. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  5483. MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
  5484. else {
  5485. LLVMContext &Ctx = *DAG.getContext();
  5486. Ctx.emitError(CS.getInstruction(),
  5487. "inline asm error: This value"
  5488. " type register class is not natively supported!");
  5489. return;
  5490. }
  5491. }
  5492. SDLoc dl = getCurSDLoc();
  5493. // Use the produced MatchedRegs object to
  5494. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  5495. Chain, &Flag, CS.getInstruction());
  5496. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  5497. true, OpInfo.getMatchedOperand(), dl,
  5498. DAG, AsmNodeOperands);
  5499. break;
  5500. }
  5501. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  5502. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  5503. "Unexpected number of operands");
  5504. // Add information to the INLINEASM node to know about this input.
  5505. // See InlineAsm.h isUseOperandTiedToDef.
  5506. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  5507. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  5508. OpInfo.getMatchedOperand());
  5509. AsmNodeOperands.push_back(DAG.getTargetConstant(
  5510. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  5511. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  5512. break;
  5513. }
  5514. // Treat indirect 'X' constraint as memory.
  5515. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  5516. OpInfo.isIndirect)
  5517. OpInfo.ConstraintType = TargetLowering::C_Memory;
  5518. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  5519. std::vector<SDValue> Ops;
  5520. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  5521. Ops, DAG);
  5522. if (Ops.empty()) {
  5523. LLVMContext &Ctx = *DAG.getContext();
  5524. Ctx.emitError(CS.getInstruction(),
  5525. "invalid operand for inline asm constraint '" +
  5526. Twine(OpInfo.ConstraintCode) + "'");
  5527. return;
  5528. }
  5529. // Add information to the INLINEASM node to know about this input.
  5530. unsigned ResOpType =
  5531. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  5532. AsmNodeOperands.push_back(DAG.getTargetConstant(
  5533. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  5534. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  5535. break;
  5536. }
  5537. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  5538. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  5539. assert(InOperandVal.getValueType() ==
  5540. TLI.getPointerTy(DAG.getDataLayout()) &&
  5541. "Memory operands expect pointer values");
  5542. unsigned ConstraintID =
  5543. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  5544. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  5545. "Failed to convert memory constraint code to constraint id.");
  5546. // Add information to the INLINEASM node to know about this input.
  5547. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5548. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  5549. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5550. getCurSDLoc(),
  5551. MVT::i32));
  5552. AsmNodeOperands.push_back(InOperandVal);
  5553. break;
  5554. }
  5555. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  5556. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  5557. "Unknown constraint type!");
  5558. // TODO: Support this.
  5559. if (OpInfo.isIndirect) {
  5560. LLVMContext &Ctx = *DAG.getContext();
  5561. Ctx.emitError(CS.getInstruction(),
  5562. "Don't know how to handle indirect register inputs yet "
  5563. "for constraint '" +
  5564. Twine(OpInfo.ConstraintCode) + "'");
  5565. return;
  5566. }
  5567. // Copy the input into the appropriate registers.
  5568. if (OpInfo.AssignedRegs.Regs.empty()) {
  5569. LLVMContext &Ctx = *DAG.getContext();
  5570. Ctx.emitError(CS.getInstruction(),
  5571. "couldn't allocate input reg for constraint '" +
  5572. Twine(OpInfo.ConstraintCode) + "'");
  5573. return;
  5574. }
  5575. SDLoc dl = getCurSDLoc();
  5576. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  5577. Chain, &Flag, CS.getInstruction());
  5578. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  5579. dl, DAG, AsmNodeOperands);
  5580. break;
  5581. }
  5582. case InlineAsm::isClobber: {
  5583. // Add the clobbered value to the operand list, so that the register
  5584. // allocator is aware that the physreg got clobbered.
  5585. if (!OpInfo.AssignedRegs.Regs.empty())
  5586. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  5587. false, 0, getCurSDLoc(), DAG,
  5588. AsmNodeOperands);
  5589. break;
  5590. }
  5591. }
  5592. }
  5593. // Finish up input operands. Set the input chain and add the flag last.
  5594. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  5595. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  5596. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  5597. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  5598. Flag = Chain.getValue(1);
  5599. // If this asm returns a register value, copy the result from that register
  5600. // and set it as the value of the call.
  5601. if (!RetValRegs.Regs.empty()) {
  5602. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  5603. Chain, &Flag, CS.getInstruction());
  5604. // FIXME: Why don't we do this for inline asms with MRVs?
  5605. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  5606. EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  5607. // If any of the results of the inline asm is a vector, it may have the
  5608. // wrong width/num elts. This can happen for register classes that can
  5609. // contain multiple different value types. The preg or vreg allocated may
  5610. // not have the same VT as was expected. Convert it to the right type
  5611. // with bit_convert.
  5612. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  5613. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  5614. ResultType, Val);
  5615. } else if (ResultType != Val.getValueType() &&
  5616. ResultType.isInteger() && Val.getValueType().isInteger()) {
  5617. // If a result value was tied to an input value, the computed result may
  5618. // have a wider width than the expected result. Extract the relevant
  5619. // portion.
  5620. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  5621. }
  5622. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  5623. }
  5624. setValue(CS.getInstruction(), Val);
  5625. // Don't need to use this as a chain in this case.
  5626. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  5627. return;
  5628. }
  5629. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  5630. // Process indirect outputs, first output all of the flagged copies out of
  5631. // physregs.
  5632. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  5633. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  5634. const Value *Ptr = IndirectStoresToEmit[i].second;
  5635. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  5636. Chain, &Flag, IA);
  5637. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  5638. }
  5639. // Emit the non-flagged stores from the physregs.
  5640. SmallVector<SDValue, 8> OutChains;
  5641. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  5642. SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
  5643. StoresToEmit[i].first,
  5644. getValue(StoresToEmit[i].second),
  5645. MachinePointerInfo(StoresToEmit[i].second),
  5646. false, false, 0);
  5647. OutChains.push_back(Val);
  5648. }
  5649. if (!OutChains.empty())
  5650. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  5651. DAG.setRoot(Chain);
  5652. }
  5653. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  5654. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  5655. MVT::Other, getRoot(),
  5656. getValue(I.getArgOperand(0)),
  5657. DAG.getSrcValue(I.getArgOperand(0))));
  5658. }
  5659. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  5660. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5661. const DataLayout &DL = DAG.getDataLayout();
  5662. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5663. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  5664. DAG.getSrcValue(I.getOperand(0)),
  5665. DL.getABITypeAlignment(I.getType()));
  5666. setValue(&I, V);
  5667. DAG.setRoot(V.getValue(1));
  5668. }
  5669. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  5670. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  5671. MVT::Other, getRoot(),
  5672. getValue(I.getArgOperand(0)),
  5673. DAG.getSrcValue(I.getArgOperand(0))));
  5674. }
  5675. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  5676. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  5677. MVT::Other, getRoot(),
  5678. getValue(I.getArgOperand(0)),
  5679. getValue(I.getArgOperand(1)),
  5680. DAG.getSrcValue(I.getArgOperand(0)),
  5681. DAG.getSrcValue(I.getArgOperand(1))));
  5682. }
  5683. /// \brief Lower an argument list according to the target calling convention.
  5684. ///
  5685. /// \return A tuple of <return-value, token-chain>
  5686. ///
  5687. /// This is a helper for lowering intrinsics that follow a target calling
  5688. /// convention or require stack pointer adjustment. Only a subset of the
  5689. /// intrinsic's operands need to participate in the calling convention.
  5690. std::pair<SDValue, SDValue>
  5691. SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
  5692. unsigned NumArgs, SDValue Callee,
  5693. Type *ReturnTy,
  5694. MachineBasicBlock *LandingPad,
  5695. bool IsPatchPoint) {
  5696. TargetLowering::ArgListTy Args;
  5697. Args.reserve(NumArgs);
  5698. // Populate the argument list.
  5699. // Attributes for args start at offset 1, after the return attribute.
  5700. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
  5701. ArgI != ArgE; ++ArgI) {
  5702. const Value *V = CS->getOperand(ArgI);
  5703. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  5704. TargetLowering::ArgListEntry Entry;
  5705. Entry.Node = getValue(V);
  5706. Entry.Ty = V->getType();
  5707. Entry.setAttributes(&CS, AttrI);
  5708. Args.push_back(Entry);
  5709. }
  5710. TargetLowering::CallLoweringInfo CLI(DAG);
  5711. CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
  5712. .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args), NumArgs)
  5713. .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint);
  5714. return lowerInvokable(CLI, LandingPad);
  5715. }
  5716. /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
  5717. /// or patchpoint target node's operand list.
  5718. ///
  5719. /// Constants are converted to TargetConstants purely as an optimization to
  5720. /// avoid constant materialization and register allocation.
  5721. ///
  5722. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  5723. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  5724. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  5725. /// address materialization and register allocation, but may also be required
  5726. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  5727. /// alloca in the entry block, then the runtime may assume that the alloca's
  5728. /// StackMap location can be read immediately after compilation and that the
  5729. /// location is valid at any point during execution (this is similar to the
  5730. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  5731. /// only available in a register, then the runtime would need to trap when
  5732. /// execution reaches the StackMap in order to read the alloca's location.
  5733. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  5734. SDLoc DL, SmallVectorImpl<SDValue> &Ops,
  5735. SelectionDAGBuilder &Builder) {
  5736. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  5737. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  5738. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  5739. Ops.push_back(
  5740. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  5741. Ops.push_back(
  5742. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  5743. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  5744. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  5745. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  5746. FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
  5747. } else
  5748. Ops.push_back(OpVal);
  5749. }
  5750. }
  5751. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  5752. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  5753. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  5754. // [live variables...])
  5755. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  5756. SDValue Chain, InFlag, Callee, NullPtr;
  5757. SmallVector<SDValue, 32> Ops;
  5758. SDLoc DL = getCurSDLoc();
  5759. Callee = getValue(CI.getCalledValue());
  5760. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  5761. // The stackmap intrinsic only records the live variables (the arguemnts
  5762. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  5763. // intrinsic, this won't be lowered to a function call. This means we don't
  5764. // have to worry about calling conventions and target specific lowering code.
  5765. // Instead we perform the call lowering right here.
  5766. //
  5767. // chain, flag = CALLSEQ_START(chain, 0)
  5768. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  5769. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  5770. //
  5771. Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
  5772. InFlag = Chain.getValue(1);
  5773. // Add the <id> and <numBytes> constants.
  5774. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  5775. Ops.push_back(DAG.getTargetConstant(
  5776. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  5777. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  5778. Ops.push_back(DAG.getTargetConstant(
  5779. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  5780. MVT::i32));
  5781. // Push live variables for the stack map.
  5782. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  5783. // We are not pushing any register mask info here on the operands list,
  5784. // because the stackmap doesn't clobber anything.
  5785. // Push the chain and the glue flag.
  5786. Ops.push_back(Chain);
  5787. Ops.push_back(InFlag);
  5788. // Create the STACKMAP node.
  5789. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5790. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  5791. Chain = SDValue(SM, 0);
  5792. InFlag = Chain.getValue(1);
  5793. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  5794. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  5795. // Set the root to the target-lowered call chain.
  5796. DAG.setRoot(Chain);
  5797. // Inform the Frame Information that we have a stackmap in this function.
  5798. FuncInfo.MF->getFrameInfo()->setHasStackMap();
  5799. }
  5800. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  5801. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  5802. MachineBasicBlock *LandingPad) {
  5803. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  5804. // i32 <numBytes>,
  5805. // i8* <target>,
  5806. // i32 <numArgs>,
  5807. // [Args...],
  5808. // [live variables...])
  5809. CallingConv::ID CC = CS.getCallingConv();
  5810. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  5811. bool HasDef = !CS->getType()->isVoidTy();
  5812. SDLoc dl = getCurSDLoc();
  5813. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  5814. // Handle immediate and symbolic callees.
  5815. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  5816. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  5817. /*isTarget=*/true);
  5818. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  5819. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  5820. SDLoc(SymbolicCallee),
  5821. SymbolicCallee->getValueType(0));
  5822. // Get the real number of arguments participating in the call <numArgs>
  5823. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  5824. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  5825. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  5826. // Intrinsics include all meta-operands up to but not including CC.
  5827. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  5828. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  5829. "Not enough arguments provided to the patchpoint intrinsic");
  5830. // For AnyRegCC the arguments are lowered later on manually.
  5831. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  5832. Type *ReturnTy =
  5833. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  5834. std::pair<SDValue, SDValue> Result =
  5835. lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
  5836. LandingPad, true);
  5837. SDNode *CallEnd = Result.second.getNode();
  5838. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  5839. CallEnd = CallEnd->getOperand(0).getNode();
  5840. /// Get a call instruction from the call sequence chain.
  5841. /// Tail calls are not allowed.
  5842. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  5843. "Expected a callseq node.");
  5844. SDNode *Call = CallEnd->getOperand(0).getNode();
  5845. bool HasGlue = Call->getGluedNode();
  5846. // Replace the target specific call node with the patchable intrinsic.
  5847. SmallVector<SDValue, 8> Ops;
  5848. // Add the <id> and <numBytes> constants.
  5849. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  5850. Ops.push_back(DAG.getTargetConstant(
  5851. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  5852. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  5853. Ops.push_back(DAG.getTargetConstant(
  5854. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  5855. MVT::i32));
  5856. // Add the callee.
  5857. Ops.push_back(Callee);
  5858. // Adjust <numArgs> to account for any arguments that have been passed on the
  5859. // stack instead.
  5860. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  5861. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  5862. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  5863. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  5864. // Add the calling convention
  5865. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  5866. // Add the arguments we omitted previously. The register allocator should
  5867. // place these in any free register.
  5868. if (IsAnyRegCC)
  5869. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  5870. Ops.push_back(getValue(CS.getArgument(i)));
  5871. // Push the arguments from the call instruction up to the register mask.
  5872. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  5873. Ops.append(Call->op_begin() + 2, e);
  5874. // Push live variables for the stack map.
  5875. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  5876. // Push the register mask info.
  5877. if (HasGlue)
  5878. Ops.push_back(*(Call->op_end()-2));
  5879. else
  5880. Ops.push_back(*(Call->op_end()-1));
  5881. // Push the chain (this is originally the first operand of the call, but
  5882. // becomes now the last or second to last operand).
  5883. Ops.push_back(*(Call->op_begin()));
  5884. // Push the glue flag (last operand).
  5885. if (HasGlue)
  5886. Ops.push_back(*(Call->op_end()-1));
  5887. SDVTList NodeTys;
  5888. if (IsAnyRegCC && HasDef) {
  5889. // Create the return types based on the intrinsic definition
  5890. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5891. SmallVector<EVT, 3> ValueVTs;
  5892. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  5893. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  5894. // There is always a chain and a glue type at the end
  5895. ValueVTs.push_back(MVT::Other);
  5896. ValueVTs.push_back(MVT::Glue);
  5897. NodeTys = DAG.getVTList(ValueVTs);
  5898. } else
  5899. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5900. // Replace the target specific call node with a PATCHPOINT node.
  5901. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  5902. dl, NodeTys, Ops);
  5903. // Update the NodeMap.
  5904. if (HasDef) {
  5905. if (IsAnyRegCC)
  5906. setValue(CS.getInstruction(), SDValue(MN, 0));
  5907. else
  5908. setValue(CS.getInstruction(), Result.first);
  5909. }
  5910. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  5911. // call sequence. Furthermore the location of the chain and glue can change
  5912. // when the AnyReg calling convention is used and the intrinsic returns a
  5913. // value.
  5914. if (IsAnyRegCC && HasDef) {
  5915. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  5916. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  5917. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  5918. } else
  5919. DAG.ReplaceAllUsesWith(Call, MN);
  5920. DAG.DeleteNode(Call);
  5921. // Inform the Frame Information that we have a patchpoint in this function.
  5922. FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
  5923. }
  5924. /// Returns an AttributeSet representing the attributes applied to the return
  5925. /// value of the given call.
  5926. static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  5927. SmallVector<Attribute::AttrKind, 2> Attrs;
  5928. if (CLI.RetSExt)
  5929. Attrs.push_back(Attribute::SExt);
  5930. if (CLI.RetZExt)
  5931. Attrs.push_back(Attribute::ZExt);
  5932. if (CLI.IsInReg)
  5933. Attrs.push_back(Attribute::InReg);
  5934. return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
  5935. Attrs);
  5936. }
  5937. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  5938. /// implementation, which just calls LowerCall.
  5939. /// FIXME: When all targets are
  5940. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  5941. std::pair<SDValue, SDValue>
  5942. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  5943. // Handle the incoming return values from the call.
  5944. CLI.Ins.clear();
  5945. Type *OrigRetTy = CLI.RetTy;
  5946. SmallVector<EVT, 4> RetTys;
  5947. SmallVector<uint64_t, 4> Offsets;
  5948. auto &DL = CLI.DAG.getDataLayout();
  5949. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  5950. SmallVector<ISD::OutputArg, 4> Outs;
  5951. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  5952. bool CanLowerReturn =
  5953. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  5954. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  5955. SDValue DemoteStackSlot;
  5956. int DemoteStackIdx = -100;
  5957. if (!CanLowerReturn) {
  5958. // FIXME: equivalent assert?
  5959. // assert(!CS.hasInAllocaArgument() &&
  5960. // "sret demotion is incompatible with inalloca");
  5961. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  5962. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  5963. MachineFunction &MF = CLI.DAG.getMachineFunction();
  5964. DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  5965. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  5966. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
  5967. ArgListEntry Entry;
  5968. Entry.Node = DemoteStackSlot;
  5969. Entry.Ty = StackSlotPtrType;
  5970. Entry.isSExt = false;
  5971. Entry.isZExt = false;
  5972. Entry.isInReg = false;
  5973. Entry.isSRet = true;
  5974. Entry.isNest = false;
  5975. Entry.isByVal = false;
  5976. Entry.isReturned = false;
  5977. Entry.Alignment = Align;
  5978. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  5979. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  5980. // sret demotion isn't compatible with tail-calls, since the sret argument
  5981. // points into the callers stack frame.
  5982. CLI.IsTailCall = false;
  5983. } else {
  5984. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5985. EVT VT = RetTys[I];
  5986. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  5987. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  5988. for (unsigned i = 0; i != NumRegs; ++i) {
  5989. ISD::InputArg MyFlags;
  5990. MyFlags.VT = RegisterVT;
  5991. MyFlags.ArgVT = VT;
  5992. MyFlags.Used = CLI.IsReturnValueUsed;
  5993. if (CLI.RetSExt)
  5994. MyFlags.Flags.setSExt();
  5995. if (CLI.RetZExt)
  5996. MyFlags.Flags.setZExt();
  5997. if (CLI.IsInReg)
  5998. MyFlags.Flags.setInReg();
  5999. CLI.Ins.push_back(MyFlags);
  6000. }
  6001. }
  6002. }
  6003. // Handle all of the outgoing arguments.
  6004. CLI.Outs.clear();
  6005. CLI.OutVals.clear();
  6006. ArgListTy &Args = CLI.getArgs();
  6007. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  6008. SmallVector<EVT, 4> ValueVTs;
  6009. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  6010. Type *FinalType = Args[i].Ty;
  6011. if (Args[i].isByVal)
  6012. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  6013. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  6014. FinalType, CLI.CallConv, CLI.IsVarArg);
  6015. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  6016. ++Value) {
  6017. EVT VT = ValueVTs[Value];
  6018. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  6019. SDValue Op = SDValue(Args[i].Node.getNode(),
  6020. Args[i].Node.getResNo() + Value);
  6021. ISD::ArgFlagsTy Flags;
  6022. unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
  6023. if (Args[i].isZExt)
  6024. Flags.setZExt();
  6025. if (Args[i].isSExt)
  6026. Flags.setSExt();
  6027. if (Args[i].isInReg)
  6028. Flags.setInReg();
  6029. if (Args[i].isSRet)
  6030. Flags.setSRet();
  6031. if (Args[i].isByVal)
  6032. Flags.setByVal();
  6033. if (Args[i].isInAlloca) {
  6034. Flags.setInAlloca();
  6035. // Set the byval flag for CCAssignFn callbacks that don't know about
  6036. // inalloca. This way we can know how many bytes we should've allocated
  6037. // and how many bytes a callee cleanup function will pop. If we port
  6038. // inalloca to more targets, we'll have to add custom inalloca handling
  6039. // in the various CC lowering callbacks.
  6040. Flags.setByVal();
  6041. }
  6042. if (Args[i].isByVal || Args[i].isInAlloca) {
  6043. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  6044. Type *ElementTy = Ty->getElementType();
  6045. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  6046. // For ByVal, alignment should come from FE. BE will guess if this
  6047. // info is not there but there are cases it cannot get right.
  6048. unsigned FrameAlign;
  6049. if (Args[i].Alignment)
  6050. FrameAlign = Args[i].Alignment;
  6051. else
  6052. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  6053. Flags.setByValAlign(FrameAlign);
  6054. }
  6055. if (Args[i].isNest)
  6056. Flags.setNest();
  6057. if (NeedsRegBlock)
  6058. Flags.setInConsecutiveRegs();
  6059. Flags.setOrigAlign(OriginalAlignment);
  6060. MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6061. unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
  6062. SmallVector<SDValue, 4> Parts(NumParts);
  6063. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  6064. if (Args[i].isSExt)
  6065. ExtendKind = ISD::SIGN_EXTEND;
  6066. else if (Args[i].isZExt)
  6067. ExtendKind = ISD::ZERO_EXTEND;
  6068. // Conservatively only handle 'returned' on non-vectors for now
  6069. if (Args[i].isReturned && !Op.getValueType().isVector()) {
  6070. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  6071. "unexpected use of 'returned'");
  6072. // Before passing 'returned' to the target lowering code, ensure that
  6073. // either the register MVT and the actual EVT are the same size or that
  6074. // the return value and argument are extended in the same way; in these
  6075. // cases it's safe to pass the argument register value unchanged as the
  6076. // return register value (although it's at the target's option whether
  6077. // to do so)
  6078. // TODO: allow code generation to take advantage of partially preserved
  6079. // registers rather than clobbering the entire register when the
  6080. // parameter extension method is not compatible with the return
  6081. // extension method
  6082. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  6083. (ExtendKind != ISD::ANY_EXTEND &&
  6084. CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
  6085. Flags.setReturned();
  6086. }
  6087. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  6088. CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
  6089. for (unsigned j = 0; j != NumParts; ++j) {
  6090. // if it isn't first piece, alignment must be 1
  6091. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  6092. i < CLI.NumFixedArgs,
  6093. i, j*Parts[j].getValueType().getStoreSize());
  6094. if (NumParts > 1 && j == 0)
  6095. MyFlags.Flags.setSplit();
  6096. else if (j != 0)
  6097. MyFlags.Flags.setOrigAlign(1);
  6098. CLI.Outs.push_back(MyFlags);
  6099. CLI.OutVals.push_back(Parts[j]);
  6100. }
  6101. if (NeedsRegBlock && Value == NumValues - 1)
  6102. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  6103. }
  6104. }
  6105. SmallVector<SDValue, 4> InVals;
  6106. CLI.Chain = LowerCall(CLI, InVals);
  6107. // Verify that the target's LowerCall behaved as expected.
  6108. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  6109. "LowerCall didn't return a valid chain!");
  6110. assert((!CLI.IsTailCall || InVals.empty()) &&
  6111. "LowerCall emitted a return value for a tail call!");
  6112. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  6113. "LowerCall didn't emit the correct number of values!");
  6114. // For a tail call, the return value is merely live-out and there aren't
  6115. // any nodes in the DAG representing it. Return a special value to
  6116. // indicate that a tail call has been emitted and no more Instructions
  6117. // should be processed in the current block.
  6118. if (CLI.IsTailCall) {
  6119. CLI.DAG.setRoot(CLI.Chain);
  6120. return std::make_pair(SDValue(), SDValue());
  6121. }
  6122. DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  6123. assert(InVals[i].getNode() &&
  6124. "LowerCall emitted a null value!");
  6125. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  6126. "LowerCall emitted a value with the wrong type!");
  6127. });
  6128. SmallVector<SDValue, 4> ReturnValues;
  6129. if (!CanLowerReturn) {
  6130. // The instruction result is the result of loading from the
  6131. // hidden sret parameter.
  6132. SmallVector<EVT, 1> PVTs;
  6133. Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
  6134. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  6135. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  6136. EVT PtrVT = PVTs[0];
  6137. unsigned NumValues = RetTys.size();
  6138. ReturnValues.resize(NumValues);
  6139. SmallVector<SDValue, 4> Chains(NumValues);
  6140. for (unsigned i = 0; i < NumValues; ++i) {
  6141. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  6142. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  6143. PtrVT));
  6144. SDValue L = CLI.DAG.getLoad(
  6145. RetTys[i], CLI.DL, CLI.Chain, Add,
  6146. MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
  6147. false, false, 1);
  6148. ReturnValues[i] = L;
  6149. Chains[i] = L.getValue(1);
  6150. }
  6151. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  6152. } else {
  6153. // Collect the legal value parts into potentially illegal values
  6154. // that correspond to the original function's return values.
  6155. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6156. if (CLI.RetSExt)
  6157. AssertOp = ISD::AssertSext;
  6158. else if (CLI.RetZExt)
  6159. AssertOp = ISD::AssertZext;
  6160. unsigned CurReg = 0;
  6161. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6162. EVT VT = RetTys[I];
  6163. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6164. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6165. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  6166. NumRegs, RegisterVT, VT, nullptr,
  6167. AssertOp));
  6168. CurReg += NumRegs;
  6169. }
  6170. // For a function returning void, there is no return value. We can't create
  6171. // such a node, so we just return a null return value in that case. In
  6172. // that case, nothing will actually look at the value.
  6173. if (ReturnValues.empty())
  6174. return std::make_pair(SDValue(), CLI.Chain);
  6175. }
  6176. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  6177. CLI.DAG.getVTList(RetTys), ReturnValues);
  6178. return std::make_pair(Res, CLI.Chain);
  6179. }
  6180. void TargetLowering::LowerOperationWrapper(SDNode *N,
  6181. SmallVectorImpl<SDValue> &Results,
  6182. SelectionDAG &DAG) const {
  6183. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  6184. if (Res.getNode())
  6185. Results.push_back(Res);
  6186. }
  6187. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  6188. llvm_unreachable("LowerOperation not implemented for this target!");
  6189. }
  6190. void
  6191. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  6192. SDValue Op = getNonRegisterValue(V);
  6193. assert((Op.getOpcode() != ISD::CopyFromReg ||
  6194. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  6195. "Copy from a reg to the same reg!");
  6196. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  6197. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6198. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  6199. V->getType());
  6200. SDValue Chain = DAG.getEntryNode();
  6201. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  6202. FuncInfo.PreferredExtendType.end())
  6203. ? ISD::ANY_EXTEND
  6204. : FuncInfo.PreferredExtendType[V];
  6205. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  6206. PendingExports.push_back(Chain);
  6207. }
  6208. #include "llvm/CodeGen/SelectionDAGISel.h"
  6209. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  6210. /// entry block, return true. This includes arguments used by switches, since
  6211. /// the switch may expand into multiple basic blocks.
  6212. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  6213. // With FastISel active, we may be splitting blocks, so force creation
  6214. // of virtual registers for all non-dead arguments.
  6215. if (FastISel)
  6216. return A->use_empty();
  6217. const BasicBlock *Entry = A->getParent()->begin();
  6218. for (const User *U : A->users())
  6219. if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
  6220. return false; // Use not in entry block.
  6221. return true;
  6222. }
  6223. void SelectionDAGISel::LowerArguments(const Function &F) {
  6224. SelectionDAG &DAG = SDB->DAG;
  6225. SDLoc dl = SDB->getCurSDLoc();
  6226. const DataLayout &DL = DAG.getDataLayout();
  6227. SmallVector<ISD::InputArg, 16> Ins;
  6228. if (!FuncInfo->CanLowerReturn) {
  6229. // Put in an sret pointer parameter before all the other parameters.
  6230. SmallVector<EVT, 1> ValueVTs;
  6231. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  6232. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6233. // NOTE: Assuming that a pointer will never break down to more than one VT
  6234. // or one register.
  6235. ISD::ArgFlagsTy Flags;
  6236. Flags.setSRet();
  6237. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  6238. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  6239. ISD::InputArg::NoArgIndex, 0);
  6240. Ins.push_back(RetArg);
  6241. }
  6242. // Set up the incoming argument description vector.
  6243. unsigned Idx = 1;
  6244. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
  6245. I != E; ++I, ++Idx) {
  6246. SmallVector<EVT, 4> ValueVTs;
  6247. ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
  6248. bool isArgValueUsed = !I->use_empty();
  6249. unsigned PartBase = 0;
  6250. Type *FinalType = I->getType();
  6251. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  6252. FinalType = cast<PointerType>(FinalType)->getElementType();
  6253. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  6254. FinalType, F.getCallingConv(), F.isVarArg());
  6255. for (unsigned Value = 0, NumValues = ValueVTs.size();
  6256. Value != NumValues; ++Value) {
  6257. EVT VT = ValueVTs[Value];
  6258. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  6259. ISD::ArgFlagsTy Flags;
  6260. unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
  6261. if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6262. Flags.setZExt();
  6263. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6264. Flags.setSExt();
  6265. if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
  6266. Flags.setInReg();
  6267. if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
  6268. Flags.setSRet();
  6269. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  6270. Flags.setByVal();
  6271. if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
  6272. Flags.setInAlloca();
  6273. // Set the byval flag for CCAssignFn callbacks that don't know about
  6274. // inalloca. This way we can know how many bytes we should've allocated
  6275. // and how many bytes a callee cleanup function will pop. If we port
  6276. // inalloca to more targets, we'll have to add custom inalloca handling
  6277. // in the various CC lowering callbacks.
  6278. Flags.setByVal();
  6279. }
  6280. if (Flags.isByVal() || Flags.isInAlloca()) {
  6281. PointerType *Ty = cast<PointerType>(I->getType());
  6282. Type *ElementTy = Ty->getElementType();
  6283. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  6284. // For ByVal, alignment should be passed from FE. BE will guess if
  6285. // this info is not there but there are cases it cannot get right.
  6286. unsigned FrameAlign;
  6287. if (F.getParamAlignment(Idx))
  6288. FrameAlign = F.getParamAlignment(Idx);
  6289. else
  6290. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  6291. Flags.setByValAlign(FrameAlign);
  6292. }
  6293. if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
  6294. Flags.setNest();
  6295. if (NeedsRegBlock)
  6296. Flags.setInConsecutiveRegs();
  6297. Flags.setOrigAlign(OriginalAlignment);
  6298. MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6299. unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6300. for (unsigned i = 0; i != NumRegs; ++i) {
  6301. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  6302. Idx-1, PartBase+i*RegisterVT.getStoreSize());
  6303. if (NumRegs > 1 && i == 0)
  6304. MyFlags.Flags.setSplit();
  6305. // if it isn't first piece, alignment must be 1
  6306. else if (i > 0)
  6307. MyFlags.Flags.setOrigAlign(1);
  6308. Ins.push_back(MyFlags);
  6309. }
  6310. if (NeedsRegBlock && Value == NumValues - 1)
  6311. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  6312. PartBase += VT.getStoreSize();
  6313. }
  6314. }
  6315. // Call the target to set up the argument values.
  6316. SmallVector<SDValue, 8> InVals;
  6317. SDValue NewRoot = TLI->LowerFormalArguments(
  6318. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  6319. // Verify that the target's LowerFormalArguments behaved as expected.
  6320. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  6321. "LowerFormalArguments didn't return a valid chain!");
  6322. assert(InVals.size() == Ins.size() &&
  6323. "LowerFormalArguments didn't emit the correct number of values!");
  6324. DEBUG({
  6325. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  6326. assert(InVals[i].getNode() &&
  6327. "LowerFormalArguments emitted a null value!");
  6328. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  6329. "LowerFormalArguments emitted a value with the wrong type!");
  6330. }
  6331. });
  6332. // Update the DAG with the new chain value resulting from argument lowering.
  6333. DAG.setRoot(NewRoot);
  6334. // Set up the argument values.
  6335. unsigned i = 0;
  6336. Idx = 1;
  6337. if (!FuncInfo->CanLowerReturn) {
  6338. // Create a virtual register for the sret pointer, and put in a copy
  6339. // from the sret argument into it.
  6340. SmallVector<EVT, 1> ValueVTs;
  6341. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  6342. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6343. MVT VT = ValueVTs[0].getSimpleVT();
  6344. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6345. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6346. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  6347. RegVT, VT, nullptr, AssertOp);
  6348. MachineFunction& MF = SDB->DAG.getMachineFunction();
  6349. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  6350. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  6351. FuncInfo->DemoteRegister = SRetReg;
  6352. NewRoot =
  6353. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  6354. DAG.setRoot(NewRoot);
  6355. // i indexes lowered arguments. Bump it past the hidden sret argument.
  6356. // Idx indexes LLVM arguments. Don't touch it.
  6357. ++i;
  6358. }
  6359. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  6360. ++I, ++Idx) {
  6361. SmallVector<SDValue, 4> ArgValues;
  6362. SmallVector<EVT, 4> ValueVTs;
  6363. ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
  6364. unsigned NumValues = ValueVTs.size();
  6365. // If this argument is unused then remember its value. It is used to generate
  6366. // debugging information.
  6367. if (I->use_empty() && NumValues) {
  6368. SDB->setUnusedArgValue(I, InVals[i]);
  6369. // Also remember any frame index for use in FastISel.
  6370. if (FrameIndexSDNode *FI =
  6371. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  6372. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6373. }
  6374. for (unsigned Val = 0; Val != NumValues; ++Val) {
  6375. EVT VT = ValueVTs[Val];
  6376. MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6377. unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6378. if (!I->use_empty()) {
  6379. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6380. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6381. AssertOp = ISD::AssertSext;
  6382. else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6383. AssertOp = ISD::AssertZext;
  6384. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  6385. NumParts, PartVT, VT,
  6386. nullptr, AssertOp));
  6387. }
  6388. i += NumParts;
  6389. }
  6390. // We don't need to do anything else for unused arguments.
  6391. if (ArgValues.empty())
  6392. continue;
  6393. // Note down frame index.
  6394. if (FrameIndexSDNode *FI =
  6395. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  6396. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6397. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  6398. SDB->getCurSDLoc());
  6399. SDB->setValue(I, Res);
  6400. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  6401. if (LoadSDNode *LNode =
  6402. dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
  6403. if (FrameIndexSDNode *FI =
  6404. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  6405. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6406. }
  6407. // If this argument is live outside of the entry block, insert a copy from
  6408. // wherever we got it to the vreg that other BB's will reference it as.
  6409. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  6410. // If we can, though, try to skip creating an unnecessary vreg.
  6411. // FIXME: This isn't very clean... it would be nice to make this more
  6412. // general. It's also subtly incompatible with the hacks FastISel
  6413. // uses with vregs.
  6414. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  6415. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  6416. FuncInfo->ValueMap[I] = Reg;
  6417. continue;
  6418. }
  6419. }
  6420. if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
  6421. FuncInfo->InitializeRegForValue(I);
  6422. SDB->CopyToExportRegsIfNeeded(I);
  6423. }
  6424. }
  6425. assert(i == InVals.size() && "Argument register count mismatch!");
  6426. // Finally, if the target has anything special to do, allow it to do so.
  6427. EmitFunctionEntryCode();
  6428. }
  6429. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  6430. /// ensure constants are generated when needed. Remember the virtual registers
  6431. /// that need to be added to the Machine PHI nodes as input. We cannot just
  6432. /// directly add them, because expansion might result in multiple MBB's for one
  6433. /// BB. As such, the start of the BB might correspond to a different MBB than
  6434. /// the end.
  6435. ///
  6436. void
  6437. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  6438. const TerminatorInst *TI = LLVMBB->getTerminator();
  6439. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  6440. // Check PHI nodes in successors that expect a value to be available from this
  6441. // block.
  6442. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  6443. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  6444. if (!isa<PHINode>(SuccBB->begin())) continue;
  6445. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  6446. // If this terminator has multiple identical successors (common for
  6447. // switches), only handle each succ once.
  6448. if (!SuccsHandled.insert(SuccMBB).second)
  6449. continue;
  6450. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  6451. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  6452. // nodes and Machine PHI nodes, but the incoming operands have not been
  6453. // emitted yet.
  6454. for (BasicBlock::const_iterator I = SuccBB->begin();
  6455. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  6456. // Ignore dead phi's.
  6457. if (PN->use_empty()) continue;
  6458. // Skip empty types
  6459. if (PN->getType()->isEmptyTy())
  6460. continue;
  6461. unsigned Reg;
  6462. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  6463. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  6464. unsigned &RegOut = ConstantsOut[C];
  6465. if (RegOut == 0) {
  6466. RegOut = FuncInfo.CreateRegs(C->getType());
  6467. CopyValueToVirtualRegister(C, RegOut);
  6468. }
  6469. Reg = RegOut;
  6470. } else {
  6471. DenseMap<const Value *, unsigned>::iterator I =
  6472. FuncInfo.ValueMap.find(PHIOp);
  6473. if (I != FuncInfo.ValueMap.end())
  6474. Reg = I->second;
  6475. else {
  6476. assert(isa<AllocaInst>(PHIOp) &&
  6477. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  6478. "Didn't codegen value into a register!??");
  6479. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  6480. CopyValueToVirtualRegister(PHIOp, Reg);
  6481. }
  6482. }
  6483. // Remember that this register needs to added to the machine PHI node as
  6484. // the input for this MBB.
  6485. SmallVector<EVT, 4> ValueVTs;
  6486. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6487. ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
  6488. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  6489. EVT VT = ValueVTs[vti];
  6490. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  6491. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  6492. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  6493. Reg += NumRegisters;
  6494. }
  6495. }
  6496. }
  6497. ConstantsOut.clear();
  6498. }
  6499. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  6500. /// is 0.
  6501. MachineBasicBlock *
  6502. SelectionDAGBuilder::StackProtectorDescriptor::
  6503. AddSuccessorMBB(const BasicBlock *BB,
  6504. MachineBasicBlock *ParentMBB,
  6505. bool IsLikely,
  6506. MachineBasicBlock *SuccMBB) {
  6507. // If SuccBB has not been created yet, create it.
  6508. if (!SuccMBB) {
  6509. MachineFunction *MF = ParentMBB->getParent();
  6510. MachineFunction::iterator BBI = ParentMBB;
  6511. SuccMBB = MF->CreateMachineBasicBlock(BB);
  6512. MF->insert(++BBI, SuccMBB);
  6513. }
  6514. // Add it as a successor of ParentMBB.
  6515. ParentMBB->addSuccessor(
  6516. SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
  6517. return SuccMBB;
  6518. }
  6519. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  6520. MachineFunction::iterator I = MBB;
  6521. if (++I == FuncInfo.MF->end())
  6522. return nullptr;
  6523. return I;
  6524. }
  6525. /// During lowering new call nodes can be created (such as memset, etc.).
  6526. /// Those will become new roots of the current DAG, but complications arise
  6527. /// when they are tail calls. In such cases, the call lowering will update
  6528. /// the root, but the builder still needs to know that a tail call has been
  6529. /// lowered in order to avoid generating an additional return.
  6530. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  6531. // If the node is null, we do have a tail call.
  6532. if (MaybeTC.getNode() != nullptr)
  6533. DAG.setRoot(MaybeTC);
  6534. else
  6535. HasTailCall = true;
  6536. }
  6537. bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
  6538. unsigned *TotalCases, unsigned First,
  6539. unsigned Last) {
  6540. assert(Last >= First);
  6541. assert(TotalCases[Last] >= TotalCases[First]);
  6542. APInt LowCase = Clusters[First].Low->getValue();
  6543. APInt HighCase = Clusters[Last].High->getValue();
  6544. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  6545. // FIXME: A range of consecutive cases has 100% density, but only requires one
  6546. // comparison to lower. We should discriminate against such consecutive ranges
  6547. // in jump tables.
  6548. uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
  6549. uint64_t Range = Diff + 1;
  6550. uint64_t NumCases =
  6551. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  6552. assert(NumCases < UINT64_MAX / 100);
  6553. assert(Range >= NumCases);
  6554. return NumCases * 100 >= Range * MinJumpTableDensity;
  6555. }
  6556. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  6557. return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  6558. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
  6559. }
  6560. bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
  6561. unsigned First, unsigned Last,
  6562. const SwitchInst *SI,
  6563. MachineBasicBlock *DefaultMBB,
  6564. CaseCluster &JTCluster) {
  6565. assert(First <= Last);
  6566. uint32_t Weight = 0;
  6567. unsigned NumCmps = 0;
  6568. std::vector<MachineBasicBlock*> Table;
  6569. DenseMap<MachineBasicBlock*, uint32_t> JTWeights;
  6570. for (unsigned I = First; I <= Last; ++I) {
  6571. assert(Clusters[I].Kind == CC_Range);
  6572. Weight += Clusters[I].Weight;
  6573. assert(Weight >= Clusters[I].Weight && "Weight overflow!");
  6574. APInt Low = Clusters[I].Low->getValue();
  6575. APInt High = Clusters[I].High->getValue();
  6576. NumCmps += (Low == High) ? 1 : 2;
  6577. if (I != First) {
  6578. // Fill the gap between this and the previous cluster.
  6579. APInt PreviousHigh = Clusters[I - 1].High->getValue();
  6580. assert(PreviousHigh.slt(Low));
  6581. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  6582. for (uint64_t J = 0; J < Gap; J++)
  6583. Table.push_back(DefaultMBB);
  6584. }
  6585. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  6586. for (uint64_t J = 0; J < ClusterSize; ++J)
  6587. Table.push_back(Clusters[I].MBB);
  6588. JTWeights[Clusters[I].MBB] += Clusters[I].Weight;
  6589. }
  6590. unsigned NumDests = JTWeights.size();
  6591. if (isSuitableForBitTests(NumDests, NumCmps,
  6592. Clusters[First].Low->getValue(),
  6593. Clusters[Last].High->getValue())) {
  6594. // Clusters[First..Last] should be lowered as bit tests instead.
  6595. return false;
  6596. }
  6597. // Create the MBB that will load from and jump through the table.
  6598. // Note: We create it here, but it's not inserted into the function yet.
  6599. MachineFunction *CurMF = FuncInfo.MF;
  6600. MachineBasicBlock *JumpTableMBB =
  6601. CurMF->CreateMachineBasicBlock(SI->getParent());
  6602. // Add successors. Note: use table order for determinism.
  6603. SmallPtrSet<MachineBasicBlock *, 8> Done;
  6604. for (MachineBasicBlock *Succ : Table) {
  6605. if (Done.count(Succ))
  6606. continue;
  6607. addSuccessorWithWeight(JumpTableMBB, Succ, JTWeights[Succ]);
  6608. Done.insert(Succ);
  6609. }
  6610. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6611. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  6612. ->createJumpTableIndex(Table);
  6613. // Set up the jump table info.
  6614. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  6615. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  6616. Clusters[Last].High->getValue(), SI->getCondition(),
  6617. nullptr, false);
  6618. JTCases.emplace_back(std::move(JTH), std::move(JT));
  6619. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  6620. JTCases.size() - 1, Weight);
  6621. return true;
  6622. }
  6623. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  6624. const SwitchInst *SI,
  6625. MachineBasicBlock *DefaultMBB) {
  6626. #ifndef NDEBUG
  6627. // Clusters must be non-empty, sorted, and only contain Range clusters.
  6628. assert(!Clusters.empty());
  6629. for (CaseCluster &C : Clusters)
  6630. assert(C.Kind == CC_Range);
  6631. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  6632. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  6633. #endif
  6634. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6635. if (!areJTsAllowed(TLI))
  6636. return;
  6637. const int64_t N = Clusters.size();
  6638. const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
  6639. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  6640. SmallVector<unsigned, 8> TotalCases(N);
  6641. for (unsigned i = 0; i < N; ++i) {
  6642. APInt Hi = Clusters[i].High->getValue();
  6643. APInt Lo = Clusters[i].Low->getValue();
  6644. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  6645. if (i != 0)
  6646. TotalCases[i] += TotalCases[i - 1];
  6647. }
  6648. if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) {
  6649. // Cheap case: the whole range might be suitable for jump table.
  6650. CaseCluster JTCluster;
  6651. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  6652. Clusters[0] = JTCluster;
  6653. Clusters.resize(1);
  6654. return;
  6655. }
  6656. }
  6657. // The algorithm below is not suitable for -O0.
  6658. if (TM.getOptLevel() == CodeGenOpt::None)
  6659. return;
  6660. // Split Clusters into minimum number of dense partitions. The algorithm uses
  6661. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  6662. // for the Case Statement'" (1994), but builds the MinPartitions array in
  6663. // reverse order to make it easier to reconstruct the partitions in ascending
  6664. // order. In the choice between two optimal partitionings, it picks the one
  6665. // which yields more jump tables.
  6666. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  6667. SmallVector<unsigned, 8> MinPartitions(N);
  6668. // LastElement[i] is the last element of the partition starting at i.
  6669. SmallVector<unsigned, 8> LastElement(N);
  6670. // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
  6671. SmallVector<unsigned, 8> NumTables(N);
  6672. // Base case: There is only one way to partition Clusters[N-1].
  6673. MinPartitions[N - 1] = 1;
  6674. LastElement[N - 1] = N - 1;
  6675. assert(MinJumpTableSize > 1);
  6676. NumTables[N - 1] = 0;
  6677. // Note: loop indexes are signed to avoid underflow.
  6678. for (int64_t i = N - 2; i >= 0; i--) {
  6679. // Find optimal partitioning of Clusters[i..N-1].
  6680. // Baseline: Put Clusters[i] into a partition on its own.
  6681. MinPartitions[i] = MinPartitions[i + 1] + 1;
  6682. LastElement[i] = i;
  6683. NumTables[i] = NumTables[i + 1];
  6684. // Search for a solution that results in fewer partitions.
  6685. for (int64_t j = N - 1; j > i; j--) {
  6686. // Try building a partition from Clusters[i..j].
  6687. if (isDense(Clusters, &TotalCases[0], i, j)) {
  6688. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  6689. bool IsTable = j - i + 1 >= MinJumpTableSize;
  6690. unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
  6691. // If this j leads to fewer partitions, or same number of partitions
  6692. // with more lookup tables, it is a better partitioning.
  6693. if (NumPartitions < MinPartitions[i] ||
  6694. (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
  6695. MinPartitions[i] = NumPartitions;
  6696. LastElement[i] = j;
  6697. NumTables[i] = Tables;
  6698. }
  6699. }
  6700. }
  6701. }
  6702. // Iterate over the partitions, replacing some with jump tables in-place.
  6703. unsigned DstIndex = 0;
  6704. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  6705. Last = LastElement[First];
  6706. assert(Last >= First);
  6707. assert(DstIndex <= First);
  6708. unsigned NumClusters = Last - First + 1;
  6709. CaseCluster JTCluster;
  6710. if (NumClusters >= MinJumpTableSize &&
  6711. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  6712. Clusters[DstIndex++] = JTCluster;
  6713. } else {
  6714. for (unsigned I = First; I <= Last; ++I)
  6715. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  6716. }
  6717. }
  6718. Clusters.resize(DstIndex);
  6719. }
  6720. bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
  6721. // FIXME: Using the pointer type doesn't seem ideal.
  6722. uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
  6723. uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
  6724. return Range <= BW;
  6725. }
  6726. bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
  6727. unsigned NumCmps,
  6728. const APInt &Low,
  6729. const APInt &High) {
  6730. // FIXME: I don't think NumCmps is the correct metric: a single case and a
  6731. // range of cases both require only one branch to lower. Just looking at the
  6732. // number of clusters and destinations should be enough to decide whether to
  6733. // build bit tests.
  6734. // To lower a range with bit tests, the range must fit the bitwidth of a
  6735. // machine word.
  6736. if (!rangeFitsInWord(Low, High))
  6737. return false;
  6738. // Decide whether it's profitable to lower this range with bit tests. Each
  6739. // destination requires a bit test and branch, and there is an overall range
  6740. // check branch. For a small number of clusters, separate comparisons might be
  6741. // cheaper, and for many destinations, splitting the range might be better.
  6742. return (NumDests == 1 && NumCmps >= 3) ||
  6743. (NumDests == 2 && NumCmps >= 5) ||
  6744. (NumDests == 3 && NumCmps >= 6);
  6745. }
  6746. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  6747. unsigned First, unsigned Last,
  6748. const SwitchInst *SI,
  6749. CaseCluster &BTCluster) {
  6750. assert(First <= Last);
  6751. if (First == Last)
  6752. return false;
  6753. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  6754. unsigned NumCmps = 0;
  6755. for (int64_t I = First; I <= Last; ++I) {
  6756. assert(Clusters[I].Kind == CC_Range);
  6757. Dests.set(Clusters[I].MBB->getNumber());
  6758. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  6759. }
  6760. unsigned NumDests = Dests.count();
  6761. APInt Low = Clusters[First].Low->getValue();
  6762. APInt High = Clusters[Last].High->getValue();
  6763. assert(Low.slt(High));
  6764. if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
  6765. return false;
  6766. APInt LowBound;
  6767. APInt CmpRange;
  6768. const int BitWidth = DAG.getTargetLoweringInfo()
  6769. .getPointerTy(DAG.getDataLayout())
  6770. .getSizeInBits();
  6771. assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
  6772. if (Low.isNonNegative() && High.slt(BitWidth)) {
  6773. // Optimize the case where all the case values fit in a
  6774. // word without having to subtract minValue. In this case,
  6775. // we can optimize away the subtraction.
  6776. LowBound = APInt::getNullValue(Low.getBitWidth());
  6777. CmpRange = High;
  6778. } else {
  6779. LowBound = Low;
  6780. CmpRange = High - Low;
  6781. }
  6782. CaseBitsVector CBV;
  6783. uint32_t TotalWeight = 0;
  6784. for (unsigned i = First; i <= Last; ++i) {
  6785. // Find the CaseBits for this destination.
  6786. unsigned j;
  6787. for (j = 0; j < CBV.size(); ++j)
  6788. if (CBV[j].BB == Clusters[i].MBB)
  6789. break;
  6790. if (j == CBV.size())
  6791. CBV.push_back(CaseBits(0, Clusters[i].MBB, 0, 0));
  6792. CaseBits *CB = &CBV[j];
  6793. // Update Mask, Bits and ExtraWeight.
  6794. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  6795. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  6796. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  6797. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  6798. CB->Bits += Hi - Lo + 1;
  6799. CB->ExtraWeight += Clusters[i].Weight;
  6800. TotalWeight += Clusters[i].Weight;
  6801. assert(TotalWeight >= Clusters[i].Weight && "Weight overflow!");
  6802. }
  6803. BitTestInfo BTI;
  6804. std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
  6805. // Sort by weight first, number of bits second.
  6806. if (a.ExtraWeight != b.ExtraWeight)
  6807. return a.ExtraWeight > b.ExtraWeight;
  6808. return a.Bits > b.Bits;
  6809. });
  6810. for (auto &CB : CBV) {
  6811. MachineBasicBlock *BitTestBB =
  6812. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  6813. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraWeight));
  6814. }
  6815. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  6816. SI->getCondition(), -1U, MVT::Other, false, nullptr,
  6817. nullptr, std::move(BTI));
  6818. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  6819. BitTestCases.size() - 1, TotalWeight);
  6820. return true;
  6821. }
  6822. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  6823. const SwitchInst *SI) {
  6824. // Partition Clusters into as few subsets as possible, where each subset has a
  6825. // range that fits in a machine word and has <= 3 unique destinations.
  6826. #ifndef NDEBUG
  6827. // Clusters must be sorted and contain Range or JumpTable clusters.
  6828. assert(!Clusters.empty());
  6829. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  6830. for (const CaseCluster &C : Clusters)
  6831. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  6832. for (unsigned i = 1; i < Clusters.size(); ++i)
  6833. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  6834. #endif
  6835. // The algorithm below is not suitable for -O0.
  6836. if (TM.getOptLevel() == CodeGenOpt::None)
  6837. return;
  6838. // If target does not have legal shift left, do not emit bit tests at all.
  6839. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6840. EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
  6841. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  6842. return;
  6843. int BitWidth = PTy.getSizeInBits();
  6844. const int64_t N = Clusters.size();
  6845. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  6846. SmallVector<unsigned, 8> MinPartitions(N);
  6847. // LastElement[i] is the last element of the partition starting at i.
  6848. SmallVector<unsigned, 8> LastElement(N);
  6849. // FIXME: This might not be the best algorithm for finding bit test clusters.
  6850. // Base case: There is only one way to partition Clusters[N-1].
  6851. MinPartitions[N - 1] = 1;
  6852. LastElement[N - 1] = N - 1;
  6853. // Note: loop indexes are signed to avoid underflow.
  6854. for (int64_t i = N - 2; i >= 0; --i) {
  6855. // Find optimal partitioning of Clusters[i..N-1].
  6856. // Baseline: Put Clusters[i] into a partition on its own.
  6857. MinPartitions[i] = MinPartitions[i + 1] + 1;
  6858. LastElement[i] = i;
  6859. // Search for a solution that results in fewer partitions.
  6860. // Note: the search is limited by BitWidth, reducing time complexity.
  6861. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  6862. // Try building a partition from Clusters[i..j].
  6863. // Check the range.
  6864. if (!rangeFitsInWord(Clusters[i].Low->getValue(),
  6865. Clusters[j].High->getValue()))
  6866. continue;
  6867. // Check nbr of destinations and cluster types.
  6868. // FIXME: This works, but doesn't seem very efficient.
  6869. bool RangesOnly = true;
  6870. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  6871. for (int64_t k = i; k <= j; k++) {
  6872. if (Clusters[k].Kind != CC_Range) {
  6873. RangesOnly = false;
  6874. break;
  6875. }
  6876. Dests.set(Clusters[k].MBB->getNumber());
  6877. }
  6878. if (!RangesOnly || Dests.count() > 3)
  6879. break;
  6880. // Check if it's a better partition.
  6881. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  6882. if (NumPartitions < MinPartitions[i]) {
  6883. // Found a better partition.
  6884. MinPartitions[i] = NumPartitions;
  6885. LastElement[i] = j;
  6886. }
  6887. }
  6888. }
  6889. // Iterate over the partitions, replacing with bit-test clusters in-place.
  6890. unsigned DstIndex = 0;
  6891. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  6892. Last = LastElement[First];
  6893. assert(First <= Last);
  6894. assert(DstIndex <= First);
  6895. CaseCluster BitTestCluster;
  6896. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  6897. Clusters[DstIndex++] = BitTestCluster;
  6898. } else {
  6899. size_t NumClusters = Last - First + 1;
  6900. std::memmove(&Clusters[DstIndex], &Clusters[First],
  6901. sizeof(Clusters[0]) * NumClusters);
  6902. DstIndex += NumClusters;
  6903. }
  6904. }
  6905. Clusters.resize(DstIndex);
  6906. }
  6907. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  6908. MachineBasicBlock *SwitchMBB,
  6909. MachineBasicBlock *DefaultMBB) {
  6910. MachineFunction *CurMF = FuncInfo.MF;
  6911. MachineBasicBlock *NextMBB = nullptr;
  6912. MachineFunction::iterator BBI = W.MBB;
  6913. if (++BBI != FuncInfo.MF->end())
  6914. NextMBB = BBI;
  6915. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  6916. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  6917. if (Size == 2 && W.MBB == SwitchMBB) {
  6918. // If any two of the cases has the same destination, and if one value
  6919. // is the same as the other, but has one bit unset that the other has set,
  6920. // use bit manipulation to do two compares at once. For example:
  6921. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  6922. // TODO: This could be extended to merge any 2 cases in switches with 3
  6923. // cases.
  6924. // TODO: Handle cases where W.CaseBB != SwitchBB.
  6925. CaseCluster &Small = *W.FirstCluster;
  6926. CaseCluster &Big = *W.LastCluster;
  6927. if (Small.Low == Small.High && Big.Low == Big.High &&
  6928. Small.MBB == Big.MBB) {
  6929. const APInt &SmallValue = Small.Low->getValue();
  6930. const APInt &BigValue = Big.Low->getValue();
  6931. // Check that there is only one bit different.
  6932. APInt CommonBit = BigValue ^ SmallValue;
  6933. if (CommonBit.isPowerOf2()) {
  6934. SDValue CondLHS = getValue(Cond);
  6935. EVT VT = CondLHS.getValueType();
  6936. SDLoc DL = getCurSDLoc();
  6937. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  6938. DAG.getConstant(CommonBit, DL, VT));
  6939. SDValue Cond = DAG.getSetCC(
  6940. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  6941. ISD::SETEQ);
  6942. // Update successor info.
  6943. // Both Small and Big will jump to Small.BB, so we sum up the weights.
  6944. addSuccessorWithWeight(SwitchMBB, Small.MBB, Small.Weight + Big.Weight);
  6945. addSuccessorWithWeight(
  6946. SwitchMBB, DefaultMBB,
  6947. // The default destination is the first successor in IR.
  6948. BPI ? BPI->getEdgeWeight(SwitchMBB->getBasicBlock(), (unsigned)0)
  6949. : 0);
  6950. // Insert the true branch.
  6951. SDValue BrCond =
  6952. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  6953. DAG.getBasicBlock(Small.MBB));
  6954. // Insert the false branch.
  6955. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  6956. DAG.getBasicBlock(DefaultMBB));
  6957. DAG.setRoot(BrCond);
  6958. return;
  6959. }
  6960. }
  6961. }
  6962. if (TM.getOptLevel() != CodeGenOpt::None) {
  6963. // Order cases by weight so the most likely case will be checked first.
  6964. std::sort(W.FirstCluster, W.LastCluster + 1,
  6965. [](const CaseCluster &a, const CaseCluster &b) {
  6966. return a.Weight > b.Weight;
  6967. });
  6968. // Rearrange the case blocks so that the last one falls through if possible
  6969. // without without changing the order of weights.
  6970. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  6971. --I;
  6972. if (I->Weight > W.LastCluster->Weight)
  6973. break;
  6974. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  6975. std::swap(*I, *W.LastCluster);
  6976. break;
  6977. }
  6978. }
  6979. }
  6980. // Compute total weight.
  6981. uint32_t UnhandledWeights = 0;
  6982. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) {
  6983. UnhandledWeights += I->Weight;
  6984. assert(UnhandledWeights >= I->Weight && "Weight overflow!");
  6985. }
  6986. MachineBasicBlock *CurMBB = W.MBB;
  6987. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  6988. MachineBasicBlock *Fallthrough;
  6989. if (I == W.LastCluster) {
  6990. // For the last cluster, fall through to the default destination.
  6991. Fallthrough = DefaultMBB;
  6992. } else {
  6993. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  6994. CurMF->insert(BBI, Fallthrough);
  6995. // Put Cond in a virtual register to make it available from the new blocks.
  6996. ExportFromCurrentBlock(Cond);
  6997. }
  6998. switch (I->Kind) {
  6999. case CC_JumpTable: {
  7000. // FIXME: Optimize away range check based on pivot comparisons.
  7001. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  7002. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  7003. // The jump block hasn't been inserted yet; insert it here.
  7004. MachineBasicBlock *JumpMBB = JT->MBB;
  7005. CurMF->insert(BBI, JumpMBB);
  7006. addSuccessorWithWeight(CurMBB, Fallthrough);
  7007. addSuccessorWithWeight(CurMBB, JumpMBB);
  7008. // The jump table header will be inserted in our current block, do the
  7009. // range check, and fall through to our fallthrough block.
  7010. JTH->HeaderBB = CurMBB;
  7011. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  7012. // If we're in the right place, emit the jump table header right now.
  7013. if (CurMBB == SwitchMBB) {
  7014. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  7015. JTH->Emitted = true;
  7016. }
  7017. break;
  7018. }
  7019. case CC_BitTests: {
  7020. // FIXME: Optimize away range check based on pivot comparisons.
  7021. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  7022. // The bit test blocks haven't been inserted yet; insert them here.
  7023. for (BitTestCase &BTC : BTB->Cases)
  7024. CurMF->insert(BBI, BTC.ThisBB);
  7025. // Fill in fields of the BitTestBlock.
  7026. BTB->Parent = CurMBB;
  7027. BTB->Default = Fallthrough;
  7028. // If we're in the right place, emit the bit test header header right now.
  7029. if (CurMBB ==SwitchMBB) {
  7030. visitBitTestHeader(*BTB, SwitchMBB);
  7031. BTB->Emitted = true;
  7032. }
  7033. break;
  7034. }
  7035. case CC_Range: {
  7036. const Value *RHS, *LHS, *MHS;
  7037. ISD::CondCode CC;
  7038. if (I->Low == I->High) {
  7039. // Check Cond == I->Low.
  7040. CC = ISD::SETEQ;
  7041. LHS = Cond;
  7042. RHS=I->Low;
  7043. MHS = nullptr;
  7044. } else {
  7045. // Check I->Low <= Cond <= I->High.
  7046. CC = ISD::SETLE;
  7047. LHS = I->Low;
  7048. MHS = Cond;
  7049. RHS = I->High;
  7050. }
  7051. // The false weight is the sum of all unhandled cases.
  7052. UnhandledWeights -= I->Weight;
  7053. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Weight,
  7054. UnhandledWeights);
  7055. if (CurMBB == SwitchMBB)
  7056. visitSwitchCase(CB, SwitchMBB);
  7057. else
  7058. SwitchCases.push_back(CB);
  7059. break;
  7060. }
  7061. }
  7062. CurMBB = Fallthrough;
  7063. }
  7064. }
  7065. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  7066. CaseClusterIt First,
  7067. CaseClusterIt Last) {
  7068. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  7069. if (X.Weight != CC.Weight)
  7070. return X.Weight > CC.Weight;
  7071. // Ties are broken by comparing the case value.
  7072. return X.Low->getValue().slt(CC.Low->getValue());
  7073. });
  7074. }
  7075. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  7076. const SwitchWorkListItem &W,
  7077. Value *Cond,
  7078. MachineBasicBlock *SwitchMBB) {
  7079. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  7080. "Clusters not sorted?");
  7081. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  7082. // Balance the tree based on branch weights to create a near-optimal (in terms
  7083. // of search time given key frequency) binary search tree. See e.g. Kurt
  7084. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  7085. CaseClusterIt LastLeft = W.FirstCluster;
  7086. CaseClusterIt FirstRight = W.LastCluster;
  7087. uint32_t LeftWeight = LastLeft->Weight;
  7088. uint32_t RightWeight = FirstRight->Weight;
  7089. // Move LastLeft and FirstRight towards each other from opposite directions to
  7090. // find a partitioning of the clusters which balances the weight on both
  7091. // sides. If LeftWeight and RightWeight are equal, alternate which side is
  7092. // taken to ensure 0-weight nodes are distributed evenly.
  7093. unsigned I = 0;
  7094. while (LastLeft + 1 < FirstRight) {
  7095. if (LeftWeight < RightWeight || (LeftWeight == RightWeight && (I & 1)))
  7096. LeftWeight += (++LastLeft)->Weight;
  7097. else
  7098. RightWeight += (--FirstRight)->Weight;
  7099. I++;
  7100. }
  7101. for (;;) {
  7102. // Our binary search tree differs from a typical BST in that ours can have up
  7103. // to three values in each leaf. The pivot selection above doesn't take that
  7104. // into account, which means the tree might require more nodes and be less
  7105. // efficient. We compensate for this here.
  7106. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  7107. unsigned NumRight = W.LastCluster - FirstRight + 1;
  7108. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  7109. // If one side has less than 3 clusters, and the other has more than 3,
  7110. // consider taking a cluster from the other side.
  7111. if (NumLeft < NumRight) {
  7112. // Consider moving the first cluster on the right to the left side.
  7113. CaseCluster &CC = *FirstRight;
  7114. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  7115. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  7116. if (LeftSideRank <= RightSideRank) {
  7117. // Moving the cluster to the left does not demote it.
  7118. ++LastLeft;
  7119. ++FirstRight;
  7120. continue;
  7121. }
  7122. } else {
  7123. assert(NumRight < NumLeft);
  7124. // Consider moving the last element on the left to the right side.
  7125. CaseCluster &CC = *LastLeft;
  7126. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  7127. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  7128. if (RightSideRank <= LeftSideRank) {
  7129. // Moving the cluster to the right does not demot it.
  7130. --LastLeft;
  7131. --FirstRight;
  7132. continue;
  7133. }
  7134. }
  7135. }
  7136. break;
  7137. }
  7138. assert(LastLeft + 1 == FirstRight);
  7139. assert(LastLeft >= W.FirstCluster);
  7140. assert(FirstRight <= W.LastCluster);
  7141. // Use the first element on the right as pivot since we will make less-than
  7142. // comparisons against it.
  7143. CaseClusterIt PivotCluster = FirstRight;
  7144. assert(PivotCluster > W.FirstCluster);
  7145. assert(PivotCluster <= W.LastCluster);
  7146. CaseClusterIt FirstLeft = W.FirstCluster;
  7147. CaseClusterIt LastRight = W.LastCluster;
  7148. const ConstantInt *Pivot = PivotCluster->Low;
  7149. // New blocks will be inserted immediately after the current one.
  7150. MachineFunction::iterator BBI = W.MBB;
  7151. ++BBI;
  7152. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  7153. // we can branch to its destination directly if it's squeezed exactly in
  7154. // between the known lower bound and Pivot - 1.
  7155. MachineBasicBlock *LeftMBB;
  7156. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  7157. FirstLeft->Low == W.GE &&
  7158. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  7159. LeftMBB = FirstLeft->MBB;
  7160. } else {
  7161. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  7162. FuncInfo.MF->insert(BBI, LeftMBB);
  7163. WorkList.push_back({LeftMBB, FirstLeft, LastLeft, W.GE, Pivot});
  7164. // Put Cond in a virtual register to make it available from the new blocks.
  7165. ExportFromCurrentBlock(Cond);
  7166. }
  7167. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  7168. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  7169. // directly if RHS.High equals the current upper bound.
  7170. MachineBasicBlock *RightMBB;
  7171. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  7172. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  7173. RightMBB = FirstRight->MBB;
  7174. } else {
  7175. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  7176. FuncInfo.MF->insert(BBI, RightMBB);
  7177. WorkList.push_back({RightMBB, FirstRight, LastRight, Pivot, W.LT});
  7178. // Put Cond in a virtual register to make it available from the new blocks.
  7179. ExportFromCurrentBlock(Cond);
  7180. }
  7181. // Create the CaseBlock record that will be used to lower the branch.
  7182. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  7183. LeftWeight, RightWeight);
  7184. if (W.MBB == SwitchMBB)
  7185. visitSwitchCase(CB, SwitchMBB);
  7186. else
  7187. SwitchCases.push_back(CB);
  7188. }
  7189. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  7190. // Extract cases from the switch.
  7191. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  7192. CaseClusterVector Clusters;
  7193. Clusters.reserve(SI.getNumCases());
  7194. for (auto I : SI.cases()) {
  7195. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  7196. const ConstantInt *CaseVal = I.getCaseValue();
  7197. uint32_t Weight =
  7198. BPI ? BPI->getEdgeWeight(SI.getParent(), I.getSuccessorIndex()) : 0;
  7199. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Weight));
  7200. }
  7201. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  7202. // Cluster adjacent cases with the same destination. We do this at all
  7203. // optimization levels because it's cheap to do and will make codegen faster
  7204. // if there are many clusters.
  7205. sortAndRangeify(Clusters);
  7206. if (TM.getOptLevel() != CodeGenOpt::None) {
  7207. // Replace an unreachable default with the most popular destination.
  7208. // FIXME: Exploit unreachable default more aggressively.
  7209. bool UnreachableDefault =
  7210. isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
  7211. if (UnreachableDefault && !Clusters.empty()) {
  7212. DenseMap<const BasicBlock *, unsigned> Popularity;
  7213. unsigned MaxPop = 0;
  7214. const BasicBlock *MaxBB = nullptr;
  7215. for (auto I : SI.cases()) {
  7216. const BasicBlock *BB = I.getCaseSuccessor();
  7217. if (++Popularity[BB] > MaxPop) {
  7218. MaxPop = Popularity[BB];
  7219. MaxBB = BB;
  7220. }
  7221. }
  7222. // Set new default.
  7223. assert(MaxPop > 0 && MaxBB);
  7224. DefaultMBB = FuncInfo.MBBMap[MaxBB];
  7225. // Remove cases that were pointing to the destination that is now the
  7226. // default.
  7227. CaseClusterVector New;
  7228. New.reserve(Clusters.size());
  7229. for (CaseCluster &CC : Clusters) {
  7230. if (CC.MBB != DefaultMBB)
  7231. New.push_back(CC);
  7232. }
  7233. Clusters = std::move(New);
  7234. }
  7235. }
  7236. // If there is only the default destination, jump there directly.
  7237. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  7238. if (Clusters.empty()) {
  7239. SwitchMBB->addSuccessor(DefaultMBB);
  7240. if (DefaultMBB != NextBlock(SwitchMBB)) {
  7241. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  7242. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  7243. }
  7244. return;
  7245. }
  7246. findJumpTables(Clusters, &SI, DefaultMBB);
  7247. findBitTestClusters(Clusters, &SI);
  7248. DEBUG({
  7249. dbgs() << "Case clusters: ";
  7250. for (const CaseCluster &C : Clusters) {
  7251. if (C.Kind == CC_JumpTable) dbgs() << "JT:";
  7252. if (C.Kind == CC_BitTests) dbgs() << "BT:";
  7253. C.Low->getValue().print(dbgs(), true);
  7254. if (C.Low != C.High) {
  7255. dbgs() << '-';
  7256. C.High->getValue().print(dbgs(), true);
  7257. }
  7258. dbgs() << ' ';
  7259. }
  7260. dbgs() << '\n';
  7261. });
  7262. assert(!Clusters.empty());
  7263. SwitchWorkList WorkList;
  7264. CaseClusterIt First = Clusters.begin();
  7265. CaseClusterIt Last = Clusters.end() - 1;
  7266. WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr});
  7267. while (!WorkList.empty()) {
  7268. SwitchWorkListItem W = WorkList.back();
  7269. WorkList.pop_back();
  7270. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  7271. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
  7272. // For optimized builds, lower large range as a balanced binary tree.
  7273. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  7274. continue;
  7275. }
  7276. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  7277. }
  7278. }