SelectionDAGBuilder.cpp 409 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "SelectionDAGBuilder.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/Analysis/BranchProbabilityInfo.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/Loads.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/CodeGen/Analysis.h"
  38. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/ISDOpcodes.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  47. #include "llvm/CodeGen/MachineMemOperand.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/MachineOperand.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/RuntimeLibcalls.h"
  52. #include "llvm/CodeGen/SelectionDAG.h"
  53. #include "llvm/CodeGen/SelectionDAGNodes.h"
  54. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  55. #include "llvm/CodeGen/StackMaps.h"
  56. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Statepoint.h"
  92. #include "llvm/IR/Type.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/MC/MCContext.h"
  96. #include "llvm/MC/MCSymbol.h"
  97. #include "llvm/Support/AtomicOrdering.h"
  98. #include "llvm/Support/BranchProbability.h"
  99. #include "llvm/Support/Casting.h"
  100. #include "llvm/Support/CodeGen.h"
  101. #include "llvm/Support/CommandLine.h"
  102. #include "llvm/Support/Compiler.h"
  103. #include "llvm/Support/Debug.h"
  104. #include "llvm/Support/ErrorHandling.h"
  105. #include "llvm/Support/MachineValueType.h"
  106. #include "llvm/Support/MathExtras.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include "llvm/Target/TargetIntrinsicInfo.h"
  109. #include "llvm/Target/TargetMachine.h"
  110. #include "llvm/Target/TargetOptions.h"
  111. #include "llvm/Transforms/Utils/Local.h"
  112. #include <algorithm>
  113. #include <cassert>
  114. #include <cstddef>
  115. #include <cstdint>
  116. #include <cstring>
  117. #include <iterator>
  118. #include <limits>
  119. #include <numeric>
  120. #include <tuple>
  121. #include <utility>
  122. #include <vector>
  123. using namespace llvm;
  124. using namespace PatternMatch;
  125. using namespace SwitchCG;
  126. #define DEBUG_TYPE "isel"
  127. /// LimitFloatPrecision - Generate low-precision inline sequences for
  128. /// some float libcalls (6, 8 or 12 bits).
  129. static unsigned LimitFloatPrecision;
  130. static cl::opt<unsigned, true>
  131. LimitFPPrecision("limit-float-precision",
  132. cl::desc("Generate low-precision inline sequences "
  133. "for some float libcalls"),
  134. cl::location(LimitFloatPrecision), cl::Hidden,
  135. cl::init(0));
  136. static cl::opt<unsigned> SwitchPeelThreshold(
  137. "switch-peel-threshold", cl::Hidden, cl::init(66),
  138. cl::desc("Set the case probability threshold for peeling the case from a "
  139. "switch statement. A value greater than 100 will void this "
  140. "optimization"));
  141. // Limit the width of DAG chains. This is important in general to prevent
  142. // DAG-based analysis from blowing up. For example, alias analysis and
  143. // load clustering may not complete in reasonable time. It is difficult to
  144. // recognize and avoid this situation within each individual analysis, and
  145. // future analyses are likely to have the same behavior. Limiting DAG width is
  146. // the safe approach and will be especially important with global DAGs.
  147. //
  148. // MaxParallelChains default is arbitrarily high to avoid affecting
  149. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  150. // sequence over this should have been converted to llvm.memcpy by the
  151. // frontend. It is easy to induce this behavior with .ll code such as:
  152. // %buffer = alloca [4096 x i8]
  153. // %data = load [4096 x i8]* %argPtr
  154. // store [4096 x i8] %data, [4096 x i8]* %buffer
  155. static const unsigned MaxParallelChains = 64;
  156. // Return the calling convention if the Value passed requires ABI mangling as it
  157. // is a parameter to a function or a return value from a function which is not
  158. // an intrinsic.
  159. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  160. if (auto *R = dyn_cast<ReturnInst>(V))
  161. return R->getParent()->getParent()->getCallingConv();
  162. if (auto *CI = dyn_cast<CallInst>(V)) {
  163. const bool IsInlineAsm = CI->isInlineAsm();
  164. const bool IsIndirectFunctionCall =
  165. !IsInlineAsm && !CI->getCalledFunction();
  166. // It is possible that the call instruction is an inline asm statement or an
  167. // indirect function call in which case the return value of
  168. // getCalledFunction() would be nullptr.
  169. const bool IsInstrinsicCall =
  170. !IsInlineAsm && !IsIndirectFunctionCall &&
  171. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  172. if (!IsInlineAsm && !IsInstrinsicCall)
  173. return CI->getCallingConv();
  174. }
  175. return None;
  176. }
  177. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  178. const SDValue *Parts, unsigned NumParts,
  179. MVT PartVT, EVT ValueVT, const Value *V,
  180. Optional<CallingConv::ID> CC);
  181. /// getCopyFromParts - Create a value that contains the specified legal parts
  182. /// combined into the value they represent. If the parts combine to a type
  183. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  184. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  185. /// (ISD::AssertSext).
  186. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  187. const SDValue *Parts, unsigned NumParts,
  188. MVT PartVT, EVT ValueVT, const Value *V,
  189. Optional<CallingConv::ID> CC = None,
  190. Optional<ISD::NodeType> AssertOp = None) {
  191. if (ValueVT.isVector())
  192. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  193. CC);
  194. assert(NumParts > 0 && "No parts to assemble!");
  195. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  196. SDValue Val = Parts[0];
  197. if (NumParts > 1) {
  198. // Assemble the value from multiple parts.
  199. if (ValueVT.isInteger()) {
  200. unsigned PartBits = PartVT.getSizeInBits();
  201. unsigned ValueBits = ValueVT.getSizeInBits();
  202. // Assemble the power of 2 part.
  203. unsigned RoundParts =
  204. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  205. unsigned RoundBits = PartBits * RoundParts;
  206. EVT RoundVT = RoundBits == ValueBits ?
  207. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  208. SDValue Lo, Hi;
  209. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  210. if (RoundParts > 2) {
  211. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  212. PartVT, HalfVT, V);
  213. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  214. RoundParts / 2, PartVT, HalfVT, V);
  215. } else {
  216. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  217. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  218. }
  219. if (DAG.getDataLayout().isBigEndian())
  220. std::swap(Lo, Hi);
  221. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  222. if (RoundParts < NumParts) {
  223. // Assemble the trailing non-power-of-2 part.
  224. unsigned OddParts = NumParts - RoundParts;
  225. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  226. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  227. OddVT, V, CC);
  228. // Combine the round and odd parts.
  229. Lo = Val;
  230. if (DAG.getDataLayout().isBigEndian())
  231. std::swap(Lo, Hi);
  232. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  233. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  234. Hi =
  235. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  236. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  237. TLI.getPointerTy(DAG.getDataLayout())));
  238. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  239. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  240. }
  241. } else if (PartVT.isFloatingPoint()) {
  242. // FP split into multiple FP parts (for ppcf128)
  243. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  244. "Unexpected split");
  245. SDValue Lo, Hi;
  246. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  247. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  248. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  249. std::swap(Lo, Hi);
  250. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  251. } else {
  252. // FP split into integer parts (soft fp)
  253. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  254. !PartVT.isVector() && "Unexpected split");
  255. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  256. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  257. }
  258. }
  259. // There is now one part, held in Val. Correct it to match ValueVT.
  260. // PartEVT is the type of the register class that holds the value.
  261. // ValueVT is the type of the inline asm operation.
  262. EVT PartEVT = Val.getValueType();
  263. if (PartEVT == ValueVT)
  264. return Val;
  265. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  266. ValueVT.bitsLT(PartEVT)) {
  267. // For an FP value in an integer part, we need to truncate to the right
  268. // width first.
  269. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  270. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  271. }
  272. // Handle types that have the same size.
  273. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  274. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  275. // Handle types with different sizes.
  276. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  277. if (ValueVT.bitsLT(PartEVT)) {
  278. // For a truncate, see if we have any information to
  279. // indicate whether the truncated bits will always be
  280. // zero or sign-extension.
  281. if (AssertOp.hasValue())
  282. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  283. DAG.getValueType(ValueVT));
  284. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  285. }
  286. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  287. }
  288. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  289. // FP_ROUND's are always exact here.
  290. if (ValueVT.bitsLT(Val.getValueType()))
  291. return DAG.getNode(
  292. ISD::FP_ROUND, DL, ValueVT, Val,
  293. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  294. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  295. }
  296. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  297. // then truncating.
  298. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  299. ValueVT.bitsLT(PartEVT)) {
  300. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  301. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  302. }
  303. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  304. }
  305. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  306. const Twine &ErrMsg) {
  307. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  308. if (!V)
  309. return Ctx.emitError(ErrMsg);
  310. const char *AsmError = ", possible invalid constraint for vector type";
  311. if (const CallInst *CI = dyn_cast<CallInst>(I))
  312. if (isa<InlineAsm>(CI->getCalledValue()))
  313. return Ctx.emitError(I, ErrMsg + AsmError);
  314. return Ctx.emitError(I, ErrMsg);
  315. }
  316. /// getCopyFromPartsVector - Create a value that contains the specified legal
  317. /// parts combined into the value they represent. If the parts combine to a
  318. /// type larger than ValueVT then AssertOp can be used to specify whether the
  319. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  320. /// ValueVT (ISD::AssertSext).
  321. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  322. const SDValue *Parts, unsigned NumParts,
  323. MVT PartVT, EVT ValueVT, const Value *V,
  324. Optional<CallingConv::ID> CallConv) {
  325. assert(ValueVT.isVector() && "Not a vector value");
  326. assert(NumParts > 0 && "No parts to assemble!");
  327. const bool IsABIRegCopy = CallConv.hasValue();
  328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  329. SDValue Val = Parts[0];
  330. // Handle a multi-element vector.
  331. if (NumParts > 1) {
  332. EVT IntermediateVT;
  333. MVT RegisterVT;
  334. unsigned NumIntermediates;
  335. unsigned NumRegs;
  336. if (IsABIRegCopy) {
  337. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  338. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  339. NumIntermediates, RegisterVT);
  340. } else {
  341. NumRegs =
  342. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  343. NumIntermediates, RegisterVT);
  344. }
  345. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  346. NumParts = NumRegs; // Silence a compiler warning.
  347. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  348. assert(RegisterVT.getSizeInBits() ==
  349. Parts[0].getSimpleValueType().getSizeInBits() &&
  350. "Part type sizes don't match!");
  351. // Assemble the parts into intermediate operands.
  352. SmallVector<SDValue, 8> Ops(NumIntermediates);
  353. if (NumIntermediates == NumParts) {
  354. // If the register was not expanded, truncate or copy the value,
  355. // as appropriate.
  356. for (unsigned i = 0; i != NumParts; ++i)
  357. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  358. PartVT, IntermediateVT, V);
  359. } else if (NumParts > 0) {
  360. // If the intermediate type was expanded, build the intermediate
  361. // operands from the parts.
  362. assert(NumParts % NumIntermediates == 0 &&
  363. "Must expand into a divisible number of parts!");
  364. unsigned Factor = NumParts / NumIntermediates;
  365. for (unsigned i = 0; i != NumIntermediates; ++i)
  366. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  367. PartVT, IntermediateVT, V);
  368. }
  369. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  370. // intermediate operands.
  371. EVT BuiltVectorTy =
  372. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  373. (IntermediateVT.isVector()
  374. ? IntermediateVT.getVectorNumElements() * NumParts
  375. : NumIntermediates));
  376. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  377. : ISD::BUILD_VECTOR,
  378. DL, BuiltVectorTy, Ops);
  379. }
  380. // There is now one part, held in Val. Correct it to match ValueVT.
  381. EVT PartEVT = Val.getValueType();
  382. if (PartEVT == ValueVT)
  383. return Val;
  384. if (PartEVT.isVector()) {
  385. // If the element type of the source/dest vectors are the same, but the
  386. // parts vector has more elements than the value vector, then we have a
  387. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  388. // elements we want.
  389. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  390. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  391. "Cannot narrow, it would be a lossy transformation");
  392. return DAG.getNode(
  393. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  394. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  395. }
  396. // Vector/Vector bitcast.
  397. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  398. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  399. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  400. "Cannot handle this kind of promotion");
  401. // Promoted vector extract
  402. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  403. }
  404. // Trivial bitcast if the types are the same size and the destination
  405. // vector type is legal.
  406. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  407. TLI.isTypeLegal(ValueVT))
  408. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  409. if (ValueVT.getVectorNumElements() != 1) {
  410. // Certain ABIs require that vectors are passed as integers. For vectors
  411. // are the same size, this is an obvious bitcast.
  412. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  413. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  414. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  415. // Bitcast Val back the original type and extract the corresponding
  416. // vector we want.
  417. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  418. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  419. ValueVT.getVectorElementType(), Elts);
  420. Val = DAG.getBitcast(WiderVecType, Val);
  421. return DAG.getNode(
  422. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  423. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  424. }
  425. diagnosePossiblyInvalidConstraint(
  426. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  427. return DAG.getUNDEF(ValueVT);
  428. }
  429. // Handle cases such as i8 -> <1 x i1>
  430. EVT ValueSVT = ValueVT.getVectorElementType();
  431. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  432. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  433. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  434. return DAG.getBuildVector(ValueVT, DL, Val);
  435. }
  436. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  437. SDValue Val, SDValue *Parts, unsigned NumParts,
  438. MVT PartVT, const Value *V,
  439. Optional<CallingConv::ID> CallConv);
  440. /// getCopyToParts - Create a series of nodes that contain the specified value
  441. /// split into legal parts. If the parts contain more bits than Val, then, for
  442. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  443. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  444. SDValue *Parts, unsigned NumParts, MVT PartVT,
  445. const Value *V,
  446. Optional<CallingConv::ID> CallConv = None,
  447. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  448. EVT ValueVT = Val.getValueType();
  449. // Handle the vector case separately.
  450. if (ValueVT.isVector())
  451. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  452. CallConv);
  453. unsigned PartBits = PartVT.getSizeInBits();
  454. unsigned OrigNumParts = NumParts;
  455. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  456. "Copying to an illegal type!");
  457. if (NumParts == 0)
  458. return;
  459. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  460. EVT PartEVT = PartVT;
  461. if (PartEVT == ValueVT) {
  462. assert(NumParts == 1 && "No-op copy with multiple parts!");
  463. Parts[0] = Val;
  464. return;
  465. }
  466. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  467. // If the parts cover more bits than the value has, promote the value.
  468. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  469. assert(NumParts == 1 && "Do not know what to promote to!");
  470. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  471. } else {
  472. if (ValueVT.isFloatingPoint()) {
  473. // FP values need to be bitcast, then extended if they are being put
  474. // into a larger container.
  475. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  476. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  477. }
  478. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  479. ValueVT.isInteger() &&
  480. "Unknown mismatch!");
  481. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  482. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  483. if (PartVT == MVT::x86mmx)
  484. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  485. }
  486. } else if (PartBits == ValueVT.getSizeInBits()) {
  487. // Different types of the same size.
  488. assert(NumParts == 1 && PartEVT != ValueVT);
  489. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  490. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  491. // If the parts cover less bits than value has, truncate the value.
  492. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  493. ValueVT.isInteger() &&
  494. "Unknown mismatch!");
  495. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  496. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  497. if (PartVT == MVT::x86mmx)
  498. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  499. }
  500. // The value may have changed - recompute ValueVT.
  501. ValueVT = Val.getValueType();
  502. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  503. "Failed to tile the value with PartVT!");
  504. if (NumParts == 1) {
  505. if (PartEVT != ValueVT) {
  506. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  507. "scalar-to-vector conversion failed");
  508. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  509. }
  510. Parts[0] = Val;
  511. return;
  512. }
  513. // Expand the value into multiple parts.
  514. if (NumParts & (NumParts - 1)) {
  515. // The number of parts is not a power of 2. Split off and copy the tail.
  516. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  517. "Do not know what to expand to!");
  518. unsigned RoundParts = 1 << Log2_32(NumParts);
  519. unsigned RoundBits = RoundParts * PartBits;
  520. unsigned OddParts = NumParts - RoundParts;
  521. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  522. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  523. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  524. CallConv);
  525. if (DAG.getDataLayout().isBigEndian())
  526. // The odd parts were reversed by getCopyToParts - unreverse them.
  527. std::reverse(Parts + RoundParts, Parts + NumParts);
  528. NumParts = RoundParts;
  529. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  530. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  531. }
  532. // The number of parts is a power of 2. Repeatedly bisect the value using
  533. // EXTRACT_ELEMENT.
  534. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  535. EVT::getIntegerVT(*DAG.getContext(),
  536. ValueVT.getSizeInBits()),
  537. Val);
  538. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  539. for (unsigned i = 0; i < NumParts; i += StepSize) {
  540. unsigned ThisBits = StepSize * PartBits / 2;
  541. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  542. SDValue &Part0 = Parts[i];
  543. SDValue &Part1 = Parts[i+StepSize/2];
  544. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  545. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  546. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  547. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  548. if (ThisBits == PartBits && ThisVT != PartVT) {
  549. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  550. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  551. }
  552. }
  553. }
  554. if (DAG.getDataLayout().isBigEndian())
  555. std::reverse(Parts, Parts + OrigNumParts);
  556. }
  557. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  558. SDValue Val, const SDLoc &DL, EVT PartVT) {
  559. if (!PartVT.isVector())
  560. return SDValue();
  561. EVT ValueVT = Val.getValueType();
  562. unsigned PartNumElts = PartVT.getVectorNumElements();
  563. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  564. if (PartNumElts > ValueNumElts &&
  565. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  566. EVT ElementVT = PartVT.getVectorElementType();
  567. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  568. // undef elements.
  569. SmallVector<SDValue, 16> Ops;
  570. DAG.ExtractVectorElements(Val, Ops);
  571. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  572. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  573. Ops.push_back(EltUndef);
  574. // FIXME: Use CONCAT for 2x -> 4x.
  575. return DAG.getBuildVector(PartVT, DL, Ops);
  576. }
  577. return SDValue();
  578. }
  579. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  580. /// value split into legal parts.
  581. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  582. SDValue Val, SDValue *Parts, unsigned NumParts,
  583. MVT PartVT, const Value *V,
  584. Optional<CallingConv::ID> CallConv) {
  585. EVT ValueVT = Val.getValueType();
  586. assert(ValueVT.isVector() && "Not a vector");
  587. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  588. const bool IsABIRegCopy = CallConv.hasValue();
  589. if (NumParts == 1) {
  590. EVT PartEVT = PartVT;
  591. if (PartEVT == ValueVT) {
  592. // Nothing to do.
  593. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  594. // Bitconvert vector->vector case.
  595. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  596. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  597. Val = Widened;
  598. } else if (PartVT.isVector() &&
  599. PartEVT.getVectorElementType().bitsGE(
  600. ValueVT.getVectorElementType()) &&
  601. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  602. // Promoted vector extract
  603. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  604. } else {
  605. if (ValueVT.getVectorNumElements() == 1) {
  606. Val = DAG.getNode(
  607. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  608. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  609. } else {
  610. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  611. "lossy conversion of vector to scalar type");
  612. EVT IntermediateType =
  613. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  614. Val = DAG.getBitcast(IntermediateType, Val);
  615. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  616. }
  617. }
  618. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  619. Parts[0] = Val;
  620. return;
  621. }
  622. // Handle a multi-element vector.
  623. EVT IntermediateVT;
  624. MVT RegisterVT;
  625. unsigned NumIntermediates;
  626. unsigned NumRegs;
  627. if (IsABIRegCopy) {
  628. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  629. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  630. NumIntermediates, RegisterVT);
  631. } else {
  632. NumRegs =
  633. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  634. NumIntermediates, RegisterVT);
  635. }
  636. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  637. NumParts = NumRegs; // Silence a compiler warning.
  638. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  639. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  640. IntermediateVT.getVectorNumElements() : 1;
  641. // Convert the vector to the appropiate type if necessary.
  642. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  643. EVT BuiltVectorTy = EVT::getVectorVT(
  644. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  645. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  646. if (ValueVT != BuiltVectorTy) {
  647. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  648. Val = Widened;
  649. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  650. }
  651. // Split the vector into intermediate operands.
  652. SmallVector<SDValue, 8> Ops(NumIntermediates);
  653. for (unsigned i = 0; i != NumIntermediates; ++i) {
  654. if (IntermediateVT.isVector()) {
  655. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  656. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  657. } else {
  658. Ops[i] = DAG.getNode(
  659. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  660. DAG.getConstant(i, DL, IdxVT));
  661. }
  662. }
  663. // Split the intermediate operands into legal parts.
  664. if (NumParts == NumIntermediates) {
  665. // If the register was not expanded, promote or copy the value,
  666. // as appropriate.
  667. for (unsigned i = 0; i != NumParts; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  669. } else if (NumParts > 0) {
  670. // If the intermediate type was expanded, split each the value into
  671. // legal parts.
  672. assert(NumIntermediates != 0 && "division by zero");
  673. assert(NumParts % NumIntermediates == 0 &&
  674. "Must expand into a divisible number of parts!");
  675. unsigned Factor = NumParts / NumIntermediates;
  676. for (unsigned i = 0; i != NumIntermediates; ++i)
  677. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  678. CallConv);
  679. }
  680. }
  681. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  682. EVT valuevt, Optional<CallingConv::ID> CC)
  683. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  684. RegCount(1, regs.size()), CallConv(CC) {}
  685. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  686. const DataLayout &DL, unsigned Reg, Type *Ty,
  687. Optional<CallingConv::ID> CC) {
  688. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  689. CallConv = CC;
  690. for (EVT ValueVT : ValueVTs) {
  691. unsigned NumRegs =
  692. isABIMangled()
  693. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  694. : TLI.getNumRegisters(Context, ValueVT);
  695. MVT RegisterVT =
  696. isABIMangled()
  697. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  698. : TLI.getRegisterType(Context, ValueVT);
  699. for (unsigned i = 0; i != NumRegs; ++i)
  700. Regs.push_back(Reg + i);
  701. RegVTs.push_back(RegisterVT);
  702. RegCount.push_back(NumRegs);
  703. Reg += NumRegs;
  704. }
  705. }
  706. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  707. FunctionLoweringInfo &FuncInfo,
  708. const SDLoc &dl, SDValue &Chain,
  709. SDValue *Flag, const Value *V) const {
  710. // A Value with type {} or [0 x %t] needs no registers.
  711. if (ValueVTs.empty())
  712. return SDValue();
  713. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  714. // Assemble the legal parts into the final values.
  715. SmallVector<SDValue, 4> Values(ValueVTs.size());
  716. SmallVector<SDValue, 8> Parts;
  717. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  718. // Copy the legal parts from the registers.
  719. EVT ValueVT = ValueVTs[Value];
  720. unsigned NumRegs = RegCount[Value];
  721. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  722. *DAG.getContext(),
  723. CallConv.getValue(), RegVTs[Value])
  724. : RegVTs[Value];
  725. Parts.resize(NumRegs);
  726. for (unsigned i = 0; i != NumRegs; ++i) {
  727. SDValue P;
  728. if (!Flag) {
  729. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  730. } else {
  731. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  732. *Flag = P.getValue(2);
  733. }
  734. Chain = P.getValue(1);
  735. Parts[i] = P;
  736. // If the source register was virtual and if we know something about it,
  737. // add an assert node.
  738. if (!Register::isVirtualRegister(Regs[Part + i]) ||
  739. !RegisterVT.isInteger())
  740. continue;
  741. const FunctionLoweringInfo::LiveOutInfo *LOI =
  742. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  743. if (!LOI)
  744. continue;
  745. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  746. unsigned NumSignBits = LOI->NumSignBits;
  747. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  748. if (NumZeroBits == RegSize) {
  749. // The current value is a zero.
  750. // Explicitly express that as it would be easier for
  751. // optimizations to kick in.
  752. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  753. continue;
  754. }
  755. // FIXME: We capture more information than the dag can represent. For
  756. // now, just use the tightest assertzext/assertsext possible.
  757. bool isSExt;
  758. EVT FromVT(MVT::Other);
  759. if (NumZeroBits) {
  760. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  761. isSExt = false;
  762. } else if (NumSignBits > 1) {
  763. FromVT =
  764. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  765. isSExt = true;
  766. } else {
  767. continue;
  768. }
  769. // Add an assertion node.
  770. assert(FromVT != MVT::Other);
  771. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  772. RegisterVT, P, DAG.getValueType(FromVT));
  773. }
  774. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  775. RegisterVT, ValueVT, V, CallConv);
  776. Part += NumRegs;
  777. Parts.clear();
  778. }
  779. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  780. }
  781. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  782. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  783. const Value *V,
  784. ISD::NodeType PreferredExtendType) const {
  785. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  786. ISD::NodeType ExtendKind = PreferredExtendType;
  787. // Get the list of the values's legal parts.
  788. unsigned NumRegs = Regs.size();
  789. SmallVector<SDValue, 8> Parts(NumRegs);
  790. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  791. unsigned NumParts = RegCount[Value];
  792. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  793. *DAG.getContext(),
  794. CallConv.getValue(), RegVTs[Value])
  795. : RegVTs[Value];
  796. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  797. ExtendKind = ISD::ZERO_EXTEND;
  798. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  799. NumParts, RegisterVT, V, CallConv, ExtendKind);
  800. Part += NumParts;
  801. }
  802. // Copy the parts into the registers.
  803. SmallVector<SDValue, 8> Chains(NumRegs);
  804. for (unsigned i = 0; i != NumRegs; ++i) {
  805. SDValue Part;
  806. if (!Flag) {
  807. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  808. } else {
  809. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  810. *Flag = Part.getValue(1);
  811. }
  812. Chains[i] = Part.getValue(0);
  813. }
  814. if (NumRegs == 1 || Flag)
  815. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  816. // flagged to it. That is the CopyToReg nodes and the user are considered
  817. // a single scheduling unit. If we create a TokenFactor and return it as
  818. // chain, then the TokenFactor is both a predecessor (operand) of the
  819. // user as well as a successor (the TF operands are flagged to the user).
  820. // c1, f1 = CopyToReg
  821. // c2, f2 = CopyToReg
  822. // c3 = TokenFactor c1, c2
  823. // ...
  824. // = op c3, ..., f2
  825. Chain = Chains[NumRegs-1];
  826. else
  827. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  828. }
  829. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  830. unsigned MatchingIdx, const SDLoc &dl,
  831. SelectionDAG &DAG,
  832. std::vector<SDValue> &Ops) const {
  833. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  834. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  835. if (HasMatching)
  836. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  837. else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
  838. // Put the register class of the virtual registers in the flag word. That
  839. // way, later passes can recompute register class constraints for inline
  840. // assembly as well as normal instructions.
  841. // Don't do this for tied operands that can use the regclass information
  842. // from the def.
  843. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  844. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  845. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  846. }
  847. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  848. Ops.push_back(Res);
  849. if (Code == InlineAsm::Kind_Clobber) {
  850. // Clobbers should always have a 1:1 mapping with registers, and may
  851. // reference registers that have illegal (e.g. vector) types. Hence, we
  852. // shouldn't try to apply any sort of splitting logic to them.
  853. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  854. "No 1:1 mapping from clobbers to regs?");
  855. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  856. (void)SP;
  857. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  858. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  859. assert(
  860. (Regs[I] != SP ||
  861. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  862. "If we clobbered the stack pointer, MFI should know about it.");
  863. }
  864. return;
  865. }
  866. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  867. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  868. MVT RegisterVT = RegVTs[Value];
  869. for (unsigned i = 0; i != NumRegs; ++i) {
  870. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  871. unsigned TheReg = Regs[Reg++];
  872. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  873. }
  874. }
  875. }
  876. SmallVector<std::pair<unsigned, unsigned>, 4>
  877. RegsForValue::getRegsAndSizes() const {
  878. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  879. unsigned I = 0;
  880. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  881. unsigned RegCount = std::get<0>(CountAndVT);
  882. MVT RegisterVT = std::get<1>(CountAndVT);
  883. unsigned RegisterSize = RegisterVT.getSizeInBits();
  884. for (unsigned E = I + RegCount; I != E; ++I)
  885. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  886. }
  887. return OutVec;
  888. }
  889. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  890. const TargetLibraryInfo *li) {
  891. AA = aa;
  892. GFI = gfi;
  893. LibInfo = li;
  894. DL = &DAG.getDataLayout();
  895. Context = DAG.getContext();
  896. LPadToCallSiteMap.clear();
  897. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  898. }
  899. void SelectionDAGBuilder::clear() {
  900. NodeMap.clear();
  901. UnusedArgNodeMap.clear();
  902. PendingLoads.clear();
  903. PendingExports.clear();
  904. CurInst = nullptr;
  905. HasTailCall = false;
  906. SDNodeOrder = LowestSDNodeOrder;
  907. StatepointLowering.clear();
  908. }
  909. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  910. DanglingDebugInfoMap.clear();
  911. }
  912. SDValue SelectionDAGBuilder::getRoot() {
  913. if (PendingLoads.empty())
  914. return DAG.getRoot();
  915. if (PendingLoads.size() == 1) {
  916. SDValue Root = PendingLoads[0];
  917. DAG.setRoot(Root);
  918. PendingLoads.clear();
  919. return Root;
  920. }
  921. // Otherwise, we have to make a token factor node.
  922. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  923. PendingLoads.clear();
  924. DAG.setRoot(Root);
  925. return Root;
  926. }
  927. SDValue SelectionDAGBuilder::getControlRoot() {
  928. SDValue Root = DAG.getRoot();
  929. if (PendingExports.empty())
  930. return Root;
  931. // Turn all of the CopyToReg chains into one factored node.
  932. if (Root.getOpcode() != ISD::EntryToken) {
  933. unsigned i = 0, e = PendingExports.size();
  934. for (; i != e; ++i) {
  935. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  936. if (PendingExports[i].getNode()->getOperand(0) == Root)
  937. break; // Don't add the root if we already indirectly depend on it.
  938. }
  939. if (i == e)
  940. PendingExports.push_back(Root);
  941. }
  942. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  943. PendingExports);
  944. PendingExports.clear();
  945. DAG.setRoot(Root);
  946. return Root;
  947. }
  948. void SelectionDAGBuilder::visit(const Instruction &I) {
  949. // Set up outgoing PHI node register values before emitting the terminator.
  950. if (I.isTerminator()) {
  951. HandlePHINodesInSuccessorBlocks(I.getParent());
  952. }
  953. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  954. if (!isa<DbgInfoIntrinsic>(I))
  955. ++SDNodeOrder;
  956. CurInst = &I;
  957. visit(I.getOpcode(), I);
  958. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  959. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  960. // maps to this instruction.
  961. // TODO: We could handle all flags (nsw, etc) here.
  962. // TODO: If an IR instruction maps to >1 node, only the final node will have
  963. // flags set.
  964. if (SDNode *Node = getNodeForIRValue(&I)) {
  965. SDNodeFlags IncomingFlags;
  966. IncomingFlags.copyFMF(*FPMO);
  967. if (!Node->getFlags().isDefined())
  968. Node->setFlags(IncomingFlags);
  969. else
  970. Node->intersectFlagsWith(IncomingFlags);
  971. }
  972. }
  973. if (!I.isTerminator() && !HasTailCall &&
  974. !isStatepoint(&I)) // statepoints handle their exports internally
  975. CopyToExportRegsIfNeeded(&I);
  976. CurInst = nullptr;
  977. }
  978. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  979. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  980. }
  981. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  982. // Note: this doesn't use InstVisitor, because it has to work with
  983. // ConstantExpr's in addition to instructions.
  984. switch (Opcode) {
  985. default: llvm_unreachable("Unknown instruction type encountered!");
  986. // Build the switch statement using the Instruction.def file.
  987. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  988. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  989. #include "llvm/IR/Instruction.def"
  990. }
  991. }
  992. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  993. const DIExpression *Expr) {
  994. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  995. const DbgValueInst *DI = DDI.getDI();
  996. DIVariable *DanglingVariable = DI->getVariable();
  997. DIExpression *DanglingExpr = DI->getExpression();
  998. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  999. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  1000. return true;
  1001. }
  1002. return false;
  1003. };
  1004. for (auto &DDIMI : DanglingDebugInfoMap) {
  1005. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1006. // If debug info is to be dropped, run it through final checks to see
  1007. // whether it can be salvaged.
  1008. for (auto &DDI : DDIV)
  1009. if (isMatchingDbgValue(DDI))
  1010. salvageUnresolvedDbgValue(DDI);
  1011. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1012. }
  1013. }
  1014. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1015. // generate the debug data structures now that we've seen its definition.
  1016. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1017. SDValue Val) {
  1018. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1019. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1020. return;
  1021. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1022. for (auto &DDI : DDIV) {
  1023. const DbgValueInst *DI = DDI.getDI();
  1024. assert(DI && "Ill-formed DanglingDebugInfo");
  1025. DebugLoc dl = DDI.getdl();
  1026. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1027. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1028. DILocalVariable *Variable = DI->getVariable();
  1029. DIExpression *Expr = DI->getExpression();
  1030. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1031. "Expected inlined-at fields to agree");
  1032. SDDbgValue *SDV;
  1033. if (Val.getNode()) {
  1034. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1035. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1036. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1037. // in the first place we should not be more successful here). Unless we
  1038. // have some test case that prove this to be correct we should avoid
  1039. // calling EmitFuncArgumentDbgValue here.
  1040. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1041. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1042. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1043. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1044. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1045. // inserted after the definition of Val when emitting the instructions
  1046. // after ISel. An alternative could be to teach
  1047. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1048. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1049. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1050. << ValSDNodeOrder << "\n");
  1051. SDV = getDbgValue(Val, Variable, Expr, dl,
  1052. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1053. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1054. } else
  1055. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1056. << "in EmitFuncArgumentDbgValue\n");
  1057. } else {
  1058. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1059. auto Undef =
  1060. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1061. auto SDV =
  1062. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1063. DAG.AddDbgValue(SDV, nullptr, false);
  1064. }
  1065. }
  1066. DDIV.clear();
  1067. }
  1068. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1069. Value *V = DDI.getDI()->getValue();
  1070. DILocalVariable *Var = DDI.getDI()->getVariable();
  1071. DIExpression *Expr = DDI.getDI()->getExpression();
  1072. DebugLoc DL = DDI.getdl();
  1073. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1074. unsigned SDOrder = DDI.getSDNodeOrder();
  1075. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1076. // that DW_OP_stack_value is desired.
  1077. assert(isa<DbgValueInst>(DDI.getDI()));
  1078. bool StackValue = true;
  1079. // Can this Value can be encoded without any further work?
  1080. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1081. return;
  1082. // Attempt to salvage back through as many instructions as possible. Bail if
  1083. // a non-instruction is seen, such as a constant expression or global
  1084. // variable. FIXME: Further work could recover those too.
  1085. while (isa<Instruction>(V)) {
  1086. Instruction &VAsInst = *cast<Instruction>(V);
  1087. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1088. // If we cannot salvage any further, and haven't yet found a suitable debug
  1089. // expression, bail out.
  1090. if (!NewExpr)
  1091. break;
  1092. // New value and expr now represent this debuginfo.
  1093. V = VAsInst.getOperand(0);
  1094. Expr = NewExpr;
  1095. // Some kind of simplification occurred: check whether the operand of the
  1096. // salvaged debug expression can be encoded in this DAG.
  1097. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1098. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1099. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1100. return;
  1101. }
  1102. }
  1103. // This was the final opportunity to salvage this debug information, and it
  1104. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1105. // any earlier variable location.
  1106. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1107. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1108. DAG.AddDbgValue(SDV, nullptr, false);
  1109. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1110. << "\n");
  1111. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1112. << "\n");
  1113. }
  1114. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1115. DIExpression *Expr, DebugLoc dl,
  1116. DebugLoc InstDL, unsigned Order) {
  1117. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1118. SDDbgValue *SDV;
  1119. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1120. isa<ConstantPointerNull>(V)) {
  1121. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1122. DAG.AddDbgValue(SDV, nullptr, false);
  1123. return true;
  1124. }
  1125. // If the Value is a frame index, we can create a FrameIndex debug value
  1126. // without relying on the DAG at all.
  1127. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1128. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1129. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1130. auto SDV =
  1131. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1132. /*IsIndirect*/ false, dl, SDNodeOrder);
  1133. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1134. // is still available even if the SDNode gets optimized out.
  1135. DAG.AddDbgValue(SDV, nullptr, false);
  1136. return true;
  1137. }
  1138. }
  1139. // Do not use getValue() in here; we don't want to generate code at
  1140. // this point if it hasn't been done yet.
  1141. SDValue N = NodeMap[V];
  1142. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1143. N = UnusedArgNodeMap[V];
  1144. if (N.getNode()) {
  1145. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1146. return true;
  1147. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1148. DAG.AddDbgValue(SDV, N.getNode(), false);
  1149. return true;
  1150. }
  1151. // Special rules apply for the first dbg.values of parameter variables in a
  1152. // function. Identify them by the fact they reference Argument Values, that
  1153. // they're parameters, and they are parameters of the current function. We
  1154. // need to let them dangle until they get an SDNode.
  1155. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1156. !InstDL.getInlinedAt();
  1157. if (!IsParamOfFunc) {
  1158. // The value is not used in this block yet (or it would have an SDNode).
  1159. // We still want the value to appear for the user if possible -- if it has
  1160. // an associated VReg, we can refer to that instead.
  1161. auto VMI = FuncInfo.ValueMap.find(V);
  1162. if (VMI != FuncInfo.ValueMap.end()) {
  1163. unsigned Reg = VMI->second;
  1164. // If this is a PHI node, it may be split up into several MI PHI nodes
  1165. // (in FunctionLoweringInfo::set).
  1166. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1167. V->getType(), None);
  1168. if (RFV.occupiesMultipleRegs()) {
  1169. unsigned Offset = 0;
  1170. unsigned BitsToDescribe = 0;
  1171. if (auto VarSize = Var->getSizeInBits())
  1172. BitsToDescribe = *VarSize;
  1173. if (auto Fragment = Expr->getFragmentInfo())
  1174. BitsToDescribe = Fragment->SizeInBits;
  1175. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1176. unsigned RegisterSize = RegAndSize.second;
  1177. // Bail out if all bits are described already.
  1178. if (Offset >= BitsToDescribe)
  1179. break;
  1180. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1181. ? BitsToDescribe - Offset
  1182. : RegisterSize;
  1183. auto FragmentExpr = DIExpression::createFragmentExpression(
  1184. Expr, Offset, FragmentSize);
  1185. if (!FragmentExpr)
  1186. continue;
  1187. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1188. false, dl, SDNodeOrder);
  1189. DAG.AddDbgValue(SDV, nullptr, false);
  1190. Offset += RegisterSize;
  1191. }
  1192. } else {
  1193. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1194. DAG.AddDbgValue(SDV, nullptr, false);
  1195. }
  1196. return true;
  1197. }
  1198. }
  1199. return false;
  1200. }
  1201. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1202. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1203. for (auto &Pair : DanglingDebugInfoMap)
  1204. for (auto &DDI : Pair.second)
  1205. salvageUnresolvedDbgValue(DDI);
  1206. clearDanglingDebugInfo();
  1207. }
  1208. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1209. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1210. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1211. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1212. SDValue Result;
  1213. if (It != FuncInfo.ValueMap.end()) {
  1214. unsigned InReg = It->second;
  1215. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1216. DAG.getDataLayout(), InReg, Ty,
  1217. None); // This is not an ABI copy.
  1218. SDValue Chain = DAG.getEntryNode();
  1219. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1220. V);
  1221. resolveDanglingDebugInfo(V, Result);
  1222. }
  1223. return Result;
  1224. }
  1225. /// getValue - Return an SDValue for the given Value.
  1226. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1227. // If we already have an SDValue for this value, use it. It's important
  1228. // to do this first, so that we don't create a CopyFromReg if we already
  1229. // have a regular SDValue.
  1230. SDValue &N = NodeMap[V];
  1231. if (N.getNode()) return N;
  1232. // If there's a virtual register allocated and initialized for this
  1233. // value, use it.
  1234. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1235. return copyFromReg;
  1236. // Otherwise create a new SDValue and remember it.
  1237. SDValue Val = getValueImpl(V);
  1238. NodeMap[V] = Val;
  1239. resolveDanglingDebugInfo(V, Val);
  1240. return Val;
  1241. }
  1242. // Return true if SDValue exists for the given Value
  1243. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1244. return (NodeMap.find(V) != NodeMap.end()) ||
  1245. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1246. }
  1247. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1248. /// don't look in FuncInfo.ValueMap for a virtual register.
  1249. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1250. // If we already have an SDValue for this value, use it.
  1251. SDValue &N = NodeMap[V];
  1252. if (N.getNode()) {
  1253. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1254. // Remove the debug location from the node as the node is about to be used
  1255. // in a location which may differ from the original debug location. This
  1256. // is relevant to Constant and ConstantFP nodes because they can appear
  1257. // as constant expressions inside PHI nodes.
  1258. N->setDebugLoc(DebugLoc());
  1259. }
  1260. return N;
  1261. }
  1262. // Otherwise create a new SDValue and remember it.
  1263. SDValue Val = getValueImpl(V);
  1264. NodeMap[V] = Val;
  1265. resolveDanglingDebugInfo(V, Val);
  1266. return Val;
  1267. }
  1268. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1269. /// Create an SDValue for the given value.
  1270. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1271. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1272. if (const Constant *C = dyn_cast<Constant>(V)) {
  1273. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1274. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1275. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1276. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1277. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1278. if (isa<ConstantPointerNull>(C)) {
  1279. unsigned AS = V->getType()->getPointerAddressSpace();
  1280. return DAG.getConstant(0, getCurSDLoc(),
  1281. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1282. }
  1283. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1284. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1285. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1286. return DAG.getUNDEF(VT);
  1287. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1288. visit(CE->getOpcode(), *CE);
  1289. SDValue N1 = NodeMap[V];
  1290. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1291. return N1;
  1292. }
  1293. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1294. SmallVector<SDValue, 4> Constants;
  1295. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1296. OI != OE; ++OI) {
  1297. SDNode *Val = getValue(*OI).getNode();
  1298. // If the operand is an empty aggregate, there are no values.
  1299. if (!Val) continue;
  1300. // Add each leaf value from the operand to the Constants list
  1301. // to form a flattened list of all the values.
  1302. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1303. Constants.push_back(SDValue(Val, i));
  1304. }
  1305. return DAG.getMergeValues(Constants, getCurSDLoc());
  1306. }
  1307. if (const ConstantDataSequential *CDS =
  1308. dyn_cast<ConstantDataSequential>(C)) {
  1309. SmallVector<SDValue, 4> Ops;
  1310. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1311. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1312. // Add each leaf value from the operand to the Constants list
  1313. // to form a flattened list of all the values.
  1314. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1315. Ops.push_back(SDValue(Val, i));
  1316. }
  1317. if (isa<ArrayType>(CDS->getType()))
  1318. return DAG.getMergeValues(Ops, getCurSDLoc());
  1319. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1320. }
  1321. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1322. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1323. "Unknown struct or array constant!");
  1324. SmallVector<EVT, 4> ValueVTs;
  1325. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1326. unsigned NumElts = ValueVTs.size();
  1327. if (NumElts == 0)
  1328. return SDValue(); // empty struct
  1329. SmallVector<SDValue, 4> Constants(NumElts);
  1330. for (unsigned i = 0; i != NumElts; ++i) {
  1331. EVT EltVT = ValueVTs[i];
  1332. if (isa<UndefValue>(C))
  1333. Constants[i] = DAG.getUNDEF(EltVT);
  1334. else if (EltVT.isFloatingPoint())
  1335. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1336. else
  1337. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1338. }
  1339. return DAG.getMergeValues(Constants, getCurSDLoc());
  1340. }
  1341. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1342. return DAG.getBlockAddress(BA, VT);
  1343. VectorType *VecTy = cast<VectorType>(V->getType());
  1344. unsigned NumElements = VecTy->getNumElements();
  1345. // Now that we know the number and type of the elements, get that number of
  1346. // elements into the Ops array based on what kind of constant it is.
  1347. SmallVector<SDValue, 16> Ops;
  1348. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1349. for (unsigned i = 0; i != NumElements; ++i)
  1350. Ops.push_back(getValue(CV->getOperand(i)));
  1351. } else {
  1352. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1353. EVT EltVT =
  1354. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1355. SDValue Op;
  1356. if (EltVT.isFloatingPoint())
  1357. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1358. else
  1359. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1360. Ops.assign(NumElements, Op);
  1361. }
  1362. // Create a BUILD_VECTOR node.
  1363. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1364. }
  1365. // If this is a static alloca, generate it as the frameindex instead of
  1366. // computation.
  1367. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1368. DenseMap<const AllocaInst*, int>::iterator SI =
  1369. FuncInfo.StaticAllocaMap.find(AI);
  1370. if (SI != FuncInfo.StaticAllocaMap.end())
  1371. return DAG.getFrameIndex(SI->second,
  1372. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1373. }
  1374. // If this is an instruction which fast-isel has deferred, select it now.
  1375. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1376. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1377. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1378. Inst->getType(), getABIRegCopyCC(V));
  1379. SDValue Chain = DAG.getEntryNode();
  1380. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1381. }
  1382. llvm_unreachable("Can't get register for value!");
  1383. }
  1384. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1385. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1386. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1387. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1388. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1389. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1390. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1391. if (!IsSEH)
  1392. CatchPadMBB->setIsEHScopeEntry();
  1393. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1394. if (IsMSVCCXX || IsCoreCLR)
  1395. CatchPadMBB->setIsEHFuncletEntry();
  1396. // Wasm does not need catchpads anymore
  1397. if (!IsWasmCXX)
  1398. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1399. getControlRoot()));
  1400. }
  1401. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1402. // Update machine-CFG edge.
  1403. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1404. FuncInfo.MBB->addSuccessor(TargetMBB);
  1405. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1406. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1407. if (IsSEH) {
  1408. // If this is not a fall-through branch or optimizations are switched off,
  1409. // emit the branch.
  1410. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1411. TM.getOptLevel() == CodeGenOpt::None)
  1412. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1413. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1414. return;
  1415. }
  1416. // Figure out the funclet membership for the catchret's successor.
  1417. // This will be used by the FuncletLayout pass to determine how to order the
  1418. // BB's.
  1419. // A 'catchret' returns to the outer scope's color.
  1420. Value *ParentPad = I.getCatchSwitchParentPad();
  1421. const BasicBlock *SuccessorColor;
  1422. if (isa<ConstantTokenNone>(ParentPad))
  1423. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1424. else
  1425. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1426. assert(SuccessorColor && "No parent funclet for catchret!");
  1427. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1428. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1429. // Create the terminator node.
  1430. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1431. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1432. DAG.getBasicBlock(SuccessorColorMBB));
  1433. DAG.setRoot(Ret);
  1434. }
  1435. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1436. // Don't emit any special code for the cleanuppad instruction. It just marks
  1437. // the start of an EH scope/funclet.
  1438. FuncInfo.MBB->setIsEHScopeEntry();
  1439. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1440. if (Pers != EHPersonality::Wasm_CXX) {
  1441. FuncInfo.MBB->setIsEHFuncletEntry();
  1442. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1443. }
  1444. }
  1445. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1446. // the control flow always stops at the single catch pad, as it does for a
  1447. // cleanup pad. In case the exception caught is not of the types the catch pad
  1448. // catches, it will be rethrown by a rethrow.
  1449. static void findWasmUnwindDestinations(
  1450. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1451. BranchProbability Prob,
  1452. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1453. &UnwindDests) {
  1454. while (EHPadBB) {
  1455. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1456. if (isa<CleanupPadInst>(Pad)) {
  1457. // Stop on cleanup pads.
  1458. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1459. UnwindDests.back().first->setIsEHScopeEntry();
  1460. break;
  1461. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1462. // Add the catchpad handlers to the possible destinations. We don't
  1463. // continue to the unwind destination of the catchswitch for wasm.
  1464. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1465. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1466. UnwindDests.back().first->setIsEHScopeEntry();
  1467. }
  1468. break;
  1469. } else {
  1470. continue;
  1471. }
  1472. }
  1473. }
  1474. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1475. /// many places it could ultimately go. In the IR, we have a single unwind
  1476. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1477. /// This function skips over imaginary basic blocks that hold catchswitch
  1478. /// instructions, and finds all the "real" machine
  1479. /// basic block destinations. As those destinations may not be successors of
  1480. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1481. /// The passed-in Prob is the edge probability to EHPadBB.
  1482. static void findUnwindDestinations(
  1483. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1484. BranchProbability Prob,
  1485. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1486. &UnwindDests) {
  1487. EHPersonality Personality =
  1488. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1489. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1490. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1491. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1492. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1493. if (IsWasmCXX) {
  1494. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1495. assert(UnwindDests.size() <= 1 &&
  1496. "There should be at most one unwind destination for wasm");
  1497. return;
  1498. }
  1499. while (EHPadBB) {
  1500. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1501. BasicBlock *NewEHPadBB = nullptr;
  1502. if (isa<LandingPadInst>(Pad)) {
  1503. // Stop on landingpads. They are not funclets.
  1504. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1505. break;
  1506. } else if (isa<CleanupPadInst>(Pad)) {
  1507. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1508. // personalities.
  1509. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1510. UnwindDests.back().first->setIsEHScopeEntry();
  1511. UnwindDests.back().first->setIsEHFuncletEntry();
  1512. break;
  1513. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1514. // Add the catchpad handlers to the possible destinations.
  1515. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1516. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1517. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1518. if (IsMSVCCXX || IsCoreCLR)
  1519. UnwindDests.back().first->setIsEHFuncletEntry();
  1520. if (!IsSEH)
  1521. UnwindDests.back().first->setIsEHScopeEntry();
  1522. }
  1523. NewEHPadBB = CatchSwitch->getUnwindDest();
  1524. } else {
  1525. continue;
  1526. }
  1527. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1528. if (BPI && NewEHPadBB)
  1529. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1530. EHPadBB = NewEHPadBB;
  1531. }
  1532. }
  1533. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1534. // Update successor info.
  1535. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1536. auto UnwindDest = I.getUnwindDest();
  1537. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1538. BranchProbability UnwindDestProb =
  1539. (BPI && UnwindDest)
  1540. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1541. : BranchProbability::getZero();
  1542. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1543. for (auto &UnwindDest : UnwindDests) {
  1544. UnwindDest.first->setIsEHPad();
  1545. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1546. }
  1547. FuncInfo.MBB->normalizeSuccProbs();
  1548. // Create the terminator node.
  1549. SDValue Ret =
  1550. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1551. DAG.setRoot(Ret);
  1552. }
  1553. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1554. report_fatal_error("visitCatchSwitch not yet implemented!");
  1555. }
  1556. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1557. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1558. auto &DL = DAG.getDataLayout();
  1559. SDValue Chain = getControlRoot();
  1560. SmallVector<ISD::OutputArg, 8> Outs;
  1561. SmallVector<SDValue, 8> OutVals;
  1562. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1563. // lower
  1564. //
  1565. // %val = call <ty> @llvm.experimental.deoptimize()
  1566. // ret <ty> %val
  1567. //
  1568. // differently.
  1569. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1570. LowerDeoptimizingReturn();
  1571. return;
  1572. }
  1573. if (!FuncInfo.CanLowerReturn) {
  1574. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1575. const Function *F = I.getParent()->getParent();
  1576. // Emit a store of the return value through the virtual register.
  1577. // Leave Outs empty so that LowerReturn won't try to load return
  1578. // registers the usual way.
  1579. SmallVector<EVT, 1> PtrValueVTs;
  1580. ComputeValueVTs(TLI, DL,
  1581. F->getReturnType()->getPointerTo(
  1582. DAG.getDataLayout().getAllocaAddrSpace()),
  1583. PtrValueVTs);
  1584. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1585. DemoteReg, PtrValueVTs[0]);
  1586. SDValue RetOp = getValue(I.getOperand(0));
  1587. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1588. SmallVector<uint64_t, 4> Offsets;
  1589. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1590. &Offsets);
  1591. unsigned NumValues = ValueVTs.size();
  1592. SmallVector<SDValue, 4> Chains(NumValues);
  1593. for (unsigned i = 0; i != NumValues; ++i) {
  1594. // An aggregate return value cannot wrap around the address space, so
  1595. // offsets to its parts don't wrap either.
  1596. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1597. SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
  1598. if (MemVTs[i] != ValueVTs[i])
  1599. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1600. Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
  1601. // FIXME: better loc info would be nice.
  1602. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1603. }
  1604. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1605. MVT::Other, Chains);
  1606. } else if (I.getNumOperands() != 0) {
  1607. SmallVector<EVT, 4> ValueVTs;
  1608. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1609. unsigned NumValues = ValueVTs.size();
  1610. if (NumValues) {
  1611. SDValue RetOp = getValue(I.getOperand(0));
  1612. const Function *F = I.getParent()->getParent();
  1613. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1614. I.getOperand(0)->getType(), F->getCallingConv(),
  1615. /*IsVarArg*/ false);
  1616. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1617. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1618. Attribute::SExt))
  1619. ExtendKind = ISD::SIGN_EXTEND;
  1620. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1621. Attribute::ZExt))
  1622. ExtendKind = ISD::ZERO_EXTEND;
  1623. LLVMContext &Context = F->getContext();
  1624. bool RetInReg = F->getAttributes().hasAttribute(
  1625. AttributeList::ReturnIndex, Attribute::InReg);
  1626. for (unsigned j = 0; j != NumValues; ++j) {
  1627. EVT VT = ValueVTs[j];
  1628. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1629. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1630. CallingConv::ID CC = F->getCallingConv();
  1631. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1632. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1633. SmallVector<SDValue, 4> Parts(NumParts);
  1634. getCopyToParts(DAG, getCurSDLoc(),
  1635. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1636. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1637. // 'inreg' on function refers to return value
  1638. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1639. if (RetInReg)
  1640. Flags.setInReg();
  1641. if (I.getOperand(0)->getType()->isPointerTy()) {
  1642. Flags.setPointer();
  1643. Flags.setPointerAddrSpace(
  1644. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1645. }
  1646. if (NeedsRegBlock) {
  1647. Flags.setInConsecutiveRegs();
  1648. if (j == NumValues - 1)
  1649. Flags.setInConsecutiveRegsLast();
  1650. }
  1651. // Propagate extension type if any
  1652. if (ExtendKind == ISD::SIGN_EXTEND)
  1653. Flags.setSExt();
  1654. else if (ExtendKind == ISD::ZERO_EXTEND)
  1655. Flags.setZExt();
  1656. for (unsigned i = 0; i < NumParts; ++i) {
  1657. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1658. VT, /*isfixed=*/true, 0, 0));
  1659. OutVals.push_back(Parts[i]);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. // Push in swifterror virtual register as the last element of Outs. This makes
  1665. // sure swifterror virtual register will be returned in the swifterror
  1666. // physical register.
  1667. const Function *F = I.getParent()->getParent();
  1668. if (TLI.supportSwiftError() &&
  1669. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1670. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1671. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1672. Flags.setSwiftError();
  1673. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1674. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1675. true /*isfixed*/, 1 /*origidx*/,
  1676. 0 /*partOffs*/));
  1677. // Create SDNode for the swifterror virtual register.
  1678. OutVals.push_back(
  1679. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1680. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1681. EVT(TLI.getPointerTy(DL))));
  1682. }
  1683. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1684. CallingConv::ID CallConv =
  1685. DAG.getMachineFunction().getFunction().getCallingConv();
  1686. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1687. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1688. // Verify that the target's LowerReturn behaved as expected.
  1689. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1690. "LowerReturn didn't return a valid chain!");
  1691. // Update the DAG with the new chain value resulting from return lowering.
  1692. DAG.setRoot(Chain);
  1693. }
  1694. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1695. /// created for it, emit nodes to copy the value into the virtual
  1696. /// registers.
  1697. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1698. // Skip empty types
  1699. if (V->getType()->isEmptyTy())
  1700. return;
  1701. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1702. if (VMI != FuncInfo.ValueMap.end()) {
  1703. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1704. CopyValueToVirtualRegister(V, VMI->second);
  1705. }
  1706. }
  1707. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1708. /// the current basic block, add it to ValueMap now so that we'll get a
  1709. /// CopyTo/FromReg.
  1710. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1711. // No need to export constants.
  1712. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1713. // Already exported?
  1714. if (FuncInfo.isExportedInst(V)) return;
  1715. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1716. CopyValueToVirtualRegister(V, Reg);
  1717. }
  1718. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1719. const BasicBlock *FromBB) {
  1720. // The operands of the setcc have to be in this block. We don't know
  1721. // how to export them from some other block.
  1722. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1723. // Can export from current BB.
  1724. if (VI->getParent() == FromBB)
  1725. return true;
  1726. // Is already exported, noop.
  1727. return FuncInfo.isExportedInst(V);
  1728. }
  1729. // If this is an argument, we can export it if the BB is the entry block or
  1730. // if it is already exported.
  1731. if (isa<Argument>(V)) {
  1732. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1733. return true;
  1734. // Otherwise, can only export this if it is already exported.
  1735. return FuncInfo.isExportedInst(V);
  1736. }
  1737. // Otherwise, constants can always be exported.
  1738. return true;
  1739. }
  1740. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1741. BranchProbability
  1742. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1743. const MachineBasicBlock *Dst) const {
  1744. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1745. const BasicBlock *SrcBB = Src->getBasicBlock();
  1746. const BasicBlock *DstBB = Dst->getBasicBlock();
  1747. if (!BPI) {
  1748. // If BPI is not available, set the default probability as 1 / N, where N is
  1749. // the number of successors.
  1750. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1751. return BranchProbability(1, SuccSize);
  1752. }
  1753. return BPI->getEdgeProbability(SrcBB, DstBB);
  1754. }
  1755. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1756. MachineBasicBlock *Dst,
  1757. BranchProbability Prob) {
  1758. if (!FuncInfo.BPI)
  1759. Src->addSuccessorWithoutProb(Dst);
  1760. else {
  1761. if (Prob.isUnknown())
  1762. Prob = getEdgeProbability(Src, Dst);
  1763. Src->addSuccessor(Dst, Prob);
  1764. }
  1765. }
  1766. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1767. if (const Instruction *I = dyn_cast<Instruction>(V))
  1768. return I->getParent() == BB;
  1769. return true;
  1770. }
  1771. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1772. /// This function emits a branch and is used at the leaves of an OR or an
  1773. /// AND operator tree.
  1774. void
  1775. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1776. MachineBasicBlock *TBB,
  1777. MachineBasicBlock *FBB,
  1778. MachineBasicBlock *CurBB,
  1779. MachineBasicBlock *SwitchBB,
  1780. BranchProbability TProb,
  1781. BranchProbability FProb,
  1782. bool InvertCond) {
  1783. const BasicBlock *BB = CurBB->getBasicBlock();
  1784. // If the leaf of the tree is a comparison, merge the condition into
  1785. // the caseblock.
  1786. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1787. // The operands of the cmp have to be in this block. We don't know
  1788. // how to export them from some other block. If this is the first block
  1789. // of the sequence, no exporting is needed.
  1790. if (CurBB == SwitchBB ||
  1791. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1792. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1793. ISD::CondCode Condition;
  1794. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1795. ICmpInst::Predicate Pred =
  1796. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1797. Condition = getICmpCondCode(Pred);
  1798. } else {
  1799. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1800. FCmpInst::Predicate Pred =
  1801. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1802. Condition = getFCmpCondCode(Pred);
  1803. if (TM.Options.NoNaNsFPMath)
  1804. Condition = getFCmpCodeWithoutNaN(Condition);
  1805. }
  1806. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1807. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1808. SL->SwitchCases.push_back(CB);
  1809. return;
  1810. }
  1811. }
  1812. // Create a CaseBlock record representing this branch.
  1813. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1814. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1815. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1816. SL->SwitchCases.push_back(CB);
  1817. }
  1818. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1819. MachineBasicBlock *TBB,
  1820. MachineBasicBlock *FBB,
  1821. MachineBasicBlock *CurBB,
  1822. MachineBasicBlock *SwitchBB,
  1823. Instruction::BinaryOps Opc,
  1824. BranchProbability TProb,
  1825. BranchProbability FProb,
  1826. bool InvertCond) {
  1827. // Skip over not part of the tree and remember to invert op and operands at
  1828. // next level.
  1829. Value *NotCond;
  1830. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1831. InBlock(NotCond, CurBB->getBasicBlock())) {
  1832. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1833. !InvertCond);
  1834. return;
  1835. }
  1836. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1837. // Compute the effective opcode for Cond, taking into account whether it needs
  1838. // to be inverted, e.g.
  1839. // and (not (or A, B)), C
  1840. // gets lowered as
  1841. // and (and (not A, not B), C)
  1842. unsigned BOpc = 0;
  1843. if (BOp) {
  1844. BOpc = BOp->getOpcode();
  1845. if (InvertCond) {
  1846. if (BOpc == Instruction::And)
  1847. BOpc = Instruction::Or;
  1848. else if (BOpc == Instruction::Or)
  1849. BOpc = Instruction::And;
  1850. }
  1851. }
  1852. // If this node is not part of the or/and tree, emit it as a branch.
  1853. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1854. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1855. BOp->getParent() != CurBB->getBasicBlock() ||
  1856. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1857. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1858. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1859. TProb, FProb, InvertCond);
  1860. return;
  1861. }
  1862. // Create TmpBB after CurBB.
  1863. MachineFunction::iterator BBI(CurBB);
  1864. MachineFunction &MF = DAG.getMachineFunction();
  1865. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1866. CurBB->getParent()->insert(++BBI, TmpBB);
  1867. if (Opc == Instruction::Or) {
  1868. // Codegen X | Y as:
  1869. // BB1:
  1870. // jmp_if_X TBB
  1871. // jmp TmpBB
  1872. // TmpBB:
  1873. // jmp_if_Y TBB
  1874. // jmp FBB
  1875. //
  1876. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1877. // The requirement is that
  1878. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1879. // = TrueProb for original BB.
  1880. // Assuming the original probabilities are A and B, one choice is to set
  1881. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1882. // A/(1+B) and 2B/(1+B). This choice assumes that
  1883. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1884. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1885. // TmpBB, but the math is more complicated.
  1886. auto NewTrueProb = TProb / 2;
  1887. auto NewFalseProb = TProb / 2 + FProb;
  1888. // Emit the LHS condition.
  1889. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1890. NewTrueProb, NewFalseProb, InvertCond);
  1891. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1892. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1893. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1894. // Emit the RHS condition into TmpBB.
  1895. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1896. Probs[0], Probs[1], InvertCond);
  1897. } else {
  1898. assert(Opc == Instruction::And && "Unknown merge op!");
  1899. // Codegen X & Y as:
  1900. // BB1:
  1901. // jmp_if_X TmpBB
  1902. // jmp FBB
  1903. // TmpBB:
  1904. // jmp_if_Y TBB
  1905. // jmp FBB
  1906. //
  1907. // This requires creation of TmpBB after CurBB.
  1908. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1909. // The requirement is that
  1910. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1911. // = FalseProb for original BB.
  1912. // Assuming the original probabilities are A and B, one choice is to set
  1913. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1914. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1915. // TrueProb for BB1 * FalseProb for TmpBB.
  1916. auto NewTrueProb = TProb + FProb / 2;
  1917. auto NewFalseProb = FProb / 2;
  1918. // Emit the LHS condition.
  1919. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1920. NewTrueProb, NewFalseProb, InvertCond);
  1921. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1922. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1923. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1924. // Emit the RHS condition into TmpBB.
  1925. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1926. Probs[0], Probs[1], InvertCond);
  1927. }
  1928. }
  1929. /// If the set of cases should be emitted as a series of branches, return true.
  1930. /// If we should emit this as a bunch of and/or'd together conditions, return
  1931. /// false.
  1932. bool
  1933. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1934. if (Cases.size() != 2) return true;
  1935. // If this is two comparisons of the same values or'd or and'd together, they
  1936. // will get folded into a single comparison, so don't emit two blocks.
  1937. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1938. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1939. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1940. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1941. return false;
  1942. }
  1943. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1944. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1945. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1946. Cases[0].CC == Cases[1].CC &&
  1947. isa<Constant>(Cases[0].CmpRHS) &&
  1948. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1949. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1950. return false;
  1951. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1952. return false;
  1953. }
  1954. return true;
  1955. }
  1956. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1957. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1958. // Update machine-CFG edges.
  1959. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1960. if (I.isUnconditional()) {
  1961. // Update machine-CFG edges.
  1962. BrMBB->addSuccessor(Succ0MBB);
  1963. // If this is not a fall-through branch or optimizations are switched off,
  1964. // emit the branch.
  1965. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1966. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1967. MVT::Other, getControlRoot(),
  1968. DAG.getBasicBlock(Succ0MBB)));
  1969. return;
  1970. }
  1971. // If this condition is one of the special cases we handle, do special stuff
  1972. // now.
  1973. const Value *CondVal = I.getCondition();
  1974. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1975. // If this is a series of conditions that are or'd or and'd together, emit
  1976. // this as a sequence of branches instead of setcc's with and/or operations.
  1977. // As long as jumps are not expensive, this should improve performance.
  1978. // For example, instead of something like:
  1979. // cmp A, B
  1980. // C = seteq
  1981. // cmp D, E
  1982. // F = setle
  1983. // or C, F
  1984. // jnz foo
  1985. // Emit:
  1986. // cmp A, B
  1987. // je foo
  1988. // cmp D, E
  1989. // jle foo
  1990. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1991. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1992. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1993. !I.hasMetadata(LLVMContext::MD_unpredictable) &&
  1994. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1995. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1996. Opcode,
  1997. getEdgeProbability(BrMBB, Succ0MBB),
  1998. getEdgeProbability(BrMBB, Succ1MBB),
  1999. /*InvertCond=*/false);
  2000. // If the compares in later blocks need to use values not currently
  2001. // exported from this block, export them now. This block should always
  2002. // be the first entry.
  2003. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2004. // Allow some cases to be rejected.
  2005. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2006. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2007. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2008. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2009. }
  2010. // Emit the branch for this block.
  2011. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2012. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2013. return;
  2014. }
  2015. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2016. // SwitchCases.
  2017. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2018. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2019. SL->SwitchCases.clear();
  2020. }
  2021. }
  2022. // Create a CaseBlock record representing this branch.
  2023. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2024. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2025. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2026. // cond branch.
  2027. visitSwitchCase(CB, BrMBB);
  2028. }
  2029. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2030. /// the binary search tree resulting from lowering a switch instruction.
  2031. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2032. MachineBasicBlock *SwitchBB) {
  2033. SDValue Cond;
  2034. SDValue CondLHS = getValue(CB.CmpLHS);
  2035. SDLoc dl = CB.DL;
  2036. if (CB.CC == ISD::SETTRUE) {
  2037. // Branch or fall through to TrueBB.
  2038. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2039. SwitchBB->normalizeSuccProbs();
  2040. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2041. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2042. DAG.getBasicBlock(CB.TrueBB)));
  2043. }
  2044. return;
  2045. }
  2046. auto &TLI = DAG.getTargetLoweringInfo();
  2047. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2048. // Build the setcc now.
  2049. if (!CB.CmpMHS) {
  2050. // Fold "(X == true)" to X and "(X == false)" to !X to
  2051. // handle common cases produced by branch lowering.
  2052. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2053. CB.CC == ISD::SETEQ)
  2054. Cond = CondLHS;
  2055. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2056. CB.CC == ISD::SETEQ) {
  2057. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2058. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2059. } else {
  2060. SDValue CondRHS = getValue(CB.CmpRHS);
  2061. // If a pointer's DAG type is larger than its memory type then the DAG
  2062. // values are zero-extended. This breaks signed comparisons so truncate
  2063. // back to the underlying type before doing the compare.
  2064. if (CondLHS.getValueType() != MemVT) {
  2065. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2066. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2067. }
  2068. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2069. }
  2070. } else {
  2071. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2072. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2073. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2074. SDValue CmpOp = getValue(CB.CmpMHS);
  2075. EVT VT = CmpOp.getValueType();
  2076. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2077. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2078. ISD::SETLE);
  2079. } else {
  2080. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2081. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2082. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2083. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2084. }
  2085. }
  2086. // Update successor info
  2087. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2088. // TrueBB and FalseBB are always different unless the incoming IR is
  2089. // degenerate. This only happens when running llc on weird IR.
  2090. if (CB.TrueBB != CB.FalseBB)
  2091. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2092. SwitchBB->normalizeSuccProbs();
  2093. // If the lhs block is the next block, invert the condition so that we can
  2094. // fall through to the lhs instead of the rhs block.
  2095. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2096. std::swap(CB.TrueBB, CB.FalseBB);
  2097. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2098. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2099. }
  2100. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2101. MVT::Other, getControlRoot(), Cond,
  2102. DAG.getBasicBlock(CB.TrueBB));
  2103. // Insert the false branch. Do this even if it's a fall through branch,
  2104. // this makes it easier to do DAG optimizations which require inverting
  2105. // the branch condition.
  2106. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2107. DAG.getBasicBlock(CB.FalseBB));
  2108. DAG.setRoot(BrCond);
  2109. }
  2110. /// visitJumpTable - Emit JumpTable node in the current MBB
  2111. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2112. // Emit the code for the jump table
  2113. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2114. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2115. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2116. JT.Reg, PTy);
  2117. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2118. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2119. MVT::Other, Index.getValue(1),
  2120. Table, Index);
  2121. DAG.setRoot(BrJumpTable);
  2122. }
  2123. /// visitJumpTableHeader - This function emits necessary code to produce index
  2124. /// in the JumpTable from switch case.
  2125. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2126. JumpTableHeader &JTH,
  2127. MachineBasicBlock *SwitchBB) {
  2128. SDLoc dl = getCurSDLoc();
  2129. // Subtract the lowest switch case value from the value being switched on.
  2130. SDValue SwitchOp = getValue(JTH.SValue);
  2131. EVT VT = SwitchOp.getValueType();
  2132. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2133. DAG.getConstant(JTH.First, dl, VT));
  2134. // The SDNode we just created, which holds the value being switched on minus
  2135. // the smallest case value, needs to be copied to a virtual register so it
  2136. // can be used as an index into the jump table in a subsequent basic block.
  2137. // This value may be smaller or larger than the target's pointer type, and
  2138. // therefore require extension or truncating.
  2139. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2140. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2141. unsigned JumpTableReg =
  2142. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2143. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2144. JumpTableReg, SwitchOp);
  2145. JT.Reg = JumpTableReg;
  2146. if (!JTH.OmitRangeCheck) {
  2147. // Emit the range check for the jump table, and branch to the default block
  2148. // for the switch statement if the value being switched on exceeds the
  2149. // largest case in the switch.
  2150. SDValue CMP = DAG.getSetCC(
  2151. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2152. Sub.getValueType()),
  2153. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2154. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2155. MVT::Other, CopyTo, CMP,
  2156. DAG.getBasicBlock(JT.Default));
  2157. // Avoid emitting unnecessary branches to the next block.
  2158. if (JT.MBB != NextBlock(SwitchBB))
  2159. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2160. DAG.getBasicBlock(JT.MBB));
  2161. DAG.setRoot(BrCond);
  2162. } else {
  2163. // Avoid emitting unnecessary branches to the next block.
  2164. if (JT.MBB != NextBlock(SwitchBB))
  2165. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2166. DAG.getBasicBlock(JT.MBB)));
  2167. else
  2168. DAG.setRoot(CopyTo);
  2169. }
  2170. }
  2171. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2172. /// variable if there exists one.
  2173. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2174. SDValue &Chain) {
  2175. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2176. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2177. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2178. MachineFunction &MF = DAG.getMachineFunction();
  2179. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2180. MachineSDNode *Node =
  2181. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2182. if (Global) {
  2183. MachinePointerInfo MPInfo(Global);
  2184. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2185. MachineMemOperand::MODereferenceable;
  2186. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2187. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2188. DAG.setNodeMemRefs(Node, {MemRef});
  2189. }
  2190. if (PtrTy != PtrMemTy)
  2191. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2192. return SDValue(Node, 0);
  2193. }
  2194. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2195. /// tail spliced into a stack protector check success bb.
  2196. ///
  2197. /// For a high level explanation of how this fits into the stack protector
  2198. /// generation see the comment on the declaration of class
  2199. /// StackProtectorDescriptor.
  2200. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2201. MachineBasicBlock *ParentBB) {
  2202. // First create the loads to the guard/stack slot for the comparison.
  2203. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2204. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2205. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2206. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2207. int FI = MFI.getStackProtectorIndex();
  2208. SDValue Guard;
  2209. SDLoc dl = getCurSDLoc();
  2210. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2211. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2212. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2213. // Generate code to load the content of the guard slot.
  2214. SDValue GuardVal = DAG.getLoad(
  2215. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2216. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2217. MachineMemOperand::MOVolatile);
  2218. if (TLI.useStackGuardXorFP())
  2219. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2220. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2221. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2222. // The target provides a guard check function to validate the guard value.
  2223. // Generate a call to that function with the content of the guard slot as
  2224. // argument.
  2225. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2226. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2227. TargetLowering::ArgListTy Args;
  2228. TargetLowering::ArgListEntry Entry;
  2229. Entry.Node = GuardVal;
  2230. Entry.Ty = FnTy->getParamType(0);
  2231. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2232. Entry.IsInReg = true;
  2233. Args.push_back(Entry);
  2234. TargetLowering::CallLoweringInfo CLI(DAG);
  2235. CLI.setDebugLoc(getCurSDLoc())
  2236. .setChain(DAG.getEntryNode())
  2237. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2238. getValue(GuardCheckFn), std::move(Args));
  2239. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2240. DAG.setRoot(Result.second);
  2241. return;
  2242. }
  2243. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2244. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2245. SDValue Chain = DAG.getEntryNode();
  2246. if (TLI.useLoadStackGuardNode()) {
  2247. Guard = getLoadStackGuard(DAG, dl, Chain);
  2248. } else {
  2249. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2250. SDValue GuardPtr = getValue(IRGuard);
  2251. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2252. MachinePointerInfo(IRGuard, 0), Align,
  2253. MachineMemOperand::MOVolatile);
  2254. }
  2255. // Perform the comparison via a subtract/getsetcc.
  2256. EVT VT = Guard.getValueType();
  2257. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2258. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2259. *DAG.getContext(),
  2260. Sub.getValueType()),
  2261. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2262. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2263. // branch to failure MBB.
  2264. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2265. MVT::Other, GuardVal.getOperand(0),
  2266. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2267. // Otherwise branch to success MBB.
  2268. SDValue Br = DAG.getNode(ISD::BR, dl,
  2269. MVT::Other, BrCond,
  2270. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2271. DAG.setRoot(Br);
  2272. }
  2273. /// Codegen the failure basic block for a stack protector check.
  2274. ///
  2275. /// A failure stack protector machine basic block consists simply of a call to
  2276. /// __stack_chk_fail().
  2277. ///
  2278. /// For a high level explanation of how this fits into the stack protector
  2279. /// generation see the comment on the declaration of class
  2280. /// StackProtectorDescriptor.
  2281. void
  2282. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2283. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2284. TargetLowering::MakeLibCallOptions CallOptions;
  2285. CallOptions.setDiscardResult(true);
  2286. SDValue Chain =
  2287. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2288. None, CallOptions, getCurSDLoc()).second;
  2289. // On PS4, the "return address" must still be within the calling function,
  2290. // even if it's at the very end, so emit an explicit TRAP here.
  2291. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2292. if (TM.getTargetTriple().isPS4CPU())
  2293. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2294. DAG.setRoot(Chain);
  2295. }
  2296. /// visitBitTestHeader - This function emits necessary code to produce value
  2297. /// suitable for "bit tests"
  2298. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2299. MachineBasicBlock *SwitchBB) {
  2300. SDLoc dl = getCurSDLoc();
  2301. // Subtract the minimum value.
  2302. SDValue SwitchOp = getValue(B.SValue);
  2303. EVT VT = SwitchOp.getValueType();
  2304. SDValue RangeSub =
  2305. DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
  2306. // Determine the type of the test operands.
  2307. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2308. bool UsePtrType = false;
  2309. if (!TLI.isTypeLegal(VT)) {
  2310. UsePtrType = true;
  2311. } else {
  2312. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2313. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2314. // Switch table case range are encoded into series of masks.
  2315. // Just use pointer type, it's guaranteed to fit.
  2316. UsePtrType = true;
  2317. break;
  2318. }
  2319. }
  2320. SDValue Sub = RangeSub;
  2321. if (UsePtrType) {
  2322. VT = TLI.getPointerTy(DAG.getDataLayout());
  2323. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2324. }
  2325. B.RegVT = VT.getSimpleVT();
  2326. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2327. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2328. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2329. if (!B.OmitRangeCheck)
  2330. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2331. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2332. SwitchBB->normalizeSuccProbs();
  2333. SDValue Root = CopyTo;
  2334. if (!B.OmitRangeCheck) {
  2335. // Conditional branch to the default block.
  2336. SDValue RangeCmp = DAG.getSetCC(dl,
  2337. TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2338. RangeSub.getValueType()),
  2339. RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
  2340. ISD::SETUGT);
  2341. Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
  2342. DAG.getBasicBlock(B.Default));
  2343. }
  2344. // Avoid emitting unnecessary branches to the next block.
  2345. if (MBB != NextBlock(SwitchBB))
  2346. Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
  2347. DAG.setRoot(Root);
  2348. }
  2349. /// visitBitTestCase - this function produces one "bit test"
  2350. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2351. MachineBasicBlock* NextMBB,
  2352. BranchProbability BranchProbToNext,
  2353. unsigned Reg,
  2354. BitTestCase &B,
  2355. MachineBasicBlock *SwitchBB) {
  2356. SDLoc dl = getCurSDLoc();
  2357. MVT VT = BB.RegVT;
  2358. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2359. SDValue Cmp;
  2360. unsigned PopCount = countPopulation(B.Mask);
  2361. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2362. if (PopCount == 1) {
  2363. // Testing for a single bit; just compare the shift count with what it
  2364. // would need to be to shift a 1 bit in that position.
  2365. Cmp = DAG.getSetCC(
  2366. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2367. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2368. ISD::SETEQ);
  2369. } else if (PopCount == BB.Range) {
  2370. // There is only one zero bit in the range, test for it directly.
  2371. Cmp = DAG.getSetCC(
  2372. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2373. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2374. ISD::SETNE);
  2375. } else {
  2376. // Make desired shift
  2377. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2378. DAG.getConstant(1, dl, VT), ShiftOp);
  2379. // Emit bit tests and jumps
  2380. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2381. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2382. Cmp = DAG.getSetCC(
  2383. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2384. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2385. }
  2386. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2387. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2388. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2389. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2390. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2391. // one as they are relative probabilities (and thus work more like weights),
  2392. // and hence we need to normalize them to let the sum of them become one.
  2393. SwitchBB->normalizeSuccProbs();
  2394. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2395. MVT::Other, getControlRoot(),
  2396. Cmp, DAG.getBasicBlock(B.TargetBB));
  2397. // Avoid emitting unnecessary branches to the next block.
  2398. if (NextMBB != NextBlock(SwitchBB))
  2399. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2400. DAG.getBasicBlock(NextMBB));
  2401. DAG.setRoot(BrAnd);
  2402. }
  2403. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2404. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2405. // Retrieve successors. Look through artificial IR level blocks like
  2406. // catchswitch for successors.
  2407. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2408. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2409. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2410. // have to do anything here to lower funclet bundles.
  2411. assert(!I.hasOperandBundlesOtherThan(
  2412. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2413. "Cannot lower invokes with arbitrary operand bundles yet!");
  2414. const Value *Callee(I.getCalledValue());
  2415. const Function *Fn = dyn_cast<Function>(Callee);
  2416. if (isa<InlineAsm>(Callee))
  2417. visitInlineAsm(&I);
  2418. else if (Fn && Fn->isIntrinsic()) {
  2419. switch (Fn->getIntrinsicID()) {
  2420. default:
  2421. llvm_unreachable("Cannot invoke this intrinsic");
  2422. case Intrinsic::donothing:
  2423. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2424. break;
  2425. case Intrinsic::experimental_patchpoint_void:
  2426. case Intrinsic::experimental_patchpoint_i64:
  2427. visitPatchpoint(&I, EHPadBB);
  2428. break;
  2429. case Intrinsic::experimental_gc_statepoint:
  2430. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2431. break;
  2432. case Intrinsic::wasm_rethrow_in_catch: {
  2433. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2434. // special because it can be invoked, so we manually lower it to a DAG
  2435. // node here.
  2436. SmallVector<SDValue, 8> Ops;
  2437. Ops.push_back(getRoot()); // inchain
  2438. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2439. Ops.push_back(
  2440. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2441. TLI.getPointerTy(DAG.getDataLayout())));
  2442. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2443. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2444. break;
  2445. }
  2446. }
  2447. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2448. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2449. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2450. // intrinsic, and right now there are no plans to support other intrinsics
  2451. // with deopt state.
  2452. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2453. } else {
  2454. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2455. }
  2456. // If the value of the invoke is used outside of its defining block, make it
  2457. // available as a virtual register.
  2458. // We already took care of the exported value for the statepoint instruction
  2459. // during call to the LowerStatepoint.
  2460. if (!isStatepoint(I)) {
  2461. CopyToExportRegsIfNeeded(&I);
  2462. }
  2463. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2464. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2465. BranchProbability EHPadBBProb =
  2466. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2467. : BranchProbability::getZero();
  2468. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2469. // Update successor info.
  2470. addSuccessorWithProb(InvokeMBB, Return);
  2471. for (auto &UnwindDest : UnwindDests) {
  2472. UnwindDest.first->setIsEHPad();
  2473. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2474. }
  2475. InvokeMBB->normalizeSuccProbs();
  2476. // Drop into normal successor.
  2477. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2478. DAG.getBasicBlock(Return)));
  2479. }
  2480. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2481. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2482. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2483. // have to do anything here to lower funclet bundles.
  2484. assert(!I.hasOperandBundlesOtherThan(
  2485. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2486. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2487. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2488. "Only know how to handle inlineasm callbr");
  2489. visitInlineAsm(&I);
  2490. // Retrieve successors.
  2491. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2492. // Update successor info.
  2493. addSuccessorWithProb(CallBrMBB, Return);
  2494. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2495. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2496. addSuccessorWithProb(CallBrMBB, Target);
  2497. }
  2498. CallBrMBB->normalizeSuccProbs();
  2499. // Drop into default successor.
  2500. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2501. MVT::Other, getControlRoot(),
  2502. DAG.getBasicBlock(Return)));
  2503. }
  2504. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2505. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2506. }
  2507. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2508. assert(FuncInfo.MBB->isEHPad() &&
  2509. "Call to landingpad not in landing pad!");
  2510. // If there aren't registers to copy the values into (e.g., during SjLj
  2511. // exceptions), then don't bother to create these DAG nodes.
  2512. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2513. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2514. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2515. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2516. return;
  2517. // If landingpad's return type is token type, we don't create DAG nodes
  2518. // for its exception pointer and selector value. The extraction of exception
  2519. // pointer or selector value from token type landingpads is not currently
  2520. // supported.
  2521. if (LP.getType()->isTokenTy())
  2522. return;
  2523. SmallVector<EVT, 2> ValueVTs;
  2524. SDLoc dl = getCurSDLoc();
  2525. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2526. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2527. // Get the two live-in registers as SDValues. The physregs have already been
  2528. // copied into virtual registers.
  2529. SDValue Ops[2];
  2530. if (FuncInfo.ExceptionPointerVirtReg) {
  2531. Ops[0] = DAG.getZExtOrTrunc(
  2532. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2533. FuncInfo.ExceptionPointerVirtReg,
  2534. TLI.getPointerTy(DAG.getDataLayout())),
  2535. dl, ValueVTs[0]);
  2536. } else {
  2537. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2538. }
  2539. Ops[1] = DAG.getZExtOrTrunc(
  2540. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2541. FuncInfo.ExceptionSelectorVirtReg,
  2542. TLI.getPointerTy(DAG.getDataLayout())),
  2543. dl, ValueVTs[1]);
  2544. // Merge into one.
  2545. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2546. DAG.getVTList(ValueVTs), Ops);
  2547. setValue(&LP, Res);
  2548. }
  2549. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2550. MachineBasicBlock *Last) {
  2551. // Update JTCases.
  2552. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2553. if (SL->JTCases[i].first.HeaderBB == First)
  2554. SL->JTCases[i].first.HeaderBB = Last;
  2555. // Update BitTestCases.
  2556. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2557. if (SL->BitTestCases[i].Parent == First)
  2558. SL->BitTestCases[i].Parent = Last;
  2559. }
  2560. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2561. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2562. // Update machine-CFG edges with unique successors.
  2563. SmallSet<BasicBlock*, 32> Done;
  2564. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2565. BasicBlock *BB = I.getSuccessor(i);
  2566. bool Inserted = Done.insert(BB).second;
  2567. if (!Inserted)
  2568. continue;
  2569. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2570. addSuccessorWithProb(IndirectBrMBB, Succ);
  2571. }
  2572. IndirectBrMBB->normalizeSuccProbs();
  2573. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2574. MVT::Other, getControlRoot(),
  2575. getValue(I.getAddress())));
  2576. }
  2577. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2578. if (!DAG.getTarget().Options.TrapUnreachable)
  2579. return;
  2580. // We may be able to ignore unreachable behind a noreturn call.
  2581. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2582. const BasicBlock &BB = *I.getParent();
  2583. if (&I != &BB.front()) {
  2584. BasicBlock::const_iterator PredI =
  2585. std::prev(BasicBlock::const_iterator(&I));
  2586. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2587. if (Call->doesNotReturn())
  2588. return;
  2589. }
  2590. }
  2591. }
  2592. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2593. }
  2594. void SelectionDAGBuilder::visitFSub(const User &I) {
  2595. // -0.0 - X --> fneg
  2596. Type *Ty = I.getType();
  2597. if (isa<Constant>(I.getOperand(0)) &&
  2598. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2599. SDValue Op2 = getValue(I.getOperand(1));
  2600. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2601. Op2.getValueType(), Op2));
  2602. return;
  2603. }
  2604. visitBinary(I, ISD::FSUB);
  2605. }
  2606. /// Checks if the given instruction performs a vector reduction, in which case
  2607. /// we have the freedom to alter the elements in the result as long as the
  2608. /// reduction of them stays unchanged.
  2609. static bool isVectorReductionOp(const User *I) {
  2610. const Instruction *Inst = dyn_cast<Instruction>(I);
  2611. if (!Inst || !Inst->getType()->isVectorTy())
  2612. return false;
  2613. auto OpCode = Inst->getOpcode();
  2614. switch (OpCode) {
  2615. case Instruction::Add:
  2616. case Instruction::Mul:
  2617. case Instruction::And:
  2618. case Instruction::Or:
  2619. case Instruction::Xor:
  2620. break;
  2621. case Instruction::FAdd:
  2622. case Instruction::FMul:
  2623. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2624. if (FPOp->getFastMathFlags().isFast())
  2625. break;
  2626. LLVM_FALLTHROUGH;
  2627. default:
  2628. return false;
  2629. }
  2630. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2631. // Ensure the reduction size is a power of 2.
  2632. if (!isPowerOf2_32(ElemNum))
  2633. return false;
  2634. unsigned ElemNumToReduce = ElemNum;
  2635. // Do DFS search on the def-use chain from the given instruction. We only
  2636. // allow four kinds of operations during the search until we reach the
  2637. // instruction that extracts the first element from the vector:
  2638. //
  2639. // 1. The reduction operation of the same opcode as the given instruction.
  2640. //
  2641. // 2. PHI node.
  2642. //
  2643. // 3. ShuffleVector instruction together with a reduction operation that
  2644. // does a partial reduction.
  2645. //
  2646. // 4. ExtractElement that extracts the first element from the vector, and we
  2647. // stop searching the def-use chain here.
  2648. //
  2649. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2650. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2651. // a reduction operation if we meet any other instructions other than those
  2652. // listed above.
  2653. SmallVector<const User *, 16> UsersToVisit{Inst};
  2654. SmallPtrSet<const User *, 16> Visited;
  2655. bool ReduxExtracted = false;
  2656. while (!UsersToVisit.empty()) {
  2657. auto User = UsersToVisit.back();
  2658. UsersToVisit.pop_back();
  2659. if (!Visited.insert(User).second)
  2660. continue;
  2661. for (const auto &U : User->users()) {
  2662. auto Inst = dyn_cast<Instruction>(U);
  2663. if (!Inst)
  2664. return false;
  2665. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2666. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2667. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2668. return false;
  2669. UsersToVisit.push_back(U);
  2670. } else if (const ShuffleVectorInst *ShufInst =
  2671. dyn_cast<ShuffleVectorInst>(U)) {
  2672. // Detect the following pattern: A ShuffleVector instruction together
  2673. // with a reduction that do partial reduction on the first and second
  2674. // ElemNumToReduce / 2 elements, and store the result in
  2675. // ElemNumToReduce / 2 elements in another vector.
  2676. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2677. if (ResultElements < ElemNum)
  2678. return false;
  2679. if (ElemNumToReduce == 1)
  2680. return false;
  2681. if (!isa<UndefValue>(U->getOperand(1)))
  2682. return false;
  2683. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2684. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2685. return false;
  2686. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2687. if (ShufInst->getMaskValue(i) != -1)
  2688. return false;
  2689. // There is only one user of this ShuffleVector instruction, which
  2690. // must be a reduction operation.
  2691. if (!U->hasOneUse())
  2692. return false;
  2693. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2694. if (!U2 || U2->getOpcode() != OpCode)
  2695. return false;
  2696. // Check operands of the reduction operation.
  2697. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2698. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2699. UsersToVisit.push_back(U2);
  2700. ElemNumToReduce /= 2;
  2701. } else
  2702. return false;
  2703. } else if (isa<ExtractElementInst>(U)) {
  2704. // At this moment we should have reduced all elements in the vector.
  2705. if (ElemNumToReduce != 1)
  2706. return false;
  2707. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2708. if (!Val || !Val->isZero())
  2709. return false;
  2710. ReduxExtracted = true;
  2711. } else
  2712. return false;
  2713. }
  2714. }
  2715. return ReduxExtracted;
  2716. }
  2717. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2718. SDNodeFlags Flags;
  2719. SDValue Op = getValue(I.getOperand(0));
  2720. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2721. Op, Flags);
  2722. setValue(&I, UnNodeValue);
  2723. }
  2724. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2725. SDNodeFlags Flags;
  2726. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2727. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2728. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2729. }
  2730. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2731. Flags.setExact(ExactOp->isExact());
  2732. }
  2733. if (isVectorReductionOp(&I)) {
  2734. Flags.setVectorReduction(true);
  2735. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2736. }
  2737. SDValue Op1 = getValue(I.getOperand(0));
  2738. SDValue Op2 = getValue(I.getOperand(1));
  2739. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2740. Op1, Op2, Flags);
  2741. setValue(&I, BinNodeValue);
  2742. }
  2743. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2744. SDValue Op1 = getValue(I.getOperand(0));
  2745. SDValue Op2 = getValue(I.getOperand(1));
  2746. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2747. Op1.getValueType(), DAG.getDataLayout());
  2748. // Coerce the shift amount to the right type if we can.
  2749. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2750. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2751. unsigned Op2Size = Op2.getValueSizeInBits();
  2752. SDLoc DL = getCurSDLoc();
  2753. // If the operand is smaller than the shift count type, promote it.
  2754. if (ShiftSize > Op2Size)
  2755. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2756. // If the operand is larger than the shift count type but the shift
  2757. // count type has enough bits to represent any shift value, truncate
  2758. // it now. This is a common case and it exposes the truncate to
  2759. // optimization early.
  2760. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2761. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2762. // Otherwise we'll need to temporarily settle for some other convenient
  2763. // type. Type legalization will make adjustments once the shiftee is split.
  2764. else
  2765. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2766. }
  2767. bool nuw = false;
  2768. bool nsw = false;
  2769. bool exact = false;
  2770. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2771. if (const OverflowingBinaryOperator *OFBinOp =
  2772. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2773. nuw = OFBinOp->hasNoUnsignedWrap();
  2774. nsw = OFBinOp->hasNoSignedWrap();
  2775. }
  2776. if (const PossiblyExactOperator *ExactOp =
  2777. dyn_cast<const PossiblyExactOperator>(&I))
  2778. exact = ExactOp->isExact();
  2779. }
  2780. SDNodeFlags Flags;
  2781. Flags.setExact(exact);
  2782. Flags.setNoSignedWrap(nsw);
  2783. Flags.setNoUnsignedWrap(nuw);
  2784. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2785. Flags);
  2786. setValue(&I, Res);
  2787. }
  2788. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2789. SDValue Op1 = getValue(I.getOperand(0));
  2790. SDValue Op2 = getValue(I.getOperand(1));
  2791. SDNodeFlags Flags;
  2792. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2793. cast<PossiblyExactOperator>(&I)->isExact());
  2794. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2795. Op2, Flags));
  2796. }
  2797. void SelectionDAGBuilder::visitICmp(const User &I) {
  2798. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2799. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2800. predicate = IC->getPredicate();
  2801. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2802. predicate = ICmpInst::Predicate(IC->getPredicate());
  2803. SDValue Op1 = getValue(I.getOperand(0));
  2804. SDValue Op2 = getValue(I.getOperand(1));
  2805. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2806. auto &TLI = DAG.getTargetLoweringInfo();
  2807. EVT MemVT =
  2808. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2809. // If a pointer's DAG type is larger than its memory type then the DAG values
  2810. // are zero-extended. This breaks signed comparisons so truncate back to the
  2811. // underlying type before doing the compare.
  2812. if (Op1.getValueType() != MemVT) {
  2813. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2814. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2815. }
  2816. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2817. I.getType());
  2818. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2819. }
  2820. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2821. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2822. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2823. predicate = FC->getPredicate();
  2824. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2825. predicate = FCmpInst::Predicate(FC->getPredicate());
  2826. SDValue Op1 = getValue(I.getOperand(0));
  2827. SDValue Op2 = getValue(I.getOperand(1));
  2828. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2829. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2830. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2831. Condition = getFCmpCodeWithoutNaN(Condition);
  2832. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2833. I.getType());
  2834. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2835. }
  2836. // Check if the condition of the select has one use or two users that are both
  2837. // selects with the same condition.
  2838. static bool hasOnlySelectUsers(const Value *Cond) {
  2839. return llvm::all_of(Cond->users(), [](const Value *V) {
  2840. return isa<SelectInst>(V);
  2841. });
  2842. }
  2843. void SelectionDAGBuilder::visitSelect(const User &I) {
  2844. SmallVector<EVT, 4> ValueVTs;
  2845. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2846. ValueVTs);
  2847. unsigned NumValues = ValueVTs.size();
  2848. if (NumValues == 0) return;
  2849. SmallVector<SDValue, 4> Values(NumValues);
  2850. SDValue Cond = getValue(I.getOperand(0));
  2851. SDValue LHSVal = getValue(I.getOperand(1));
  2852. SDValue RHSVal = getValue(I.getOperand(2));
  2853. auto BaseOps = {Cond};
  2854. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2855. ISD::VSELECT : ISD::SELECT;
  2856. bool IsUnaryAbs = false;
  2857. // Min/max matching is only viable if all output VTs are the same.
  2858. if (is_splat(ValueVTs)) {
  2859. EVT VT = ValueVTs[0];
  2860. LLVMContext &Ctx = *DAG.getContext();
  2861. auto &TLI = DAG.getTargetLoweringInfo();
  2862. // We care about the legality of the operation after it has been type
  2863. // legalized.
  2864. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
  2865. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2866. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2867. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2868. // min/max is legal on the scalar type.
  2869. bool UseScalarMinMax = VT.isVector() &&
  2870. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2871. Value *LHS, *RHS;
  2872. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2873. ISD::NodeType Opc = ISD::DELETED_NODE;
  2874. switch (SPR.Flavor) {
  2875. case SPF_UMAX: Opc = ISD::UMAX; break;
  2876. case SPF_UMIN: Opc = ISD::UMIN; break;
  2877. case SPF_SMAX: Opc = ISD::SMAX; break;
  2878. case SPF_SMIN: Opc = ISD::SMIN; break;
  2879. case SPF_FMINNUM:
  2880. switch (SPR.NaNBehavior) {
  2881. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2882. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2883. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2884. case SPNB_RETURNS_ANY: {
  2885. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2886. Opc = ISD::FMINNUM;
  2887. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2888. Opc = ISD::FMINIMUM;
  2889. else if (UseScalarMinMax)
  2890. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2891. ISD::FMINNUM : ISD::FMINIMUM;
  2892. break;
  2893. }
  2894. }
  2895. break;
  2896. case SPF_FMAXNUM:
  2897. switch (SPR.NaNBehavior) {
  2898. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2899. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2900. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2901. case SPNB_RETURNS_ANY:
  2902. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2903. Opc = ISD::FMAXNUM;
  2904. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2905. Opc = ISD::FMAXIMUM;
  2906. else if (UseScalarMinMax)
  2907. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2908. ISD::FMAXNUM : ISD::FMAXIMUM;
  2909. break;
  2910. }
  2911. break;
  2912. case SPF_ABS:
  2913. IsUnaryAbs = true;
  2914. Opc = ISD::ABS;
  2915. break;
  2916. case SPF_NABS:
  2917. // TODO: we need to produce sub(0, abs(X)).
  2918. default: break;
  2919. }
  2920. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2921. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2922. (UseScalarMinMax &&
  2923. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2924. // If the underlying comparison instruction is used by any other
  2925. // instruction, the consumed instructions won't be destroyed, so it is
  2926. // not profitable to convert to a min/max.
  2927. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2928. OpCode = Opc;
  2929. LHSVal = getValue(LHS);
  2930. RHSVal = getValue(RHS);
  2931. BaseOps = {};
  2932. }
  2933. if (IsUnaryAbs) {
  2934. OpCode = Opc;
  2935. LHSVal = getValue(LHS);
  2936. BaseOps = {};
  2937. }
  2938. }
  2939. if (IsUnaryAbs) {
  2940. for (unsigned i = 0; i != NumValues; ++i) {
  2941. Values[i] =
  2942. DAG.getNode(OpCode, getCurSDLoc(),
  2943. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2944. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2945. }
  2946. } else {
  2947. for (unsigned i = 0; i != NumValues; ++i) {
  2948. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2949. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2950. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2951. Values[i] = DAG.getNode(
  2952. OpCode, getCurSDLoc(),
  2953. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2954. }
  2955. }
  2956. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2957. DAG.getVTList(ValueVTs), Values));
  2958. }
  2959. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2960. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2961. SDValue N = getValue(I.getOperand(0));
  2962. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2963. I.getType());
  2964. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2965. }
  2966. void SelectionDAGBuilder::visitZExt(const User &I) {
  2967. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2968. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2969. SDValue N = getValue(I.getOperand(0));
  2970. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2971. I.getType());
  2972. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2973. }
  2974. void SelectionDAGBuilder::visitSExt(const User &I) {
  2975. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2976. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2977. SDValue N = getValue(I.getOperand(0));
  2978. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2979. I.getType());
  2980. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2981. }
  2982. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2983. // FPTrunc is never a no-op cast, no need to check
  2984. SDValue N = getValue(I.getOperand(0));
  2985. SDLoc dl = getCurSDLoc();
  2986. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2987. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2988. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2989. DAG.getTargetConstant(
  2990. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2991. }
  2992. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2993. // FPExt is never a no-op cast, no need to check
  2994. SDValue N = getValue(I.getOperand(0));
  2995. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2996. I.getType());
  2997. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2998. }
  2999. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  3000. // FPToUI is never a no-op cast, no need to check
  3001. SDValue N = getValue(I.getOperand(0));
  3002. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3003. I.getType());
  3004. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3005. }
  3006. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3007. // FPToSI is never a no-op cast, no need to check
  3008. SDValue N = getValue(I.getOperand(0));
  3009. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3010. I.getType());
  3011. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3012. }
  3013. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3014. // UIToFP is never a no-op cast, no need to check
  3015. SDValue N = getValue(I.getOperand(0));
  3016. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3017. I.getType());
  3018. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3019. }
  3020. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3021. // SIToFP is never a no-op cast, no need to check
  3022. SDValue N = getValue(I.getOperand(0));
  3023. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3024. I.getType());
  3025. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3026. }
  3027. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3028. // What to do depends on the size of the integer and the size of the pointer.
  3029. // We can either truncate, zero extend, or no-op, accordingly.
  3030. SDValue N = getValue(I.getOperand(0));
  3031. auto &TLI = DAG.getTargetLoweringInfo();
  3032. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3033. I.getType());
  3034. EVT PtrMemVT =
  3035. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3036. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3037. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3038. setValue(&I, N);
  3039. }
  3040. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3041. // What to do depends on the size of the integer and the size of the pointer.
  3042. // We can either truncate, zero extend, or no-op, accordingly.
  3043. SDValue N = getValue(I.getOperand(0));
  3044. auto &TLI = DAG.getTargetLoweringInfo();
  3045. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3046. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3047. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3048. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3049. setValue(&I, N);
  3050. }
  3051. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3052. SDValue N = getValue(I.getOperand(0));
  3053. SDLoc dl = getCurSDLoc();
  3054. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3055. I.getType());
  3056. // BitCast assures us that source and destination are the same size so this is
  3057. // either a BITCAST or a no-op.
  3058. if (DestVT != N.getValueType())
  3059. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3060. DestVT, N)); // convert types.
  3061. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3062. // might fold any kind of constant expression to an integer constant and that
  3063. // is not what we are looking for. Only recognize a bitcast of a genuine
  3064. // constant integer as an opaque constant.
  3065. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3066. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3067. /*isOpaque*/true));
  3068. else
  3069. setValue(&I, N); // noop cast.
  3070. }
  3071. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3072. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3073. const Value *SV = I.getOperand(0);
  3074. SDValue N = getValue(SV);
  3075. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3076. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3077. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3078. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3079. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3080. setValue(&I, N);
  3081. }
  3082. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3083. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3084. SDValue InVec = getValue(I.getOperand(0));
  3085. SDValue InVal = getValue(I.getOperand(1));
  3086. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3087. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3088. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3089. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3090. InVec, InVal, InIdx));
  3091. }
  3092. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3093. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3094. SDValue InVec = getValue(I.getOperand(0));
  3095. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3096. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3097. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3098. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3099. InVec, InIdx));
  3100. }
  3101. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3102. SDValue Src1 = getValue(I.getOperand(0));
  3103. SDValue Src2 = getValue(I.getOperand(1));
  3104. SDLoc DL = getCurSDLoc();
  3105. SmallVector<int, 8> Mask;
  3106. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3107. unsigned MaskNumElts = Mask.size();
  3108. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3109. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3110. EVT SrcVT = Src1.getValueType();
  3111. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3112. if (SrcNumElts == MaskNumElts) {
  3113. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3114. return;
  3115. }
  3116. // Normalize the shuffle vector since mask and vector length don't match.
  3117. if (SrcNumElts < MaskNumElts) {
  3118. // Mask is longer than the source vectors. We can use concatenate vector to
  3119. // make the mask and vectors lengths match.
  3120. if (MaskNumElts % SrcNumElts == 0) {
  3121. // Mask length is a multiple of the source vector length.
  3122. // Check if the shuffle is some kind of concatenation of the input
  3123. // vectors.
  3124. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3125. bool IsConcat = true;
  3126. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3127. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3128. int Idx = Mask[i];
  3129. if (Idx < 0)
  3130. continue;
  3131. // Ensure the indices in each SrcVT sized piece are sequential and that
  3132. // the same source is used for the whole piece.
  3133. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3134. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3135. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3136. IsConcat = false;
  3137. break;
  3138. }
  3139. // Remember which source this index came from.
  3140. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3141. }
  3142. // The shuffle is concatenating multiple vectors together. Just emit
  3143. // a CONCAT_VECTORS operation.
  3144. if (IsConcat) {
  3145. SmallVector<SDValue, 8> ConcatOps;
  3146. for (auto Src : ConcatSrcs) {
  3147. if (Src < 0)
  3148. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3149. else if (Src == 0)
  3150. ConcatOps.push_back(Src1);
  3151. else
  3152. ConcatOps.push_back(Src2);
  3153. }
  3154. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3155. return;
  3156. }
  3157. }
  3158. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3159. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3160. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3161. PaddedMaskNumElts);
  3162. // Pad both vectors with undefs to make them the same length as the mask.
  3163. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3164. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3165. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3166. MOps1[0] = Src1;
  3167. MOps2[0] = Src2;
  3168. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3169. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3170. // Readjust mask for new input vector length.
  3171. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3172. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3173. int Idx = Mask[i];
  3174. if (Idx >= (int)SrcNumElts)
  3175. Idx -= SrcNumElts - PaddedMaskNumElts;
  3176. MappedOps[i] = Idx;
  3177. }
  3178. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3179. // If the concatenated vector was padded, extract a subvector with the
  3180. // correct number of elements.
  3181. if (MaskNumElts != PaddedMaskNumElts)
  3182. Result = DAG.getNode(
  3183. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3184. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3185. setValue(&I, Result);
  3186. return;
  3187. }
  3188. if (SrcNumElts > MaskNumElts) {
  3189. // Analyze the access pattern of the vector to see if we can extract
  3190. // two subvectors and do the shuffle.
  3191. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3192. bool CanExtract = true;
  3193. for (int Idx : Mask) {
  3194. unsigned Input = 0;
  3195. if (Idx < 0)
  3196. continue;
  3197. if (Idx >= (int)SrcNumElts) {
  3198. Input = 1;
  3199. Idx -= SrcNumElts;
  3200. }
  3201. // If all the indices come from the same MaskNumElts sized portion of
  3202. // the sources we can use extract. Also make sure the extract wouldn't
  3203. // extract past the end of the source.
  3204. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3205. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3206. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3207. CanExtract = false;
  3208. // Make sure we always update StartIdx as we use it to track if all
  3209. // elements are undef.
  3210. StartIdx[Input] = NewStartIdx;
  3211. }
  3212. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3213. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3214. return;
  3215. }
  3216. if (CanExtract) {
  3217. // Extract appropriate subvector and generate a vector shuffle
  3218. for (unsigned Input = 0; Input < 2; ++Input) {
  3219. SDValue &Src = Input == 0 ? Src1 : Src2;
  3220. if (StartIdx[Input] < 0)
  3221. Src = DAG.getUNDEF(VT);
  3222. else {
  3223. Src = DAG.getNode(
  3224. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3225. DAG.getConstant(StartIdx[Input], DL,
  3226. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3227. }
  3228. }
  3229. // Calculate new mask.
  3230. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3231. for (int &Idx : MappedOps) {
  3232. if (Idx >= (int)SrcNumElts)
  3233. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3234. else if (Idx >= 0)
  3235. Idx -= StartIdx[0];
  3236. }
  3237. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3238. return;
  3239. }
  3240. }
  3241. // We can't use either concat vectors or extract subvectors so fall back to
  3242. // replacing the shuffle with extract and build vector.
  3243. // to insert and build vector.
  3244. EVT EltVT = VT.getVectorElementType();
  3245. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3246. SmallVector<SDValue,8> Ops;
  3247. for (int Idx : Mask) {
  3248. SDValue Res;
  3249. if (Idx < 0) {
  3250. Res = DAG.getUNDEF(EltVT);
  3251. } else {
  3252. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3253. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3254. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3255. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3256. }
  3257. Ops.push_back(Res);
  3258. }
  3259. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3260. }
  3261. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3262. ArrayRef<unsigned> Indices;
  3263. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3264. Indices = IV->getIndices();
  3265. else
  3266. Indices = cast<ConstantExpr>(&I)->getIndices();
  3267. const Value *Op0 = I.getOperand(0);
  3268. const Value *Op1 = I.getOperand(1);
  3269. Type *AggTy = I.getType();
  3270. Type *ValTy = Op1->getType();
  3271. bool IntoUndef = isa<UndefValue>(Op0);
  3272. bool FromUndef = isa<UndefValue>(Op1);
  3273. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3274. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3275. SmallVector<EVT, 4> AggValueVTs;
  3276. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3277. SmallVector<EVT, 4> ValValueVTs;
  3278. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3279. unsigned NumAggValues = AggValueVTs.size();
  3280. unsigned NumValValues = ValValueVTs.size();
  3281. SmallVector<SDValue, 4> Values(NumAggValues);
  3282. // Ignore an insertvalue that produces an empty object
  3283. if (!NumAggValues) {
  3284. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3285. return;
  3286. }
  3287. SDValue Agg = getValue(Op0);
  3288. unsigned i = 0;
  3289. // Copy the beginning value(s) from the original aggregate.
  3290. for (; i != LinearIndex; ++i)
  3291. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3292. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3293. // Copy values from the inserted value(s).
  3294. if (NumValValues) {
  3295. SDValue Val = getValue(Op1);
  3296. for (; i != LinearIndex + NumValValues; ++i)
  3297. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3298. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3299. }
  3300. // Copy remaining value(s) from the original aggregate.
  3301. for (; i != NumAggValues; ++i)
  3302. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3303. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3304. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3305. DAG.getVTList(AggValueVTs), Values));
  3306. }
  3307. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3308. ArrayRef<unsigned> Indices;
  3309. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3310. Indices = EV->getIndices();
  3311. else
  3312. Indices = cast<ConstantExpr>(&I)->getIndices();
  3313. const Value *Op0 = I.getOperand(0);
  3314. Type *AggTy = Op0->getType();
  3315. Type *ValTy = I.getType();
  3316. bool OutOfUndef = isa<UndefValue>(Op0);
  3317. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3318. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3319. SmallVector<EVT, 4> ValValueVTs;
  3320. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3321. unsigned NumValValues = ValValueVTs.size();
  3322. // Ignore a extractvalue that produces an empty object
  3323. if (!NumValValues) {
  3324. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3325. return;
  3326. }
  3327. SmallVector<SDValue, 4> Values(NumValValues);
  3328. SDValue Agg = getValue(Op0);
  3329. // Copy out the selected value(s).
  3330. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3331. Values[i - LinearIndex] =
  3332. OutOfUndef ?
  3333. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3334. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3335. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3336. DAG.getVTList(ValValueVTs), Values));
  3337. }
  3338. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3339. Value *Op0 = I.getOperand(0);
  3340. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3341. // element which holds a pointer.
  3342. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3343. SDValue N = getValue(Op0);
  3344. SDLoc dl = getCurSDLoc();
  3345. auto &TLI = DAG.getTargetLoweringInfo();
  3346. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3347. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3348. // Normalize Vector GEP - all scalar operands should be converted to the
  3349. // splat vector.
  3350. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3351. I.getType()->getVectorNumElements() : 0;
  3352. if (VectorWidth && !N.getValueType().isVector()) {
  3353. LLVMContext &Context = *DAG.getContext();
  3354. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3355. N = DAG.getSplatBuildVector(VT, dl, N);
  3356. }
  3357. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3358. GTI != E; ++GTI) {
  3359. const Value *Idx = GTI.getOperand();
  3360. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3361. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3362. if (Field) {
  3363. // N = N + Offset
  3364. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3365. // In an inbounds GEP with an offset that is nonnegative even when
  3366. // interpreted as signed, assume there is no unsigned overflow.
  3367. SDNodeFlags Flags;
  3368. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3369. Flags.setNoUnsignedWrap(true);
  3370. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3371. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3372. }
  3373. } else {
  3374. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3375. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3376. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3377. // If this is a scalar constant or a splat vector of constants,
  3378. // handle it quickly.
  3379. const auto *C = dyn_cast<Constant>(Idx);
  3380. if (C && isa<VectorType>(C->getType()))
  3381. C = C->getSplatValue();
  3382. if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
  3383. if (CI->isZero())
  3384. continue;
  3385. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3386. LLVMContext &Context = *DAG.getContext();
  3387. SDValue OffsVal = VectorWidth ?
  3388. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3389. DAG.getConstant(Offs, dl, IdxTy);
  3390. // In an inbounds GEP with an offset that is nonnegative even when
  3391. // interpreted as signed, assume there is no unsigned overflow.
  3392. SDNodeFlags Flags;
  3393. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3394. Flags.setNoUnsignedWrap(true);
  3395. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3396. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3397. continue;
  3398. }
  3399. // N = N + Idx * ElementSize;
  3400. SDValue IdxN = getValue(Idx);
  3401. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3402. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3403. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3404. }
  3405. // If the index is smaller or larger than intptr_t, truncate or extend
  3406. // it.
  3407. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3408. // If this is a multiply by a power of two, turn it into a shl
  3409. // immediately. This is a very common case.
  3410. if (ElementSize != 1) {
  3411. if (ElementSize.isPowerOf2()) {
  3412. unsigned Amt = ElementSize.logBase2();
  3413. IdxN = DAG.getNode(ISD::SHL, dl,
  3414. N.getValueType(), IdxN,
  3415. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3416. } else {
  3417. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3418. IdxN.getValueType());
  3419. IdxN = DAG.getNode(ISD::MUL, dl,
  3420. N.getValueType(), IdxN, Scale);
  3421. }
  3422. }
  3423. N = DAG.getNode(ISD::ADD, dl,
  3424. N.getValueType(), N, IdxN);
  3425. }
  3426. }
  3427. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3428. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3429. setValue(&I, N);
  3430. }
  3431. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3432. // If this is a fixed sized alloca in the entry block of the function,
  3433. // allocate it statically on the stack.
  3434. if (FuncInfo.StaticAllocaMap.count(&I))
  3435. return; // getValue will auto-populate this.
  3436. SDLoc dl = getCurSDLoc();
  3437. Type *Ty = I.getAllocatedType();
  3438. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3439. auto &DL = DAG.getDataLayout();
  3440. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3441. unsigned Align =
  3442. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3443. SDValue AllocSize = getValue(I.getArraySize());
  3444. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3445. if (AllocSize.getValueType() != IntPtr)
  3446. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3447. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3448. AllocSize,
  3449. DAG.getConstant(TySize, dl, IntPtr));
  3450. // Handle alignment. If the requested alignment is less than or equal to
  3451. // the stack alignment, ignore it. If the size is greater than or equal to
  3452. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3453. unsigned StackAlign =
  3454. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3455. if (Align <= StackAlign)
  3456. Align = 0;
  3457. // Round the size of the allocation up to the stack alignment size
  3458. // by add SA-1 to the size. This doesn't overflow because we're computing
  3459. // an address inside an alloca.
  3460. SDNodeFlags Flags;
  3461. Flags.setNoUnsignedWrap(true);
  3462. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3463. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3464. // Mask out the low bits for alignment purposes.
  3465. AllocSize =
  3466. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3467. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3468. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3469. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3470. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3471. setValue(&I, DSA);
  3472. DAG.setRoot(DSA.getValue(1));
  3473. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3474. }
  3475. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3476. if (I.isAtomic())
  3477. return visitAtomicLoad(I);
  3478. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3479. const Value *SV = I.getOperand(0);
  3480. if (TLI.supportSwiftError()) {
  3481. // Swifterror values can come from either a function parameter with
  3482. // swifterror attribute or an alloca with swifterror attribute.
  3483. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3484. if (Arg->hasSwiftErrorAttr())
  3485. return visitLoadFromSwiftError(I);
  3486. }
  3487. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3488. if (Alloca->isSwiftError())
  3489. return visitLoadFromSwiftError(I);
  3490. }
  3491. }
  3492. SDValue Ptr = getValue(SV);
  3493. Type *Ty = I.getType();
  3494. bool isVolatile = I.isVolatile();
  3495. bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
  3496. bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
  3497. bool isDereferenceable =
  3498. isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
  3499. unsigned Alignment = I.getAlignment();
  3500. AAMDNodes AAInfo;
  3501. I.getAAMetadata(AAInfo);
  3502. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3503. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3504. SmallVector<uint64_t, 4> Offsets;
  3505. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3506. unsigned NumValues = ValueVTs.size();
  3507. if (NumValues == 0)
  3508. return;
  3509. SDValue Root;
  3510. bool ConstantMemory = false;
  3511. if (isVolatile || NumValues > MaxParallelChains)
  3512. // Serialize volatile loads with other side effects.
  3513. Root = getRoot();
  3514. else if (AA &&
  3515. AA->pointsToConstantMemory(MemoryLocation(
  3516. SV,
  3517. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3518. AAInfo))) {
  3519. // Do not serialize (non-volatile) loads of constant memory with anything.
  3520. Root = DAG.getEntryNode();
  3521. ConstantMemory = true;
  3522. } else {
  3523. // Do not serialize non-volatile loads against each other.
  3524. Root = DAG.getRoot();
  3525. }
  3526. SDLoc dl = getCurSDLoc();
  3527. if (isVolatile)
  3528. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3529. // An aggregate load cannot wrap around the address space, so offsets to its
  3530. // parts don't wrap either.
  3531. SDNodeFlags Flags;
  3532. Flags.setNoUnsignedWrap(true);
  3533. SmallVector<SDValue, 4> Values(NumValues);
  3534. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3535. EVT PtrVT = Ptr.getValueType();
  3536. unsigned ChainI = 0;
  3537. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3538. // Serializing loads here may result in excessive register pressure, and
  3539. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3540. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3541. // they are side-effect free or do not alias. The optimizer should really
  3542. // avoid this case by converting large object/array copies to llvm.memcpy
  3543. // (MaxParallelChains should always remain as failsafe).
  3544. if (ChainI == MaxParallelChains) {
  3545. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3546. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3547. makeArrayRef(Chains.data(), ChainI));
  3548. Root = Chain;
  3549. ChainI = 0;
  3550. }
  3551. SDValue A = DAG.getNode(ISD::ADD, dl,
  3552. PtrVT, Ptr,
  3553. DAG.getConstant(Offsets[i], dl, PtrVT),
  3554. Flags);
  3555. auto MMOFlags = MachineMemOperand::MONone;
  3556. if (isVolatile)
  3557. MMOFlags |= MachineMemOperand::MOVolatile;
  3558. if (isNonTemporal)
  3559. MMOFlags |= MachineMemOperand::MONonTemporal;
  3560. if (isInvariant)
  3561. MMOFlags |= MachineMemOperand::MOInvariant;
  3562. if (isDereferenceable)
  3563. MMOFlags |= MachineMemOperand::MODereferenceable;
  3564. MMOFlags |= TLI.getMMOFlags(I);
  3565. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3566. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3567. MMOFlags, AAInfo, Ranges);
  3568. Chains[ChainI] = L.getValue(1);
  3569. if (MemVTs[i] != ValueVTs[i])
  3570. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3571. Values[i] = L;
  3572. }
  3573. if (!ConstantMemory) {
  3574. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3575. makeArrayRef(Chains.data(), ChainI));
  3576. if (isVolatile)
  3577. DAG.setRoot(Chain);
  3578. else
  3579. PendingLoads.push_back(Chain);
  3580. }
  3581. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3582. DAG.getVTList(ValueVTs), Values));
  3583. }
  3584. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3585. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3586. "call visitStoreToSwiftError when backend supports swifterror");
  3587. SmallVector<EVT, 4> ValueVTs;
  3588. SmallVector<uint64_t, 4> Offsets;
  3589. const Value *SrcV = I.getOperand(0);
  3590. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3591. SrcV->getType(), ValueVTs, &Offsets);
  3592. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3593. "expect a single EVT for swifterror");
  3594. SDValue Src = getValue(SrcV);
  3595. // Create a virtual register, then update the virtual register.
  3596. Register VReg =
  3597. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3598. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3599. // Chain can be getRoot or getControlRoot.
  3600. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3601. SDValue(Src.getNode(), Src.getResNo()));
  3602. DAG.setRoot(CopyNode);
  3603. }
  3604. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3605. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3606. "call visitLoadFromSwiftError when backend supports swifterror");
  3607. assert(!I.isVolatile() &&
  3608. !I.hasMetadata(LLVMContext::MD_nontemporal) &&
  3609. !I.hasMetadata(LLVMContext::MD_invariant_load) &&
  3610. "Support volatile, non temporal, invariant for load_from_swift_error");
  3611. const Value *SV = I.getOperand(0);
  3612. Type *Ty = I.getType();
  3613. AAMDNodes AAInfo;
  3614. I.getAAMetadata(AAInfo);
  3615. assert(
  3616. (!AA ||
  3617. !AA->pointsToConstantMemory(MemoryLocation(
  3618. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3619. AAInfo))) &&
  3620. "load_from_swift_error should not be constant memory");
  3621. SmallVector<EVT, 4> ValueVTs;
  3622. SmallVector<uint64_t, 4> Offsets;
  3623. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3624. ValueVTs, &Offsets);
  3625. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3626. "expect a single EVT for swifterror");
  3627. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3628. SDValue L = DAG.getCopyFromReg(
  3629. getRoot(), getCurSDLoc(),
  3630. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3631. setValue(&I, L);
  3632. }
  3633. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3634. if (I.isAtomic())
  3635. return visitAtomicStore(I);
  3636. const Value *SrcV = I.getOperand(0);
  3637. const Value *PtrV = I.getOperand(1);
  3638. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3639. if (TLI.supportSwiftError()) {
  3640. // Swifterror values can come from either a function parameter with
  3641. // swifterror attribute or an alloca with swifterror attribute.
  3642. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3643. if (Arg->hasSwiftErrorAttr())
  3644. return visitStoreToSwiftError(I);
  3645. }
  3646. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3647. if (Alloca->isSwiftError())
  3648. return visitStoreToSwiftError(I);
  3649. }
  3650. }
  3651. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3652. SmallVector<uint64_t, 4> Offsets;
  3653. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3654. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3655. unsigned NumValues = ValueVTs.size();
  3656. if (NumValues == 0)
  3657. return;
  3658. // Get the lowered operands. Note that we do this after
  3659. // checking if NumResults is zero, because with zero results
  3660. // the operands won't have values in the map.
  3661. SDValue Src = getValue(SrcV);
  3662. SDValue Ptr = getValue(PtrV);
  3663. SDValue Root = getRoot();
  3664. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3665. SDLoc dl = getCurSDLoc();
  3666. EVT PtrVT = Ptr.getValueType();
  3667. unsigned Alignment = I.getAlignment();
  3668. AAMDNodes AAInfo;
  3669. I.getAAMetadata(AAInfo);
  3670. auto MMOFlags = MachineMemOperand::MONone;
  3671. if (I.isVolatile())
  3672. MMOFlags |= MachineMemOperand::MOVolatile;
  3673. if (I.hasMetadata(LLVMContext::MD_nontemporal))
  3674. MMOFlags |= MachineMemOperand::MONonTemporal;
  3675. MMOFlags |= TLI.getMMOFlags(I);
  3676. // An aggregate load cannot wrap around the address space, so offsets to its
  3677. // parts don't wrap either.
  3678. SDNodeFlags Flags;
  3679. Flags.setNoUnsignedWrap(true);
  3680. unsigned ChainI = 0;
  3681. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3682. // See visitLoad comments.
  3683. if (ChainI == MaxParallelChains) {
  3684. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3685. makeArrayRef(Chains.data(), ChainI));
  3686. Root = Chain;
  3687. ChainI = 0;
  3688. }
  3689. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3690. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3691. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3692. if (MemVTs[i] != ValueVTs[i])
  3693. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3694. SDValue St =
  3695. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3696. Alignment, MMOFlags, AAInfo);
  3697. Chains[ChainI] = St;
  3698. }
  3699. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3700. makeArrayRef(Chains.data(), ChainI));
  3701. DAG.setRoot(StoreNode);
  3702. }
  3703. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3704. bool IsCompressing) {
  3705. SDLoc sdl = getCurSDLoc();
  3706. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3707. unsigned& Alignment) {
  3708. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3709. Src0 = I.getArgOperand(0);
  3710. Ptr = I.getArgOperand(1);
  3711. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3712. Mask = I.getArgOperand(3);
  3713. };
  3714. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3715. unsigned& Alignment) {
  3716. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3717. Src0 = I.getArgOperand(0);
  3718. Ptr = I.getArgOperand(1);
  3719. Mask = I.getArgOperand(2);
  3720. Alignment = 0;
  3721. };
  3722. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3723. unsigned Alignment;
  3724. if (IsCompressing)
  3725. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3726. else
  3727. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3728. SDValue Ptr = getValue(PtrOperand);
  3729. SDValue Src0 = getValue(Src0Operand);
  3730. SDValue Mask = getValue(MaskOperand);
  3731. EVT VT = Src0.getValueType();
  3732. if (!Alignment)
  3733. Alignment = DAG.getEVTAlignment(VT);
  3734. AAMDNodes AAInfo;
  3735. I.getAAMetadata(AAInfo);
  3736. MachineMemOperand *MMO =
  3737. DAG.getMachineFunction().
  3738. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3739. MachineMemOperand::MOStore, VT.getStoreSize(),
  3740. Alignment, AAInfo);
  3741. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3742. MMO, false /* Truncating */,
  3743. IsCompressing);
  3744. DAG.setRoot(StoreNode);
  3745. setValue(&I, StoreNode);
  3746. }
  3747. // Get a uniform base for the Gather/Scatter intrinsic.
  3748. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3749. // We try to represent it as a base pointer + vector of indices.
  3750. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3751. // The first operand of the GEP may be a single pointer or a vector of pointers
  3752. // Example:
  3753. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3754. // or
  3755. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3756. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3757. //
  3758. // When the first GEP operand is a single pointer - it is the uniform base we
  3759. // are looking for. If first operand of the GEP is a splat vector - we
  3760. // extract the splat value and use it as a uniform base.
  3761. // In all other cases the function returns 'false'.
  3762. static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
  3763. ISD::MemIndexType &IndexType, SDValue &Scale,
  3764. SelectionDAGBuilder *SDB) {
  3765. SelectionDAG& DAG = SDB->DAG;
  3766. LLVMContext &Context = *DAG.getContext();
  3767. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3768. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3769. if (!GEP)
  3770. return false;
  3771. const Value *GEPPtr = GEP->getPointerOperand();
  3772. if (!GEPPtr->getType()->isVectorTy())
  3773. Ptr = GEPPtr;
  3774. else if (!(Ptr = getSplatValue(GEPPtr)))
  3775. return false;
  3776. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3777. Value *IndexVal = GEP->getOperand(FinalIndex);
  3778. // Ensure all the other indices are 0.
  3779. for (unsigned i = 1; i < FinalIndex; ++i) {
  3780. auto *C = dyn_cast<Constant>(GEP->getOperand(i));
  3781. if (!C)
  3782. return false;
  3783. if (isa<VectorType>(C->getType()))
  3784. C = C->getSplatValue();
  3785. auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3786. if (!CI || !CI->isZero())
  3787. return false;
  3788. }
  3789. // The operands of the GEP may be defined in another basic block.
  3790. // In this case we'll not find nodes for the operands.
  3791. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3792. return false;
  3793. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3794. const DataLayout &DL = DAG.getDataLayout();
  3795. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3796. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3797. Base = SDB->getValue(Ptr);
  3798. Index = SDB->getValue(IndexVal);
  3799. IndexType = ISD::SIGNED_SCALED;
  3800. if (!Index.getValueType().isVector()) {
  3801. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3802. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3803. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3804. }
  3805. return true;
  3806. }
  3807. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3808. SDLoc sdl = getCurSDLoc();
  3809. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3810. const Value *Ptr = I.getArgOperand(1);
  3811. SDValue Src0 = getValue(I.getArgOperand(0));
  3812. SDValue Mask = getValue(I.getArgOperand(3));
  3813. EVT VT = Src0.getValueType();
  3814. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3815. if (!Alignment)
  3816. Alignment = DAG.getEVTAlignment(VT);
  3817. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3818. AAMDNodes AAInfo;
  3819. I.getAAMetadata(AAInfo);
  3820. SDValue Base;
  3821. SDValue Index;
  3822. ISD::MemIndexType IndexType;
  3823. SDValue Scale;
  3824. const Value *BasePtr = Ptr;
  3825. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3826. this);
  3827. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3828. MachineMemOperand *MMO = DAG.getMachineFunction().
  3829. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3830. MachineMemOperand::MOStore, VT.getStoreSize(),
  3831. Alignment, AAInfo);
  3832. if (!UniformBase) {
  3833. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3834. Index = getValue(Ptr);
  3835. IndexType = ISD::SIGNED_SCALED;
  3836. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3837. }
  3838. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3839. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3840. Ops, MMO, IndexType);
  3841. DAG.setRoot(Scatter);
  3842. setValue(&I, Scatter);
  3843. }
  3844. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3845. SDLoc sdl = getCurSDLoc();
  3846. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3847. unsigned& Alignment) {
  3848. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3849. Ptr = I.getArgOperand(0);
  3850. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3851. Mask = I.getArgOperand(2);
  3852. Src0 = I.getArgOperand(3);
  3853. };
  3854. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3855. unsigned& Alignment) {
  3856. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3857. Ptr = I.getArgOperand(0);
  3858. Alignment = 0;
  3859. Mask = I.getArgOperand(1);
  3860. Src0 = I.getArgOperand(2);
  3861. };
  3862. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3863. unsigned Alignment;
  3864. if (IsExpanding)
  3865. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3866. else
  3867. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3868. SDValue Ptr = getValue(PtrOperand);
  3869. SDValue Src0 = getValue(Src0Operand);
  3870. SDValue Mask = getValue(MaskOperand);
  3871. EVT VT = Src0.getValueType();
  3872. if (!Alignment)
  3873. Alignment = DAG.getEVTAlignment(VT);
  3874. AAMDNodes AAInfo;
  3875. I.getAAMetadata(AAInfo);
  3876. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3877. // Do not serialize masked loads of constant memory with anything.
  3878. bool AddToChain =
  3879. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3880. PtrOperand,
  3881. LocationSize::precise(
  3882. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3883. AAInfo));
  3884. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3885. MachineMemOperand *MMO =
  3886. DAG.getMachineFunction().
  3887. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3888. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3889. Alignment, AAInfo, Ranges);
  3890. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3891. ISD::NON_EXTLOAD, IsExpanding);
  3892. if (AddToChain)
  3893. PendingLoads.push_back(Load.getValue(1));
  3894. setValue(&I, Load);
  3895. }
  3896. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3897. SDLoc sdl = getCurSDLoc();
  3898. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3899. const Value *Ptr = I.getArgOperand(0);
  3900. SDValue Src0 = getValue(I.getArgOperand(3));
  3901. SDValue Mask = getValue(I.getArgOperand(2));
  3902. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3903. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3904. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3905. if (!Alignment)
  3906. Alignment = DAG.getEVTAlignment(VT);
  3907. AAMDNodes AAInfo;
  3908. I.getAAMetadata(AAInfo);
  3909. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3910. SDValue Root = DAG.getRoot();
  3911. SDValue Base;
  3912. SDValue Index;
  3913. ISD::MemIndexType IndexType;
  3914. SDValue Scale;
  3915. const Value *BasePtr = Ptr;
  3916. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3917. this);
  3918. bool ConstantMemory = false;
  3919. if (UniformBase && AA &&
  3920. AA->pointsToConstantMemory(
  3921. MemoryLocation(BasePtr,
  3922. LocationSize::precise(
  3923. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3924. AAInfo))) {
  3925. // Do not serialize (non-volatile) loads of constant memory with anything.
  3926. Root = DAG.getEntryNode();
  3927. ConstantMemory = true;
  3928. }
  3929. MachineMemOperand *MMO =
  3930. DAG.getMachineFunction().
  3931. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3932. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3933. Alignment, AAInfo, Ranges);
  3934. if (!UniformBase) {
  3935. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3936. Index = getValue(Ptr);
  3937. IndexType = ISD::SIGNED_SCALED;
  3938. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3939. }
  3940. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3941. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3942. Ops, MMO, IndexType);
  3943. SDValue OutChain = Gather.getValue(1);
  3944. if (!ConstantMemory)
  3945. PendingLoads.push_back(OutChain);
  3946. setValue(&I, Gather);
  3947. }
  3948. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3949. SDLoc dl = getCurSDLoc();
  3950. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3951. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3952. SyncScope::ID SSID = I.getSyncScopeID();
  3953. SDValue InChain = getRoot();
  3954. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3955. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3956. auto Alignment = DAG.getEVTAlignment(MemVT);
  3957. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3958. if (I.isVolatile())
  3959. Flags |= MachineMemOperand::MOVolatile;
  3960. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3961. MachineFunction &MF = DAG.getMachineFunction();
  3962. MachineMemOperand *MMO =
  3963. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3964. Flags, MemVT.getStoreSize(), Alignment,
  3965. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3966. FailureOrdering);
  3967. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3968. dl, MemVT, VTs, InChain,
  3969. getValue(I.getPointerOperand()),
  3970. getValue(I.getCompareOperand()),
  3971. getValue(I.getNewValOperand()), MMO);
  3972. SDValue OutChain = L.getValue(2);
  3973. setValue(&I, L);
  3974. DAG.setRoot(OutChain);
  3975. }
  3976. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3977. SDLoc dl = getCurSDLoc();
  3978. ISD::NodeType NT;
  3979. switch (I.getOperation()) {
  3980. default: llvm_unreachable("Unknown atomicrmw operation");
  3981. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3982. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3983. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3984. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3985. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3986. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3987. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3988. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3989. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3990. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3991. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3992. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3993. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3994. }
  3995. AtomicOrdering Ordering = I.getOrdering();
  3996. SyncScope::ID SSID = I.getSyncScopeID();
  3997. SDValue InChain = getRoot();
  3998. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3999. auto Alignment = DAG.getEVTAlignment(MemVT);
  4000. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  4001. if (I.isVolatile())
  4002. Flags |= MachineMemOperand::MOVolatile;
  4003. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  4004. MachineFunction &MF = DAG.getMachineFunction();
  4005. MachineMemOperand *MMO =
  4006. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4007. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  4008. nullptr, SSID, Ordering);
  4009. SDValue L =
  4010. DAG.getAtomic(NT, dl, MemVT, InChain,
  4011. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4012. MMO);
  4013. SDValue OutChain = L.getValue(1);
  4014. setValue(&I, L);
  4015. DAG.setRoot(OutChain);
  4016. }
  4017. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4018. SDLoc dl = getCurSDLoc();
  4019. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4020. SDValue Ops[3];
  4021. Ops[0] = getRoot();
  4022. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4023. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4024. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4025. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4026. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4027. }
  4028. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4029. SDLoc dl = getCurSDLoc();
  4030. AtomicOrdering Order = I.getOrdering();
  4031. SyncScope::ID SSID = I.getSyncScopeID();
  4032. SDValue InChain = getRoot();
  4033. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4034. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4035. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4036. if (!TLI.supportsUnalignedAtomics() &&
  4037. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4038. report_fatal_error("Cannot generate unaligned atomic load");
  4039. auto Flags = MachineMemOperand::MOLoad;
  4040. if (I.isVolatile())
  4041. Flags |= MachineMemOperand::MOVolatile;
  4042. if (I.hasMetadata(LLVMContext::MD_invariant_load))
  4043. Flags |= MachineMemOperand::MOInvariant;
  4044. if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
  4045. DAG.getDataLayout()))
  4046. Flags |= MachineMemOperand::MODereferenceable;
  4047. Flags |= TLI.getMMOFlags(I);
  4048. MachineMemOperand *MMO =
  4049. DAG.getMachineFunction().
  4050. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4051. Flags, MemVT.getStoreSize(),
  4052. I.getAlignment() ? I.getAlignment() :
  4053. DAG.getEVTAlignment(MemVT),
  4054. AAMDNodes(), nullptr, SSID, Order);
  4055. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4056. SDValue Ptr = getValue(I.getPointerOperand());
  4057. if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
  4058. // TODO: Once this is better exercised by tests, it should be merged with
  4059. // the normal path for loads to prevent future divergence.
  4060. SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
  4061. if (MemVT != VT)
  4062. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4063. setValue(&I, L);
  4064. SDValue OutChain = L.getValue(1);
  4065. if (!I.isUnordered())
  4066. DAG.setRoot(OutChain);
  4067. else
  4068. PendingLoads.push_back(OutChain);
  4069. return;
  4070. }
  4071. SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4072. Ptr, MMO);
  4073. SDValue OutChain = L.getValue(1);
  4074. if (MemVT != VT)
  4075. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4076. setValue(&I, L);
  4077. DAG.setRoot(OutChain);
  4078. }
  4079. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4080. SDLoc dl = getCurSDLoc();
  4081. AtomicOrdering Ordering = I.getOrdering();
  4082. SyncScope::ID SSID = I.getSyncScopeID();
  4083. SDValue InChain = getRoot();
  4084. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4085. EVT MemVT =
  4086. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4087. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4088. report_fatal_error("Cannot generate unaligned atomic store");
  4089. auto Flags = MachineMemOperand::MOStore;
  4090. if (I.isVolatile())
  4091. Flags |= MachineMemOperand::MOVolatile;
  4092. Flags |= TLI.getMMOFlags(I);
  4093. MachineFunction &MF = DAG.getMachineFunction();
  4094. MachineMemOperand *MMO =
  4095. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4096. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4097. nullptr, SSID, Ordering);
  4098. SDValue Val = getValue(I.getValueOperand());
  4099. if (Val.getValueType() != MemVT)
  4100. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4101. SDValue Ptr = getValue(I.getPointerOperand());
  4102. if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
  4103. // TODO: Once this is better exercised by tests, it should be merged with
  4104. // the normal path for stores to prevent future divergence.
  4105. SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
  4106. DAG.setRoot(S);
  4107. return;
  4108. }
  4109. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4110. Ptr, Val, MMO);
  4111. DAG.setRoot(OutChain);
  4112. }
  4113. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4114. /// node.
  4115. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4116. unsigned Intrinsic) {
  4117. // Ignore the callsite's attributes. A specific call site may be marked with
  4118. // readnone, but the lowering code will expect the chain based on the
  4119. // definition.
  4120. const Function *F = I.getCalledFunction();
  4121. bool HasChain = !F->doesNotAccessMemory();
  4122. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4123. // Build the operand list.
  4124. SmallVector<SDValue, 8> Ops;
  4125. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4126. if (OnlyLoad) {
  4127. // We don't need to serialize loads against other loads.
  4128. Ops.push_back(DAG.getRoot());
  4129. } else {
  4130. Ops.push_back(getRoot());
  4131. }
  4132. }
  4133. // Info is set by getTgtMemInstrinsic
  4134. TargetLowering::IntrinsicInfo Info;
  4135. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4136. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4137. DAG.getMachineFunction(),
  4138. Intrinsic);
  4139. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4140. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4141. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4142. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4143. TLI.getPointerTy(DAG.getDataLayout())));
  4144. // Add all operands of the call to the operand list.
  4145. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4146. const Value *Arg = I.getArgOperand(i);
  4147. if (!I.paramHasAttr(i, Attribute::ImmArg)) {
  4148. Ops.push_back(getValue(Arg));
  4149. continue;
  4150. }
  4151. // Use TargetConstant instead of a regular constant for immarg.
  4152. EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
  4153. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
  4154. assert(CI->getBitWidth() <= 64 &&
  4155. "large intrinsic immediates not handled");
  4156. Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
  4157. } else {
  4158. Ops.push_back(
  4159. DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
  4160. }
  4161. }
  4162. SmallVector<EVT, 4> ValueVTs;
  4163. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4164. if (HasChain)
  4165. ValueVTs.push_back(MVT::Other);
  4166. SDVTList VTs = DAG.getVTList(ValueVTs);
  4167. // Create the node.
  4168. SDValue Result;
  4169. if (IsTgtIntrinsic) {
  4170. // This is target intrinsic that touches memory
  4171. AAMDNodes AAInfo;
  4172. I.getAAMetadata(AAInfo);
  4173. Result = DAG.getMemIntrinsicNode(
  4174. Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4175. MachinePointerInfo(Info.ptrVal, Info.offset),
  4176. Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
  4177. } else if (!HasChain) {
  4178. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4179. } else if (!I.getType()->isVoidTy()) {
  4180. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4181. } else {
  4182. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4183. }
  4184. if (HasChain) {
  4185. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4186. if (OnlyLoad)
  4187. PendingLoads.push_back(Chain);
  4188. else
  4189. DAG.setRoot(Chain);
  4190. }
  4191. if (!I.getType()->isVoidTy()) {
  4192. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4193. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4194. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4195. } else
  4196. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4197. setValue(&I, Result);
  4198. }
  4199. }
  4200. /// GetSignificand - Get the significand and build it into a floating-point
  4201. /// number with exponent of 1:
  4202. ///
  4203. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4204. ///
  4205. /// where Op is the hexadecimal representation of floating point value.
  4206. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4207. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4208. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4209. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4210. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4211. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4212. }
  4213. /// GetExponent - Get the exponent:
  4214. ///
  4215. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4216. ///
  4217. /// where Op is the hexadecimal representation of floating point value.
  4218. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4219. const TargetLowering &TLI, const SDLoc &dl) {
  4220. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4221. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4222. SDValue t1 = DAG.getNode(
  4223. ISD::SRL, dl, MVT::i32, t0,
  4224. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4225. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4226. DAG.getConstant(127, dl, MVT::i32));
  4227. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4228. }
  4229. /// getF32Constant - Get 32-bit floating point constant.
  4230. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4231. const SDLoc &dl) {
  4232. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4233. MVT::f32);
  4234. }
  4235. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4236. SelectionDAG &DAG) {
  4237. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4238. // IntegerPartOfX = ((int32_t)(t0);
  4239. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4240. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4241. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4242. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4243. // IntegerPartOfX <<= 23;
  4244. IntegerPartOfX = DAG.getNode(
  4245. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4246. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4247. DAG.getDataLayout())));
  4248. SDValue TwoToFractionalPartOfX;
  4249. if (LimitFloatPrecision <= 6) {
  4250. // For floating-point precision of 6:
  4251. //
  4252. // TwoToFractionalPartOfX =
  4253. // 0.997535578f +
  4254. // (0.735607626f + 0.252464424f * x) * x;
  4255. //
  4256. // error 0.0144103317, which is 6 bits
  4257. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4258. getF32Constant(DAG, 0x3e814304, dl));
  4259. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4260. getF32Constant(DAG, 0x3f3c50c8, dl));
  4261. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4262. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4263. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4264. } else if (LimitFloatPrecision <= 12) {
  4265. // For floating-point precision of 12:
  4266. //
  4267. // TwoToFractionalPartOfX =
  4268. // 0.999892986f +
  4269. // (0.696457318f +
  4270. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4271. //
  4272. // error 0.000107046256, which is 13 to 14 bits
  4273. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4274. getF32Constant(DAG, 0x3da235e3, dl));
  4275. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4276. getF32Constant(DAG, 0x3e65b8f3, dl));
  4277. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4278. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4279. getF32Constant(DAG, 0x3f324b07, dl));
  4280. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4281. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4282. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4283. } else { // LimitFloatPrecision <= 18
  4284. // For floating-point precision of 18:
  4285. //
  4286. // TwoToFractionalPartOfX =
  4287. // 0.999999982f +
  4288. // (0.693148872f +
  4289. // (0.240227044f +
  4290. // (0.554906021e-1f +
  4291. // (0.961591928e-2f +
  4292. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4293. // error 2.47208000*10^(-7), which is better than 18 bits
  4294. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4295. getF32Constant(DAG, 0x3924b03e, dl));
  4296. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4297. getF32Constant(DAG, 0x3ab24b87, dl));
  4298. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4299. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4300. getF32Constant(DAG, 0x3c1d8c17, dl));
  4301. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4302. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4303. getF32Constant(DAG, 0x3d634a1d, dl));
  4304. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4305. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4306. getF32Constant(DAG, 0x3e75fe14, dl));
  4307. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4308. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4309. getF32Constant(DAG, 0x3f317234, dl));
  4310. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4311. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4312. getF32Constant(DAG, 0x3f800000, dl));
  4313. }
  4314. // Add the exponent into the result in integer domain.
  4315. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4316. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4317. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4318. }
  4319. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4320. /// limited-precision mode.
  4321. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4322. const TargetLowering &TLI) {
  4323. if (Op.getValueType() == MVT::f32 &&
  4324. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4325. // Put the exponent in the right bit position for later addition to the
  4326. // final result:
  4327. //
  4328. // #define LOG2OFe 1.4426950f
  4329. // t0 = Op * LOG2OFe
  4330. // TODO: What fast-math-flags should be set here?
  4331. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4332. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4333. return getLimitedPrecisionExp2(t0, dl, DAG);
  4334. }
  4335. // No special expansion.
  4336. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4337. }
  4338. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4339. /// limited-precision mode.
  4340. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4341. const TargetLowering &TLI) {
  4342. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4343. if (Op.getValueType() == MVT::f32 &&
  4344. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4345. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4346. // Scale the exponent by log(2) [0.69314718f].
  4347. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4348. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4349. getF32Constant(DAG, 0x3f317218, dl));
  4350. // Get the significand and build it into a floating-point number with
  4351. // exponent of 1.
  4352. SDValue X = GetSignificand(DAG, Op1, dl);
  4353. SDValue LogOfMantissa;
  4354. if (LimitFloatPrecision <= 6) {
  4355. // For floating-point precision of 6:
  4356. //
  4357. // LogofMantissa =
  4358. // -1.1609546f +
  4359. // (1.4034025f - 0.23903021f * x) * x;
  4360. //
  4361. // error 0.0034276066, which is better than 8 bits
  4362. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4363. getF32Constant(DAG, 0xbe74c456, dl));
  4364. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4365. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4366. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4367. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4368. getF32Constant(DAG, 0x3f949a29, dl));
  4369. } else if (LimitFloatPrecision <= 12) {
  4370. // For floating-point precision of 12:
  4371. //
  4372. // LogOfMantissa =
  4373. // -1.7417939f +
  4374. // (2.8212026f +
  4375. // (-1.4699568f +
  4376. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4377. //
  4378. // error 0.000061011436, which is 14 bits
  4379. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4380. getF32Constant(DAG, 0xbd67b6d6, dl));
  4381. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4382. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4383. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4384. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4385. getF32Constant(DAG, 0x3fbc278b, dl));
  4386. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4387. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4388. getF32Constant(DAG, 0x40348e95, dl));
  4389. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4390. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4391. getF32Constant(DAG, 0x3fdef31a, dl));
  4392. } else { // LimitFloatPrecision <= 18
  4393. // For floating-point precision of 18:
  4394. //
  4395. // LogOfMantissa =
  4396. // -2.1072184f +
  4397. // (4.2372794f +
  4398. // (-3.7029485f +
  4399. // (2.2781945f +
  4400. // (-0.87823314f +
  4401. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4402. //
  4403. // error 0.0000023660568, which is better than 18 bits
  4404. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4405. getF32Constant(DAG, 0xbc91e5ac, dl));
  4406. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4407. getF32Constant(DAG, 0x3e4350aa, dl));
  4408. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4409. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4410. getF32Constant(DAG, 0x3f60d3e3, dl));
  4411. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4412. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4413. getF32Constant(DAG, 0x4011cdf0, dl));
  4414. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4415. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4416. getF32Constant(DAG, 0x406cfd1c, dl));
  4417. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4418. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4419. getF32Constant(DAG, 0x408797cb, dl));
  4420. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4421. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4422. getF32Constant(DAG, 0x4006dcab, dl));
  4423. }
  4424. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4425. }
  4426. // No special expansion.
  4427. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4428. }
  4429. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4430. /// limited-precision mode.
  4431. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4432. const TargetLowering &TLI) {
  4433. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4434. if (Op.getValueType() == MVT::f32 &&
  4435. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4436. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4437. // Get the exponent.
  4438. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4439. // Get the significand and build it into a floating-point number with
  4440. // exponent of 1.
  4441. SDValue X = GetSignificand(DAG, Op1, dl);
  4442. // Different possible minimax approximations of significand in
  4443. // floating-point for various degrees of accuracy over [1,2].
  4444. SDValue Log2ofMantissa;
  4445. if (LimitFloatPrecision <= 6) {
  4446. // For floating-point precision of 6:
  4447. //
  4448. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4449. //
  4450. // error 0.0049451742, which is more than 7 bits
  4451. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4452. getF32Constant(DAG, 0xbeb08fe0, dl));
  4453. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4454. getF32Constant(DAG, 0x40019463, dl));
  4455. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4456. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4457. getF32Constant(DAG, 0x3fd6633d, dl));
  4458. } else if (LimitFloatPrecision <= 12) {
  4459. // For floating-point precision of 12:
  4460. //
  4461. // Log2ofMantissa =
  4462. // -2.51285454f +
  4463. // (4.07009056f +
  4464. // (-2.12067489f +
  4465. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4466. //
  4467. // error 0.0000876136000, which is better than 13 bits
  4468. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4469. getF32Constant(DAG, 0xbda7262e, dl));
  4470. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4471. getF32Constant(DAG, 0x3f25280b, dl));
  4472. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4473. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4474. getF32Constant(DAG, 0x4007b923, dl));
  4475. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4476. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4477. getF32Constant(DAG, 0x40823e2f, dl));
  4478. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4479. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4480. getF32Constant(DAG, 0x4020d29c, dl));
  4481. } else { // LimitFloatPrecision <= 18
  4482. // For floating-point precision of 18:
  4483. //
  4484. // Log2ofMantissa =
  4485. // -3.0400495f +
  4486. // (6.1129976f +
  4487. // (-5.3420409f +
  4488. // (3.2865683f +
  4489. // (-1.2669343f +
  4490. // (0.27515199f -
  4491. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4492. //
  4493. // error 0.0000018516, which is better than 18 bits
  4494. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4495. getF32Constant(DAG, 0xbcd2769e, dl));
  4496. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4497. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4498. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4499. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4500. getF32Constant(DAG, 0x3fa22ae7, dl));
  4501. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4502. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4503. getF32Constant(DAG, 0x40525723, dl));
  4504. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4505. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4506. getF32Constant(DAG, 0x40aaf200, dl));
  4507. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4508. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4509. getF32Constant(DAG, 0x40c39dad, dl));
  4510. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4511. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4512. getF32Constant(DAG, 0x4042902c, dl));
  4513. }
  4514. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4515. }
  4516. // No special expansion.
  4517. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4518. }
  4519. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4520. /// limited-precision mode.
  4521. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4522. const TargetLowering &TLI) {
  4523. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4524. if (Op.getValueType() == MVT::f32 &&
  4525. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4526. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4527. // Scale the exponent by log10(2) [0.30102999f].
  4528. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4529. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4530. getF32Constant(DAG, 0x3e9a209a, dl));
  4531. // Get the significand and build it into a floating-point number with
  4532. // exponent of 1.
  4533. SDValue X = GetSignificand(DAG, Op1, dl);
  4534. SDValue Log10ofMantissa;
  4535. if (LimitFloatPrecision <= 6) {
  4536. // For floating-point precision of 6:
  4537. //
  4538. // Log10ofMantissa =
  4539. // -0.50419619f +
  4540. // (0.60948995f - 0.10380950f * x) * x;
  4541. //
  4542. // error 0.0014886165, which is 6 bits
  4543. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4544. getF32Constant(DAG, 0xbdd49a13, dl));
  4545. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4546. getF32Constant(DAG, 0x3f1c0789, dl));
  4547. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4548. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4549. getF32Constant(DAG, 0x3f011300, dl));
  4550. } else if (LimitFloatPrecision <= 12) {
  4551. // For floating-point precision of 12:
  4552. //
  4553. // Log10ofMantissa =
  4554. // -0.64831180f +
  4555. // (0.91751397f +
  4556. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4557. //
  4558. // error 0.00019228036, which is better than 12 bits
  4559. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4560. getF32Constant(DAG, 0x3d431f31, dl));
  4561. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4562. getF32Constant(DAG, 0x3ea21fb2, dl));
  4563. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4564. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4565. getF32Constant(DAG, 0x3f6ae232, dl));
  4566. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4567. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4568. getF32Constant(DAG, 0x3f25f7c3, dl));
  4569. } else { // LimitFloatPrecision <= 18
  4570. // For floating-point precision of 18:
  4571. //
  4572. // Log10ofMantissa =
  4573. // -0.84299375f +
  4574. // (1.5327582f +
  4575. // (-1.0688956f +
  4576. // (0.49102474f +
  4577. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4578. //
  4579. // error 0.0000037995730, which is better than 18 bits
  4580. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4581. getF32Constant(DAG, 0x3c5d51ce, dl));
  4582. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4583. getF32Constant(DAG, 0x3e00685a, dl));
  4584. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4585. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4586. getF32Constant(DAG, 0x3efb6798, dl));
  4587. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4588. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4589. getF32Constant(DAG, 0x3f88d192, dl));
  4590. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4591. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4592. getF32Constant(DAG, 0x3fc4316c, dl));
  4593. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4594. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4595. getF32Constant(DAG, 0x3f57ce70, dl));
  4596. }
  4597. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4598. }
  4599. // No special expansion.
  4600. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4601. }
  4602. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4603. /// limited-precision mode.
  4604. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4605. const TargetLowering &TLI) {
  4606. if (Op.getValueType() == MVT::f32 &&
  4607. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4608. return getLimitedPrecisionExp2(Op, dl, DAG);
  4609. // No special expansion.
  4610. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4611. }
  4612. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4613. /// limited-precision mode with x == 10.0f.
  4614. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4615. SelectionDAG &DAG, const TargetLowering &TLI) {
  4616. bool IsExp10 = false;
  4617. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4618. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4619. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4620. APFloat Ten(10.0f);
  4621. IsExp10 = LHSC->isExactlyValue(Ten);
  4622. }
  4623. }
  4624. // TODO: What fast-math-flags should be set on the FMUL node?
  4625. if (IsExp10) {
  4626. // Put the exponent in the right bit position for later addition to the
  4627. // final result:
  4628. //
  4629. // #define LOG2OF10 3.3219281f
  4630. // t0 = Op * LOG2OF10;
  4631. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4632. getF32Constant(DAG, 0x40549a78, dl));
  4633. return getLimitedPrecisionExp2(t0, dl, DAG);
  4634. }
  4635. // No special expansion.
  4636. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4637. }
  4638. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4639. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4640. SelectionDAG &DAG) {
  4641. // If RHS is a constant, we can expand this out to a multiplication tree,
  4642. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4643. // optimizing for size, we only want to do this if the expansion would produce
  4644. // a small number of multiplies, otherwise we do the full expansion.
  4645. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4646. // Get the exponent as a positive value.
  4647. unsigned Val = RHSC->getSExtValue();
  4648. if ((int)Val < 0) Val = -Val;
  4649. // powi(x, 0) -> 1.0
  4650. if (Val == 0)
  4651. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4652. const Function &F = DAG.getMachineFunction().getFunction();
  4653. if (!F.hasOptSize() ||
  4654. // If optimizing for size, don't insert too many multiplies.
  4655. // This inserts up to 5 multiplies.
  4656. countPopulation(Val) + Log2_32(Val) < 7) {
  4657. // We use the simple binary decomposition method to generate the multiply
  4658. // sequence. There are more optimal ways to do this (for example,
  4659. // powi(x,15) generates one more multiply than it should), but this has
  4660. // the benefit of being both really simple and much better than a libcall.
  4661. SDValue Res; // Logically starts equal to 1.0
  4662. SDValue CurSquare = LHS;
  4663. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4664. // nodes.
  4665. while (Val) {
  4666. if (Val & 1) {
  4667. if (Res.getNode())
  4668. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4669. else
  4670. Res = CurSquare; // 1.0*CurSquare.
  4671. }
  4672. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4673. CurSquare, CurSquare);
  4674. Val >>= 1;
  4675. }
  4676. // If the original was negative, invert the result, producing 1/(x*x*x).
  4677. if (RHSC->getSExtValue() < 0)
  4678. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4679. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4680. return Res;
  4681. }
  4682. }
  4683. // Otherwise, expand to a libcall.
  4684. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4685. }
  4686. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4687. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4688. static void
  4689. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
  4690. const SDValue &N) {
  4691. switch (N.getOpcode()) {
  4692. case ISD::CopyFromReg: {
  4693. SDValue Op = N.getOperand(1);
  4694. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4695. Op.getValueType().getSizeInBits());
  4696. return;
  4697. }
  4698. case ISD::BITCAST:
  4699. case ISD::AssertZext:
  4700. case ISD::AssertSext:
  4701. case ISD::TRUNCATE:
  4702. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4703. return;
  4704. case ISD::BUILD_PAIR:
  4705. case ISD::BUILD_VECTOR:
  4706. case ISD::CONCAT_VECTORS:
  4707. for (SDValue Op : N->op_values())
  4708. getUnderlyingArgRegs(Regs, Op);
  4709. return;
  4710. default:
  4711. return;
  4712. }
  4713. }
  4714. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4715. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4716. /// instruction selection, they will be inserted to the entry BB.
  4717. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4718. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4719. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4720. const Argument *Arg = dyn_cast<Argument>(V);
  4721. if (!Arg)
  4722. return false;
  4723. if (!IsDbgDeclare) {
  4724. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4725. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4726. // the entry block.
  4727. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4728. if (!IsInEntryBlock)
  4729. return false;
  4730. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4731. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4732. // variable that also is a param.
  4733. //
  4734. // Although, if we are at the top of the entry block already, we can still
  4735. // emit using ArgDbgValue. This might catch some situations when the
  4736. // dbg.value refers to an argument that isn't used in the entry block, so
  4737. // any CopyToReg node would be optimized out and the only way to express
  4738. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4739. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4740. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4741. // current function, and the dbg.value intrinsic is found in the entry
  4742. // block.
  4743. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4744. !DL->getInlinedAt();
  4745. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4746. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4747. return false;
  4748. // Here we assume that a function argument on IR level only can be used to
  4749. // describe one input parameter on source level. If we for example have
  4750. // source code like this
  4751. //
  4752. // struct A { long x, y; };
  4753. // void foo(struct A a, long b) {
  4754. // ...
  4755. // b = a.x;
  4756. // ...
  4757. // }
  4758. //
  4759. // and IR like this
  4760. //
  4761. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4762. // entry:
  4763. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4764. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4765. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4766. // ...
  4767. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4768. // ...
  4769. //
  4770. // then the last dbg.value is describing a parameter "b" using a value that
  4771. // is an argument. But since we already has used %a1 to describe a parameter
  4772. // we should not handle that last dbg.value here (that would result in an
  4773. // incorrect hoisting of the DBG_VALUE to the function entry).
  4774. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4775. // for the situation with fragments above.
  4776. if (VariableIsFunctionInputArg) {
  4777. unsigned ArgNo = Arg->getArgNo();
  4778. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4779. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4780. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4781. return false;
  4782. FuncInfo.DescribedArgs.set(ArgNo);
  4783. }
  4784. }
  4785. MachineFunction &MF = DAG.getMachineFunction();
  4786. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4787. bool IsIndirect = false;
  4788. Optional<MachineOperand> Op;
  4789. // Some arguments' frame index is recorded during argument lowering.
  4790. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4791. if (FI != std::numeric_limits<int>::max())
  4792. Op = MachineOperand::CreateFI(FI);
  4793. SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
  4794. if (!Op && N.getNode()) {
  4795. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4796. Register Reg;
  4797. if (ArgRegsAndSizes.size() == 1)
  4798. Reg = ArgRegsAndSizes.front().first;
  4799. if (Reg && Reg.isVirtual()) {
  4800. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4801. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4802. if (PR)
  4803. Reg = PR;
  4804. }
  4805. if (Reg) {
  4806. Op = MachineOperand::CreateReg(Reg, false);
  4807. IsIndirect = IsDbgDeclare;
  4808. }
  4809. }
  4810. if (!Op && N.getNode()) {
  4811. // Check if frame index is available.
  4812. SDValue LCandidate = peekThroughBitcasts(N);
  4813. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4814. if (FrameIndexSDNode *FINode =
  4815. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4816. Op = MachineOperand::CreateFI(FINode->getIndex());
  4817. }
  4818. if (!Op) {
  4819. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  4820. auto splitMultiRegDbgValue
  4821. = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
  4822. unsigned Offset = 0;
  4823. for (auto RegAndSize : SplitRegs) {
  4824. auto FragmentExpr = DIExpression::createFragmentExpression(
  4825. Expr, Offset, RegAndSize.second);
  4826. if (!FragmentExpr)
  4827. continue;
  4828. FuncInfo.ArgDbgValues.push_back(
  4829. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4830. RegAndSize.first, Variable, *FragmentExpr));
  4831. Offset += RegAndSize.second;
  4832. }
  4833. };
  4834. // Check if ValueMap has reg number.
  4835. DenseMap<const Value *, unsigned>::const_iterator
  4836. VMI = FuncInfo.ValueMap.find(V);
  4837. if (VMI != FuncInfo.ValueMap.end()) {
  4838. const auto &TLI = DAG.getTargetLoweringInfo();
  4839. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4840. V->getType(), getABIRegCopyCC(V));
  4841. if (RFV.occupiesMultipleRegs()) {
  4842. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  4843. return true;
  4844. }
  4845. Op = MachineOperand::CreateReg(VMI->second, false);
  4846. IsIndirect = IsDbgDeclare;
  4847. } else if (ArgRegsAndSizes.size() > 1) {
  4848. // This was split due to the calling convention, and no virtual register
  4849. // mapping exists for the value.
  4850. splitMultiRegDbgValue(ArgRegsAndSizes);
  4851. return true;
  4852. }
  4853. }
  4854. if (!Op)
  4855. return false;
  4856. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4857. "Expected inlined-at fields to agree");
  4858. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4859. FuncInfo.ArgDbgValues.push_back(
  4860. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4861. *Op, Variable, Expr));
  4862. return true;
  4863. }
  4864. /// Return the appropriate SDDbgValue based on N.
  4865. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4866. DILocalVariable *Variable,
  4867. DIExpression *Expr,
  4868. const DebugLoc &dl,
  4869. unsigned DbgSDNodeOrder) {
  4870. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4871. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4872. // stack slot locations.
  4873. //
  4874. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4875. // debug values here after optimization:
  4876. //
  4877. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4878. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4879. //
  4880. // Both describe the direct values of their associated variables.
  4881. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4882. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4883. }
  4884. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4885. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4886. }
  4887. // VisualStudio defines setjmp as _setjmp
  4888. #if defined(_MSC_VER) && defined(setjmp) && \
  4889. !defined(setjmp_undefined_for_msvc)
  4890. # pragma push_macro("setjmp")
  4891. # undef setjmp
  4892. # define setjmp_undefined_for_msvc
  4893. #endif
  4894. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4895. switch (Intrinsic) {
  4896. case Intrinsic::smul_fix:
  4897. return ISD::SMULFIX;
  4898. case Intrinsic::umul_fix:
  4899. return ISD::UMULFIX;
  4900. default:
  4901. llvm_unreachable("Unhandled fixed point intrinsic");
  4902. }
  4903. }
  4904. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4905. const char *FunctionName) {
  4906. assert(FunctionName && "FunctionName must not be nullptr");
  4907. SDValue Callee = DAG.getExternalSymbol(
  4908. FunctionName,
  4909. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4910. LowerCallTo(&I, Callee, I.isTailCall());
  4911. }
  4912. /// Lower the call to the specified intrinsic function.
  4913. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4914. unsigned Intrinsic) {
  4915. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4916. SDLoc sdl = getCurSDLoc();
  4917. DebugLoc dl = getCurDebugLoc();
  4918. SDValue Res;
  4919. switch (Intrinsic) {
  4920. default:
  4921. // By default, turn this into a target intrinsic node.
  4922. visitTargetIntrinsic(I, Intrinsic);
  4923. return;
  4924. case Intrinsic::vastart: visitVAStart(I); return;
  4925. case Intrinsic::vaend: visitVAEnd(I); return;
  4926. case Intrinsic::vacopy: visitVACopy(I); return;
  4927. case Intrinsic::returnaddress:
  4928. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4929. TLI.getPointerTy(DAG.getDataLayout()),
  4930. getValue(I.getArgOperand(0))));
  4931. return;
  4932. case Intrinsic::addressofreturnaddress:
  4933. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4934. TLI.getPointerTy(DAG.getDataLayout())));
  4935. return;
  4936. case Intrinsic::sponentry:
  4937. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4938. TLI.getFrameIndexTy(DAG.getDataLayout())));
  4939. return;
  4940. case Intrinsic::frameaddress:
  4941. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4942. TLI.getFrameIndexTy(DAG.getDataLayout()),
  4943. getValue(I.getArgOperand(0))));
  4944. return;
  4945. case Intrinsic::read_register: {
  4946. Value *Reg = I.getArgOperand(0);
  4947. SDValue Chain = getRoot();
  4948. SDValue RegName =
  4949. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4950. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4951. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4952. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4953. setValue(&I, Res);
  4954. DAG.setRoot(Res.getValue(1));
  4955. return;
  4956. }
  4957. case Intrinsic::write_register: {
  4958. Value *Reg = I.getArgOperand(0);
  4959. Value *RegValue = I.getArgOperand(1);
  4960. SDValue Chain = getRoot();
  4961. SDValue RegName =
  4962. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4963. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4964. RegName, getValue(RegValue)));
  4965. return;
  4966. }
  4967. case Intrinsic::setjmp:
  4968. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4969. return;
  4970. case Intrinsic::longjmp:
  4971. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4972. return;
  4973. case Intrinsic::memcpy: {
  4974. const auto &MCI = cast<MemCpyInst>(I);
  4975. SDValue Op1 = getValue(I.getArgOperand(0));
  4976. SDValue Op2 = getValue(I.getArgOperand(1));
  4977. SDValue Op3 = getValue(I.getArgOperand(2));
  4978. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4979. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4980. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4981. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4982. bool isVol = MCI.isVolatile();
  4983. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4984. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4985. // node.
  4986. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4987. false, isTC,
  4988. MachinePointerInfo(I.getArgOperand(0)),
  4989. MachinePointerInfo(I.getArgOperand(1)));
  4990. updateDAGForMaybeTailCall(MC);
  4991. return;
  4992. }
  4993. case Intrinsic::memset: {
  4994. const auto &MSI = cast<MemSetInst>(I);
  4995. SDValue Op1 = getValue(I.getArgOperand(0));
  4996. SDValue Op2 = getValue(I.getArgOperand(1));
  4997. SDValue Op3 = getValue(I.getArgOperand(2));
  4998. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4999. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  5000. bool isVol = MSI.isVolatile();
  5001. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5002. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  5003. isTC, MachinePointerInfo(I.getArgOperand(0)));
  5004. updateDAGForMaybeTailCall(MS);
  5005. return;
  5006. }
  5007. case Intrinsic::memmove: {
  5008. const auto &MMI = cast<MemMoveInst>(I);
  5009. SDValue Op1 = getValue(I.getArgOperand(0));
  5010. SDValue Op2 = getValue(I.getArgOperand(1));
  5011. SDValue Op3 = getValue(I.getArgOperand(2));
  5012. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  5013. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  5014. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  5015. unsigned Align = MinAlign(DstAlign, SrcAlign);
  5016. bool isVol = MMI.isVolatile();
  5017. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5018. // FIXME: Support passing different dest/src alignments to the memmove DAG
  5019. // node.
  5020. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  5021. isTC, MachinePointerInfo(I.getArgOperand(0)),
  5022. MachinePointerInfo(I.getArgOperand(1)));
  5023. updateDAGForMaybeTailCall(MM);
  5024. return;
  5025. }
  5026. case Intrinsic::memcpy_element_unordered_atomic: {
  5027. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  5028. SDValue Dst = getValue(MI.getRawDest());
  5029. SDValue Src = getValue(MI.getRawSource());
  5030. SDValue Length = getValue(MI.getLength());
  5031. unsigned DstAlign = MI.getDestAlignment();
  5032. unsigned SrcAlign = MI.getSourceAlignment();
  5033. Type *LengthTy = MI.getLength()->getType();
  5034. unsigned ElemSz = MI.getElementSizeInBytes();
  5035. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5036. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  5037. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5038. MachinePointerInfo(MI.getRawDest()),
  5039. MachinePointerInfo(MI.getRawSource()));
  5040. updateDAGForMaybeTailCall(MC);
  5041. return;
  5042. }
  5043. case Intrinsic::memmove_element_unordered_atomic: {
  5044. auto &MI = cast<AtomicMemMoveInst>(I);
  5045. SDValue Dst = getValue(MI.getRawDest());
  5046. SDValue Src = getValue(MI.getRawSource());
  5047. SDValue Length = getValue(MI.getLength());
  5048. unsigned DstAlign = MI.getDestAlignment();
  5049. unsigned SrcAlign = MI.getSourceAlignment();
  5050. Type *LengthTy = MI.getLength()->getType();
  5051. unsigned ElemSz = MI.getElementSizeInBytes();
  5052. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5053. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  5054. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5055. MachinePointerInfo(MI.getRawDest()),
  5056. MachinePointerInfo(MI.getRawSource()));
  5057. updateDAGForMaybeTailCall(MC);
  5058. return;
  5059. }
  5060. case Intrinsic::memset_element_unordered_atomic: {
  5061. auto &MI = cast<AtomicMemSetInst>(I);
  5062. SDValue Dst = getValue(MI.getRawDest());
  5063. SDValue Val = getValue(MI.getValue());
  5064. SDValue Length = getValue(MI.getLength());
  5065. unsigned DstAlign = MI.getDestAlignment();
  5066. Type *LengthTy = MI.getLength()->getType();
  5067. unsigned ElemSz = MI.getElementSizeInBytes();
  5068. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5069. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5070. LengthTy, ElemSz, isTC,
  5071. MachinePointerInfo(MI.getRawDest()));
  5072. updateDAGForMaybeTailCall(MC);
  5073. return;
  5074. }
  5075. case Intrinsic::dbg_addr:
  5076. case Intrinsic::dbg_declare: {
  5077. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5078. DILocalVariable *Variable = DI.getVariable();
  5079. DIExpression *Expression = DI.getExpression();
  5080. dropDanglingDebugInfo(Variable, Expression);
  5081. assert(Variable && "Missing variable");
  5082. // Check if address has undef value.
  5083. const Value *Address = DI.getVariableLocation();
  5084. if (!Address || isa<UndefValue>(Address) ||
  5085. (Address->use_empty() && !isa<Argument>(Address))) {
  5086. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5087. return;
  5088. }
  5089. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5090. // Check if this variable can be described by a frame index, typically
  5091. // either as a static alloca or a byval parameter.
  5092. int FI = std::numeric_limits<int>::max();
  5093. if (const auto *AI =
  5094. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5095. if (AI->isStaticAlloca()) {
  5096. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5097. if (I != FuncInfo.StaticAllocaMap.end())
  5098. FI = I->second;
  5099. }
  5100. } else if (const auto *Arg = dyn_cast<Argument>(
  5101. Address->stripInBoundsConstantOffsets())) {
  5102. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5103. }
  5104. // llvm.dbg.addr is control dependent and always generates indirect
  5105. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5106. // the MachineFunction variable table.
  5107. if (FI != std::numeric_limits<int>::max()) {
  5108. if (Intrinsic == Intrinsic::dbg_addr) {
  5109. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5110. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5111. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5112. }
  5113. return;
  5114. }
  5115. SDValue &N = NodeMap[Address];
  5116. if (!N.getNode() && isa<Argument>(Address))
  5117. // Check unused arguments map.
  5118. N = UnusedArgNodeMap[Address];
  5119. SDDbgValue *SDV;
  5120. if (N.getNode()) {
  5121. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5122. Address = BCI->getOperand(0);
  5123. // Parameters are handled specially.
  5124. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5125. if (isParameter && FINode) {
  5126. // Byval parameter. We have a frame index at this point.
  5127. SDV =
  5128. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5129. /*IsIndirect*/ true, dl, SDNodeOrder);
  5130. } else if (isa<Argument>(Address)) {
  5131. // Address is an argument, so try to emit its dbg value using
  5132. // virtual register info from the FuncInfo.ValueMap.
  5133. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5134. return;
  5135. } else {
  5136. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5137. true, dl, SDNodeOrder);
  5138. }
  5139. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5140. } else {
  5141. // If Address is an argument then try to emit its dbg value using
  5142. // virtual register info from the FuncInfo.ValueMap.
  5143. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5144. N)) {
  5145. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5146. }
  5147. }
  5148. return;
  5149. }
  5150. case Intrinsic::dbg_label: {
  5151. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5152. DILabel *Label = DI.getLabel();
  5153. assert(Label && "Missing label");
  5154. SDDbgLabel *SDV;
  5155. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5156. DAG.AddDbgLabel(SDV);
  5157. return;
  5158. }
  5159. case Intrinsic::dbg_value: {
  5160. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5161. assert(DI.getVariable() && "Missing variable");
  5162. DILocalVariable *Variable = DI.getVariable();
  5163. DIExpression *Expression = DI.getExpression();
  5164. dropDanglingDebugInfo(Variable, Expression);
  5165. const Value *V = DI.getValue();
  5166. if (!V)
  5167. return;
  5168. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5169. SDNodeOrder))
  5170. return;
  5171. // TODO: Dangling debug info will eventually either be resolved or produce
  5172. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5173. // between the original dbg.value location and its resolved DBG_VALUE, which
  5174. // we should ideally fill with an extra Undef DBG_VALUE.
  5175. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5176. return;
  5177. }
  5178. case Intrinsic::eh_typeid_for: {
  5179. // Find the type id for the given typeinfo.
  5180. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5181. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5182. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5183. setValue(&I, Res);
  5184. return;
  5185. }
  5186. case Intrinsic::eh_return_i32:
  5187. case Intrinsic::eh_return_i64:
  5188. DAG.getMachineFunction().setCallsEHReturn(true);
  5189. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5190. MVT::Other,
  5191. getControlRoot(),
  5192. getValue(I.getArgOperand(0)),
  5193. getValue(I.getArgOperand(1))));
  5194. return;
  5195. case Intrinsic::eh_unwind_init:
  5196. DAG.getMachineFunction().setCallsUnwindInit(true);
  5197. return;
  5198. case Intrinsic::eh_dwarf_cfa:
  5199. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5200. TLI.getPointerTy(DAG.getDataLayout()),
  5201. getValue(I.getArgOperand(0))));
  5202. return;
  5203. case Intrinsic::eh_sjlj_callsite: {
  5204. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5205. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5206. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5207. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5208. MMI.setCurrentCallSite(CI->getZExtValue());
  5209. return;
  5210. }
  5211. case Intrinsic::eh_sjlj_functioncontext: {
  5212. // Get and store the index of the function context.
  5213. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5214. AllocaInst *FnCtx =
  5215. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5216. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5217. MFI.setFunctionContextIndex(FI);
  5218. return;
  5219. }
  5220. case Intrinsic::eh_sjlj_setjmp: {
  5221. SDValue Ops[2];
  5222. Ops[0] = getRoot();
  5223. Ops[1] = getValue(I.getArgOperand(0));
  5224. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5225. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5226. setValue(&I, Op.getValue(0));
  5227. DAG.setRoot(Op.getValue(1));
  5228. return;
  5229. }
  5230. case Intrinsic::eh_sjlj_longjmp:
  5231. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5232. getRoot(), getValue(I.getArgOperand(0))));
  5233. return;
  5234. case Intrinsic::eh_sjlj_setup_dispatch:
  5235. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5236. getRoot()));
  5237. return;
  5238. case Intrinsic::masked_gather:
  5239. visitMaskedGather(I);
  5240. return;
  5241. case Intrinsic::masked_load:
  5242. visitMaskedLoad(I);
  5243. return;
  5244. case Intrinsic::masked_scatter:
  5245. visitMaskedScatter(I);
  5246. return;
  5247. case Intrinsic::masked_store:
  5248. visitMaskedStore(I);
  5249. return;
  5250. case Intrinsic::masked_expandload:
  5251. visitMaskedLoad(I, true /* IsExpanding */);
  5252. return;
  5253. case Intrinsic::masked_compressstore:
  5254. visitMaskedStore(I, true /* IsCompressing */);
  5255. return;
  5256. case Intrinsic::powi:
  5257. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5258. getValue(I.getArgOperand(1)), DAG));
  5259. return;
  5260. case Intrinsic::log:
  5261. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5262. return;
  5263. case Intrinsic::log2:
  5264. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5265. return;
  5266. case Intrinsic::log10:
  5267. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5268. return;
  5269. case Intrinsic::exp:
  5270. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5271. return;
  5272. case Intrinsic::exp2:
  5273. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5274. return;
  5275. case Intrinsic::pow:
  5276. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5277. getValue(I.getArgOperand(1)), DAG, TLI));
  5278. return;
  5279. case Intrinsic::sqrt:
  5280. case Intrinsic::fabs:
  5281. case Intrinsic::sin:
  5282. case Intrinsic::cos:
  5283. case Intrinsic::floor:
  5284. case Intrinsic::ceil:
  5285. case Intrinsic::trunc:
  5286. case Intrinsic::rint:
  5287. case Intrinsic::nearbyint:
  5288. case Intrinsic::round:
  5289. case Intrinsic::canonicalize: {
  5290. unsigned Opcode;
  5291. switch (Intrinsic) {
  5292. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5293. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5294. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5295. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5296. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5297. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5298. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5299. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5300. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5301. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5302. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5303. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5304. }
  5305. setValue(&I, DAG.getNode(Opcode, sdl,
  5306. getValue(I.getArgOperand(0)).getValueType(),
  5307. getValue(I.getArgOperand(0))));
  5308. return;
  5309. }
  5310. case Intrinsic::lround:
  5311. case Intrinsic::llround:
  5312. case Intrinsic::lrint:
  5313. case Intrinsic::llrint: {
  5314. unsigned Opcode;
  5315. switch (Intrinsic) {
  5316. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5317. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5318. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5319. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5320. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5321. }
  5322. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5323. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5324. getValue(I.getArgOperand(0))));
  5325. return;
  5326. }
  5327. case Intrinsic::minnum:
  5328. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5329. getValue(I.getArgOperand(0)).getValueType(),
  5330. getValue(I.getArgOperand(0)),
  5331. getValue(I.getArgOperand(1))));
  5332. return;
  5333. case Intrinsic::maxnum:
  5334. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5335. getValue(I.getArgOperand(0)).getValueType(),
  5336. getValue(I.getArgOperand(0)),
  5337. getValue(I.getArgOperand(1))));
  5338. return;
  5339. case Intrinsic::minimum:
  5340. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5341. getValue(I.getArgOperand(0)).getValueType(),
  5342. getValue(I.getArgOperand(0)),
  5343. getValue(I.getArgOperand(1))));
  5344. return;
  5345. case Intrinsic::maximum:
  5346. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5347. getValue(I.getArgOperand(0)).getValueType(),
  5348. getValue(I.getArgOperand(0)),
  5349. getValue(I.getArgOperand(1))));
  5350. return;
  5351. case Intrinsic::copysign:
  5352. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5353. getValue(I.getArgOperand(0)).getValueType(),
  5354. getValue(I.getArgOperand(0)),
  5355. getValue(I.getArgOperand(1))));
  5356. return;
  5357. case Intrinsic::fma:
  5358. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5359. getValue(I.getArgOperand(0)).getValueType(),
  5360. getValue(I.getArgOperand(0)),
  5361. getValue(I.getArgOperand(1)),
  5362. getValue(I.getArgOperand(2))));
  5363. return;
  5364. case Intrinsic::experimental_constrained_fadd:
  5365. case Intrinsic::experimental_constrained_fsub:
  5366. case Intrinsic::experimental_constrained_fmul:
  5367. case Intrinsic::experimental_constrained_fdiv:
  5368. case Intrinsic::experimental_constrained_frem:
  5369. case Intrinsic::experimental_constrained_fma:
  5370. case Intrinsic::experimental_constrained_fptosi:
  5371. case Intrinsic::experimental_constrained_fptoui:
  5372. case Intrinsic::experimental_constrained_fptrunc:
  5373. case Intrinsic::experimental_constrained_fpext:
  5374. case Intrinsic::experimental_constrained_sqrt:
  5375. case Intrinsic::experimental_constrained_pow:
  5376. case Intrinsic::experimental_constrained_powi:
  5377. case Intrinsic::experimental_constrained_sin:
  5378. case Intrinsic::experimental_constrained_cos:
  5379. case Intrinsic::experimental_constrained_exp:
  5380. case Intrinsic::experimental_constrained_exp2:
  5381. case Intrinsic::experimental_constrained_log:
  5382. case Intrinsic::experimental_constrained_log10:
  5383. case Intrinsic::experimental_constrained_log2:
  5384. case Intrinsic::experimental_constrained_rint:
  5385. case Intrinsic::experimental_constrained_nearbyint:
  5386. case Intrinsic::experimental_constrained_maxnum:
  5387. case Intrinsic::experimental_constrained_minnum:
  5388. case Intrinsic::experimental_constrained_ceil:
  5389. case Intrinsic::experimental_constrained_floor:
  5390. case Intrinsic::experimental_constrained_round:
  5391. case Intrinsic::experimental_constrained_trunc:
  5392. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5393. return;
  5394. case Intrinsic::fmuladd: {
  5395. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5396. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5397. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5398. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5399. getValue(I.getArgOperand(0)).getValueType(),
  5400. getValue(I.getArgOperand(0)),
  5401. getValue(I.getArgOperand(1)),
  5402. getValue(I.getArgOperand(2))));
  5403. } else {
  5404. // TODO: Intrinsic calls should have fast-math-flags.
  5405. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5406. getValue(I.getArgOperand(0)).getValueType(),
  5407. getValue(I.getArgOperand(0)),
  5408. getValue(I.getArgOperand(1)));
  5409. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5410. getValue(I.getArgOperand(0)).getValueType(),
  5411. Mul,
  5412. getValue(I.getArgOperand(2)));
  5413. setValue(&I, Add);
  5414. }
  5415. return;
  5416. }
  5417. case Intrinsic::convert_to_fp16:
  5418. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5419. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5420. getValue(I.getArgOperand(0)),
  5421. DAG.getTargetConstant(0, sdl,
  5422. MVT::i32))));
  5423. return;
  5424. case Intrinsic::convert_from_fp16:
  5425. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5426. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5427. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5428. getValue(I.getArgOperand(0)))));
  5429. return;
  5430. case Intrinsic::pcmarker: {
  5431. SDValue Tmp = getValue(I.getArgOperand(0));
  5432. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5433. return;
  5434. }
  5435. case Intrinsic::readcyclecounter: {
  5436. SDValue Op = getRoot();
  5437. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5438. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5439. setValue(&I, Res);
  5440. DAG.setRoot(Res.getValue(1));
  5441. return;
  5442. }
  5443. case Intrinsic::bitreverse:
  5444. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5445. getValue(I.getArgOperand(0)).getValueType(),
  5446. getValue(I.getArgOperand(0))));
  5447. return;
  5448. case Intrinsic::bswap:
  5449. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5450. getValue(I.getArgOperand(0)).getValueType(),
  5451. getValue(I.getArgOperand(0))));
  5452. return;
  5453. case Intrinsic::cttz: {
  5454. SDValue Arg = getValue(I.getArgOperand(0));
  5455. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5456. EVT Ty = Arg.getValueType();
  5457. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5458. sdl, Ty, Arg));
  5459. return;
  5460. }
  5461. case Intrinsic::ctlz: {
  5462. SDValue Arg = getValue(I.getArgOperand(0));
  5463. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5464. EVT Ty = Arg.getValueType();
  5465. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5466. sdl, Ty, Arg));
  5467. return;
  5468. }
  5469. case Intrinsic::ctpop: {
  5470. SDValue Arg = getValue(I.getArgOperand(0));
  5471. EVT Ty = Arg.getValueType();
  5472. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5473. return;
  5474. }
  5475. case Intrinsic::fshl:
  5476. case Intrinsic::fshr: {
  5477. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5478. SDValue X = getValue(I.getArgOperand(0));
  5479. SDValue Y = getValue(I.getArgOperand(1));
  5480. SDValue Z = getValue(I.getArgOperand(2));
  5481. EVT VT = X.getValueType();
  5482. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5483. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5484. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5485. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5486. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5487. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5488. return;
  5489. }
  5490. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5491. // avoid the select that is necessary in the general case to filter out
  5492. // the 0-shift possibility that leads to UB.
  5493. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5494. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5495. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5496. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5497. return;
  5498. }
  5499. // Some targets only rotate one way. Try the opposite direction.
  5500. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5501. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5502. // Negate the shift amount because it is safe to ignore the high bits.
  5503. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5504. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5505. return;
  5506. }
  5507. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5508. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5509. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5510. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5511. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5512. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5513. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5514. return;
  5515. }
  5516. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5517. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5518. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5519. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5520. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5521. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5522. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5523. // and that is undefined. We must compare and select to avoid UB.
  5524. EVT CCVT = MVT::i1;
  5525. if (VT.isVector())
  5526. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5527. // For fshl, 0-shift returns the 1st arg (X).
  5528. // For fshr, 0-shift returns the 2nd arg (Y).
  5529. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5530. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5531. return;
  5532. }
  5533. case Intrinsic::sadd_sat: {
  5534. SDValue Op1 = getValue(I.getArgOperand(0));
  5535. SDValue Op2 = getValue(I.getArgOperand(1));
  5536. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5537. return;
  5538. }
  5539. case Intrinsic::uadd_sat: {
  5540. SDValue Op1 = getValue(I.getArgOperand(0));
  5541. SDValue Op2 = getValue(I.getArgOperand(1));
  5542. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5543. return;
  5544. }
  5545. case Intrinsic::ssub_sat: {
  5546. SDValue Op1 = getValue(I.getArgOperand(0));
  5547. SDValue Op2 = getValue(I.getArgOperand(1));
  5548. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5549. return;
  5550. }
  5551. case Intrinsic::usub_sat: {
  5552. SDValue Op1 = getValue(I.getArgOperand(0));
  5553. SDValue Op2 = getValue(I.getArgOperand(1));
  5554. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5555. return;
  5556. }
  5557. case Intrinsic::smul_fix:
  5558. case Intrinsic::umul_fix: {
  5559. SDValue Op1 = getValue(I.getArgOperand(0));
  5560. SDValue Op2 = getValue(I.getArgOperand(1));
  5561. SDValue Op3 = getValue(I.getArgOperand(2));
  5562. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5563. Op1.getValueType(), Op1, Op2, Op3));
  5564. return;
  5565. }
  5566. case Intrinsic::smul_fix_sat: {
  5567. SDValue Op1 = getValue(I.getArgOperand(0));
  5568. SDValue Op2 = getValue(I.getArgOperand(1));
  5569. SDValue Op3 = getValue(I.getArgOperand(2));
  5570. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5571. Op3));
  5572. return;
  5573. }
  5574. case Intrinsic::umul_fix_sat: {
  5575. SDValue Op1 = getValue(I.getArgOperand(0));
  5576. SDValue Op2 = getValue(I.getArgOperand(1));
  5577. SDValue Op3 = getValue(I.getArgOperand(2));
  5578. setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5579. Op3));
  5580. return;
  5581. }
  5582. case Intrinsic::stacksave: {
  5583. SDValue Op = getRoot();
  5584. Res = DAG.getNode(
  5585. ISD::STACKSAVE, sdl,
  5586. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5587. setValue(&I, Res);
  5588. DAG.setRoot(Res.getValue(1));
  5589. return;
  5590. }
  5591. case Intrinsic::stackrestore:
  5592. Res = getValue(I.getArgOperand(0));
  5593. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5594. return;
  5595. case Intrinsic::get_dynamic_area_offset: {
  5596. SDValue Op = getRoot();
  5597. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5598. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5599. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5600. // target.
  5601. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5602. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5603. " intrinsic!");
  5604. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5605. Op);
  5606. DAG.setRoot(Op);
  5607. setValue(&I, Res);
  5608. return;
  5609. }
  5610. case Intrinsic::stackguard: {
  5611. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5612. MachineFunction &MF = DAG.getMachineFunction();
  5613. const Module &M = *MF.getFunction().getParent();
  5614. SDValue Chain = getRoot();
  5615. if (TLI.useLoadStackGuardNode()) {
  5616. Res = getLoadStackGuard(DAG, sdl, Chain);
  5617. } else {
  5618. const Value *Global = TLI.getSDagStackGuard(M);
  5619. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5620. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5621. MachinePointerInfo(Global, 0), Align,
  5622. MachineMemOperand::MOVolatile);
  5623. }
  5624. if (TLI.useStackGuardXorFP())
  5625. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5626. DAG.setRoot(Chain);
  5627. setValue(&I, Res);
  5628. return;
  5629. }
  5630. case Intrinsic::stackprotector: {
  5631. // Emit code into the DAG to store the stack guard onto the stack.
  5632. MachineFunction &MF = DAG.getMachineFunction();
  5633. MachineFrameInfo &MFI = MF.getFrameInfo();
  5634. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5635. SDValue Src, Chain = getRoot();
  5636. if (TLI.useLoadStackGuardNode())
  5637. Src = getLoadStackGuard(DAG, sdl, Chain);
  5638. else
  5639. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5640. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5641. int FI = FuncInfo.StaticAllocaMap[Slot];
  5642. MFI.setStackProtectorIndex(FI);
  5643. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5644. // Store the stack protector onto the stack.
  5645. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5646. DAG.getMachineFunction(), FI),
  5647. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5648. setValue(&I, Res);
  5649. DAG.setRoot(Res);
  5650. return;
  5651. }
  5652. case Intrinsic::objectsize: {
  5653. // If we don't know by now, we're never going to know.
  5654. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5655. assert(CI && "Non-constant type in __builtin_object_size?");
  5656. SDValue Arg = getValue(I.getCalledValue());
  5657. EVT Ty = Arg.getValueType();
  5658. if (CI->isZero())
  5659. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5660. else
  5661. Res = DAG.getConstant(0, sdl, Ty);
  5662. setValue(&I, Res);
  5663. return;
  5664. }
  5665. case Intrinsic::is_constant:
  5666. // If this wasn't constant-folded away by now, then it's not a
  5667. // constant.
  5668. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5669. return;
  5670. case Intrinsic::annotation:
  5671. case Intrinsic::ptr_annotation:
  5672. case Intrinsic::launder_invariant_group:
  5673. case Intrinsic::strip_invariant_group:
  5674. // Drop the intrinsic, but forward the value
  5675. setValue(&I, getValue(I.getOperand(0)));
  5676. return;
  5677. case Intrinsic::assume:
  5678. case Intrinsic::var_annotation:
  5679. case Intrinsic::sideeffect:
  5680. // Discard annotate attributes, assumptions, and artificial side-effects.
  5681. return;
  5682. case Intrinsic::codeview_annotation: {
  5683. // Emit a label associated with this metadata.
  5684. MachineFunction &MF = DAG.getMachineFunction();
  5685. MCSymbol *Label =
  5686. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5687. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5688. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5689. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5690. DAG.setRoot(Res);
  5691. return;
  5692. }
  5693. case Intrinsic::init_trampoline: {
  5694. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5695. SDValue Ops[6];
  5696. Ops[0] = getRoot();
  5697. Ops[1] = getValue(I.getArgOperand(0));
  5698. Ops[2] = getValue(I.getArgOperand(1));
  5699. Ops[3] = getValue(I.getArgOperand(2));
  5700. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5701. Ops[5] = DAG.getSrcValue(F);
  5702. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5703. DAG.setRoot(Res);
  5704. return;
  5705. }
  5706. case Intrinsic::adjust_trampoline:
  5707. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5708. TLI.getPointerTy(DAG.getDataLayout()),
  5709. getValue(I.getArgOperand(0))));
  5710. return;
  5711. case Intrinsic::gcroot: {
  5712. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5713. "only valid in functions with gc specified, enforced by Verifier");
  5714. assert(GFI && "implied by previous");
  5715. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5716. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5717. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5718. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5719. return;
  5720. }
  5721. case Intrinsic::gcread:
  5722. case Intrinsic::gcwrite:
  5723. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5724. case Intrinsic::flt_rounds:
  5725. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5726. return;
  5727. case Intrinsic::expect:
  5728. // Just replace __builtin_expect(exp, c) with EXP.
  5729. setValue(&I, getValue(I.getArgOperand(0)));
  5730. return;
  5731. case Intrinsic::debugtrap:
  5732. case Intrinsic::trap: {
  5733. StringRef TrapFuncName =
  5734. I.getAttributes()
  5735. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5736. .getValueAsString();
  5737. if (TrapFuncName.empty()) {
  5738. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5739. ISD::TRAP : ISD::DEBUGTRAP;
  5740. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5741. return;
  5742. }
  5743. TargetLowering::ArgListTy Args;
  5744. TargetLowering::CallLoweringInfo CLI(DAG);
  5745. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5746. CallingConv::C, I.getType(),
  5747. DAG.getExternalSymbol(TrapFuncName.data(),
  5748. TLI.getPointerTy(DAG.getDataLayout())),
  5749. std::move(Args));
  5750. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5751. DAG.setRoot(Result.second);
  5752. return;
  5753. }
  5754. case Intrinsic::uadd_with_overflow:
  5755. case Intrinsic::sadd_with_overflow:
  5756. case Intrinsic::usub_with_overflow:
  5757. case Intrinsic::ssub_with_overflow:
  5758. case Intrinsic::umul_with_overflow:
  5759. case Intrinsic::smul_with_overflow: {
  5760. ISD::NodeType Op;
  5761. switch (Intrinsic) {
  5762. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5763. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5764. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5765. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5766. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5767. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5768. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5769. }
  5770. SDValue Op1 = getValue(I.getArgOperand(0));
  5771. SDValue Op2 = getValue(I.getArgOperand(1));
  5772. EVT ResultVT = Op1.getValueType();
  5773. EVT OverflowVT = MVT::i1;
  5774. if (ResultVT.isVector())
  5775. OverflowVT = EVT::getVectorVT(
  5776. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5777. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5778. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5779. return;
  5780. }
  5781. case Intrinsic::prefetch: {
  5782. SDValue Ops[5];
  5783. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5784. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5785. Ops[0] = DAG.getRoot();
  5786. Ops[1] = getValue(I.getArgOperand(0));
  5787. Ops[2] = getValue(I.getArgOperand(1));
  5788. Ops[3] = getValue(I.getArgOperand(2));
  5789. Ops[4] = getValue(I.getArgOperand(3));
  5790. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5791. DAG.getVTList(MVT::Other), Ops,
  5792. EVT::getIntegerVT(*Context, 8),
  5793. MachinePointerInfo(I.getArgOperand(0)),
  5794. 0, /* align */
  5795. Flags);
  5796. // Chain the prefetch in parallell with any pending loads, to stay out of
  5797. // the way of later optimizations.
  5798. PendingLoads.push_back(Result);
  5799. Result = getRoot();
  5800. DAG.setRoot(Result);
  5801. return;
  5802. }
  5803. case Intrinsic::lifetime_start:
  5804. case Intrinsic::lifetime_end: {
  5805. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5806. // Stack coloring is not enabled in O0, discard region information.
  5807. if (TM.getOptLevel() == CodeGenOpt::None)
  5808. return;
  5809. const int64_t ObjectSize =
  5810. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5811. Value *const ObjectPtr = I.getArgOperand(1);
  5812. SmallVector<const Value *, 4> Allocas;
  5813. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5814. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5815. E = Allocas.end(); Object != E; ++Object) {
  5816. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5817. // Could not find an Alloca.
  5818. if (!LifetimeObject)
  5819. continue;
  5820. // First check that the Alloca is static, otherwise it won't have a
  5821. // valid frame index.
  5822. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5823. if (SI == FuncInfo.StaticAllocaMap.end())
  5824. return;
  5825. const int FrameIndex = SI->second;
  5826. int64_t Offset;
  5827. if (GetPointerBaseWithConstantOffset(
  5828. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5829. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5830. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5831. Offset);
  5832. DAG.setRoot(Res);
  5833. }
  5834. return;
  5835. }
  5836. case Intrinsic::invariant_start:
  5837. // Discard region information.
  5838. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5839. return;
  5840. case Intrinsic::invariant_end:
  5841. // Discard region information.
  5842. return;
  5843. case Intrinsic::clear_cache:
  5844. /// FunctionName may be null.
  5845. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5846. lowerCallToExternalSymbol(I, FunctionName);
  5847. return;
  5848. case Intrinsic::donothing:
  5849. // ignore
  5850. return;
  5851. case Intrinsic::experimental_stackmap:
  5852. visitStackmap(I);
  5853. return;
  5854. case Intrinsic::experimental_patchpoint_void:
  5855. case Intrinsic::experimental_patchpoint_i64:
  5856. visitPatchpoint(&I);
  5857. return;
  5858. case Intrinsic::experimental_gc_statepoint:
  5859. LowerStatepoint(ImmutableStatepoint(&I));
  5860. return;
  5861. case Intrinsic::experimental_gc_result:
  5862. visitGCResult(cast<GCResultInst>(I));
  5863. return;
  5864. case Intrinsic::experimental_gc_relocate:
  5865. visitGCRelocate(cast<GCRelocateInst>(I));
  5866. return;
  5867. case Intrinsic::instrprof_increment:
  5868. llvm_unreachable("instrprof failed to lower an increment");
  5869. case Intrinsic::instrprof_value_profile:
  5870. llvm_unreachable("instrprof failed to lower a value profiling call");
  5871. case Intrinsic::localescape: {
  5872. MachineFunction &MF = DAG.getMachineFunction();
  5873. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5874. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5875. // is the same on all targets.
  5876. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5877. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5878. if (isa<ConstantPointerNull>(Arg))
  5879. continue; // Skip null pointers. They represent a hole in index space.
  5880. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5881. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5882. "can only escape static allocas");
  5883. int FI = FuncInfo.StaticAllocaMap[Slot];
  5884. MCSymbol *FrameAllocSym =
  5885. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5886. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5887. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5888. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5889. .addSym(FrameAllocSym)
  5890. .addFrameIndex(FI);
  5891. }
  5892. return;
  5893. }
  5894. case Intrinsic::localrecover: {
  5895. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5896. MachineFunction &MF = DAG.getMachineFunction();
  5897. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5898. // Get the symbol that defines the frame offset.
  5899. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5900. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5901. unsigned IdxVal =
  5902. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5903. MCSymbol *FrameAllocSym =
  5904. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5905. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5906. // Create a MCSymbol for the label to avoid any target lowering
  5907. // that would make this PC relative.
  5908. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5909. SDValue OffsetVal =
  5910. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5911. // Add the offset to the FP.
  5912. Value *FP = I.getArgOperand(1);
  5913. SDValue FPVal = getValue(FP);
  5914. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5915. setValue(&I, Add);
  5916. return;
  5917. }
  5918. case Intrinsic::eh_exceptionpointer:
  5919. case Intrinsic::eh_exceptioncode: {
  5920. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5921. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5922. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5923. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5924. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5925. SDValue N =
  5926. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5927. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5928. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5929. setValue(&I, N);
  5930. return;
  5931. }
  5932. case Intrinsic::xray_customevent: {
  5933. // Here we want to make sure that the intrinsic behaves as if it has a
  5934. // specific calling convention, and only for x86_64.
  5935. // FIXME: Support other platforms later.
  5936. const auto &Triple = DAG.getTarget().getTargetTriple();
  5937. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5938. return;
  5939. SDLoc DL = getCurSDLoc();
  5940. SmallVector<SDValue, 8> Ops;
  5941. // We want to say that we always want the arguments in registers.
  5942. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5943. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5944. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5945. SDValue Chain = getRoot();
  5946. Ops.push_back(LogEntryVal);
  5947. Ops.push_back(StrSizeVal);
  5948. Ops.push_back(Chain);
  5949. // We need to enforce the calling convention for the callsite, so that
  5950. // argument ordering is enforced correctly, and that register allocation can
  5951. // see that some registers may be assumed clobbered and have to preserve
  5952. // them across calls to the intrinsic.
  5953. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5954. DL, NodeTys, Ops);
  5955. SDValue patchableNode = SDValue(MN, 0);
  5956. DAG.setRoot(patchableNode);
  5957. setValue(&I, patchableNode);
  5958. return;
  5959. }
  5960. case Intrinsic::xray_typedevent: {
  5961. // Here we want to make sure that the intrinsic behaves as if it has a
  5962. // specific calling convention, and only for x86_64.
  5963. // FIXME: Support other platforms later.
  5964. const auto &Triple = DAG.getTarget().getTargetTriple();
  5965. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5966. return;
  5967. SDLoc DL = getCurSDLoc();
  5968. SmallVector<SDValue, 8> Ops;
  5969. // We want to say that we always want the arguments in registers.
  5970. // It's unclear to me how manipulating the selection DAG here forces callers
  5971. // to provide arguments in registers instead of on the stack.
  5972. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5973. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5974. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5975. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5976. SDValue Chain = getRoot();
  5977. Ops.push_back(LogTypeId);
  5978. Ops.push_back(LogEntryVal);
  5979. Ops.push_back(StrSizeVal);
  5980. Ops.push_back(Chain);
  5981. // We need to enforce the calling convention for the callsite, so that
  5982. // argument ordering is enforced correctly, and that register allocation can
  5983. // see that some registers may be assumed clobbered and have to preserve
  5984. // them across calls to the intrinsic.
  5985. MachineSDNode *MN = DAG.getMachineNode(
  5986. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5987. SDValue patchableNode = SDValue(MN, 0);
  5988. DAG.setRoot(patchableNode);
  5989. setValue(&I, patchableNode);
  5990. return;
  5991. }
  5992. case Intrinsic::experimental_deoptimize:
  5993. LowerDeoptimizeCall(&I);
  5994. return;
  5995. case Intrinsic::experimental_vector_reduce_v2_fadd:
  5996. case Intrinsic::experimental_vector_reduce_v2_fmul:
  5997. case Intrinsic::experimental_vector_reduce_add:
  5998. case Intrinsic::experimental_vector_reduce_mul:
  5999. case Intrinsic::experimental_vector_reduce_and:
  6000. case Intrinsic::experimental_vector_reduce_or:
  6001. case Intrinsic::experimental_vector_reduce_xor:
  6002. case Intrinsic::experimental_vector_reduce_smax:
  6003. case Intrinsic::experimental_vector_reduce_smin:
  6004. case Intrinsic::experimental_vector_reduce_umax:
  6005. case Intrinsic::experimental_vector_reduce_umin:
  6006. case Intrinsic::experimental_vector_reduce_fmax:
  6007. case Intrinsic::experimental_vector_reduce_fmin:
  6008. visitVectorReduce(I, Intrinsic);
  6009. return;
  6010. case Intrinsic::icall_branch_funnel: {
  6011. SmallVector<SDValue, 16> Ops;
  6012. Ops.push_back(getValue(I.getArgOperand(0)));
  6013. int64_t Offset;
  6014. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6015. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6016. if (!Base)
  6017. report_fatal_error(
  6018. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6019. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  6020. struct BranchFunnelTarget {
  6021. int64_t Offset;
  6022. SDValue Target;
  6023. };
  6024. SmallVector<BranchFunnelTarget, 8> Targets;
  6025. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6026. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6027. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6028. if (ElemBase != Base)
  6029. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6030. "to the same GlobalValue");
  6031. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6032. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6033. if (!GA)
  6034. report_fatal_error(
  6035. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6036. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6037. GA->getGlobal(), getCurSDLoc(),
  6038. Val.getValueType(), GA->getOffset())});
  6039. }
  6040. llvm::sort(Targets,
  6041. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6042. return T1.Offset < T2.Offset;
  6043. });
  6044. for (auto &T : Targets) {
  6045. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6046. Ops.push_back(T.Target);
  6047. }
  6048. Ops.push_back(DAG.getRoot()); // Chain
  6049. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6050. getCurSDLoc(), MVT::Other, Ops),
  6051. 0);
  6052. DAG.setRoot(N);
  6053. setValue(&I, N);
  6054. HasTailCall = true;
  6055. return;
  6056. }
  6057. case Intrinsic::wasm_landingpad_index:
  6058. // Information this intrinsic contained has been transferred to
  6059. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6060. // delete it now.
  6061. return;
  6062. case Intrinsic::aarch64_settag:
  6063. case Intrinsic::aarch64_settag_zero: {
  6064. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6065. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6066. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6067. DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
  6068. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6069. ZeroMemory);
  6070. DAG.setRoot(Val);
  6071. setValue(&I, Val);
  6072. return;
  6073. }
  6074. case Intrinsic::ptrmask: {
  6075. SDValue Ptr = getValue(I.getOperand(0));
  6076. SDValue Const = getValue(I.getOperand(1));
  6077. EVT DestVT =
  6078. EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6079. setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
  6080. DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
  6081. return;
  6082. }
  6083. }
  6084. }
  6085. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6086. const ConstrainedFPIntrinsic &FPI) {
  6087. SDLoc sdl = getCurSDLoc();
  6088. unsigned Opcode;
  6089. switch (FPI.getIntrinsicID()) {
  6090. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6091. case Intrinsic::experimental_constrained_fadd:
  6092. Opcode = ISD::STRICT_FADD;
  6093. break;
  6094. case Intrinsic::experimental_constrained_fsub:
  6095. Opcode = ISD::STRICT_FSUB;
  6096. break;
  6097. case Intrinsic::experimental_constrained_fmul:
  6098. Opcode = ISD::STRICT_FMUL;
  6099. break;
  6100. case Intrinsic::experimental_constrained_fdiv:
  6101. Opcode = ISD::STRICT_FDIV;
  6102. break;
  6103. case Intrinsic::experimental_constrained_frem:
  6104. Opcode = ISD::STRICT_FREM;
  6105. break;
  6106. case Intrinsic::experimental_constrained_fma:
  6107. Opcode = ISD::STRICT_FMA;
  6108. break;
  6109. case Intrinsic::experimental_constrained_fptosi:
  6110. Opcode = ISD::STRICT_FP_TO_SINT;
  6111. break;
  6112. case Intrinsic::experimental_constrained_fptoui:
  6113. Opcode = ISD::STRICT_FP_TO_UINT;
  6114. break;
  6115. case Intrinsic::experimental_constrained_fptrunc:
  6116. Opcode = ISD::STRICT_FP_ROUND;
  6117. break;
  6118. case Intrinsic::experimental_constrained_fpext:
  6119. Opcode = ISD::STRICT_FP_EXTEND;
  6120. break;
  6121. case Intrinsic::experimental_constrained_sqrt:
  6122. Opcode = ISD::STRICT_FSQRT;
  6123. break;
  6124. case Intrinsic::experimental_constrained_pow:
  6125. Opcode = ISD::STRICT_FPOW;
  6126. break;
  6127. case Intrinsic::experimental_constrained_powi:
  6128. Opcode = ISD::STRICT_FPOWI;
  6129. break;
  6130. case Intrinsic::experimental_constrained_sin:
  6131. Opcode = ISD::STRICT_FSIN;
  6132. break;
  6133. case Intrinsic::experimental_constrained_cos:
  6134. Opcode = ISD::STRICT_FCOS;
  6135. break;
  6136. case Intrinsic::experimental_constrained_exp:
  6137. Opcode = ISD::STRICT_FEXP;
  6138. break;
  6139. case Intrinsic::experimental_constrained_exp2:
  6140. Opcode = ISD::STRICT_FEXP2;
  6141. break;
  6142. case Intrinsic::experimental_constrained_log:
  6143. Opcode = ISD::STRICT_FLOG;
  6144. break;
  6145. case Intrinsic::experimental_constrained_log10:
  6146. Opcode = ISD::STRICT_FLOG10;
  6147. break;
  6148. case Intrinsic::experimental_constrained_log2:
  6149. Opcode = ISD::STRICT_FLOG2;
  6150. break;
  6151. case Intrinsic::experimental_constrained_rint:
  6152. Opcode = ISD::STRICT_FRINT;
  6153. break;
  6154. case Intrinsic::experimental_constrained_nearbyint:
  6155. Opcode = ISD::STRICT_FNEARBYINT;
  6156. break;
  6157. case Intrinsic::experimental_constrained_maxnum:
  6158. Opcode = ISD::STRICT_FMAXNUM;
  6159. break;
  6160. case Intrinsic::experimental_constrained_minnum:
  6161. Opcode = ISD::STRICT_FMINNUM;
  6162. break;
  6163. case Intrinsic::experimental_constrained_ceil:
  6164. Opcode = ISD::STRICT_FCEIL;
  6165. break;
  6166. case Intrinsic::experimental_constrained_floor:
  6167. Opcode = ISD::STRICT_FFLOOR;
  6168. break;
  6169. case Intrinsic::experimental_constrained_round:
  6170. Opcode = ISD::STRICT_FROUND;
  6171. break;
  6172. case Intrinsic::experimental_constrained_trunc:
  6173. Opcode = ISD::STRICT_FTRUNC;
  6174. break;
  6175. }
  6176. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6177. SDValue Chain = getRoot();
  6178. SmallVector<EVT, 4> ValueVTs;
  6179. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6180. ValueVTs.push_back(MVT::Other); // Out chain
  6181. SDVTList VTs = DAG.getVTList(ValueVTs);
  6182. SDValue Result;
  6183. if (Opcode == ISD::STRICT_FP_ROUND)
  6184. Result = DAG.getNode(Opcode, sdl, VTs,
  6185. { Chain, getValue(FPI.getArgOperand(0)),
  6186. DAG.getTargetConstant(0, sdl,
  6187. TLI.getPointerTy(DAG.getDataLayout())) });
  6188. else if (FPI.isUnaryOp())
  6189. Result = DAG.getNode(Opcode, sdl, VTs,
  6190. { Chain, getValue(FPI.getArgOperand(0)) });
  6191. else if (FPI.isTernaryOp())
  6192. Result = DAG.getNode(Opcode, sdl, VTs,
  6193. { Chain, getValue(FPI.getArgOperand(0)),
  6194. getValue(FPI.getArgOperand(1)),
  6195. getValue(FPI.getArgOperand(2)) });
  6196. else
  6197. Result = DAG.getNode(Opcode, sdl, VTs,
  6198. { Chain, getValue(FPI.getArgOperand(0)),
  6199. getValue(FPI.getArgOperand(1)) });
  6200. if (FPI.getExceptionBehavior() !=
  6201. ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
  6202. SDNodeFlags Flags;
  6203. Flags.setFPExcept(true);
  6204. Result->setFlags(Flags);
  6205. }
  6206. assert(Result.getNode()->getNumValues() == 2);
  6207. SDValue OutChain = Result.getValue(1);
  6208. DAG.setRoot(OutChain);
  6209. SDValue FPResult = Result.getValue(0);
  6210. setValue(&FPI, FPResult);
  6211. }
  6212. std::pair<SDValue, SDValue>
  6213. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6214. const BasicBlock *EHPadBB) {
  6215. MachineFunction &MF = DAG.getMachineFunction();
  6216. MachineModuleInfo &MMI = MF.getMMI();
  6217. MCSymbol *BeginLabel = nullptr;
  6218. if (EHPadBB) {
  6219. // Insert a label before the invoke call to mark the try range. This can be
  6220. // used to detect deletion of the invoke via the MachineModuleInfo.
  6221. BeginLabel = MMI.getContext().createTempSymbol();
  6222. // For SjLj, keep track of which landing pads go with which invokes
  6223. // so as to maintain the ordering of pads in the LSDA.
  6224. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6225. if (CallSiteIndex) {
  6226. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6227. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6228. // Now that the call site is handled, stop tracking it.
  6229. MMI.setCurrentCallSite(0);
  6230. }
  6231. // Both PendingLoads and PendingExports must be flushed here;
  6232. // this call might not return.
  6233. (void)getRoot();
  6234. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6235. CLI.setChain(getRoot());
  6236. }
  6237. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6238. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6239. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6240. "Non-null chain expected with non-tail call!");
  6241. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6242. "Null value expected with tail call!");
  6243. if (!Result.second.getNode()) {
  6244. // As a special case, a null chain means that a tail call has been emitted
  6245. // and the DAG root is already updated.
  6246. HasTailCall = true;
  6247. // Since there's no actual continuation from this block, nothing can be
  6248. // relying on us setting vregs for them.
  6249. PendingExports.clear();
  6250. } else {
  6251. DAG.setRoot(Result.second);
  6252. }
  6253. if (EHPadBB) {
  6254. // Insert a label at the end of the invoke call to mark the try range. This
  6255. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6256. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6257. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6258. // Inform MachineModuleInfo of range.
  6259. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6260. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6261. // actually use outlined funclets and their LSDA info style.
  6262. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6263. assert(CLI.CS);
  6264. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6265. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6266. BeginLabel, EndLabel);
  6267. } else if (!isScopedEHPersonality(Pers)) {
  6268. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6269. }
  6270. }
  6271. return Result;
  6272. }
  6273. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6274. bool isTailCall,
  6275. const BasicBlock *EHPadBB) {
  6276. auto &DL = DAG.getDataLayout();
  6277. FunctionType *FTy = CS.getFunctionType();
  6278. Type *RetTy = CS.getType();
  6279. TargetLowering::ArgListTy Args;
  6280. Args.reserve(CS.arg_size());
  6281. const Value *SwiftErrorVal = nullptr;
  6282. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6283. // We can't tail call inside a function with a swifterror argument. Lowering
  6284. // does not support this yet. It would have to move into the swifterror
  6285. // register before the call.
  6286. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6287. if (TLI.supportSwiftError() &&
  6288. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6289. isTailCall = false;
  6290. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6291. i != e; ++i) {
  6292. TargetLowering::ArgListEntry Entry;
  6293. const Value *V = *i;
  6294. // Skip empty types
  6295. if (V->getType()->isEmptyTy())
  6296. continue;
  6297. SDValue ArgNode = getValue(V);
  6298. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6299. Entry.setAttributes(&CS, i - CS.arg_begin());
  6300. // Use swifterror virtual register as input to the call.
  6301. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6302. SwiftErrorVal = V;
  6303. // We find the virtual register for the actual swifterror argument.
  6304. // Instead of using the Value, we use the virtual register instead.
  6305. Entry.Node = DAG.getRegister(
  6306. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6307. EVT(TLI.getPointerTy(DL)));
  6308. }
  6309. Args.push_back(Entry);
  6310. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6311. // might point to function-local memory), we can't meaningfully tail-call.
  6312. if (Entry.IsSRet && isa<Instruction>(V))
  6313. isTailCall = false;
  6314. }
  6315. // Check if target-independent constraints permit a tail call here.
  6316. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6317. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6318. isTailCall = false;
  6319. // Disable tail calls if there is an swifterror argument. Targets have not
  6320. // been updated to support tail calls.
  6321. if (TLI.supportSwiftError() && SwiftErrorVal)
  6322. isTailCall = false;
  6323. TargetLowering::CallLoweringInfo CLI(DAG);
  6324. CLI.setDebugLoc(getCurSDLoc())
  6325. .setChain(getRoot())
  6326. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6327. .setTailCall(isTailCall)
  6328. .setConvergent(CS.isConvergent());
  6329. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6330. if (Result.first.getNode()) {
  6331. const Instruction *Inst = CS.getInstruction();
  6332. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6333. setValue(Inst, Result.first);
  6334. }
  6335. // The last element of CLI.InVals has the SDValue for swifterror return.
  6336. // Here we copy it to a virtual register and update SwiftErrorMap for
  6337. // book-keeping.
  6338. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6339. // Get the last element of InVals.
  6340. SDValue Src = CLI.InVals.back();
  6341. Register VReg = SwiftError.getOrCreateVRegDefAt(
  6342. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6343. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6344. DAG.setRoot(CopyNode);
  6345. }
  6346. }
  6347. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6348. SelectionDAGBuilder &Builder) {
  6349. // Check to see if this load can be trivially constant folded, e.g. if the
  6350. // input is from a string literal.
  6351. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6352. // Cast pointer to the type we really want to load.
  6353. Type *LoadTy =
  6354. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6355. if (LoadVT.isVector())
  6356. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6357. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6358. PointerType::getUnqual(LoadTy));
  6359. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6360. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6361. return Builder.getValue(LoadCst);
  6362. }
  6363. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6364. // still constant memory, the input chain can be the entry node.
  6365. SDValue Root;
  6366. bool ConstantMemory = false;
  6367. // Do not serialize (non-volatile) loads of constant memory with anything.
  6368. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6369. Root = Builder.DAG.getEntryNode();
  6370. ConstantMemory = true;
  6371. } else {
  6372. // Do not serialize non-volatile loads against each other.
  6373. Root = Builder.DAG.getRoot();
  6374. }
  6375. SDValue Ptr = Builder.getValue(PtrVal);
  6376. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6377. Ptr, MachinePointerInfo(PtrVal),
  6378. /* Alignment = */ 1);
  6379. if (!ConstantMemory)
  6380. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6381. return LoadVal;
  6382. }
  6383. /// Record the value for an instruction that produces an integer result,
  6384. /// converting the type where necessary.
  6385. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6386. SDValue Value,
  6387. bool IsSigned) {
  6388. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6389. I.getType(), true);
  6390. if (IsSigned)
  6391. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6392. else
  6393. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6394. setValue(&I, Value);
  6395. }
  6396. /// See if we can lower a memcmp call into an optimized form. If so, return
  6397. /// true and lower it. Otherwise return false, and it will be lowered like a
  6398. /// normal call.
  6399. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6400. /// correct prototype.
  6401. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6402. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6403. const Value *Size = I.getArgOperand(2);
  6404. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6405. if (CSize && CSize->getZExtValue() == 0) {
  6406. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6407. I.getType(), true);
  6408. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6409. return true;
  6410. }
  6411. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6412. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6413. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6414. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6415. if (Res.first.getNode()) {
  6416. processIntegerCallValue(I, Res.first, true);
  6417. PendingLoads.push_back(Res.second);
  6418. return true;
  6419. }
  6420. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6421. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6422. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6423. return false;
  6424. // If the target has a fast compare for the given size, it will return a
  6425. // preferred load type for that size. Require that the load VT is legal and
  6426. // that the target supports unaligned loads of that type. Otherwise, return
  6427. // INVALID.
  6428. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6429. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6430. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6431. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6432. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6433. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6434. // TODO: Check alignment of src and dest ptrs.
  6435. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6436. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6437. if (!TLI.isTypeLegal(LVT) ||
  6438. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6439. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6440. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6441. }
  6442. return LVT;
  6443. };
  6444. // This turns into unaligned loads. We only do this if the target natively
  6445. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6446. // we'll only produce a small number of byte loads.
  6447. MVT LoadVT;
  6448. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6449. switch (NumBitsToCompare) {
  6450. default:
  6451. return false;
  6452. case 16:
  6453. LoadVT = MVT::i16;
  6454. break;
  6455. case 32:
  6456. LoadVT = MVT::i32;
  6457. break;
  6458. case 64:
  6459. case 128:
  6460. case 256:
  6461. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6462. break;
  6463. }
  6464. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6465. return false;
  6466. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6467. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6468. // Bitcast to a wide integer type if the loads are vectors.
  6469. if (LoadVT.isVector()) {
  6470. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6471. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6472. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6473. }
  6474. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6475. processIntegerCallValue(I, Cmp, false);
  6476. return true;
  6477. }
  6478. /// See if we can lower a memchr call into an optimized form. If so, return
  6479. /// true and lower it. Otherwise return false, and it will be lowered like a
  6480. /// normal call.
  6481. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6482. /// correct prototype.
  6483. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6484. const Value *Src = I.getArgOperand(0);
  6485. const Value *Char = I.getArgOperand(1);
  6486. const Value *Length = I.getArgOperand(2);
  6487. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6488. std::pair<SDValue, SDValue> Res =
  6489. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6490. getValue(Src), getValue(Char), getValue(Length),
  6491. MachinePointerInfo(Src));
  6492. if (Res.first.getNode()) {
  6493. setValue(&I, Res.first);
  6494. PendingLoads.push_back(Res.second);
  6495. return true;
  6496. }
  6497. return false;
  6498. }
  6499. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6500. /// true and lower it. Otherwise return false, and it will be lowered like a
  6501. /// normal call.
  6502. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6503. /// correct prototype.
  6504. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6505. SDValue Dst = getValue(I.getArgOperand(0));
  6506. SDValue Src = getValue(I.getArgOperand(1));
  6507. SDValue Size = getValue(I.getArgOperand(2));
  6508. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6509. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6510. unsigned Align = std::min(DstAlign, SrcAlign);
  6511. if (Align == 0) // Alignment of one or both could not be inferred.
  6512. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6513. bool isVol = false;
  6514. SDLoc sdl = getCurSDLoc();
  6515. // In the mempcpy context we need to pass in a false value for isTailCall
  6516. // because the return pointer needs to be adjusted by the size of
  6517. // the copied memory.
  6518. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6519. false, /*isTailCall=*/false,
  6520. MachinePointerInfo(I.getArgOperand(0)),
  6521. MachinePointerInfo(I.getArgOperand(1)));
  6522. assert(MC.getNode() != nullptr &&
  6523. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6524. DAG.setRoot(MC);
  6525. // Check if Size needs to be truncated or extended.
  6526. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6527. // Adjust return pointer to point just past the last dst byte.
  6528. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6529. Dst, Size);
  6530. setValue(&I, DstPlusSize);
  6531. return true;
  6532. }
  6533. /// See if we can lower a strcpy call into an optimized form. If so, return
  6534. /// true and lower it, otherwise return false and it will be lowered like a
  6535. /// normal call.
  6536. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6537. /// correct prototype.
  6538. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6539. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6540. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6541. std::pair<SDValue, SDValue> Res =
  6542. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6543. getValue(Arg0), getValue(Arg1),
  6544. MachinePointerInfo(Arg0),
  6545. MachinePointerInfo(Arg1), isStpcpy);
  6546. if (Res.first.getNode()) {
  6547. setValue(&I, Res.first);
  6548. DAG.setRoot(Res.second);
  6549. return true;
  6550. }
  6551. return false;
  6552. }
  6553. /// See if we can lower a strcmp call into an optimized form. If so, return
  6554. /// true and lower it, otherwise return false and it will be lowered like a
  6555. /// normal call.
  6556. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6557. /// correct prototype.
  6558. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6559. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6560. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6561. std::pair<SDValue, SDValue> Res =
  6562. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6563. getValue(Arg0), getValue(Arg1),
  6564. MachinePointerInfo(Arg0),
  6565. MachinePointerInfo(Arg1));
  6566. if (Res.first.getNode()) {
  6567. processIntegerCallValue(I, Res.first, true);
  6568. PendingLoads.push_back(Res.second);
  6569. return true;
  6570. }
  6571. return false;
  6572. }
  6573. /// See if we can lower a strlen call into an optimized form. If so, return
  6574. /// true and lower it, otherwise return false and it will be lowered like a
  6575. /// normal call.
  6576. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6577. /// correct prototype.
  6578. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6579. const Value *Arg0 = I.getArgOperand(0);
  6580. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6581. std::pair<SDValue, SDValue> Res =
  6582. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6583. getValue(Arg0), MachinePointerInfo(Arg0));
  6584. if (Res.first.getNode()) {
  6585. processIntegerCallValue(I, Res.first, false);
  6586. PendingLoads.push_back(Res.second);
  6587. return true;
  6588. }
  6589. return false;
  6590. }
  6591. /// See if we can lower a strnlen call into an optimized form. If so, return
  6592. /// true and lower it, otherwise return false and it will be lowered like a
  6593. /// normal call.
  6594. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6595. /// correct prototype.
  6596. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6597. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6598. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6599. std::pair<SDValue, SDValue> Res =
  6600. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6601. getValue(Arg0), getValue(Arg1),
  6602. MachinePointerInfo(Arg0));
  6603. if (Res.first.getNode()) {
  6604. processIntegerCallValue(I, Res.first, false);
  6605. PendingLoads.push_back(Res.second);
  6606. return true;
  6607. }
  6608. return false;
  6609. }
  6610. /// See if we can lower a unary floating-point operation into an SDNode with
  6611. /// the specified Opcode. If so, return true and lower it, otherwise return
  6612. /// false and it will be lowered like a normal call.
  6613. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6614. /// correct prototype.
  6615. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6616. unsigned Opcode) {
  6617. // We already checked this call's prototype; verify it doesn't modify errno.
  6618. if (!I.onlyReadsMemory())
  6619. return false;
  6620. SDValue Tmp = getValue(I.getArgOperand(0));
  6621. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6622. return true;
  6623. }
  6624. /// See if we can lower a binary floating-point operation into an SDNode with
  6625. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6626. /// false, and it will be lowered like a normal call.
  6627. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6628. /// correct prototype.
  6629. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6630. unsigned Opcode) {
  6631. // We already checked this call's prototype; verify it doesn't modify errno.
  6632. if (!I.onlyReadsMemory())
  6633. return false;
  6634. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6635. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6636. EVT VT = Tmp0.getValueType();
  6637. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6638. return true;
  6639. }
  6640. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6641. // Handle inline assembly differently.
  6642. if (isa<InlineAsm>(I.getCalledValue())) {
  6643. visitInlineAsm(&I);
  6644. return;
  6645. }
  6646. if (Function *F = I.getCalledFunction()) {
  6647. if (F->isDeclaration()) {
  6648. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6649. unsigned IID = F->getIntrinsicID();
  6650. if (!IID)
  6651. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6652. IID = II->getIntrinsicID(F);
  6653. if (IID) {
  6654. visitIntrinsicCall(I, IID);
  6655. return;
  6656. }
  6657. }
  6658. // Check for well-known libc/libm calls. If the function is internal, it
  6659. // can't be a library call. Don't do the check if marked as nobuiltin for
  6660. // some reason or the call site requires strict floating point semantics.
  6661. LibFunc Func;
  6662. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6663. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6664. LibInfo->hasOptimizedCodeGen(Func)) {
  6665. switch (Func) {
  6666. default: break;
  6667. case LibFunc_copysign:
  6668. case LibFunc_copysignf:
  6669. case LibFunc_copysignl:
  6670. // We already checked this call's prototype; verify it doesn't modify
  6671. // errno.
  6672. if (I.onlyReadsMemory()) {
  6673. SDValue LHS = getValue(I.getArgOperand(0));
  6674. SDValue RHS = getValue(I.getArgOperand(1));
  6675. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6676. LHS.getValueType(), LHS, RHS));
  6677. return;
  6678. }
  6679. break;
  6680. case LibFunc_fabs:
  6681. case LibFunc_fabsf:
  6682. case LibFunc_fabsl:
  6683. if (visitUnaryFloatCall(I, ISD::FABS))
  6684. return;
  6685. break;
  6686. case LibFunc_fmin:
  6687. case LibFunc_fminf:
  6688. case LibFunc_fminl:
  6689. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6690. return;
  6691. break;
  6692. case LibFunc_fmax:
  6693. case LibFunc_fmaxf:
  6694. case LibFunc_fmaxl:
  6695. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6696. return;
  6697. break;
  6698. case LibFunc_sin:
  6699. case LibFunc_sinf:
  6700. case LibFunc_sinl:
  6701. if (visitUnaryFloatCall(I, ISD::FSIN))
  6702. return;
  6703. break;
  6704. case LibFunc_cos:
  6705. case LibFunc_cosf:
  6706. case LibFunc_cosl:
  6707. if (visitUnaryFloatCall(I, ISD::FCOS))
  6708. return;
  6709. break;
  6710. case LibFunc_sqrt:
  6711. case LibFunc_sqrtf:
  6712. case LibFunc_sqrtl:
  6713. case LibFunc_sqrt_finite:
  6714. case LibFunc_sqrtf_finite:
  6715. case LibFunc_sqrtl_finite:
  6716. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6717. return;
  6718. break;
  6719. case LibFunc_floor:
  6720. case LibFunc_floorf:
  6721. case LibFunc_floorl:
  6722. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6723. return;
  6724. break;
  6725. case LibFunc_nearbyint:
  6726. case LibFunc_nearbyintf:
  6727. case LibFunc_nearbyintl:
  6728. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6729. return;
  6730. break;
  6731. case LibFunc_ceil:
  6732. case LibFunc_ceilf:
  6733. case LibFunc_ceill:
  6734. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6735. return;
  6736. break;
  6737. case LibFunc_rint:
  6738. case LibFunc_rintf:
  6739. case LibFunc_rintl:
  6740. if (visitUnaryFloatCall(I, ISD::FRINT))
  6741. return;
  6742. break;
  6743. case LibFunc_round:
  6744. case LibFunc_roundf:
  6745. case LibFunc_roundl:
  6746. if (visitUnaryFloatCall(I, ISD::FROUND))
  6747. return;
  6748. break;
  6749. case LibFunc_trunc:
  6750. case LibFunc_truncf:
  6751. case LibFunc_truncl:
  6752. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6753. return;
  6754. break;
  6755. case LibFunc_log2:
  6756. case LibFunc_log2f:
  6757. case LibFunc_log2l:
  6758. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6759. return;
  6760. break;
  6761. case LibFunc_exp2:
  6762. case LibFunc_exp2f:
  6763. case LibFunc_exp2l:
  6764. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6765. return;
  6766. break;
  6767. case LibFunc_memcmp:
  6768. if (visitMemCmpCall(I))
  6769. return;
  6770. break;
  6771. case LibFunc_mempcpy:
  6772. if (visitMemPCpyCall(I))
  6773. return;
  6774. break;
  6775. case LibFunc_memchr:
  6776. if (visitMemChrCall(I))
  6777. return;
  6778. break;
  6779. case LibFunc_strcpy:
  6780. if (visitStrCpyCall(I, false))
  6781. return;
  6782. break;
  6783. case LibFunc_stpcpy:
  6784. if (visitStrCpyCall(I, true))
  6785. return;
  6786. break;
  6787. case LibFunc_strcmp:
  6788. if (visitStrCmpCall(I))
  6789. return;
  6790. break;
  6791. case LibFunc_strlen:
  6792. if (visitStrLenCall(I))
  6793. return;
  6794. break;
  6795. case LibFunc_strnlen:
  6796. if (visitStrNLenCall(I))
  6797. return;
  6798. break;
  6799. }
  6800. }
  6801. }
  6802. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6803. // have to do anything here to lower funclet bundles.
  6804. assert(!I.hasOperandBundlesOtherThan(
  6805. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6806. "Cannot lower calls with arbitrary operand bundles!");
  6807. SDValue Callee = getValue(I.getCalledValue());
  6808. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6809. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6810. else
  6811. // Check if we can potentially perform a tail call. More detailed checking
  6812. // is be done within LowerCallTo, after more information about the call is
  6813. // known.
  6814. LowerCallTo(&I, Callee, I.isTailCall());
  6815. }
  6816. namespace {
  6817. /// AsmOperandInfo - This contains information for each constraint that we are
  6818. /// lowering.
  6819. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6820. public:
  6821. /// CallOperand - If this is the result output operand or a clobber
  6822. /// this is null, otherwise it is the incoming operand to the CallInst.
  6823. /// This gets modified as the asm is processed.
  6824. SDValue CallOperand;
  6825. /// AssignedRegs - If this is a register or register class operand, this
  6826. /// contains the set of register corresponding to the operand.
  6827. RegsForValue AssignedRegs;
  6828. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6829. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6830. }
  6831. /// Whether or not this operand accesses memory
  6832. bool hasMemory(const TargetLowering &TLI) const {
  6833. // Indirect operand accesses access memory.
  6834. if (isIndirect)
  6835. return true;
  6836. for (const auto &Code : Codes)
  6837. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6838. return true;
  6839. return false;
  6840. }
  6841. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6842. /// corresponds to. If there is no Value* for this operand, it returns
  6843. /// MVT::Other.
  6844. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6845. const DataLayout &DL) const {
  6846. if (!CallOperandVal) return MVT::Other;
  6847. if (isa<BasicBlock>(CallOperandVal))
  6848. return TLI.getPointerTy(DL);
  6849. llvm::Type *OpTy = CallOperandVal->getType();
  6850. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6851. // If this is an indirect operand, the operand is a pointer to the
  6852. // accessed type.
  6853. if (isIndirect) {
  6854. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6855. if (!PtrTy)
  6856. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6857. OpTy = PtrTy->getElementType();
  6858. }
  6859. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6860. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6861. if (STy->getNumElements() == 1)
  6862. OpTy = STy->getElementType(0);
  6863. // If OpTy is not a single value, it may be a struct/union that we
  6864. // can tile with integers.
  6865. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6866. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6867. switch (BitSize) {
  6868. default: break;
  6869. case 1:
  6870. case 8:
  6871. case 16:
  6872. case 32:
  6873. case 64:
  6874. case 128:
  6875. OpTy = IntegerType::get(Context, BitSize);
  6876. break;
  6877. }
  6878. }
  6879. return TLI.getValueType(DL, OpTy, true);
  6880. }
  6881. };
  6882. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6883. } // end anonymous namespace
  6884. /// Make sure that the output operand \p OpInfo and its corresponding input
  6885. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6886. /// out).
  6887. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6888. SDISelAsmOperandInfo &MatchingOpInfo,
  6889. SelectionDAG &DAG) {
  6890. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6891. return;
  6892. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6893. const auto &TLI = DAG.getTargetLoweringInfo();
  6894. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6895. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6896. OpInfo.ConstraintVT);
  6897. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6898. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6899. MatchingOpInfo.ConstraintVT);
  6900. if ((OpInfo.ConstraintVT.isInteger() !=
  6901. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6902. (MatchRC.second != InputRC.second)) {
  6903. // FIXME: error out in a more elegant fashion
  6904. report_fatal_error("Unsupported asm: input constraint"
  6905. " with a matching output constraint of"
  6906. " incompatible type!");
  6907. }
  6908. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6909. }
  6910. /// Get a direct memory input to behave well as an indirect operand.
  6911. /// This may introduce stores, hence the need for a \p Chain.
  6912. /// \return The (possibly updated) chain.
  6913. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6914. SDISelAsmOperandInfo &OpInfo,
  6915. SelectionDAG &DAG) {
  6916. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6917. // If we don't have an indirect input, put it in the constpool if we can,
  6918. // otherwise spill it to a stack slot.
  6919. // TODO: This isn't quite right. We need to handle these according to
  6920. // the addressing mode that the constraint wants. Also, this may take
  6921. // an additional register for the computation and we don't want that
  6922. // either.
  6923. // If the operand is a float, integer, or vector constant, spill to a
  6924. // constant pool entry to get its address.
  6925. const Value *OpVal = OpInfo.CallOperandVal;
  6926. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6927. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6928. OpInfo.CallOperand = DAG.getConstantPool(
  6929. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6930. return Chain;
  6931. }
  6932. // Otherwise, create a stack slot and emit a store to it before the asm.
  6933. Type *Ty = OpVal->getType();
  6934. auto &DL = DAG.getDataLayout();
  6935. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6936. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6937. MachineFunction &MF = DAG.getMachineFunction();
  6938. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6939. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6940. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6941. MachinePointerInfo::getFixedStack(MF, SSFI),
  6942. TLI.getMemValueType(DL, Ty));
  6943. OpInfo.CallOperand = StackSlot;
  6944. return Chain;
  6945. }
  6946. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6947. /// specified operand. We prefer to assign virtual registers, to allow the
  6948. /// register allocator to handle the assignment process. However, if the asm
  6949. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6950. /// allocation. This produces generally horrible, but correct, code.
  6951. ///
  6952. /// OpInfo describes the operand
  6953. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6954. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6955. SDISelAsmOperandInfo &OpInfo,
  6956. SDISelAsmOperandInfo &RefOpInfo) {
  6957. LLVMContext &Context = *DAG.getContext();
  6958. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6959. MachineFunction &MF = DAG.getMachineFunction();
  6960. SmallVector<unsigned, 4> Regs;
  6961. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6962. // No work to do for memory operations.
  6963. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6964. return;
  6965. // If this is a constraint for a single physreg, or a constraint for a
  6966. // register class, find it.
  6967. unsigned AssignedReg;
  6968. const TargetRegisterClass *RC;
  6969. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6970. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6971. // RC is unset only on failure. Return immediately.
  6972. if (!RC)
  6973. return;
  6974. // Get the actual register value type. This is important, because the user
  6975. // may have asked for (e.g.) the AX register in i32 type. We need to
  6976. // remember that AX is actually i16 to get the right extension.
  6977. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6978. if (OpInfo.ConstraintVT != MVT::Other) {
  6979. // If this is an FP operand in an integer register (or visa versa), or more
  6980. // generally if the operand value disagrees with the register class we plan
  6981. // to stick it in, fix the operand type.
  6982. //
  6983. // If this is an input value, the bitcast to the new type is done now.
  6984. // Bitcast for output value is done at the end of visitInlineAsm().
  6985. if ((OpInfo.Type == InlineAsm::isOutput ||
  6986. OpInfo.Type == InlineAsm::isInput) &&
  6987. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6988. // Try to convert to the first EVT that the reg class contains. If the
  6989. // types are identical size, use a bitcast to convert (e.g. two differing
  6990. // vector types). Note: output bitcast is done at the end of
  6991. // visitInlineAsm().
  6992. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6993. // Exclude indirect inputs while they are unsupported because the code
  6994. // to perform the load is missing and thus OpInfo.CallOperand still
  6995. // refers to the input address rather than the pointed-to value.
  6996. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6997. OpInfo.CallOperand =
  6998. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6999. OpInfo.ConstraintVT = RegVT;
  7000. // If the operand is an FP value and we want it in integer registers,
  7001. // use the corresponding integer type. This turns an f64 value into
  7002. // i64, which can be passed with two i32 values on a 32-bit machine.
  7003. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7004. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7005. if (OpInfo.Type == InlineAsm::isInput)
  7006. OpInfo.CallOperand =
  7007. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7008. OpInfo.ConstraintVT = VT;
  7009. }
  7010. }
  7011. }
  7012. // No need to allocate a matching input constraint since the constraint it's
  7013. // matching to has already been allocated.
  7014. if (OpInfo.isMatchingInputConstraint())
  7015. return;
  7016. EVT ValueVT = OpInfo.ConstraintVT;
  7017. if (OpInfo.ConstraintVT == MVT::Other)
  7018. ValueVT = RegVT;
  7019. // Initialize NumRegs.
  7020. unsigned NumRegs = 1;
  7021. if (OpInfo.ConstraintVT != MVT::Other)
  7022. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  7023. // If this is a constraint for a specific physical register, like {r17},
  7024. // assign it now.
  7025. // If this associated to a specific register, initialize iterator to correct
  7026. // place. If virtual, make sure we have enough registers
  7027. // Initialize iterator if necessary
  7028. TargetRegisterClass::iterator I = RC->begin();
  7029. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7030. // Do not check for single registers.
  7031. if (AssignedReg) {
  7032. for (; *I != AssignedReg; ++I)
  7033. assert(I != RC->end() && "AssignedReg should be member of RC");
  7034. }
  7035. for (; NumRegs; --NumRegs, ++I) {
  7036. assert(I != RC->end() && "Ran out of registers to allocate!");
  7037. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7038. Regs.push_back(R);
  7039. }
  7040. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7041. }
  7042. static unsigned
  7043. findMatchingInlineAsmOperand(unsigned OperandNo,
  7044. const std::vector<SDValue> &AsmNodeOperands) {
  7045. // Scan until we find the definition we already emitted of this operand.
  7046. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7047. for (; OperandNo; --OperandNo) {
  7048. // Advance to the next operand.
  7049. unsigned OpFlag =
  7050. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7051. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7052. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7053. InlineAsm::isMemKind(OpFlag)) &&
  7054. "Skipped past definitions?");
  7055. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7056. }
  7057. return CurOp;
  7058. }
  7059. namespace {
  7060. class ExtraFlags {
  7061. unsigned Flags = 0;
  7062. public:
  7063. explicit ExtraFlags(ImmutableCallSite CS) {
  7064. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7065. if (IA->hasSideEffects())
  7066. Flags |= InlineAsm::Extra_HasSideEffects;
  7067. if (IA->isAlignStack())
  7068. Flags |= InlineAsm::Extra_IsAlignStack;
  7069. if (CS.isConvergent())
  7070. Flags |= InlineAsm::Extra_IsConvergent;
  7071. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7072. }
  7073. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7074. // Ideally, we would only check against memory constraints. However, the
  7075. // meaning of an Other constraint can be target-specific and we can't easily
  7076. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7077. // for Other constraints as well.
  7078. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7079. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7080. if (OpInfo.Type == InlineAsm::isInput)
  7081. Flags |= InlineAsm::Extra_MayLoad;
  7082. else if (OpInfo.Type == InlineAsm::isOutput)
  7083. Flags |= InlineAsm::Extra_MayStore;
  7084. else if (OpInfo.Type == InlineAsm::isClobber)
  7085. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7086. }
  7087. }
  7088. unsigned get() const { return Flags; }
  7089. };
  7090. } // end anonymous namespace
  7091. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7092. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7093. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7094. /// ConstraintOperands - Information about all of the constraints.
  7095. SDISelAsmOperandInfoVector ConstraintOperands;
  7096. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7097. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7098. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7099. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7100. // AsmDialect, MayLoad, MayStore).
  7101. bool HasSideEffect = IA->hasSideEffects();
  7102. ExtraFlags ExtraInfo(CS);
  7103. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7104. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7105. for (auto &T : TargetConstraints) {
  7106. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7107. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7108. // Compute the value type for each operand.
  7109. if (OpInfo.Type == InlineAsm::isInput ||
  7110. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7111. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7112. // Process the call argument. BasicBlocks are labels, currently appearing
  7113. // only in asm's.
  7114. const Instruction *I = CS.getInstruction();
  7115. if (isa<CallBrInst>(I) &&
  7116. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7117. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7118. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7119. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7120. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7121. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7122. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7123. } else {
  7124. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7125. }
  7126. OpInfo.ConstraintVT =
  7127. OpInfo
  7128. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7129. .getSimpleVT();
  7130. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7131. // The return value of the call is this value. As such, there is no
  7132. // corresponding argument.
  7133. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7134. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7135. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7136. DAG.getDataLayout(), STy->getElementType(ResNo));
  7137. } else {
  7138. assert(ResNo == 0 && "Asm only has one result!");
  7139. OpInfo.ConstraintVT =
  7140. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7141. }
  7142. ++ResNo;
  7143. } else {
  7144. OpInfo.ConstraintVT = MVT::Other;
  7145. }
  7146. if (!HasSideEffect)
  7147. HasSideEffect = OpInfo.hasMemory(TLI);
  7148. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7149. // FIXME: Could we compute this on OpInfo rather than T?
  7150. // Compute the constraint code and ConstraintType to use.
  7151. TLI.ComputeConstraintToUse(T, SDValue());
  7152. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7153. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7154. // We've delayed emitting a diagnostic like the "n" constraint because
  7155. // inlining could cause an integer showing up.
  7156. return emitInlineAsmError(
  7157. CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
  7158. "integer constant expression");
  7159. ExtraInfo.update(T);
  7160. }
  7161. // We won't need to flush pending loads if this asm doesn't touch
  7162. // memory and is nonvolatile.
  7163. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7164. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7165. if (IsCallBr) {
  7166. // If this is a callbr we need to flush pending exports since inlineasm_br
  7167. // is a terminator. We need to do this before nodes are glued to
  7168. // the inlineasm_br node.
  7169. Chain = getControlRoot();
  7170. }
  7171. // Second pass over the constraints: compute which constraint option to use.
  7172. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7173. // If this is an output operand with a matching input operand, look up the
  7174. // matching input. If their types mismatch, e.g. one is an integer, the
  7175. // other is floating point, or their sizes are different, flag it as an
  7176. // error.
  7177. if (OpInfo.hasMatchingInput()) {
  7178. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7179. patchMatchingInput(OpInfo, Input, DAG);
  7180. }
  7181. // Compute the constraint code and ConstraintType to use.
  7182. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7183. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7184. OpInfo.Type == InlineAsm::isClobber)
  7185. continue;
  7186. // If this is a memory input, and if the operand is not indirect, do what we
  7187. // need to provide an address for the memory input.
  7188. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7189. !OpInfo.isIndirect) {
  7190. assert((OpInfo.isMultipleAlternative ||
  7191. (OpInfo.Type == InlineAsm::isInput)) &&
  7192. "Can only indirectify direct input operands!");
  7193. // Memory operands really want the address of the value.
  7194. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7195. // There is no longer a Value* corresponding to this operand.
  7196. OpInfo.CallOperandVal = nullptr;
  7197. // It is now an indirect operand.
  7198. OpInfo.isIndirect = true;
  7199. }
  7200. }
  7201. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7202. std::vector<SDValue> AsmNodeOperands;
  7203. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7204. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7205. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7206. // If we have a !srcloc metadata node associated with it, we want to attach
  7207. // this to the ultimately generated inline asm machineinstr. To do this, we
  7208. // pass in the third operand as this (potentially null) inline asm MDNode.
  7209. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7210. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7211. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7212. // bits as operand 3.
  7213. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7214. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7215. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7216. // this, assign virtual and physical registers for inputs and otput.
  7217. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7218. // Assign Registers.
  7219. SDISelAsmOperandInfo &RefOpInfo =
  7220. OpInfo.isMatchingInputConstraint()
  7221. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7222. : OpInfo;
  7223. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7224. switch (OpInfo.Type) {
  7225. case InlineAsm::isOutput:
  7226. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7227. ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7228. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7229. OpInfo.isIndirect)) {
  7230. unsigned ConstraintID =
  7231. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7232. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7233. "Failed to convert memory constraint code to constraint id.");
  7234. // Add information to the INLINEASM node to know about this output.
  7235. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7236. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7237. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7238. MVT::i32));
  7239. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7240. break;
  7241. } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7242. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7243. !OpInfo.isIndirect) ||
  7244. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7245. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7246. // Otherwise, this outputs to a register (directly for C_Register /
  7247. // C_RegisterClass, and a target-defined fashion for
  7248. // C_Immediate/C_Other). Find a register that we can use.
  7249. if (OpInfo.AssignedRegs.Regs.empty()) {
  7250. emitInlineAsmError(
  7251. CS, "couldn't allocate output register for constraint '" +
  7252. Twine(OpInfo.ConstraintCode) + "'");
  7253. return;
  7254. }
  7255. // Add information to the INLINEASM node to know that this register is
  7256. // set.
  7257. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7258. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7259. : InlineAsm::Kind_RegDef,
  7260. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7261. }
  7262. break;
  7263. case InlineAsm::isInput: {
  7264. SDValue InOperandVal = OpInfo.CallOperand;
  7265. if (OpInfo.isMatchingInputConstraint()) {
  7266. // If this is required to match an output register we have already set,
  7267. // just use its register.
  7268. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7269. AsmNodeOperands);
  7270. unsigned OpFlag =
  7271. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7272. if (InlineAsm::isRegDefKind(OpFlag) ||
  7273. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7274. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7275. if (OpInfo.isIndirect) {
  7276. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7277. emitInlineAsmError(CS, "inline asm not supported yet:"
  7278. " don't know how to handle tied "
  7279. "indirect register inputs");
  7280. return;
  7281. }
  7282. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7283. SmallVector<unsigned, 4> Regs;
  7284. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7285. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7286. MachineRegisterInfo &RegInfo =
  7287. DAG.getMachineFunction().getRegInfo();
  7288. for (unsigned i = 0; i != NumRegs; ++i)
  7289. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7290. } else {
  7291. emitInlineAsmError(CS, "inline asm error: This value type register "
  7292. "class is not natively supported!");
  7293. return;
  7294. }
  7295. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7296. SDLoc dl = getCurSDLoc();
  7297. // Use the produced MatchedRegs object to
  7298. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7299. CS.getInstruction());
  7300. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7301. true, OpInfo.getMatchedOperand(), dl,
  7302. DAG, AsmNodeOperands);
  7303. break;
  7304. }
  7305. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7306. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7307. "Unexpected number of operands");
  7308. // Add information to the INLINEASM node to know about this input.
  7309. // See InlineAsm.h isUseOperandTiedToDef.
  7310. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7311. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7312. OpInfo.getMatchedOperand());
  7313. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7314. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7315. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7316. break;
  7317. }
  7318. // Treat indirect 'X' constraint as memory.
  7319. if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7320. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7321. OpInfo.isIndirect)
  7322. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7323. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7324. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7325. std::vector<SDValue> Ops;
  7326. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7327. Ops, DAG);
  7328. if (Ops.empty()) {
  7329. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  7330. if (isa<ConstantSDNode>(InOperandVal)) {
  7331. emitInlineAsmError(CS, "value out of range for constraint '" +
  7332. Twine(OpInfo.ConstraintCode) + "'");
  7333. return;
  7334. }
  7335. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7336. Twine(OpInfo.ConstraintCode) + "'");
  7337. return;
  7338. }
  7339. // Add information to the INLINEASM node to know about this input.
  7340. unsigned ResOpType =
  7341. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7342. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7343. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7344. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7345. break;
  7346. }
  7347. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7348. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7349. assert(InOperandVal.getValueType() ==
  7350. TLI.getPointerTy(DAG.getDataLayout()) &&
  7351. "Memory operands expect pointer values");
  7352. unsigned ConstraintID =
  7353. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7354. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7355. "Failed to convert memory constraint code to constraint id.");
  7356. // Add information to the INLINEASM node to know about this input.
  7357. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7358. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7359. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7360. getCurSDLoc(),
  7361. MVT::i32));
  7362. AsmNodeOperands.push_back(InOperandVal);
  7363. break;
  7364. }
  7365. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7366. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7367. OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
  7368. "Unknown constraint type!");
  7369. // TODO: Support this.
  7370. if (OpInfo.isIndirect) {
  7371. emitInlineAsmError(
  7372. CS, "Don't know how to handle indirect register inputs yet "
  7373. "for constraint '" +
  7374. Twine(OpInfo.ConstraintCode) + "'");
  7375. return;
  7376. }
  7377. // Copy the input into the appropriate registers.
  7378. if (OpInfo.AssignedRegs.Regs.empty()) {
  7379. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7380. Twine(OpInfo.ConstraintCode) + "'");
  7381. return;
  7382. }
  7383. SDLoc dl = getCurSDLoc();
  7384. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7385. Chain, &Flag, CS.getInstruction());
  7386. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7387. dl, DAG, AsmNodeOperands);
  7388. break;
  7389. }
  7390. case InlineAsm::isClobber:
  7391. // Add the clobbered value to the operand list, so that the register
  7392. // allocator is aware that the physreg got clobbered.
  7393. if (!OpInfo.AssignedRegs.Regs.empty())
  7394. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7395. false, 0, getCurSDLoc(), DAG,
  7396. AsmNodeOperands);
  7397. break;
  7398. }
  7399. }
  7400. // Finish up input operands. Set the input chain and add the flag last.
  7401. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7402. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7403. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7404. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7405. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7406. Flag = Chain.getValue(1);
  7407. // Do additional work to generate outputs.
  7408. SmallVector<EVT, 1> ResultVTs;
  7409. SmallVector<SDValue, 1> ResultValues;
  7410. SmallVector<SDValue, 8> OutChains;
  7411. llvm::Type *CSResultType = CS.getType();
  7412. ArrayRef<Type *> ResultTypes;
  7413. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7414. ResultTypes = StructResult->elements();
  7415. else if (!CSResultType->isVoidTy())
  7416. ResultTypes = makeArrayRef(CSResultType);
  7417. auto CurResultType = ResultTypes.begin();
  7418. auto handleRegAssign = [&](SDValue V) {
  7419. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7420. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7421. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7422. ++CurResultType;
  7423. // If the type of the inline asm call site return value is different but has
  7424. // same size as the type of the asm output bitcast it. One example of this
  7425. // is for vectors with different width / number of elements. This can
  7426. // happen for register classes that can contain multiple different value
  7427. // types. The preg or vreg allocated may not have the same VT as was
  7428. // expected.
  7429. //
  7430. // This can also happen for a return value that disagrees with the register
  7431. // class it is put in, eg. a double in a general-purpose register on a
  7432. // 32-bit machine.
  7433. if (ResultVT != V.getValueType() &&
  7434. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7435. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7436. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7437. V.getValueType().isInteger()) {
  7438. // If a result value was tied to an input value, the computed result
  7439. // may have a wider width than the expected result. Extract the
  7440. // relevant portion.
  7441. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7442. }
  7443. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7444. ResultVTs.push_back(ResultVT);
  7445. ResultValues.push_back(V);
  7446. };
  7447. // Deal with output operands.
  7448. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7449. if (OpInfo.Type == InlineAsm::isOutput) {
  7450. SDValue Val;
  7451. // Skip trivial output operands.
  7452. if (OpInfo.AssignedRegs.Regs.empty())
  7453. continue;
  7454. switch (OpInfo.ConstraintType) {
  7455. case TargetLowering::C_Register:
  7456. case TargetLowering::C_RegisterClass:
  7457. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7458. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7459. break;
  7460. case TargetLowering::C_Immediate:
  7461. case TargetLowering::C_Other:
  7462. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7463. OpInfo, DAG);
  7464. break;
  7465. case TargetLowering::C_Memory:
  7466. break; // Already handled.
  7467. case TargetLowering::C_Unknown:
  7468. assert(false && "Unexpected unknown constraint");
  7469. }
  7470. // Indirect output manifest as stores. Record output chains.
  7471. if (OpInfo.isIndirect) {
  7472. const Value *Ptr = OpInfo.CallOperandVal;
  7473. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7474. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7475. MachinePointerInfo(Ptr));
  7476. OutChains.push_back(Store);
  7477. } else {
  7478. // generate CopyFromRegs to associated registers.
  7479. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7480. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7481. for (const SDValue &V : Val->op_values())
  7482. handleRegAssign(V);
  7483. } else
  7484. handleRegAssign(Val);
  7485. }
  7486. }
  7487. }
  7488. // Set results.
  7489. if (!ResultValues.empty()) {
  7490. assert(CurResultType == ResultTypes.end() &&
  7491. "Mismatch in number of ResultTypes");
  7492. assert(ResultValues.size() == ResultTypes.size() &&
  7493. "Mismatch in number of output operands in asm result");
  7494. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7495. DAG.getVTList(ResultVTs), ResultValues);
  7496. setValue(CS.getInstruction(), V);
  7497. }
  7498. // Collect store chains.
  7499. if (!OutChains.empty())
  7500. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7501. // Only Update Root if inline assembly has a memory effect.
  7502. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7503. DAG.setRoot(Chain);
  7504. }
  7505. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7506. const Twine &Message) {
  7507. LLVMContext &Ctx = *DAG.getContext();
  7508. Ctx.emitError(CS.getInstruction(), Message);
  7509. // Make sure we leave the DAG in a valid state
  7510. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7511. SmallVector<EVT, 1> ValueVTs;
  7512. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7513. if (ValueVTs.empty())
  7514. return;
  7515. SmallVector<SDValue, 1> Ops;
  7516. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7517. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7518. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7519. }
  7520. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7521. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7522. MVT::Other, getRoot(),
  7523. getValue(I.getArgOperand(0)),
  7524. DAG.getSrcValue(I.getArgOperand(0))));
  7525. }
  7526. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7527. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7528. const DataLayout &DL = DAG.getDataLayout();
  7529. SDValue V = DAG.getVAArg(
  7530. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7531. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7532. DL.getABITypeAlignment(I.getType()));
  7533. DAG.setRoot(V.getValue(1));
  7534. if (I.getType()->isPointerTy())
  7535. V = DAG.getPtrExtOrTrunc(
  7536. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7537. setValue(&I, V);
  7538. }
  7539. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7540. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7541. MVT::Other, getRoot(),
  7542. getValue(I.getArgOperand(0)),
  7543. DAG.getSrcValue(I.getArgOperand(0))));
  7544. }
  7545. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7546. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7547. MVT::Other, getRoot(),
  7548. getValue(I.getArgOperand(0)),
  7549. getValue(I.getArgOperand(1)),
  7550. DAG.getSrcValue(I.getArgOperand(0)),
  7551. DAG.getSrcValue(I.getArgOperand(1))));
  7552. }
  7553. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7554. const Instruction &I,
  7555. SDValue Op) {
  7556. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7557. if (!Range)
  7558. return Op;
  7559. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7560. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7561. return Op;
  7562. APInt Lo = CR.getUnsignedMin();
  7563. if (!Lo.isMinValue())
  7564. return Op;
  7565. APInt Hi = CR.getUnsignedMax();
  7566. unsigned Bits = std::max(Hi.getActiveBits(),
  7567. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7568. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7569. SDLoc SL = getCurSDLoc();
  7570. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7571. DAG.getValueType(SmallVT));
  7572. unsigned NumVals = Op.getNode()->getNumValues();
  7573. if (NumVals == 1)
  7574. return ZExt;
  7575. SmallVector<SDValue, 4> Ops;
  7576. Ops.push_back(ZExt);
  7577. for (unsigned I = 1; I != NumVals; ++I)
  7578. Ops.push_back(Op.getValue(I));
  7579. return DAG.getMergeValues(Ops, SL);
  7580. }
  7581. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7582. /// the call being lowered.
  7583. ///
  7584. /// This is a helper for lowering intrinsics that follow a target calling
  7585. /// convention or require stack pointer adjustment. Only a subset of the
  7586. /// intrinsic's operands need to participate in the calling convention.
  7587. void SelectionDAGBuilder::populateCallLoweringInfo(
  7588. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7589. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7590. bool IsPatchPoint) {
  7591. TargetLowering::ArgListTy Args;
  7592. Args.reserve(NumArgs);
  7593. // Populate the argument list.
  7594. // Attributes for args start at offset 1, after the return attribute.
  7595. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7596. ArgI != ArgE; ++ArgI) {
  7597. const Value *V = Call->getOperand(ArgI);
  7598. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7599. TargetLowering::ArgListEntry Entry;
  7600. Entry.Node = getValue(V);
  7601. Entry.Ty = V->getType();
  7602. Entry.setAttributes(Call, ArgI);
  7603. Args.push_back(Entry);
  7604. }
  7605. CLI.setDebugLoc(getCurSDLoc())
  7606. .setChain(getRoot())
  7607. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7608. .setDiscardResult(Call->use_empty())
  7609. .setIsPatchPoint(IsPatchPoint);
  7610. }
  7611. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7612. /// or patchpoint target node's operand list.
  7613. ///
  7614. /// Constants are converted to TargetConstants purely as an optimization to
  7615. /// avoid constant materialization and register allocation.
  7616. ///
  7617. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7618. /// generate addess computation nodes, and so FinalizeISel can convert the
  7619. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7620. /// address materialization and register allocation, but may also be required
  7621. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7622. /// alloca in the entry block, then the runtime may assume that the alloca's
  7623. /// StackMap location can be read immediately after compilation and that the
  7624. /// location is valid at any point during execution (this is similar to the
  7625. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7626. /// only available in a register, then the runtime would need to trap when
  7627. /// execution reaches the StackMap in order to read the alloca's location.
  7628. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7629. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7630. SelectionDAGBuilder &Builder) {
  7631. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7632. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7633. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7634. Ops.push_back(
  7635. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7636. Ops.push_back(
  7637. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7638. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7639. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7640. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7641. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7642. } else
  7643. Ops.push_back(OpVal);
  7644. }
  7645. }
  7646. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7647. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7648. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7649. // [live variables...])
  7650. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7651. SDValue Chain, InFlag, Callee, NullPtr;
  7652. SmallVector<SDValue, 32> Ops;
  7653. SDLoc DL = getCurSDLoc();
  7654. Callee = getValue(CI.getCalledValue());
  7655. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7656. // The stackmap intrinsic only records the live variables (the arguemnts
  7657. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7658. // intrinsic, this won't be lowered to a function call. This means we don't
  7659. // have to worry about calling conventions and target specific lowering code.
  7660. // Instead we perform the call lowering right here.
  7661. //
  7662. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7663. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7664. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7665. //
  7666. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7667. InFlag = Chain.getValue(1);
  7668. // Add the <id> and <numBytes> constants.
  7669. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7670. Ops.push_back(DAG.getTargetConstant(
  7671. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7672. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7673. Ops.push_back(DAG.getTargetConstant(
  7674. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7675. MVT::i32));
  7676. // Push live variables for the stack map.
  7677. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7678. // We are not pushing any register mask info here on the operands list,
  7679. // because the stackmap doesn't clobber anything.
  7680. // Push the chain and the glue flag.
  7681. Ops.push_back(Chain);
  7682. Ops.push_back(InFlag);
  7683. // Create the STACKMAP node.
  7684. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7685. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7686. Chain = SDValue(SM, 0);
  7687. InFlag = Chain.getValue(1);
  7688. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7689. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7690. // Set the root to the target-lowered call chain.
  7691. DAG.setRoot(Chain);
  7692. // Inform the Frame Information that we have a stackmap in this function.
  7693. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7694. }
  7695. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7696. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7697. const BasicBlock *EHPadBB) {
  7698. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7699. // i32 <numBytes>,
  7700. // i8* <target>,
  7701. // i32 <numArgs>,
  7702. // [Args...],
  7703. // [live variables...])
  7704. CallingConv::ID CC = CS.getCallingConv();
  7705. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7706. bool HasDef = !CS->getType()->isVoidTy();
  7707. SDLoc dl = getCurSDLoc();
  7708. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7709. // Handle immediate and symbolic callees.
  7710. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7711. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7712. /*isTarget=*/true);
  7713. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7714. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7715. SDLoc(SymbolicCallee),
  7716. SymbolicCallee->getValueType(0));
  7717. // Get the real number of arguments participating in the call <numArgs>
  7718. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7719. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7720. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7721. // Intrinsics include all meta-operands up to but not including CC.
  7722. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7723. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7724. "Not enough arguments provided to the patchpoint intrinsic");
  7725. // For AnyRegCC the arguments are lowered later on manually.
  7726. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7727. Type *ReturnTy =
  7728. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7729. TargetLowering::CallLoweringInfo CLI(DAG);
  7730. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7731. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7732. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7733. SDNode *CallEnd = Result.second.getNode();
  7734. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7735. CallEnd = CallEnd->getOperand(0).getNode();
  7736. /// Get a call instruction from the call sequence chain.
  7737. /// Tail calls are not allowed.
  7738. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7739. "Expected a callseq node.");
  7740. SDNode *Call = CallEnd->getOperand(0).getNode();
  7741. bool HasGlue = Call->getGluedNode();
  7742. // Replace the target specific call node with the patchable intrinsic.
  7743. SmallVector<SDValue, 8> Ops;
  7744. // Add the <id> and <numBytes> constants.
  7745. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7746. Ops.push_back(DAG.getTargetConstant(
  7747. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7748. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7749. Ops.push_back(DAG.getTargetConstant(
  7750. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7751. MVT::i32));
  7752. // Add the callee.
  7753. Ops.push_back(Callee);
  7754. // Adjust <numArgs> to account for any arguments that have been passed on the
  7755. // stack instead.
  7756. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7757. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7758. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7759. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7760. // Add the calling convention
  7761. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7762. // Add the arguments we omitted previously. The register allocator should
  7763. // place these in any free register.
  7764. if (IsAnyRegCC)
  7765. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7766. Ops.push_back(getValue(CS.getArgument(i)));
  7767. // Push the arguments from the call instruction up to the register mask.
  7768. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7769. Ops.append(Call->op_begin() + 2, e);
  7770. // Push live variables for the stack map.
  7771. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7772. // Push the register mask info.
  7773. if (HasGlue)
  7774. Ops.push_back(*(Call->op_end()-2));
  7775. else
  7776. Ops.push_back(*(Call->op_end()-1));
  7777. // Push the chain (this is originally the first operand of the call, but
  7778. // becomes now the last or second to last operand).
  7779. Ops.push_back(*(Call->op_begin()));
  7780. // Push the glue flag (last operand).
  7781. if (HasGlue)
  7782. Ops.push_back(*(Call->op_end()-1));
  7783. SDVTList NodeTys;
  7784. if (IsAnyRegCC && HasDef) {
  7785. // Create the return types based on the intrinsic definition
  7786. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7787. SmallVector<EVT, 3> ValueVTs;
  7788. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7789. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7790. // There is always a chain and a glue type at the end
  7791. ValueVTs.push_back(MVT::Other);
  7792. ValueVTs.push_back(MVT::Glue);
  7793. NodeTys = DAG.getVTList(ValueVTs);
  7794. } else
  7795. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7796. // Replace the target specific call node with a PATCHPOINT node.
  7797. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7798. dl, NodeTys, Ops);
  7799. // Update the NodeMap.
  7800. if (HasDef) {
  7801. if (IsAnyRegCC)
  7802. setValue(CS.getInstruction(), SDValue(MN, 0));
  7803. else
  7804. setValue(CS.getInstruction(), Result.first);
  7805. }
  7806. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7807. // call sequence. Furthermore the location of the chain and glue can change
  7808. // when the AnyReg calling convention is used and the intrinsic returns a
  7809. // value.
  7810. if (IsAnyRegCC && HasDef) {
  7811. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7812. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7813. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7814. } else
  7815. DAG.ReplaceAllUsesWith(Call, MN);
  7816. DAG.DeleteNode(Call);
  7817. // Inform the Frame Information that we have a patchpoint in this function.
  7818. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7819. }
  7820. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7821. unsigned Intrinsic) {
  7822. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7823. SDValue Op1 = getValue(I.getArgOperand(0));
  7824. SDValue Op2;
  7825. if (I.getNumArgOperands() > 1)
  7826. Op2 = getValue(I.getArgOperand(1));
  7827. SDLoc dl = getCurSDLoc();
  7828. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7829. SDValue Res;
  7830. FastMathFlags FMF;
  7831. if (isa<FPMathOperator>(I))
  7832. FMF = I.getFastMathFlags();
  7833. switch (Intrinsic) {
  7834. case Intrinsic::experimental_vector_reduce_v2_fadd:
  7835. if (FMF.allowReassoc())
  7836. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  7837. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
  7838. else
  7839. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7840. break;
  7841. case Intrinsic::experimental_vector_reduce_v2_fmul:
  7842. if (FMF.allowReassoc())
  7843. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  7844. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
  7845. else
  7846. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7847. break;
  7848. case Intrinsic::experimental_vector_reduce_add:
  7849. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7850. break;
  7851. case Intrinsic::experimental_vector_reduce_mul:
  7852. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7853. break;
  7854. case Intrinsic::experimental_vector_reduce_and:
  7855. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7856. break;
  7857. case Intrinsic::experimental_vector_reduce_or:
  7858. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7859. break;
  7860. case Intrinsic::experimental_vector_reduce_xor:
  7861. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7862. break;
  7863. case Intrinsic::experimental_vector_reduce_smax:
  7864. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7865. break;
  7866. case Intrinsic::experimental_vector_reduce_smin:
  7867. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7868. break;
  7869. case Intrinsic::experimental_vector_reduce_umax:
  7870. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7871. break;
  7872. case Intrinsic::experimental_vector_reduce_umin:
  7873. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7874. break;
  7875. case Intrinsic::experimental_vector_reduce_fmax:
  7876. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7877. break;
  7878. case Intrinsic::experimental_vector_reduce_fmin:
  7879. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7880. break;
  7881. default:
  7882. llvm_unreachable("Unhandled vector reduce intrinsic");
  7883. }
  7884. setValue(&I, Res);
  7885. }
  7886. /// Returns an AttributeList representing the attributes applied to the return
  7887. /// value of the given call.
  7888. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7889. SmallVector<Attribute::AttrKind, 2> Attrs;
  7890. if (CLI.RetSExt)
  7891. Attrs.push_back(Attribute::SExt);
  7892. if (CLI.RetZExt)
  7893. Attrs.push_back(Attribute::ZExt);
  7894. if (CLI.IsInReg)
  7895. Attrs.push_back(Attribute::InReg);
  7896. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7897. Attrs);
  7898. }
  7899. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7900. /// implementation, which just calls LowerCall.
  7901. /// FIXME: When all targets are
  7902. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7903. std::pair<SDValue, SDValue>
  7904. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7905. // Handle the incoming return values from the call.
  7906. CLI.Ins.clear();
  7907. Type *OrigRetTy = CLI.RetTy;
  7908. SmallVector<EVT, 4> RetTys;
  7909. SmallVector<uint64_t, 4> Offsets;
  7910. auto &DL = CLI.DAG.getDataLayout();
  7911. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7912. if (CLI.IsPostTypeLegalization) {
  7913. // If we are lowering a libcall after legalization, split the return type.
  7914. SmallVector<EVT, 4> OldRetTys;
  7915. SmallVector<uint64_t, 4> OldOffsets;
  7916. RetTys.swap(OldRetTys);
  7917. Offsets.swap(OldOffsets);
  7918. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7919. EVT RetVT = OldRetTys[i];
  7920. uint64_t Offset = OldOffsets[i];
  7921. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7922. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7923. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7924. RetTys.append(NumRegs, RegisterVT);
  7925. for (unsigned j = 0; j != NumRegs; ++j)
  7926. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7927. }
  7928. }
  7929. SmallVector<ISD::OutputArg, 4> Outs;
  7930. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7931. bool CanLowerReturn =
  7932. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7933. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7934. SDValue DemoteStackSlot;
  7935. int DemoteStackIdx = -100;
  7936. if (!CanLowerReturn) {
  7937. // FIXME: equivalent assert?
  7938. // assert(!CS.hasInAllocaArgument() &&
  7939. // "sret demotion is incompatible with inalloca");
  7940. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7941. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7942. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7943. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7944. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7945. DL.getAllocaAddrSpace());
  7946. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7947. ArgListEntry Entry;
  7948. Entry.Node = DemoteStackSlot;
  7949. Entry.Ty = StackSlotPtrType;
  7950. Entry.IsSExt = false;
  7951. Entry.IsZExt = false;
  7952. Entry.IsInReg = false;
  7953. Entry.IsSRet = true;
  7954. Entry.IsNest = false;
  7955. Entry.IsByVal = false;
  7956. Entry.IsReturned = false;
  7957. Entry.IsSwiftSelf = false;
  7958. Entry.IsSwiftError = false;
  7959. Entry.Alignment = Align;
  7960. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7961. CLI.NumFixedArgs += 1;
  7962. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7963. // sret demotion isn't compatible with tail-calls, since the sret argument
  7964. // points into the callers stack frame.
  7965. CLI.IsTailCall = false;
  7966. } else {
  7967. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7968. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7969. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7970. ISD::ArgFlagsTy Flags;
  7971. if (NeedsRegBlock) {
  7972. Flags.setInConsecutiveRegs();
  7973. if (I == RetTys.size() - 1)
  7974. Flags.setInConsecutiveRegsLast();
  7975. }
  7976. EVT VT = RetTys[I];
  7977. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7978. CLI.CallConv, VT);
  7979. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7980. CLI.CallConv, VT);
  7981. for (unsigned i = 0; i != NumRegs; ++i) {
  7982. ISD::InputArg MyFlags;
  7983. MyFlags.Flags = Flags;
  7984. MyFlags.VT = RegisterVT;
  7985. MyFlags.ArgVT = VT;
  7986. MyFlags.Used = CLI.IsReturnValueUsed;
  7987. if (CLI.RetTy->isPointerTy()) {
  7988. MyFlags.Flags.setPointer();
  7989. MyFlags.Flags.setPointerAddrSpace(
  7990. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  7991. }
  7992. if (CLI.RetSExt)
  7993. MyFlags.Flags.setSExt();
  7994. if (CLI.RetZExt)
  7995. MyFlags.Flags.setZExt();
  7996. if (CLI.IsInReg)
  7997. MyFlags.Flags.setInReg();
  7998. CLI.Ins.push_back(MyFlags);
  7999. }
  8000. }
  8001. }
  8002. // We push in swifterror return as the last element of CLI.Ins.
  8003. ArgListTy &Args = CLI.getArgs();
  8004. if (supportSwiftError()) {
  8005. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8006. if (Args[i].IsSwiftError) {
  8007. ISD::InputArg MyFlags;
  8008. MyFlags.VT = getPointerTy(DL);
  8009. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8010. MyFlags.Flags.setSwiftError();
  8011. CLI.Ins.push_back(MyFlags);
  8012. }
  8013. }
  8014. }
  8015. // Handle all of the outgoing arguments.
  8016. CLI.Outs.clear();
  8017. CLI.OutVals.clear();
  8018. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8019. SmallVector<EVT, 4> ValueVTs;
  8020. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8021. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8022. Type *FinalType = Args[i].Ty;
  8023. if (Args[i].IsByVal)
  8024. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  8025. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8026. FinalType, CLI.CallConv, CLI.IsVarArg);
  8027. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8028. ++Value) {
  8029. EVT VT = ValueVTs[Value];
  8030. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8031. SDValue Op = SDValue(Args[i].Node.getNode(),
  8032. Args[i].Node.getResNo() + Value);
  8033. ISD::ArgFlagsTy Flags;
  8034. // Certain targets (such as MIPS), may have a different ABI alignment
  8035. // for a type depending on the context. Give the target a chance to
  8036. // specify the alignment it wants.
  8037. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  8038. if (Args[i].Ty->isPointerTy()) {
  8039. Flags.setPointer();
  8040. Flags.setPointerAddrSpace(
  8041. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8042. }
  8043. if (Args[i].IsZExt)
  8044. Flags.setZExt();
  8045. if (Args[i].IsSExt)
  8046. Flags.setSExt();
  8047. if (Args[i].IsInReg) {
  8048. // If we are using vectorcall calling convention, a structure that is
  8049. // passed InReg - is surely an HVA
  8050. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8051. isa<StructType>(FinalType)) {
  8052. // The first value of a structure is marked
  8053. if (0 == Value)
  8054. Flags.setHvaStart();
  8055. Flags.setHva();
  8056. }
  8057. // Set InReg Flag
  8058. Flags.setInReg();
  8059. }
  8060. if (Args[i].IsSRet)
  8061. Flags.setSRet();
  8062. if (Args[i].IsSwiftSelf)
  8063. Flags.setSwiftSelf();
  8064. if (Args[i].IsSwiftError)
  8065. Flags.setSwiftError();
  8066. if (Args[i].IsByVal)
  8067. Flags.setByVal();
  8068. if (Args[i].IsInAlloca) {
  8069. Flags.setInAlloca();
  8070. // Set the byval flag for CCAssignFn callbacks that don't know about
  8071. // inalloca. This way we can know how many bytes we should've allocated
  8072. // and how many bytes a callee cleanup function will pop. If we port
  8073. // inalloca to more targets, we'll have to add custom inalloca handling
  8074. // in the various CC lowering callbacks.
  8075. Flags.setByVal();
  8076. }
  8077. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8078. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8079. Type *ElementTy = Ty->getElementType();
  8080. unsigned FrameSize = DL.getTypeAllocSize(
  8081. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8082. Flags.setByValSize(FrameSize);
  8083. // info is not there but there are cases it cannot get right.
  8084. unsigned FrameAlign;
  8085. if (Args[i].Alignment)
  8086. FrameAlign = Args[i].Alignment;
  8087. else
  8088. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8089. Flags.setByValAlign(FrameAlign);
  8090. }
  8091. if (Args[i].IsNest)
  8092. Flags.setNest();
  8093. if (NeedsRegBlock)
  8094. Flags.setInConsecutiveRegs();
  8095. Flags.setOrigAlign(OriginalAlignment);
  8096. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8097. CLI.CallConv, VT);
  8098. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8099. CLI.CallConv, VT);
  8100. SmallVector<SDValue, 4> Parts(NumParts);
  8101. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8102. if (Args[i].IsSExt)
  8103. ExtendKind = ISD::SIGN_EXTEND;
  8104. else if (Args[i].IsZExt)
  8105. ExtendKind = ISD::ZERO_EXTEND;
  8106. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8107. // for now.
  8108. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8109. CanLowerReturn) {
  8110. assert((CLI.RetTy == Args[i].Ty ||
  8111. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8112. CLI.RetTy->getPointerAddressSpace() ==
  8113. Args[i].Ty->getPointerAddressSpace())) &&
  8114. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8115. // Before passing 'returned' to the target lowering code, ensure that
  8116. // either the register MVT and the actual EVT are the same size or that
  8117. // the return value and argument are extended in the same way; in these
  8118. // cases it's safe to pass the argument register value unchanged as the
  8119. // return register value (although it's at the target's option whether
  8120. // to do so)
  8121. // TODO: allow code generation to take advantage of partially preserved
  8122. // registers rather than clobbering the entire register when the
  8123. // parameter extension method is not compatible with the return
  8124. // extension method
  8125. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8126. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8127. CLI.RetZExt == Args[i].IsZExt))
  8128. Flags.setReturned();
  8129. }
  8130. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8131. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8132. for (unsigned j = 0; j != NumParts; ++j) {
  8133. // if it isn't first piece, alignment must be 1
  8134. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8135. i < CLI.NumFixedArgs,
  8136. i, j*Parts[j].getValueType().getStoreSize());
  8137. if (NumParts > 1 && j == 0)
  8138. MyFlags.Flags.setSplit();
  8139. else if (j != 0) {
  8140. MyFlags.Flags.setOrigAlign(1);
  8141. if (j == NumParts - 1)
  8142. MyFlags.Flags.setSplitEnd();
  8143. }
  8144. CLI.Outs.push_back(MyFlags);
  8145. CLI.OutVals.push_back(Parts[j]);
  8146. }
  8147. if (NeedsRegBlock && Value == NumValues - 1)
  8148. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8149. }
  8150. }
  8151. SmallVector<SDValue, 4> InVals;
  8152. CLI.Chain = LowerCall(CLI, InVals);
  8153. // Update CLI.InVals to use outside of this function.
  8154. CLI.InVals = InVals;
  8155. // Verify that the target's LowerCall behaved as expected.
  8156. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8157. "LowerCall didn't return a valid chain!");
  8158. assert((!CLI.IsTailCall || InVals.empty()) &&
  8159. "LowerCall emitted a return value for a tail call!");
  8160. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8161. "LowerCall didn't emit the correct number of values!");
  8162. // For a tail call, the return value is merely live-out and there aren't
  8163. // any nodes in the DAG representing it. Return a special value to
  8164. // indicate that a tail call has been emitted and no more Instructions
  8165. // should be processed in the current block.
  8166. if (CLI.IsTailCall) {
  8167. CLI.DAG.setRoot(CLI.Chain);
  8168. return std::make_pair(SDValue(), SDValue());
  8169. }
  8170. #ifndef NDEBUG
  8171. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8172. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8173. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8174. "LowerCall emitted a value with the wrong type!");
  8175. }
  8176. #endif
  8177. SmallVector<SDValue, 4> ReturnValues;
  8178. if (!CanLowerReturn) {
  8179. // The instruction result is the result of loading from the
  8180. // hidden sret parameter.
  8181. SmallVector<EVT, 1> PVTs;
  8182. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8183. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8184. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8185. EVT PtrVT = PVTs[0];
  8186. unsigned NumValues = RetTys.size();
  8187. ReturnValues.resize(NumValues);
  8188. SmallVector<SDValue, 4> Chains(NumValues);
  8189. // An aggregate return value cannot wrap around the address space, so
  8190. // offsets to its parts don't wrap either.
  8191. SDNodeFlags Flags;
  8192. Flags.setNoUnsignedWrap(true);
  8193. for (unsigned i = 0; i < NumValues; ++i) {
  8194. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8195. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8196. PtrVT), Flags);
  8197. SDValue L = CLI.DAG.getLoad(
  8198. RetTys[i], CLI.DL, CLI.Chain, Add,
  8199. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8200. DemoteStackIdx, Offsets[i]),
  8201. /* Alignment = */ 1);
  8202. ReturnValues[i] = L;
  8203. Chains[i] = L.getValue(1);
  8204. }
  8205. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8206. } else {
  8207. // Collect the legal value parts into potentially illegal values
  8208. // that correspond to the original function's return values.
  8209. Optional<ISD::NodeType> AssertOp;
  8210. if (CLI.RetSExt)
  8211. AssertOp = ISD::AssertSext;
  8212. else if (CLI.RetZExt)
  8213. AssertOp = ISD::AssertZext;
  8214. unsigned CurReg = 0;
  8215. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8216. EVT VT = RetTys[I];
  8217. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8218. CLI.CallConv, VT);
  8219. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8220. CLI.CallConv, VT);
  8221. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8222. NumRegs, RegisterVT, VT, nullptr,
  8223. CLI.CallConv, AssertOp));
  8224. CurReg += NumRegs;
  8225. }
  8226. // For a function returning void, there is no return value. We can't create
  8227. // such a node, so we just return a null return value in that case. In
  8228. // that case, nothing will actually look at the value.
  8229. if (ReturnValues.empty())
  8230. return std::make_pair(SDValue(), CLI.Chain);
  8231. }
  8232. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8233. CLI.DAG.getVTList(RetTys), ReturnValues);
  8234. return std::make_pair(Res, CLI.Chain);
  8235. }
  8236. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8237. SmallVectorImpl<SDValue> &Results,
  8238. SelectionDAG &DAG) const {
  8239. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8240. Results.push_back(Res);
  8241. }
  8242. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8243. llvm_unreachable("LowerOperation not implemented for this target!");
  8244. }
  8245. void
  8246. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8247. SDValue Op = getNonRegisterValue(V);
  8248. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8249. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8250. "Copy from a reg to the same reg!");
  8251. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  8252. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8253. // If this is an InlineAsm we have to match the registers required, not the
  8254. // notional registers required by the type.
  8255. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8256. None); // This is not an ABI copy.
  8257. SDValue Chain = DAG.getEntryNode();
  8258. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8259. FuncInfo.PreferredExtendType.end())
  8260. ? ISD::ANY_EXTEND
  8261. : FuncInfo.PreferredExtendType[V];
  8262. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8263. PendingExports.push_back(Chain);
  8264. }
  8265. #include "llvm/CodeGen/SelectionDAGISel.h"
  8266. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8267. /// entry block, return true. This includes arguments used by switches, since
  8268. /// the switch may expand into multiple basic blocks.
  8269. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8270. // With FastISel active, we may be splitting blocks, so force creation
  8271. // of virtual registers for all non-dead arguments.
  8272. if (FastISel)
  8273. return A->use_empty();
  8274. const BasicBlock &Entry = A->getParent()->front();
  8275. for (const User *U : A->users())
  8276. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8277. return false; // Use not in entry block.
  8278. return true;
  8279. }
  8280. using ArgCopyElisionMapTy =
  8281. DenseMap<const Argument *,
  8282. std::pair<const AllocaInst *, const StoreInst *>>;
  8283. /// Scan the entry block of the function in FuncInfo for arguments that look
  8284. /// like copies into a local alloca. Record any copied arguments in
  8285. /// ArgCopyElisionCandidates.
  8286. static void
  8287. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8288. FunctionLoweringInfo *FuncInfo,
  8289. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8290. // Record the state of every static alloca used in the entry block. Argument
  8291. // allocas are all used in the entry block, so we need approximately as many
  8292. // entries as we have arguments.
  8293. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8294. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8295. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8296. StaticAllocas.reserve(NumArgs * 2);
  8297. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8298. if (!V)
  8299. return nullptr;
  8300. V = V->stripPointerCasts();
  8301. const auto *AI = dyn_cast<AllocaInst>(V);
  8302. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8303. return nullptr;
  8304. auto Iter = StaticAllocas.insert({AI, Unknown});
  8305. return &Iter.first->second;
  8306. };
  8307. // Look for stores of arguments to static allocas. Look through bitcasts and
  8308. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8309. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8310. // unanalyzed store might write it.
  8311. // FIXME: Handle structs initialized with multiple stores.
  8312. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8313. // Look for stores, and handle non-store uses conservatively.
  8314. const auto *SI = dyn_cast<StoreInst>(&I);
  8315. if (!SI) {
  8316. // We will look through cast uses, so ignore them completely.
  8317. if (I.isCast())
  8318. continue;
  8319. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8320. if (isa<DbgInfoIntrinsic>(I))
  8321. continue;
  8322. // This is an unknown instruction. Assume it escapes or writes to all
  8323. // static alloca operands.
  8324. for (const Use &U : I.operands()) {
  8325. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8326. *Info = StaticAllocaInfo::Clobbered;
  8327. }
  8328. continue;
  8329. }
  8330. // If the stored value is a static alloca, mark it as escaped.
  8331. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8332. *Info = StaticAllocaInfo::Clobbered;
  8333. // Check if the destination is a static alloca.
  8334. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8335. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8336. if (!Info)
  8337. continue;
  8338. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8339. // Skip allocas that have been initialized or clobbered.
  8340. if (*Info != StaticAllocaInfo::Unknown)
  8341. continue;
  8342. // Check if the stored value is an argument, and that this store fully
  8343. // initializes the alloca. Don't elide copies from the same argument twice.
  8344. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8345. const auto *Arg = dyn_cast<Argument>(Val);
  8346. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8347. Arg->getType()->isEmptyTy() ||
  8348. DL.getTypeStoreSize(Arg->getType()) !=
  8349. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8350. ArgCopyElisionCandidates.count(Arg)) {
  8351. *Info = StaticAllocaInfo::Clobbered;
  8352. continue;
  8353. }
  8354. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8355. << '\n');
  8356. // Mark this alloca and store for argument copy elision.
  8357. *Info = StaticAllocaInfo::Elidable;
  8358. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8359. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8360. // builds, which is useful, because -O0 builds have large entry blocks and
  8361. // many allocas.
  8362. if (ArgCopyElisionCandidates.size() == NumArgs)
  8363. break;
  8364. }
  8365. }
  8366. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8367. /// ArgVal is a load from a suitable fixed stack object.
  8368. static void tryToElideArgumentCopy(
  8369. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8370. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8371. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8372. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8373. SDValue ArgVal, bool &ArgHasUses) {
  8374. // Check if this is a load from a fixed stack object.
  8375. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8376. if (!LNode)
  8377. return;
  8378. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8379. if (!FINode)
  8380. return;
  8381. // Check that the fixed stack object is the right size and alignment.
  8382. // Look at the alignment that the user wrote on the alloca instead of looking
  8383. // at the stack object.
  8384. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8385. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8386. const AllocaInst *AI = ArgCopyIter->second.first;
  8387. int FixedIndex = FINode->getIndex();
  8388. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8389. int OldIndex = AllocaIndex;
  8390. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8391. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8392. LLVM_DEBUG(
  8393. dbgs() << " argument copy elision failed due to bad fixed stack "
  8394. "object size\n");
  8395. return;
  8396. }
  8397. unsigned RequiredAlignment = AI->getAlignment();
  8398. if (!RequiredAlignment) {
  8399. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8400. AI->getAllocatedType());
  8401. }
  8402. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8403. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8404. "greater than stack argument alignment ("
  8405. << RequiredAlignment << " vs "
  8406. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8407. return;
  8408. }
  8409. // Perform the elision. Delete the old stack object and replace its only use
  8410. // in the variable info map. Mark the stack object as mutable.
  8411. LLVM_DEBUG({
  8412. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8413. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8414. << '\n';
  8415. });
  8416. MFI.RemoveStackObject(OldIndex);
  8417. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8418. AllocaIndex = FixedIndex;
  8419. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8420. Chains.push_back(ArgVal.getValue(1));
  8421. // Avoid emitting code for the store implementing the copy.
  8422. const StoreInst *SI = ArgCopyIter->second.second;
  8423. ElidedArgCopyInstrs.insert(SI);
  8424. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8425. // if it is't used by anything other than the store.
  8426. for (const Value *U : Arg.users()) {
  8427. if (U != SI) {
  8428. ArgHasUses = true;
  8429. break;
  8430. }
  8431. }
  8432. }
  8433. void SelectionDAGISel::LowerArguments(const Function &F) {
  8434. SelectionDAG &DAG = SDB->DAG;
  8435. SDLoc dl = SDB->getCurSDLoc();
  8436. const DataLayout &DL = DAG.getDataLayout();
  8437. SmallVector<ISD::InputArg, 16> Ins;
  8438. if (!FuncInfo->CanLowerReturn) {
  8439. // Put in an sret pointer parameter before all the other parameters.
  8440. SmallVector<EVT, 1> ValueVTs;
  8441. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8442. F.getReturnType()->getPointerTo(
  8443. DAG.getDataLayout().getAllocaAddrSpace()),
  8444. ValueVTs);
  8445. // NOTE: Assuming that a pointer will never break down to more than one VT
  8446. // or one register.
  8447. ISD::ArgFlagsTy Flags;
  8448. Flags.setSRet();
  8449. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8450. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8451. ISD::InputArg::NoArgIndex, 0);
  8452. Ins.push_back(RetArg);
  8453. }
  8454. // Look for stores of arguments to static allocas. Mark such arguments with a
  8455. // flag to ask the target to give us the memory location of that argument if
  8456. // available.
  8457. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8458. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8459. // Set up the incoming argument description vector.
  8460. for (const Argument &Arg : F.args()) {
  8461. unsigned ArgNo = Arg.getArgNo();
  8462. SmallVector<EVT, 4> ValueVTs;
  8463. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8464. bool isArgValueUsed = !Arg.use_empty();
  8465. unsigned PartBase = 0;
  8466. Type *FinalType = Arg.getType();
  8467. if (Arg.hasAttribute(Attribute::ByVal))
  8468. FinalType = Arg.getParamByValType();
  8469. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8470. FinalType, F.getCallingConv(), F.isVarArg());
  8471. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8472. Value != NumValues; ++Value) {
  8473. EVT VT = ValueVTs[Value];
  8474. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8475. ISD::ArgFlagsTy Flags;
  8476. // Certain targets (such as MIPS), may have a different ABI alignment
  8477. // for a type depending on the context. Give the target a chance to
  8478. // specify the alignment it wants.
  8479. unsigned OriginalAlignment =
  8480. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8481. if (Arg.getType()->isPointerTy()) {
  8482. Flags.setPointer();
  8483. Flags.setPointerAddrSpace(
  8484. cast<PointerType>(Arg.getType())->getAddressSpace());
  8485. }
  8486. if (Arg.hasAttribute(Attribute::ZExt))
  8487. Flags.setZExt();
  8488. if (Arg.hasAttribute(Attribute::SExt))
  8489. Flags.setSExt();
  8490. if (Arg.hasAttribute(Attribute::InReg)) {
  8491. // If we are using vectorcall calling convention, a structure that is
  8492. // passed InReg - is surely an HVA
  8493. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8494. isa<StructType>(Arg.getType())) {
  8495. // The first value of a structure is marked
  8496. if (0 == Value)
  8497. Flags.setHvaStart();
  8498. Flags.setHva();
  8499. }
  8500. // Set InReg Flag
  8501. Flags.setInReg();
  8502. }
  8503. if (Arg.hasAttribute(Attribute::StructRet))
  8504. Flags.setSRet();
  8505. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8506. Flags.setSwiftSelf();
  8507. if (Arg.hasAttribute(Attribute::SwiftError))
  8508. Flags.setSwiftError();
  8509. if (Arg.hasAttribute(Attribute::ByVal))
  8510. Flags.setByVal();
  8511. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8512. Flags.setInAlloca();
  8513. // Set the byval flag for CCAssignFn callbacks that don't know about
  8514. // inalloca. This way we can know how many bytes we should've allocated
  8515. // and how many bytes a callee cleanup function will pop. If we port
  8516. // inalloca to more targets, we'll have to add custom inalloca handling
  8517. // in the various CC lowering callbacks.
  8518. Flags.setByVal();
  8519. }
  8520. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8521. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8522. if (ArgNo == 0)
  8523. Flags.setByVal();
  8524. }
  8525. if (Flags.isByVal() || Flags.isInAlloca()) {
  8526. Type *ElementTy = Arg.getParamByValType();
  8527. // For ByVal, size and alignment should be passed from FE. BE will
  8528. // guess if this info is not there but there are cases it cannot get
  8529. // right.
  8530. unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
  8531. Flags.setByValSize(FrameSize);
  8532. unsigned FrameAlign;
  8533. if (Arg.getParamAlignment())
  8534. FrameAlign = Arg.getParamAlignment();
  8535. else
  8536. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8537. Flags.setByValAlign(FrameAlign);
  8538. }
  8539. if (Arg.hasAttribute(Attribute::Nest))
  8540. Flags.setNest();
  8541. if (NeedsRegBlock)
  8542. Flags.setInConsecutiveRegs();
  8543. Flags.setOrigAlign(OriginalAlignment);
  8544. if (ArgCopyElisionCandidates.count(&Arg))
  8545. Flags.setCopyElisionCandidate();
  8546. if (Arg.hasAttribute(Attribute::Returned))
  8547. Flags.setReturned();
  8548. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8549. *CurDAG->getContext(), F.getCallingConv(), VT);
  8550. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8551. *CurDAG->getContext(), F.getCallingConv(), VT);
  8552. for (unsigned i = 0; i != NumRegs; ++i) {
  8553. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8554. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8555. if (NumRegs > 1 && i == 0)
  8556. MyFlags.Flags.setSplit();
  8557. // if it isn't first piece, alignment must be 1
  8558. else if (i > 0) {
  8559. MyFlags.Flags.setOrigAlign(1);
  8560. if (i == NumRegs - 1)
  8561. MyFlags.Flags.setSplitEnd();
  8562. }
  8563. Ins.push_back(MyFlags);
  8564. }
  8565. if (NeedsRegBlock && Value == NumValues - 1)
  8566. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8567. PartBase += VT.getStoreSize();
  8568. }
  8569. }
  8570. // Call the target to set up the argument values.
  8571. SmallVector<SDValue, 8> InVals;
  8572. SDValue NewRoot = TLI->LowerFormalArguments(
  8573. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8574. // Verify that the target's LowerFormalArguments behaved as expected.
  8575. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8576. "LowerFormalArguments didn't return a valid chain!");
  8577. assert(InVals.size() == Ins.size() &&
  8578. "LowerFormalArguments didn't emit the correct number of values!");
  8579. LLVM_DEBUG({
  8580. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8581. assert(InVals[i].getNode() &&
  8582. "LowerFormalArguments emitted a null value!");
  8583. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8584. "LowerFormalArguments emitted a value with the wrong type!");
  8585. }
  8586. });
  8587. // Update the DAG with the new chain value resulting from argument lowering.
  8588. DAG.setRoot(NewRoot);
  8589. // Set up the argument values.
  8590. unsigned i = 0;
  8591. if (!FuncInfo->CanLowerReturn) {
  8592. // Create a virtual register for the sret pointer, and put in a copy
  8593. // from the sret argument into it.
  8594. SmallVector<EVT, 1> ValueVTs;
  8595. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8596. F.getReturnType()->getPointerTo(
  8597. DAG.getDataLayout().getAllocaAddrSpace()),
  8598. ValueVTs);
  8599. MVT VT = ValueVTs[0].getSimpleVT();
  8600. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8601. Optional<ISD::NodeType> AssertOp = None;
  8602. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8603. nullptr, F.getCallingConv(), AssertOp);
  8604. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8605. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8606. Register SRetReg =
  8607. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8608. FuncInfo->DemoteRegister = SRetReg;
  8609. NewRoot =
  8610. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8611. DAG.setRoot(NewRoot);
  8612. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8613. ++i;
  8614. }
  8615. SmallVector<SDValue, 4> Chains;
  8616. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8617. for (const Argument &Arg : F.args()) {
  8618. SmallVector<SDValue, 4> ArgValues;
  8619. SmallVector<EVT, 4> ValueVTs;
  8620. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8621. unsigned NumValues = ValueVTs.size();
  8622. if (NumValues == 0)
  8623. continue;
  8624. bool ArgHasUses = !Arg.use_empty();
  8625. // Elide the copying store if the target loaded this argument from a
  8626. // suitable fixed stack object.
  8627. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8628. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8629. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8630. InVals[i], ArgHasUses);
  8631. }
  8632. // If this argument is unused then remember its value. It is used to generate
  8633. // debugging information.
  8634. bool isSwiftErrorArg =
  8635. TLI->supportSwiftError() &&
  8636. Arg.hasAttribute(Attribute::SwiftError);
  8637. if (!ArgHasUses && !isSwiftErrorArg) {
  8638. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8639. // Also remember any frame index for use in FastISel.
  8640. if (FrameIndexSDNode *FI =
  8641. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8642. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8643. }
  8644. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8645. EVT VT = ValueVTs[Val];
  8646. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8647. F.getCallingConv(), VT);
  8648. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8649. *CurDAG->getContext(), F.getCallingConv(), VT);
  8650. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8651. // we do generate a copy for it that can be used on return from the
  8652. // function.
  8653. if (ArgHasUses || isSwiftErrorArg) {
  8654. Optional<ISD::NodeType> AssertOp;
  8655. if (Arg.hasAttribute(Attribute::SExt))
  8656. AssertOp = ISD::AssertSext;
  8657. else if (Arg.hasAttribute(Attribute::ZExt))
  8658. AssertOp = ISD::AssertZext;
  8659. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8660. PartVT, VT, nullptr,
  8661. F.getCallingConv(), AssertOp));
  8662. }
  8663. i += NumParts;
  8664. }
  8665. // We don't need to do anything else for unused arguments.
  8666. if (ArgValues.empty())
  8667. continue;
  8668. // Note down frame index.
  8669. if (FrameIndexSDNode *FI =
  8670. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8671. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8672. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8673. SDB->getCurSDLoc());
  8674. SDB->setValue(&Arg, Res);
  8675. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8676. // We want to associate the argument with the frame index, among
  8677. // involved operands, that correspond to the lowest address. The
  8678. // getCopyFromParts function, called earlier, is swapping the order of
  8679. // the operands to BUILD_PAIR depending on endianness. The result of
  8680. // that swapping is that the least significant bits of the argument will
  8681. // be in the first operand of the BUILD_PAIR node, and the most
  8682. // significant bits will be in the second operand.
  8683. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8684. if (LoadSDNode *LNode =
  8685. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8686. if (FrameIndexSDNode *FI =
  8687. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8688. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8689. }
  8690. // Analyses past this point are naive and don't expect an assertion.
  8691. if (Res.getOpcode() == ISD::AssertZext)
  8692. Res = Res.getOperand(0);
  8693. // Update the SwiftErrorVRegDefMap.
  8694. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8695. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8696. if (Register::isVirtualRegister(Reg))
  8697. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8698. Reg);
  8699. }
  8700. // If this argument is live outside of the entry block, insert a copy from
  8701. // wherever we got it to the vreg that other BB's will reference it as.
  8702. if (Res.getOpcode() == ISD::CopyFromReg) {
  8703. // If we can, though, try to skip creating an unnecessary vreg.
  8704. // FIXME: This isn't very clean... it would be nice to make this more
  8705. // general.
  8706. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8707. if (Register::isVirtualRegister(Reg)) {
  8708. FuncInfo->ValueMap[&Arg] = Reg;
  8709. continue;
  8710. }
  8711. }
  8712. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8713. FuncInfo->InitializeRegForValue(&Arg);
  8714. SDB->CopyToExportRegsIfNeeded(&Arg);
  8715. }
  8716. }
  8717. if (!Chains.empty()) {
  8718. Chains.push_back(NewRoot);
  8719. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8720. }
  8721. DAG.setRoot(NewRoot);
  8722. assert(i == InVals.size() && "Argument register count mismatch!");
  8723. // If any argument copy elisions occurred and we have debug info, update the
  8724. // stale frame indices used in the dbg.declare variable info table.
  8725. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8726. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8727. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8728. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8729. if (I != ArgCopyElisionFrameIndexMap.end())
  8730. VI.Slot = I->second;
  8731. }
  8732. }
  8733. // Finally, if the target has anything special to do, allow it to do so.
  8734. EmitFunctionEntryCode();
  8735. }
  8736. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8737. /// ensure constants are generated when needed. Remember the virtual registers
  8738. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8739. /// directly add them, because expansion might result in multiple MBB's for one
  8740. /// BB. As such, the start of the BB might correspond to a different MBB than
  8741. /// the end.
  8742. void
  8743. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8744. const Instruction *TI = LLVMBB->getTerminator();
  8745. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8746. // Check PHI nodes in successors that expect a value to be available from this
  8747. // block.
  8748. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8749. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8750. if (!isa<PHINode>(SuccBB->begin())) continue;
  8751. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8752. // If this terminator has multiple identical successors (common for
  8753. // switches), only handle each succ once.
  8754. if (!SuccsHandled.insert(SuccMBB).second)
  8755. continue;
  8756. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8757. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8758. // nodes and Machine PHI nodes, but the incoming operands have not been
  8759. // emitted yet.
  8760. for (const PHINode &PN : SuccBB->phis()) {
  8761. // Ignore dead phi's.
  8762. if (PN.use_empty())
  8763. continue;
  8764. // Skip empty types
  8765. if (PN.getType()->isEmptyTy())
  8766. continue;
  8767. unsigned Reg;
  8768. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8769. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8770. unsigned &RegOut = ConstantsOut[C];
  8771. if (RegOut == 0) {
  8772. RegOut = FuncInfo.CreateRegs(C);
  8773. CopyValueToVirtualRegister(C, RegOut);
  8774. }
  8775. Reg = RegOut;
  8776. } else {
  8777. DenseMap<const Value *, unsigned>::iterator I =
  8778. FuncInfo.ValueMap.find(PHIOp);
  8779. if (I != FuncInfo.ValueMap.end())
  8780. Reg = I->second;
  8781. else {
  8782. assert(isa<AllocaInst>(PHIOp) &&
  8783. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8784. "Didn't codegen value into a register!??");
  8785. Reg = FuncInfo.CreateRegs(PHIOp);
  8786. CopyValueToVirtualRegister(PHIOp, Reg);
  8787. }
  8788. }
  8789. // Remember that this register needs to added to the machine PHI node as
  8790. // the input for this MBB.
  8791. SmallVector<EVT, 4> ValueVTs;
  8792. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8793. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8794. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8795. EVT VT = ValueVTs[vti];
  8796. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8797. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8798. FuncInfo.PHINodesToUpdate.push_back(
  8799. std::make_pair(&*MBBI++, Reg + i));
  8800. Reg += NumRegisters;
  8801. }
  8802. }
  8803. }
  8804. ConstantsOut.clear();
  8805. }
  8806. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8807. /// is 0.
  8808. MachineBasicBlock *
  8809. SelectionDAGBuilder::StackProtectorDescriptor::
  8810. AddSuccessorMBB(const BasicBlock *BB,
  8811. MachineBasicBlock *ParentMBB,
  8812. bool IsLikely,
  8813. MachineBasicBlock *SuccMBB) {
  8814. // If SuccBB has not been created yet, create it.
  8815. if (!SuccMBB) {
  8816. MachineFunction *MF = ParentMBB->getParent();
  8817. MachineFunction::iterator BBI(ParentMBB);
  8818. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8819. MF->insert(++BBI, SuccMBB);
  8820. }
  8821. // Add it as a successor of ParentMBB.
  8822. ParentMBB->addSuccessor(
  8823. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8824. return SuccMBB;
  8825. }
  8826. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8827. MachineFunction::iterator I(MBB);
  8828. if (++I == FuncInfo.MF->end())
  8829. return nullptr;
  8830. return &*I;
  8831. }
  8832. /// During lowering new call nodes can be created (such as memset, etc.).
  8833. /// Those will become new roots of the current DAG, but complications arise
  8834. /// when they are tail calls. In such cases, the call lowering will update
  8835. /// the root, but the builder still needs to know that a tail call has been
  8836. /// lowered in order to avoid generating an additional return.
  8837. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8838. // If the node is null, we do have a tail call.
  8839. if (MaybeTC.getNode() != nullptr)
  8840. DAG.setRoot(MaybeTC);
  8841. else
  8842. HasTailCall = true;
  8843. }
  8844. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8845. MachineBasicBlock *SwitchMBB,
  8846. MachineBasicBlock *DefaultMBB) {
  8847. MachineFunction *CurMF = FuncInfo.MF;
  8848. MachineBasicBlock *NextMBB = nullptr;
  8849. MachineFunction::iterator BBI(W.MBB);
  8850. if (++BBI != FuncInfo.MF->end())
  8851. NextMBB = &*BBI;
  8852. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8853. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8854. if (Size == 2 && W.MBB == SwitchMBB) {
  8855. // If any two of the cases has the same destination, and if one value
  8856. // is the same as the other, but has one bit unset that the other has set,
  8857. // use bit manipulation to do two compares at once. For example:
  8858. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8859. // TODO: This could be extended to merge any 2 cases in switches with 3
  8860. // cases.
  8861. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8862. CaseCluster &Small = *W.FirstCluster;
  8863. CaseCluster &Big = *W.LastCluster;
  8864. if (Small.Low == Small.High && Big.Low == Big.High &&
  8865. Small.MBB == Big.MBB) {
  8866. const APInt &SmallValue = Small.Low->getValue();
  8867. const APInt &BigValue = Big.Low->getValue();
  8868. // Check that there is only one bit different.
  8869. APInt CommonBit = BigValue ^ SmallValue;
  8870. if (CommonBit.isPowerOf2()) {
  8871. SDValue CondLHS = getValue(Cond);
  8872. EVT VT = CondLHS.getValueType();
  8873. SDLoc DL = getCurSDLoc();
  8874. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8875. DAG.getConstant(CommonBit, DL, VT));
  8876. SDValue Cond = DAG.getSetCC(
  8877. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8878. ISD::SETEQ);
  8879. // Update successor info.
  8880. // Both Small and Big will jump to Small.BB, so we sum up the
  8881. // probabilities.
  8882. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8883. if (BPI)
  8884. addSuccessorWithProb(
  8885. SwitchMBB, DefaultMBB,
  8886. // The default destination is the first successor in IR.
  8887. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8888. else
  8889. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8890. // Insert the true branch.
  8891. SDValue BrCond =
  8892. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8893. DAG.getBasicBlock(Small.MBB));
  8894. // Insert the false branch.
  8895. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8896. DAG.getBasicBlock(DefaultMBB));
  8897. DAG.setRoot(BrCond);
  8898. return;
  8899. }
  8900. }
  8901. }
  8902. if (TM.getOptLevel() != CodeGenOpt::None) {
  8903. // Here, we order cases by probability so the most likely case will be
  8904. // checked first. However, two clusters can have the same probability in
  8905. // which case their relative ordering is non-deterministic. So we use Low
  8906. // as a tie-breaker as clusters are guaranteed to never overlap.
  8907. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8908. [](const CaseCluster &a, const CaseCluster &b) {
  8909. return a.Prob != b.Prob ?
  8910. a.Prob > b.Prob :
  8911. a.Low->getValue().slt(b.Low->getValue());
  8912. });
  8913. // Rearrange the case blocks so that the last one falls through if possible
  8914. // without changing the order of probabilities.
  8915. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8916. --I;
  8917. if (I->Prob > W.LastCluster->Prob)
  8918. break;
  8919. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8920. std::swap(*I, *W.LastCluster);
  8921. break;
  8922. }
  8923. }
  8924. }
  8925. // Compute total probability.
  8926. BranchProbability DefaultProb = W.DefaultProb;
  8927. BranchProbability UnhandledProbs = DefaultProb;
  8928. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8929. UnhandledProbs += I->Prob;
  8930. MachineBasicBlock *CurMBB = W.MBB;
  8931. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8932. bool FallthroughUnreachable = false;
  8933. MachineBasicBlock *Fallthrough;
  8934. if (I == W.LastCluster) {
  8935. // For the last cluster, fall through to the default destination.
  8936. Fallthrough = DefaultMBB;
  8937. FallthroughUnreachable = isa<UnreachableInst>(
  8938. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  8939. } else {
  8940. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8941. CurMF->insert(BBI, Fallthrough);
  8942. // Put Cond in a virtual register to make it available from the new blocks.
  8943. ExportFromCurrentBlock(Cond);
  8944. }
  8945. UnhandledProbs -= I->Prob;
  8946. switch (I->Kind) {
  8947. case CC_JumpTable: {
  8948. // FIXME: Optimize away range check based on pivot comparisons.
  8949. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  8950. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  8951. // The jump block hasn't been inserted yet; insert it here.
  8952. MachineBasicBlock *JumpMBB = JT->MBB;
  8953. CurMF->insert(BBI, JumpMBB);
  8954. auto JumpProb = I->Prob;
  8955. auto FallthroughProb = UnhandledProbs;
  8956. // If the default statement is a target of the jump table, we evenly
  8957. // distribute the default probability to successors of CurMBB. Also
  8958. // update the probability on the edge from JumpMBB to Fallthrough.
  8959. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8960. SE = JumpMBB->succ_end();
  8961. SI != SE; ++SI) {
  8962. if (*SI == DefaultMBB) {
  8963. JumpProb += DefaultProb / 2;
  8964. FallthroughProb -= DefaultProb / 2;
  8965. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8966. JumpMBB->normalizeSuccProbs();
  8967. break;
  8968. }
  8969. }
  8970. if (FallthroughUnreachable) {
  8971. // Skip the range check if the fallthrough block is unreachable.
  8972. JTH->OmitRangeCheck = true;
  8973. }
  8974. if (!JTH->OmitRangeCheck)
  8975. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8976. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8977. CurMBB->normalizeSuccProbs();
  8978. // The jump table header will be inserted in our current block, do the
  8979. // range check, and fall through to our fallthrough block.
  8980. JTH->HeaderBB = CurMBB;
  8981. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8982. // If we're in the right place, emit the jump table header right now.
  8983. if (CurMBB == SwitchMBB) {
  8984. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8985. JTH->Emitted = true;
  8986. }
  8987. break;
  8988. }
  8989. case CC_BitTests: {
  8990. // FIXME: Optimize away range check based on pivot comparisons.
  8991. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  8992. // The bit test blocks haven't been inserted yet; insert them here.
  8993. for (BitTestCase &BTC : BTB->Cases)
  8994. CurMF->insert(BBI, BTC.ThisBB);
  8995. // Fill in fields of the BitTestBlock.
  8996. BTB->Parent = CurMBB;
  8997. BTB->Default = Fallthrough;
  8998. BTB->DefaultProb = UnhandledProbs;
  8999. // If the cases in bit test don't form a contiguous range, we evenly
  9000. // distribute the probability on the edge to Fallthrough to two
  9001. // successors of CurMBB.
  9002. if (!BTB->ContiguousRange) {
  9003. BTB->Prob += DefaultProb / 2;
  9004. BTB->DefaultProb -= DefaultProb / 2;
  9005. }
  9006. if (FallthroughUnreachable) {
  9007. // Skip the range check if the fallthrough block is unreachable.
  9008. BTB->OmitRangeCheck = true;
  9009. }
  9010. // If we're in the right place, emit the bit test header right now.
  9011. if (CurMBB == SwitchMBB) {
  9012. visitBitTestHeader(*BTB, SwitchMBB);
  9013. BTB->Emitted = true;
  9014. }
  9015. break;
  9016. }
  9017. case CC_Range: {
  9018. const Value *RHS, *LHS, *MHS;
  9019. ISD::CondCode CC;
  9020. if (I->Low == I->High) {
  9021. // Check Cond == I->Low.
  9022. CC = ISD::SETEQ;
  9023. LHS = Cond;
  9024. RHS=I->Low;
  9025. MHS = nullptr;
  9026. } else {
  9027. // Check I->Low <= Cond <= I->High.
  9028. CC = ISD::SETLE;
  9029. LHS = I->Low;
  9030. MHS = Cond;
  9031. RHS = I->High;
  9032. }
  9033. // If Fallthrough is unreachable, fold away the comparison.
  9034. if (FallthroughUnreachable)
  9035. CC = ISD::SETTRUE;
  9036. // The false probability is the sum of all unhandled cases.
  9037. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9038. getCurSDLoc(), I->Prob, UnhandledProbs);
  9039. if (CurMBB == SwitchMBB)
  9040. visitSwitchCase(CB, SwitchMBB);
  9041. else
  9042. SL->SwitchCases.push_back(CB);
  9043. break;
  9044. }
  9045. }
  9046. CurMBB = Fallthrough;
  9047. }
  9048. }
  9049. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9050. CaseClusterIt First,
  9051. CaseClusterIt Last) {
  9052. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9053. if (X.Prob != CC.Prob)
  9054. return X.Prob > CC.Prob;
  9055. // Ties are broken by comparing the case value.
  9056. return X.Low->getValue().slt(CC.Low->getValue());
  9057. });
  9058. }
  9059. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9060. const SwitchWorkListItem &W,
  9061. Value *Cond,
  9062. MachineBasicBlock *SwitchMBB) {
  9063. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9064. "Clusters not sorted?");
  9065. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9066. // Balance the tree based on branch probabilities to create a near-optimal (in
  9067. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9068. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9069. CaseClusterIt LastLeft = W.FirstCluster;
  9070. CaseClusterIt FirstRight = W.LastCluster;
  9071. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9072. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9073. // Move LastLeft and FirstRight towards each other from opposite directions to
  9074. // find a partitioning of the clusters which balances the probability on both
  9075. // sides. If LeftProb and RightProb are equal, alternate which side is
  9076. // taken to ensure 0-probability nodes are distributed evenly.
  9077. unsigned I = 0;
  9078. while (LastLeft + 1 < FirstRight) {
  9079. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9080. LeftProb += (++LastLeft)->Prob;
  9081. else
  9082. RightProb += (--FirstRight)->Prob;
  9083. I++;
  9084. }
  9085. while (true) {
  9086. // Our binary search tree differs from a typical BST in that ours can have up
  9087. // to three values in each leaf. The pivot selection above doesn't take that
  9088. // into account, which means the tree might require more nodes and be less
  9089. // efficient. We compensate for this here.
  9090. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9091. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9092. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9093. // If one side has less than 3 clusters, and the other has more than 3,
  9094. // consider taking a cluster from the other side.
  9095. if (NumLeft < NumRight) {
  9096. // Consider moving the first cluster on the right to the left side.
  9097. CaseCluster &CC = *FirstRight;
  9098. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9099. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9100. if (LeftSideRank <= RightSideRank) {
  9101. // Moving the cluster to the left does not demote it.
  9102. ++LastLeft;
  9103. ++FirstRight;
  9104. continue;
  9105. }
  9106. } else {
  9107. assert(NumRight < NumLeft);
  9108. // Consider moving the last element on the left to the right side.
  9109. CaseCluster &CC = *LastLeft;
  9110. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9111. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9112. if (RightSideRank <= LeftSideRank) {
  9113. // Moving the cluster to the right does not demot it.
  9114. --LastLeft;
  9115. --FirstRight;
  9116. continue;
  9117. }
  9118. }
  9119. }
  9120. break;
  9121. }
  9122. assert(LastLeft + 1 == FirstRight);
  9123. assert(LastLeft >= W.FirstCluster);
  9124. assert(FirstRight <= W.LastCluster);
  9125. // Use the first element on the right as pivot since we will make less-than
  9126. // comparisons against it.
  9127. CaseClusterIt PivotCluster = FirstRight;
  9128. assert(PivotCluster > W.FirstCluster);
  9129. assert(PivotCluster <= W.LastCluster);
  9130. CaseClusterIt FirstLeft = W.FirstCluster;
  9131. CaseClusterIt LastRight = W.LastCluster;
  9132. const ConstantInt *Pivot = PivotCluster->Low;
  9133. // New blocks will be inserted immediately after the current one.
  9134. MachineFunction::iterator BBI(W.MBB);
  9135. ++BBI;
  9136. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9137. // we can branch to its destination directly if it's squeezed exactly in
  9138. // between the known lower bound and Pivot - 1.
  9139. MachineBasicBlock *LeftMBB;
  9140. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9141. FirstLeft->Low == W.GE &&
  9142. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9143. LeftMBB = FirstLeft->MBB;
  9144. } else {
  9145. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9146. FuncInfo.MF->insert(BBI, LeftMBB);
  9147. WorkList.push_back(
  9148. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9149. // Put Cond in a virtual register to make it available from the new blocks.
  9150. ExportFromCurrentBlock(Cond);
  9151. }
  9152. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9153. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9154. // directly if RHS.High equals the current upper bound.
  9155. MachineBasicBlock *RightMBB;
  9156. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9157. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9158. RightMBB = FirstRight->MBB;
  9159. } else {
  9160. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9161. FuncInfo.MF->insert(BBI, RightMBB);
  9162. WorkList.push_back(
  9163. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9164. // Put Cond in a virtual register to make it available from the new blocks.
  9165. ExportFromCurrentBlock(Cond);
  9166. }
  9167. // Create the CaseBlock record that will be used to lower the branch.
  9168. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9169. getCurSDLoc(), LeftProb, RightProb);
  9170. if (W.MBB == SwitchMBB)
  9171. visitSwitchCase(CB, SwitchMBB);
  9172. else
  9173. SL->SwitchCases.push_back(CB);
  9174. }
  9175. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9176. // from the swith statement.
  9177. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9178. BranchProbability PeeledCaseProb) {
  9179. if (PeeledCaseProb == BranchProbability::getOne())
  9180. return BranchProbability::getZero();
  9181. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9182. uint32_t Numerator = CaseProb.getNumerator();
  9183. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9184. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9185. }
  9186. // Try to peel the top probability case if it exceeds the threshold.
  9187. // Return current MachineBasicBlock for the switch statement if the peeling
  9188. // does not occur.
  9189. // If the peeling is performed, return the newly created MachineBasicBlock
  9190. // for the peeled switch statement. Also update Clusters to remove the peeled
  9191. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9192. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9193. const SwitchInst &SI, CaseClusterVector &Clusters,
  9194. BranchProbability &PeeledCaseProb) {
  9195. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9196. // Don't perform if there is only one cluster or optimizing for size.
  9197. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9198. TM.getOptLevel() == CodeGenOpt::None ||
  9199. SwitchMBB->getParent()->getFunction().hasMinSize())
  9200. return SwitchMBB;
  9201. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9202. unsigned PeeledCaseIndex = 0;
  9203. bool SwitchPeeled = false;
  9204. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9205. CaseCluster &CC = Clusters[Index];
  9206. if (CC.Prob < TopCaseProb)
  9207. continue;
  9208. TopCaseProb = CC.Prob;
  9209. PeeledCaseIndex = Index;
  9210. SwitchPeeled = true;
  9211. }
  9212. if (!SwitchPeeled)
  9213. return SwitchMBB;
  9214. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9215. << TopCaseProb << "\n");
  9216. // Record the MBB for the peeled switch statement.
  9217. MachineFunction::iterator BBI(SwitchMBB);
  9218. ++BBI;
  9219. MachineBasicBlock *PeeledSwitchMBB =
  9220. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9221. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9222. ExportFromCurrentBlock(SI.getCondition());
  9223. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9224. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9225. nullptr, nullptr, TopCaseProb.getCompl()};
  9226. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9227. Clusters.erase(PeeledCaseIt);
  9228. for (CaseCluster &CC : Clusters) {
  9229. LLVM_DEBUG(
  9230. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9231. << CC.Prob << "\n");
  9232. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9233. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9234. }
  9235. PeeledCaseProb = TopCaseProb;
  9236. return PeeledSwitchMBB;
  9237. }
  9238. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9239. // Extract cases from the switch.
  9240. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9241. CaseClusterVector Clusters;
  9242. Clusters.reserve(SI.getNumCases());
  9243. for (auto I : SI.cases()) {
  9244. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9245. const ConstantInt *CaseVal = I.getCaseValue();
  9246. BranchProbability Prob =
  9247. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9248. : BranchProbability(1, SI.getNumCases() + 1);
  9249. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9250. }
  9251. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9252. // Cluster adjacent cases with the same destination. We do this at all
  9253. // optimization levels because it's cheap to do and will make codegen faster
  9254. // if there are many clusters.
  9255. sortAndRangeify(Clusters);
  9256. // The branch probablity of the peeled case.
  9257. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9258. MachineBasicBlock *PeeledSwitchMBB =
  9259. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9260. // If there is only the default destination, jump there directly.
  9261. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9262. if (Clusters.empty()) {
  9263. assert(PeeledSwitchMBB == SwitchMBB);
  9264. SwitchMBB->addSuccessor(DefaultMBB);
  9265. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9266. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9267. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9268. }
  9269. return;
  9270. }
  9271. SL->findJumpTables(Clusters, &SI, DefaultMBB);
  9272. SL->findBitTestClusters(Clusters, &SI);
  9273. LLVM_DEBUG({
  9274. dbgs() << "Case clusters: ";
  9275. for (const CaseCluster &C : Clusters) {
  9276. if (C.Kind == CC_JumpTable)
  9277. dbgs() << "JT:";
  9278. if (C.Kind == CC_BitTests)
  9279. dbgs() << "BT:";
  9280. C.Low->getValue().print(dbgs(), true);
  9281. if (C.Low != C.High) {
  9282. dbgs() << '-';
  9283. C.High->getValue().print(dbgs(), true);
  9284. }
  9285. dbgs() << ' ';
  9286. }
  9287. dbgs() << '\n';
  9288. });
  9289. assert(!Clusters.empty());
  9290. SwitchWorkList WorkList;
  9291. CaseClusterIt First = Clusters.begin();
  9292. CaseClusterIt Last = Clusters.end() - 1;
  9293. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9294. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9295. // DefaultMBB is not replaced.
  9296. if (PeeledCaseProb != BranchProbability::getZero() &&
  9297. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9298. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9299. WorkList.push_back(
  9300. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9301. while (!WorkList.empty()) {
  9302. SwitchWorkListItem W = WorkList.back();
  9303. WorkList.pop_back();
  9304. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9305. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9306. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9307. // For optimized builds, lower large range as a balanced binary tree.
  9308. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9309. continue;
  9310. }
  9311. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9312. }
  9313. }