SelectionDAGBuilder.cpp 406 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444
  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 (!TargetRegisterInfo::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() &&
  838. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  839. // Put the register class of the virtual registers in the flag word. That
  840. // way, later passes can recompute register class constraints for inline
  841. // assembly as well as normal instructions.
  842. // Don't do this for tied operands that can use the regclass information
  843. // from the def.
  844. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  845. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  846. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  847. }
  848. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  849. Ops.push_back(Res);
  850. if (Code == InlineAsm::Kind_Clobber) {
  851. // Clobbers should always have a 1:1 mapping with registers, and may
  852. // reference registers that have illegal (e.g. vector) types. Hence, we
  853. // shouldn't try to apply any sort of splitting logic to them.
  854. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  855. "No 1:1 mapping from clobbers to regs?");
  856. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  857. (void)SP;
  858. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  859. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  860. assert(
  861. (Regs[I] != SP ||
  862. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  863. "If we clobbered the stack pointer, MFI should know about it.");
  864. }
  865. return;
  866. }
  867. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  868. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  869. MVT RegisterVT = RegVTs[Value];
  870. for (unsigned i = 0; i != NumRegs; ++i) {
  871. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  872. unsigned TheReg = Regs[Reg++];
  873. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  874. }
  875. }
  876. }
  877. SmallVector<std::pair<unsigned, unsigned>, 4>
  878. RegsForValue::getRegsAndSizes() const {
  879. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  880. unsigned I = 0;
  881. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  882. unsigned RegCount = std::get<0>(CountAndVT);
  883. MVT RegisterVT = std::get<1>(CountAndVT);
  884. unsigned RegisterSize = RegisterVT.getSizeInBits();
  885. for (unsigned E = I + RegCount; I != E; ++I)
  886. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  887. }
  888. return OutVec;
  889. }
  890. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  891. const TargetLibraryInfo *li) {
  892. AA = aa;
  893. GFI = gfi;
  894. LibInfo = li;
  895. DL = &DAG.getDataLayout();
  896. Context = DAG.getContext();
  897. LPadToCallSiteMap.clear();
  898. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  899. }
  900. void SelectionDAGBuilder::clear() {
  901. NodeMap.clear();
  902. UnusedArgNodeMap.clear();
  903. PendingLoads.clear();
  904. PendingExports.clear();
  905. CurInst = nullptr;
  906. HasTailCall = false;
  907. SDNodeOrder = LowestSDNodeOrder;
  908. StatepointLowering.clear();
  909. }
  910. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  911. DanglingDebugInfoMap.clear();
  912. }
  913. SDValue SelectionDAGBuilder::getRoot() {
  914. if (PendingLoads.empty())
  915. return DAG.getRoot();
  916. if (PendingLoads.size() == 1) {
  917. SDValue Root = PendingLoads[0];
  918. DAG.setRoot(Root);
  919. PendingLoads.clear();
  920. return Root;
  921. }
  922. // Otherwise, we have to make a token factor node.
  923. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  924. PendingLoads.clear();
  925. DAG.setRoot(Root);
  926. return Root;
  927. }
  928. SDValue SelectionDAGBuilder::getControlRoot() {
  929. SDValue Root = DAG.getRoot();
  930. if (PendingExports.empty())
  931. return Root;
  932. // Turn all of the CopyToReg chains into one factored node.
  933. if (Root.getOpcode() != ISD::EntryToken) {
  934. unsigned i = 0, e = PendingExports.size();
  935. for (; i != e; ++i) {
  936. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  937. if (PendingExports[i].getNode()->getOperand(0) == Root)
  938. break; // Don't add the root if we already indirectly depend on it.
  939. }
  940. if (i == e)
  941. PendingExports.push_back(Root);
  942. }
  943. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  944. PendingExports);
  945. PendingExports.clear();
  946. DAG.setRoot(Root);
  947. return Root;
  948. }
  949. void SelectionDAGBuilder::visit(const Instruction &I) {
  950. // Set up outgoing PHI node register values before emitting the terminator.
  951. if (I.isTerminator()) {
  952. HandlePHINodesInSuccessorBlocks(I.getParent());
  953. }
  954. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  955. if (!isa<DbgInfoIntrinsic>(I))
  956. ++SDNodeOrder;
  957. CurInst = &I;
  958. visit(I.getOpcode(), I);
  959. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  960. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  961. // maps to this instruction.
  962. // TODO: We could handle all flags (nsw, etc) here.
  963. // TODO: If an IR instruction maps to >1 node, only the final node will have
  964. // flags set.
  965. if (SDNode *Node = getNodeForIRValue(&I)) {
  966. SDNodeFlags IncomingFlags;
  967. IncomingFlags.copyFMF(*FPMO);
  968. if (!Node->getFlags().isDefined())
  969. Node->setFlags(IncomingFlags);
  970. else
  971. Node->intersectFlagsWith(IncomingFlags);
  972. }
  973. }
  974. if (!I.isTerminator() && !HasTailCall &&
  975. !isStatepoint(&I)) // statepoints handle their exports internally
  976. CopyToExportRegsIfNeeded(&I);
  977. CurInst = nullptr;
  978. }
  979. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  980. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  981. }
  982. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  983. // Note: this doesn't use InstVisitor, because it has to work with
  984. // ConstantExpr's in addition to instructions.
  985. switch (Opcode) {
  986. default: llvm_unreachable("Unknown instruction type encountered!");
  987. // Build the switch statement using the Instruction.def file.
  988. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  989. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  990. #include "llvm/IR/Instruction.def"
  991. }
  992. }
  993. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  994. const DIExpression *Expr) {
  995. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  996. const DbgValueInst *DI = DDI.getDI();
  997. DIVariable *DanglingVariable = DI->getVariable();
  998. DIExpression *DanglingExpr = DI->getExpression();
  999. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  1000. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  1001. return true;
  1002. }
  1003. return false;
  1004. };
  1005. for (auto &DDIMI : DanglingDebugInfoMap) {
  1006. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1007. // If debug info is to be dropped, run it through final checks to see
  1008. // whether it can be salvaged.
  1009. for (auto &DDI : DDIV)
  1010. if (isMatchingDbgValue(DDI))
  1011. salvageUnresolvedDbgValue(DDI);
  1012. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1013. }
  1014. }
  1015. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1016. // generate the debug data structures now that we've seen its definition.
  1017. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1018. SDValue Val) {
  1019. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1020. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1021. return;
  1022. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1023. for (auto &DDI : DDIV) {
  1024. const DbgValueInst *DI = DDI.getDI();
  1025. assert(DI && "Ill-formed DanglingDebugInfo");
  1026. DebugLoc dl = DDI.getdl();
  1027. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1028. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1029. DILocalVariable *Variable = DI->getVariable();
  1030. DIExpression *Expr = DI->getExpression();
  1031. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1032. "Expected inlined-at fields to agree");
  1033. SDDbgValue *SDV;
  1034. if (Val.getNode()) {
  1035. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1036. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1037. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1038. // in the first place we should not be more successful here). Unless we
  1039. // have some test case that prove this to be correct we should avoid
  1040. // calling EmitFuncArgumentDbgValue here.
  1041. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1042. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1043. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1044. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1045. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1046. // inserted after the definition of Val when emitting the instructions
  1047. // after ISel. An alternative could be to teach
  1048. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1049. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1050. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1051. << ValSDNodeOrder << "\n");
  1052. SDV = getDbgValue(Val, Variable, Expr, dl,
  1053. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1054. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1055. } else
  1056. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1057. << "in EmitFuncArgumentDbgValue\n");
  1058. } else {
  1059. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1060. auto Undef =
  1061. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1062. auto SDV =
  1063. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1064. DAG.AddDbgValue(SDV, nullptr, false);
  1065. }
  1066. }
  1067. DDIV.clear();
  1068. }
  1069. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1070. Value *V = DDI.getDI()->getValue();
  1071. DILocalVariable *Var = DDI.getDI()->getVariable();
  1072. DIExpression *Expr = DDI.getDI()->getExpression();
  1073. DebugLoc DL = DDI.getdl();
  1074. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1075. unsigned SDOrder = DDI.getSDNodeOrder();
  1076. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1077. // that DW_OP_stack_value is desired.
  1078. assert(isa<DbgValueInst>(DDI.getDI()));
  1079. bool StackValue = true;
  1080. // Can this Value can be encoded without any further work?
  1081. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1082. return;
  1083. // Attempt to salvage back through as many instructions as possible. Bail if
  1084. // a non-instruction is seen, such as a constant expression or global
  1085. // variable. FIXME: Further work could recover those too.
  1086. while (isa<Instruction>(V)) {
  1087. Instruction &VAsInst = *cast<Instruction>(V);
  1088. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1089. // If we cannot salvage any further, and haven't yet found a suitable debug
  1090. // expression, bail out.
  1091. if (!NewExpr)
  1092. break;
  1093. // New value and expr now represent this debuginfo.
  1094. V = VAsInst.getOperand(0);
  1095. Expr = NewExpr;
  1096. // Some kind of simplification occurred: check whether the operand of the
  1097. // salvaged debug expression can be encoded in this DAG.
  1098. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1099. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1100. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1101. return;
  1102. }
  1103. }
  1104. // This was the final opportunity to salvage this debug information, and it
  1105. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1106. // any earlier variable location.
  1107. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1108. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1109. DAG.AddDbgValue(SDV, nullptr, false);
  1110. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1111. << "\n");
  1112. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1113. << "\n");
  1114. }
  1115. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1116. DIExpression *Expr, DebugLoc dl,
  1117. DebugLoc InstDL, unsigned Order) {
  1118. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1119. SDDbgValue *SDV;
  1120. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1121. isa<ConstantPointerNull>(V)) {
  1122. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1123. DAG.AddDbgValue(SDV, nullptr, false);
  1124. return true;
  1125. }
  1126. // If the Value is a frame index, we can create a FrameIndex debug value
  1127. // without relying on the DAG at all.
  1128. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1129. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1130. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1131. auto SDV =
  1132. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1133. /*IsIndirect*/ false, dl, SDNodeOrder);
  1134. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1135. // is still available even if the SDNode gets optimized out.
  1136. DAG.AddDbgValue(SDV, nullptr, false);
  1137. return true;
  1138. }
  1139. }
  1140. // Do not use getValue() in here; we don't want to generate code at
  1141. // this point if it hasn't been done yet.
  1142. SDValue N = NodeMap[V];
  1143. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1144. N = UnusedArgNodeMap[V];
  1145. if (N.getNode()) {
  1146. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1147. return true;
  1148. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1149. DAG.AddDbgValue(SDV, N.getNode(), false);
  1150. return true;
  1151. }
  1152. // Special rules apply for the first dbg.values of parameter variables in a
  1153. // function. Identify them by the fact they reference Argument Values, that
  1154. // they're parameters, and they are parameters of the current function. We
  1155. // need to let them dangle until they get an SDNode.
  1156. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1157. !InstDL.getInlinedAt();
  1158. if (!IsParamOfFunc) {
  1159. // The value is not used in this block yet (or it would have an SDNode).
  1160. // We still want the value to appear for the user if possible -- if it has
  1161. // an associated VReg, we can refer to that instead.
  1162. auto VMI = FuncInfo.ValueMap.find(V);
  1163. if (VMI != FuncInfo.ValueMap.end()) {
  1164. unsigned Reg = VMI->second;
  1165. // If this is a PHI node, it may be split up into several MI PHI nodes
  1166. // (in FunctionLoweringInfo::set).
  1167. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1168. V->getType(), None);
  1169. if (RFV.occupiesMultipleRegs()) {
  1170. unsigned Offset = 0;
  1171. unsigned BitsToDescribe = 0;
  1172. if (auto VarSize = Var->getSizeInBits())
  1173. BitsToDescribe = *VarSize;
  1174. if (auto Fragment = Expr->getFragmentInfo())
  1175. BitsToDescribe = Fragment->SizeInBits;
  1176. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1177. unsigned RegisterSize = RegAndSize.second;
  1178. // Bail out if all bits are described already.
  1179. if (Offset >= BitsToDescribe)
  1180. break;
  1181. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1182. ? BitsToDescribe - Offset
  1183. : RegisterSize;
  1184. auto FragmentExpr = DIExpression::createFragmentExpression(
  1185. Expr, Offset, FragmentSize);
  1186. if (!FragmentExpr)
  1187. continue;
  1188. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1189. false, dl, SDNodeOrder);
  1190. DAG.AddDbgValue(SDV, nullptr, false);
  1191. Offset += RegisterSize;
  1192. }
  1193. } else {
  1194. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1195. DAG.AddDbgValue(SDV, nullptr, false);
  1196. }
  1197. return true;
  1198. }
  1199. }
  1200. return false;
  1201. }
  1202. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1203. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1204. for (auto &Pair : DanglingDebugInfoMap)
  1205. for (auto &DDI : Pair.second)
  1206. salvageUnresolvedDbgValue(DDI);
  1207. clearDanglingDebugInfo();
  1208. }
  1209. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1210. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1211. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1212. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1213. SDValue Result;
  1214. if (It != FuncInfo.ValueMap.end()) {
  1215. unsigned InReg = It->second;
  1216. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1217. DAG.getDataLayout(), InReg, Ty,
  1218. None); // This is not an ABI copy.
  1219. SDValue Chain = DAG.getEntryNode();
  1220. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1221. V);
  1222. resolveDanglingDebugInfo(V, Result);
  1223. }
  1224. return Result;
  1225. }
  1226. /// getValue - Return an SDValue for the given Value.
  1227. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1228. // If we already have an SDValue for this value, use it. It's important
  1229. // to do this first, so that we don't create a CopyFromReg if we already
  1230. // have a regular SDValue.
  1231. SDValue &N = NodeMap[V];
  1232. if (N.getNode()) return N;
  1233. // If there's a virtual register allocated and initialized for this
  1234. // value, use it.
  1235. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1236. return copyFromReg;
  1237. // Otherwise create a new SDValue and remember it.
  1238. SDValue Val = getValueImpl(V);
  1239. NodeMap[V] = Val;
  1240. resolveDanglingDebugInfo(V, Val);
  1241. return Val;
  1242. }
  1243. // Return true if SDValue exists for the given Value
  1244. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1245. return (NodeMap.find(V) != NodeMap.end()) ||
  1246. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1247. }
  1248. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1249. /// don't look in FuncInfo.ValueMap for a virtual register.
  1250. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1251. // If we already have an SDValue for this value, use it.
  1252. SDValue &N = NodeMap[V];
  1253. if (N.getNode()) {
  1254. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1255. // Remove the debug location from the node as the node is about to be used
  1256. // in a location which may differ from the original debug location. This
  1257. // is relevant to Constant and ConstantFP nodes because they can appear
  1258. // as constant expressions inside PHI nodes.
  1259. N->setDebugLoc(DebugLoc());
  1260. }
  1261. return N;
  1262. }
  1263. // Otherwise create a new SDValue and remember it.
  1264. SDValue Val = getValueImpl(V);
  1265. NodeMap[V] = Val;
  1266. resolveDanglingDebugInfo(V, Val);
  1267. return Val;
  1268. }
  1269. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1270. /// Create an SDValue for the given value.
  1271. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1272. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1273. if (const Constant *C = dyn_cast<Constant>(V)) {
  1274. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1275. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1276. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1277. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1278. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1279. if (isa<ConstantPointerNull>(C)) {
  1280. unsigned AS = V->getType()->getPointerAddressSpace();
  1281. return DAG.getConstant(0, getCurSDLoc(),
  1282. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1283. }
  1284. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1285. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1286. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1287. return DAG.getUNDEF(VT);
  1288. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1289. visit(CE->getOpcode(), *CE);
  1290. SDValue N1 = NodeMap[V];
  1291. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1292. return N1;
  1293. }
  1294. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1295. SmallVector<SDValue, 4> Constants;
  1296. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1297. OI != OE; ++OI) {
  1298. SDNode *Val = getValue(*OI).getNode();
  1299. // If the operand is an empty aggregate, there are no values.
  1300. if (!Val) continue;
  1301. // Add each leaf value from the operand to the Constants list
  1302. // to form a flattened list of all the values.
  1303. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1304. Constants.push_back(SDValue(Val, i));
  1305. }
  1306. return DAG.getMergeValues(Constants, getCurSDLoc());
  1307. }
  1308. if (const ConstantDataSequential *CDS =
  1309. dyn_cast<ConstantDataSequential>(C)) {
  1310. SmallVector<SDValue, 4> Ops;
  1311. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1312. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1313. // Add each leaf value from the operand to the Constants list
  1314. // to form a flattened list of all the values.
  1315. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1316. Ops.push_back(SDValue(Val, i));
  1317. }
  1318. if (isa<ArrayType>(CDS->getType()))
  1319. return DAG.getMergeValues(Ops, getCurSDLoc());
  1320. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1321. }
  1322. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1323. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1324. "Unknown struct or array constant!");
  1325. SmallVector<EVT, 4> ValueVTs;
  1326. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1327. unsigned NumElts = ValueVTs.size();
  1328. if (NumElts == 0)
  1329. return SDValue(); // empty struct
  1330. SmallVector<SDValue, 4> Constants(NumElts);
  1331. for (unsigned i = 0; i != NumElts; ++i) {
  1332. EVT EltVT = ValueVTs[i];
  1333. if (isa<UndefValue>(C))
  1334. Constants[i] = DAG.getUNDEF(EltVT);
  1335. else if (EltVT.isFloatingPoint())
  1336. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1337. else
  1338. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1339. }
  1340. return DAG.getMergeValues(Constants, getCurSDLoc());
  1341. }
  1342. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1343. return DAG.getBlockAddress(BA, VT);
  1344. VectorType *VecTy = cast<VectorType>(V->getType());
  1345. unsigned NumElements = VecTy->getNumElements();
  1346. // Now that we know the number and type of the elements, get that number of
  1347. // elements into the Ops array based on what kind of constant it is.
  1348. SmallVector<SDValue, 16> Ops;
  1349. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1350. for (unsigned i = 0; i != NumElements; ++i)
  1351. Ops.push_back(getValue(CV->getOperand(i)));
  1352. } else {
  1353. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1354. EVT EltVT =
  1355. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1356. SDValue Op;
  1357. if (EltVT.isFloatingPoint())
  1358. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1359. else
  1360. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1361. Ops.assign(NumElements, Op);
  1362. }
  1363. // Create a BUILD_VECTOR node.
  1364. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1365. }
  1366. // If this is a static alloca, generate it as the frameindex instead of
  1367. // computation.
  1368. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1369. DenseMap<const AllocaInst*, int>::iterator SI =
  1370. FuncInfo.StaticAllocaMap.find(AI);
  1371. if (SI != FuncInfo.StaticAllocaMap.end())
  1372. return DAG.getFrameIndex(SI->second,
  1373. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1374. }
  1375. // If this is an instruction which fast-isel has deferred, select it now.
  1376. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1377. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1378. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1379. Inst->getType(), getABIRegCopyCC(V));
  1380. SDValue Chain = DAG.getEntryNode();
  1381. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1382. }
  1383. llvm_unreachable("Can't get register for value!");
  1384. }
  1385. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1386. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1387. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1388. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1389. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1390. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1391. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1392. if (!IsSEH)
  1393. CatchPadMBB->setIsEHScopeEntry();
  1394. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1395. if (IsMSVCCXX || IsCoreCLR)
  1396. CatchPadMBB->setIsEHFuncletEntry();
  1397. // Wasm does not need catchpads anymore
  1398. if (!IsWasmCXX)
  1399. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1400. getControlRoot()));
  1401. }
  1402. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1403. // Update machine-CFG edge.
  1404. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1405. FuncInfo.MBB->addSuccessor(TargetMBB);
  1406. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1407. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1408. if (IsSEH) {
  1409. // If this is not a fall-through branch or optimizations are switched off,
  1410. // emit the branch.
  1411. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1412. TM.getOptLevel() == CodeGenOpt::None)
  1413. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1414. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1415. return;
  1416. }
  1417. // Figure out the funclet membership for the catchret's successor.
  1418. // This will be used by the FuncletLayout pass to determine how to order the
  1419. // BB's.
  1420. // A 'catchret' returns to the outer scope's color.
  1421. Value *ParentPad = I.getCatchSwitchParentPad();
  1422. const BasicBlock *SuccessorColor;
  1423. if (isa<ConstantTokenNone>(ParentPad))
  1424. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1425. else
  1426. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1427. assert(SuccessorColor && "No parent funclet for catchret!");
  1428. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1429. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1430. // Create the terminator node.
  1431. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1432. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1433. DAG.getBasicBlock(SuccessorColorMBB));
  1434. DAG.setRoot(Ret);
  1435. }
  1436. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1437. // Don't emit any special code for the cleanuppad instruction. It just marks
  1438. // the start of an EH scope/funclet.
  1439. FuncInfo.MBB->setIsEHScopeEntry();
  1440. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1441. if (Pers != EHPersonality::Wasm_CXX) {
  1442. FuncInfo.MBB->setIsEHFuncletEntry();
  1443. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1444. }
  1445. }
  1446. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1447. // the control flow always stops at the single catch pad, as it does for a
  1448. // cleanup pad. In case the exception caught is not of the types the catch pad
  1449. // catches, it will be rethrown by a rethrow.
  1450. static void findWasmUnwindDestinations(
  1451. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1452. BranchProbability Prob,
  1453. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1454. &UnwindDests) {
  1455. while (EHPadBB) {
  1456. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1457. if (isa<CleanupPadInst>(Pad)) {
  1458. // Stop on cleanup pads.
  1459. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1460. UnwindDests.back().first->setIsEHScopeEntry();
  1461. break;
  1462. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1463. // Add the catchpad handlers to the possible destinations. We don't
  1464. // continue to the unwind destination of the catchswitch for wasm.
  1465. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1466. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1467. UnwindDests.back().first->setIsEHScopeEntry();
  1468. }
  1469. break;
  1470. } else {
  1471. continue;
  1472. }
  1473. }
  1474. }
  1475. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1476. /// many places it could ultimately go. In the IR, we have a single unwind
  1477. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1478. /// This function skips over imaginary basic blocks that hold catchswitch
  1479. /// instructions, and finds all the "real" machine
  1480. /// basic block destinations. As those destinations may not be successors of
  1481. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1482. /// The passed-in Prob is the edge probability to EHPadBB.
  1483. static void findUnwindDestinations(
  1484. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1485. BranchProbability Prob,
  1486. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1487. &UnwindDests) {
  1488. EHPersonality Personality =
  1489. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1490. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1491. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1492. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1493. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1494. if (IsWasmCXX) {
  1495. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1496. assert(UnwindDests.size() <= 1 &&
  1497. "There should be at most one unwind destination for wasm");
  1498. return;
  1499. }
  1500. while (EHPadBB) {
  1501. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1502. BasicBlock *NewEHPadBB = nullptr;
  1503. if (isa<LandingPadInst>(Pad)) {
  1504. // Stop on landingpads. They are not funclets.
  1505. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1506. break;
  1507. } else if (isa<CleanupPadInst>(Pad)) {
  1508. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1509. // personalities.
  1510. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1511. UnwindDests.back().first->setIsEHScopeEntry();
  1512. UnwindDests.back().first->setIsEHFuncletEntry();
  1513. break;
  1514. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1515. // Add the catchpad handlers to the possible destinations.
  1516. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1517. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1518. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1519. if (IsMSVCCXX || IsCoreCLR)
  1520. UnwindDests.back().first->setIsEHFuncletEntry();
  1521. if (!IsSEH)
  1522. UnwindDests.back().first->setIsEHScopeEntry();
  1523. }
  1524. NewEHPadBB = CatchSwitch->getUnwindDest();
  1525. } else {
  1526. continue;
  1527. }
  1528. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1529. if (BPI && NewEHPadBB)
  1530. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1531. EHPadBB = NewEHPadBB;
  1532. }
  1533. }
  1534. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1535. // Update successor info.
  1536. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1537. auto UnwindDest = I.getUnwindDest();
  1538. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1539. BranchProbability UnwindDestProb =
  1540. (BPI && UnwindDest)
  1541. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1542. : BranchProbability::getZero();
  1543. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1544. for (auto &UnwindDest : UnwindDests) {
  1545. UnwindDest.first->setIsEHPad();
  1546. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1547. }
  1548. FuncInfo.MBB->normalizeSuccProbs();
  1549. // Create the terminator node.
  1550. SDValue Ret =
  1551. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1552. DAG.setRoot(Ret);
  1553. }
  1554. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1555. report_fatal_error("visitCatchSwitch not yet implemented!");
  1556. }
  1557. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1558. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1559. auto &DL = DAG.getDataLayout();
  1560. SDValue Chain = getControlRoot();
  1561. SmallVector<ISD::OutputArg, 8> Outs;
  1562. SmallVector<SDValue, 8> OutVals;
  1563. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1564. // lower
  1565. //
  1566. // %val = call <ty> @llvm.experimental.deoptimize()
  1567. // ret <ty> %val
  1568. //
  1569. // differently.
  1570. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1571. LowerDeoptimizingReturn();
  1572. return;
  1573. }
  1574. if (!FuncInfo.CanLowerReturn) {
  1575. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1576. const Function *F = I.getParent()->getParent();
  1577. // Emit a store of the return value through the virtual register.
  1578. // Leave Outs empty so that LowerReturn won't try to load return
  1579. // registers the usual way.
  1580. SmallVector<EVT, 1> PtrValueVTs;
  1581. ComputeValueVTs(TLI, DL,
  1582. F->getReturnType()->getPointerTo(
  1583. DAG.getDataLayout().getAllocaAddrSpace()),
  1584. PtrValueVTs);
  1585. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1586. DemoteReg, PtrValueVTs[0]);
  1587. SDValue RetOp = getValue(I.getOperand(0));
  1588. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1589. SmallVector<uint64_t, 4> Offsets;
  1590. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1591. &Offsets);
  1592. unsigned NumValues = ValueVTs.size();
  1593. SmallVector<SDValue, 4> Chains(NumValues);
  1594. for (unsigned i = 0; i != NumValues; ++i) {
  1595. // An aggregate return value cannot wrap around the address space, so
  1596. // offsets to its parts don't wrap either.
  1597. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1598. SDValue Val = RetOp.getValue(i);
  1599. if (MemVTs[i] != ValueVTs[i])
  1600. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1601. Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
  1602. // FIXME: better loc info would be nice.
  1603. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1604. }
  1605. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1606. MVT::Other, Chains);
  1607. } else if (I.getNumOperands() != 0) {
  1608. SmallVector<EVT, 4> ValueVTs;
  1609. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1610. unsigned NumValues = ValueVTs.size();
  1611. if (NumValues) {
  1612. SDValue RetOp = getValue(I.getOperand(0));
  1613. const Function *F = I.getParent()->getParent();
  1614. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1615. I.getOperand(0)->getType(), F->getCallingConv(),
  1616. /*IsVarArg*/ false);
  1617. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1618. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1619. Attribute::SExt))
  1620. ExtendKind = ISD::SIGN_EXTEND;
  1621. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1622. Attribute::ZExt))
  1623. ExtendKind = ISD::ZERO_EXTEND;
  1624. LLVMContext &Context = F->getContext();
  1625. bool RetInReg = F->getAttributes().hasAttribute(
  1626. AttributeList::ReturnIndex, Attribute::InReg);
  1627. for (unsigned j = 0; j != NumValues; ++j) {
  1628. EVT VT = ValueVTs[j];
  1629. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1630. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1631. CallingConv::ID CC = F->getCallingConv();
  1632. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1633. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1634. SmallVector<SDValue, 4> Parts(NumParts);
  1635. getCopyToParts(DAG, getCurSDLoc(),
  1636. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1637. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1638. // 'inreg' on function refers to return value
  1639. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1640. if (RetInReg)
  1641. Flags.setInReg();
  1642. if (I.getOperand(0)->getType()->isPointerTy()) {
  1643. Flags.setPointer();
  1644. Flags.setPointerAddrSpace(
  1645. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1646. }
  1647. if (NeedsRegBlock) {
  1648. Flags.setInConsecutiveRegs();
  1649. if (j == NumValues - 1)
  1650. Flags.setInConsecutiveRegsLast();
  1651. }
  1652. // Propagate extension type if any
  1653. if (ExtendKind == ISD::SIGN_EXTEND)
  1654. Flags.setSExt();
  1655. else if (ExtendKind == ISD::ZERO_EXTEND)
  1656. Flags.setZExt();
  1657. for (unsigned i = 0; i < NumParts; ++i) {
  1658. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1659. VT, /*isfixed=*/true, 0, 0));
  1660. OutVals.push_back(Parts[i]);
  1661. }
  1662. }
  1663. }
  1664. }
  1665. // Push in swifterror virtual register as the last element of Outs. This makes
  1666. // sure swifterror virtual register will be returned in the swifterror
  1667. // physical register.
  1668. const Function *F = I.getParent()->getParent();
  1669. if (TLI.supportSwiftError() &&
  1670. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1671. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1672. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1673. Flags.setSwiftError();
  1674. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1675. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1676. true /*isfixed*/, 1 /*origidx*/,
  1677. 0 /*partOffs*/));
  1678. // Create SDNode for the swifterror virtual register.
  1679. OutVals.push_back(
  1680. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1681. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1682. EVT(TLI.getPointerTy(DL))));
  1683. }
  1684. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1685. CallingConv::ID CallConv =
  1686. DAG.getMachineFunction().getFunction().getCallingConv();
  1687. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1688. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1689. // Verify that the target's LowerReturn behaved as expected.
  1690. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1691. "LowerReturn didn't return a valid chain!");
  1692. // Update the DAG with the new chain value resulting from return lowering.
  1693. DAG.setRoot(Chain);
  1694. }
  1695. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1696. /// created for it, emit nodes to copy the value into the virtual
  1697. /// registers.
  1698. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1699. // Skip empty types
  1700. if (V->getType()->isEmptyTy())
  1701. return;
  1702. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1703. if (VMI != FuncInfo.ValueMap.end()) {
  1704. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1705. CopyValueToVirtualRegister(V, VMI->second);
  1706. }
  1707. }
  1708. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1709. /// the current basic block, add it to ValueMap now so that we'll get a
  1710. /// CopyTo/FromReg.
  1711. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1712. // No need to export constants.
  1713. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1714. // Already exported?
  1715. if (FuncInfo.isExportedInst(V)) return;
  1716. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1717. CopyValueToVirtualRegister(V, Reg);
  1718. }
  1719. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1720. const BasicBlock *FromBB) {
  1721. // The operands of the setcc have to be in this block. We don't know
  1722. // how to export them from some other block.
  1723. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1724. // Can export from current BB.
  1725. if (VI->getParent() == FromBB)
  1726. return true;
  1727. // Is already exported, noop.
  1728. return FuncInfo.isExportedInst(V);
  1729. }
  1730. // If this is an argument, we can export it if the BB is the entry block or
  1731. // if it is already exported.
  1732. if (isa<Argument>(V)) {
  1733. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1734. return true;
  1735. // Otherwise, can only export this if it is already exported.
  1736. return FuncInfo.isExportedInst(V);
  1737. }
  1738. // Otherwise, constants can always be exported.
  1739. return true;
  1740. }
  1741. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1742. BranchProbability
  1743. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1744. const MachineBasicBlock *Dst) const {
  1745. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1746. const BasicBlock *SrcBB = Src->getBasicBlock();
  1747. const BasicBlock *DstBB = Dst->getBasicBlock();
  1748. if (!BPI) {
  1749. // If BPI is not available, set the default probability as 1 / N, where N is
  1750. // the number of successors.
  1751. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1752. return BranchProbability(1, SuccSize);
  1753. }
  1754. return BPI->getEdgeProbability(SrcBB, DstBB);
  1755. }
  1756. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1757. MachineBasicBlock *Dst,
  1758. BranchProbability Prob) {
  1759. if (!FuncInfo.BPI)
  1760. Src->addSuccessorWithoutProb(Dst);
  1761. else {
  1762. if (Prob.isUnknown())
  1763. Prob = getEdgeProbability(Src, Dst);
  1764. Src->addSuccessor(Dst, Prob);
  1765. }
  1766. }
  1767. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1768. if (const Instruction *I = dyn_cast<Instruction>(V))
  1769. return I->getParent() == BB;
  1770. return true;
  1771. }
  1772. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1773. /// This function emits a branch and is used at the leaves of an OR or an
  1774. /// AND operator tree.
  1775. void
  1776. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1777. MachineBasicBlock *TBB,
  1778. MachineBasicBlock *FBB,
  1779. MachineBasicBlock *CurBB,
  1780. MachineBasicBlock *SwitchBB,
  1781. BranchProbability TProb,
  1782. BranchProbability FProb,
  1783. bool InvertCond) {
  1784. const BasicBlock *BB = CurBB->getBasicBlock();
  1785. // If the leaf of the tree is a comparison, merge the condition into
  1786. // the caseblock.
  1787. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1788. // The operands of the cmp have to be in this block. We don't know
  1789. // how to export them from some other block. If this is the first block
  1790. // of the sequence, no exporting is needed.
  1791. if (CurBB == SwitchBB ||
  1792. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1793. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1794. ISD::CondCode Condition;
  1795. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1796. ICmpInst::Predicate Pred =
  1797. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1798. Condition = getICmpCondCode(Pred);
  1799. } else {
  1800. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1801. FCmpInst::Predicate Pred =
  1802. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1803. Condition = getFCmpCondCode(Pred);
  1804. if (TM.Options.NoNaNsFPMath)
  1805. Condition = getFCmpCodeWithoutNaN(Condition);
  1806. }
  1807. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1808. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1809. SL->SwitchCases.push_back(CB);
  1810. return;
  1811. }
  1812. }
  1813. // Create a CaseBlock record representing this branch.
  1814. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1815. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1816. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1817. SL->SwitchCases.push_back(CB);
  1818. }
  1819. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1820. MachineBasicBlock *TBB,
  1821. MachineBasicBlock *FBB,
  1822. MachineBasicBlock *CurBB,
  1823. MachineBasicBlock *SwitchBB,
  1824. Instruction::BinaryOps Opc,
  1825. BranchProbability TProb,
  1826. BranchProbability FProb,
  1827. bool InvertCond) {
  1828. // Skip over not part of the tree and remember to invert op and operands at
  1829. // next level.
  1830. Value *NotCond;
  1831. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1832. InBlock(NotCond, CurBB->getBasicBlock())) {
  1833. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1834. !InvertCond);
  1835. return;
  1836. }
  1837. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1838. // Compute the effective opcode for Cond, taking into account whether it needs
  1839. // to be inverted, e.g.
  1840. // and (not (or A, B)), C
  1841. // gets lowered as
  1842. // and (and (not A, not B), C)
  1843. unsigned BOpc = 0;
  1844. if (BOp) {
  1845. BOpc = BOp->getOpcode();
  1846. if (InvertCond) {
  1847. if (BOpc == Instruction::And)
  1848. BOpc = Instruction::Or;
  1849. else if (BOpc == Instruction::Or)
  1850. BOpc = Instruction::And;
  1851. }
  1852. }
  1853. // If this node is not part of the or/and tree, emit it as a branch.
  1854. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1855. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1856. BOp->getParent() != CurBB->getBasicBlock() ||
  1857. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1858. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1859. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1860. TProb, FProb, InvertCond);
  1861. return;
  1862. }
  1863. // Create TmpBB after CurBB.
  1864. MachineFunction::iterator BBI(CurBB);
  1865. MachineFunction &MF = DAG.getMachineFunction();
  1866. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1867. CurBB->getParent()->insert(++BBI, TmpBB);
  1868. if (Opc == Instruction::Or) {
  1869. // Codegen X | Y as:
  1870. // BB1:
  1871. // jmp_if_X TBB
  1872. // jmp TmpBB
  1873. // TmpBB:
  1874. // jmp_if_Y TBB
  1875. // jmp FBB
  1876. //
  1877. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1878. // The requirement is that
  1879. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1880. // = TrueProb for original BB.
  1881. // Assuming the original probabilities are A and B, one choice is to set
  1882. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1883. // A/(1+B) and 2B/(1+B). This choice assumes that
  1884. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1885. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1886. // TmpBB, but the math is more complicated.
  1887. auto NewTrueProb = TProb / 2;
  1888. auto NewFalseProb = TProb / 2 + FProb;
  1889. // Emit the LHS condition.
  1890. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1891. NewTrueProb, NewFalseProb, InvertCond);
  1892. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1893. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1894. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1895. // Emit the RHS condition into TmpBB.
  1896. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1897. Probs[0], Probs[1], InvertCond);
  1898. } else {
  1899. assert(Opc == Instruction::And && "Unknown merge op!");
  1900. // Codegen X & Y as:
  1901. // BB1:
  1902. // jmp_if_X TmpBB
  1903. // jmp FBB
  1904. // TmpBB:
  1905. // jmp_if_Y TBB
  1906. // jmp FBB
  1907. //
  1908. // This requires creation of TmpBB after CurBB.
  1909. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1910. // The requirement is that
  1911. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1912. // = FalseProb for original BB.
  1913. // Assuming the original probabilities are A and B, one choice is to set
  1914. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1915. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1916. // TrueProb for BB1 * FalseProb for TmpBB.
  1917. auto NewTrueProb = TProb + FProb / 2;
  1918. auto NewFalseProb = FProb / 2;
  1919. // Emit the LHS condition.
  1920. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1921. NewTrueProb, NewFalseProb, InvertCond);
  1922. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1923. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1924. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1925. // Emit the RHS condition into TmpBB.
  1926. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1927. Probs[0], Probs[1], InvertCond);
  1928. }
  1929. }
  1930. /// If the set of cases should be emitted as a series of branches, return true.
  1931. /// If we should emit this as a bunch of and/or'd together conditions, return
  1932. /// false.
  1933. bool
  1934. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1935. if (Cases.size() != 2) return true;
  1936. // If this is two comparisons of the same values or'd or and'd together, they
  1937. // will get folded into a single comparison, so don't emit two blocks.
  1938. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1939. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1940. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1941. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1942. return false;
  1943. }
  1944. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1945. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1946. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1947. Cases[0].CC == Cases[1].CC &&
  1948. isa<Constant>(Cases[0].CmpRHS) &&
  1949. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1950. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1951. return false;
  1952. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1953. return false;
  1954. }
  1955. return true;
  1956. }
  1957. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1958. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1959. // Update machine-CFG edges.
  1960. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1961. if (I.isUnconditional()) {
  1962. // Update machine-CFG edges.
  1963. BrMBB->addSuccessor(Succ0MBB);
  1964. // If this is not a fall-through branch or optimizations are switched off,
  1965. // emit the branch.
  1966. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1967. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1968. MVT::Other, getControlRoot(),
  1969. DAG.getBasicBlock(Succ0MBB)));
  1970. return;
  1971. }
  1972. // If this condition is one of the special cases we handle, do special stuff
  1973. // now.
  1974. const Value *CondVal = I.getCondition();
  1975. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1976. // If this is a series of conditions that are or'd or and'd together, emit
  1977. // this as a sequence of branches instead of setcc's with and/or operations.
  1978. // As long as jumps are not expensive, this should improve performance.
  1979. // For example, instead of something like:
  1980. // cmp A, B
  1981. // C = seteq
  1982. // cmp D, E
  1983. // F = setle
  1984. // or C, F
  1985. // jnz foo
  1986. // Emit:
  1987. // cmp A, B
  1988. // je foo
  1989. // cmp D, E
  1990. // jle foo
  1991. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1992. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1993. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1994. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1995. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1996. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1997. Opcode,
  1998. getEdgeProbability(BrMBB, Succ0MBB),
  1999. getEdgeProbability(BrMBB, Succ1MBB),
  2000. /*InvertCond=*/false);
  2001. // If the compares in later blocks need to use values not currently
  2002. // exported from this block, export them now. This block should always
  2003. // be the first entry.
  2004. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2005. // Allow some cases to be rejected.
  2006. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2007. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2008. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2009. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2010. }
  2011. // Emit the branch for this block.
  2012. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2013. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2014. return;
  2015. }
  2016. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2017. // SwitchCases.
  2018. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2019. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2020. SL->SwitchCases.clear();
  2021. }
  2022. }
  2023. // Create a CaseBlock record representing this branch.
  2024. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2025. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2026. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2027. // cond branch.
  2028. visitSwitchCase(CB, BrMBB);
  2029. }
  2030. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2031. /// the binary search tree resulting from lowering a switch instruction.
  2032. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2033. MachineBasicBlock *SwitchBB) {
  2034. SDValue Cond;
  2035. SDValue CondLHS = getValue(CB.CmpLHS);
  2036. SDLoc dl = CB.DL;
  2037. if (CB.CC == ISD::SETTRUE) {
  2038. // Branch or fall through to TrueBB.
  2039. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2040. SwitchBB->normalizeSuccProbs();
  2041. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2042. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2043. DAG.getBasicBlock(CB.TrueBB)));
  2044. }
  2045. return;
  2046. }
  2047. auto &TLI = DAG.getTargetLoweringInfo();
  2048. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2049. // Build the setcc now.
  2050. if (!CB.CmpMHS) {
  2051. // Fold "(X == true)" to X and "(X == false)" to !X to
  2052. // handle common cases produced by branch lowering.
  2053. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2054. CB.CC == ISD::SETEQ)
  2055. Cond = CondLHS;
  2056. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2057. CB.CC == ISD::SETEQ) {
  2058. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2059. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2060. } else {
  2061. SDValue CondRHS = getValue(CB.CmpRHS);
  2062. // If a pointer's DAG type is larger than its memory type then the DAG
  2063. // values are zero-extended. This breaks signed comparisons so truncate
  2064. // back to the underlying type before doing the compare.
  2065. if (CondLHS.getValueType() != MemVT) {
  2066. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2067. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2068. }
  2069. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2070. }
  2071. } else {
  2072. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2073. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2074. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2075. SDValue CmpOp = getValue(CB.CmpMHS);
  2076. EVT VT = CmpOp.getValueType();
  2077. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2078. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2079. ISD::SETLE);
  2080. } else {
  2081. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2082. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2083. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2084. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2085. }
  2086. }
  2087. // Update successor info
  2088. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2089. // TrueBB and FalseBB are always different unless the incoming IR is
  2090. // degenerate. This only happens when running llc on weird IR.
  2091. if (CB.TrueBB != CB.FalseBB)
  2092. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2093. SwitchBB->normalizeSuccProbs();
  2094. // If the lhs block is the next block, invert the condition so that we can
  2095. // fall through to the lhs instead of the rhs block.
  2096. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2097. std::swap(CB.TrueBB, CB.FalseBB);
  2098. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2099. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2100. }
  2101. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2102. MVT::Other, getControlRoot(), Cond,
  2103. DAG.getBasicBlock(CB.TrueBB));
  2104. // Insert the false branch. Do this even if it's a fall through branch,
  2105. // this makes it easier to do DAG optimizations which require inverting
  2106. // the branch condition.
  2107. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2108. DAG.getBasicBlock(CB.FalseBB));
  2109. DAG.setRoot(BrCond);
  2110. }
  2111. /// visitJumpTable - Emit JumpTable node in the current MBB
  2112. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2113. // Emit the code for the jump table
  2114. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2115. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2116. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2117. JT.Reg, PTy);
  2118. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2119. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2120. MVT::Other, Index.getValue(1),
  2121. Table, Index);
  2122. DAG.setRoot(BrJumpTable);
  2123. }
  2124. /// visitJumpTableHeader - This function emits necessary code to produce index
  2125. /// in the JumpTable from switch case.
  2126. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2127. JumpTableHeader &JTH,
  2128. MachineBasicBlock *SwitchBB) {
  2129. SDLoc dl = getCurSDLoc();
  2130. // Subtract the lowest switch case value from the value being switched on.
  2131. SDValue SwitchOp = getValue(JTH.SValue);
  2132. EVT VT = SwitchOp.getValueType();
  2133. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2134. DAG.getConstant(JTH.First, dl, VT));
  2135. // The SDNode we just created, which holds the value being switched on minus
  2136. // the smallest case value, needs to be copied to a virtual register so it
  2137. // can be used as an index into the jump table in a subsequent basic block.
  2138. // This value may be smaller or larger than the target's pointer type, and
  2139. // therefore require extension or truncating.
  2140. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2141. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2142. unsigned JumpTableReg =
  2143. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2144. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2145. JumpTableReg, SwitchOp);
  2146. JT.Reg = JumpTableReg;
  2147. if (!JTH.OmitRangeCheck) {
  2148. // Emit the range check for the jump table, and branch to the default block
  2149. // for the switch statement if the value being switched on exceeds the
  2150. // largest case in the switch.
  2151. SDValue CMP = DAG.getSetCC(
  2152. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2153. Sub.getValueType()),
  2154. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2155. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2156. MVT::Other, CopyTo, CMP,
  2157. DAG.getBasicBlock(JT.Default));
  2158. // Avoid emitting unnecessary branches to the next block.
  2159. if (JT.MBB != NextBlock(SwitchBB))
  2160. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2161. DAG.getBasicBlock(JT.MBB));
  2162. DAG.setRoot(BrCond);
  2163. } else {
  2164. // Avoid emitting unnecessary branches to the next block.
  2165. if (JT.MBB != NextBlock(SwitchBB))
  2166. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2167. DAG.getBasicBlock(JT.MBB)));
  2168. else
  2169. DAG.setRoot(CopyTo);
  2170. }
  2171. }
  2172. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2173. /// variable if there exists one.
  2174. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2175. SDValue &Chain) {
  2176. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2177. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2178. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2179. MachineFunction &MF = DAG.getMachineFunction();
  2180. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2181. MachineSDNode *Node =
  2182. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2183. if (Global) {
  2184. MachinePointerInfo MPInfo(Global);
  2185. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2186. MachineMemOperand::MODereferenceable;
  2187. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2188. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2189. DAG.setNodeMemRefs(Node, {MemRef});
  2190. }
  2191. if (PtrTy != PtrMemTy)
  2192. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2193. return SDValue(Node, 0);
  2194. }
  2195. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2196. /// tail spliced into a stack protector check success bb.
  2197. ///
  2198. /// For a high level explanation of how this fits into the stack protector
  2199. /// generation see the comment on the declaration of class
  2200. /// StackProtectorDescriptor.
  2201. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2202. MachineBasicBlock *ParentBB) {
  2203. // First create the loads to the guard/stack slot for the comparison.
  2204. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2205. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2206. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2207. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2208. int FI = MFI.getStackProtectorIndex();
  2209. SDValue Guard;
  2210. SDLoc dl = getCurSDLoc();
  2211. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2212. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2213. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2214. // Generate code to load the content of the guard slot.
  2215. SDValue GuardVal = DAG.getLoad(
  2216. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2217. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2218. MachineMemOperand::MOVolatile);
  2219. if (TLI.useStackGuardXorFP())
  2220. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2221. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2222. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2223. // The target provides a guard check function to validate the guard value.
  2224. // Generate a call to that function with the content of the guard slot as
  2225. // argument.
  2226. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2227. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2228. TargetLowering::ArgListTy Args;
  2229. TargetLowering::ArgListEntry Entry;
  2230. Entry.Node = GuardVal;
  2231. Entry.Ty = FnTy->getParamType(0);
  2232. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2233. Entry.IsInReg = true;
  2234. Args.push_back(Entry);
  2235. TargetLowering::CallLoweringInfo CLI(DAG);
  2236. CLI.setDebugLoc(getCurSDLoc())
  2237. .setChain(DAG.getEntryNode())
  2238. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2239. getValue(GuardCheckFn), std::move(Args));
  2240. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2241. DAG.setRoot(Result.second);
  2242. return;
  2243. }
  2244. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2245. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2246. SDValue Chain = DAG.getEntryNode();
  2247. if (TLI.useLoadStackGuardNode()) {
  2248. Guard = getLoadStackGuard(DAG, dl, Chain);
  2249. } else {
  2250. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2251. SDValue GuardPtr = getValue(IRGuard);
  2252. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2253. MachinePointerInfo(IRGuard, 0), Align,
  2254. MachineMemOperand::MOVolatile);
  2255. }
  2256. // Perform the comparison via a subtract/getsetcc.
  2257. EVT VT = Guard.getValueType();
  2258. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2259. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2260. *DAG.getContext(),
  2261. Sub.getValueType()),
  2262. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2263. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2264. // branch to failure MBB.
  2265. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2266. MVT::Other, GuardVal.getOperand(0),
  2267. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2268. // Otherwise branch to success MBB.
  2269. SDValue Br = DAG.getNode(ISD::BR, dl,
  2270. MVT::Other, BrCond,
  2271. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2272. DAG.setRoot(Br);
  2273. }
  2274. /// Codegen the failure basic block for a stack protector check.
  2275. ///
  2276. /// A failure stack protector machine basic block consists simply of a call to
  2277. /// __stack_chk_fail().
  2278. ///
  2279. /// For a high level explanation of how this fits into the stack protector
  2280. /// generation see the comment on the declaration of class
  2281. /// StackProtectorDescriptor.
  2282. void
  2283. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2284. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2285. SDValue Chain =
  2286. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2287. None, false, getCurSDLoc(), false, false).second;
  2288. // On PS4, the "return address" must still be within the calling function,
  2289. // even if it's at the very end, so emit an explicit TRAP here.
  2290. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2291. if (TM.getTargetTriple().isPS4CPU())
  2292. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2293. DAG.setRoot(Chain);
  2294. }
  2295. /// visitBitTestHeader - This function emits necessary code to produce value
  2296. /// suitable for "bit tests"
  2297. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2298. MachineBasicBlock *SwitchBB) {
  2299. SDLoc dl = getCurSDLoc();
  2300. // Subtract the minimum value
  2301. SDValue SwitchOp = getValue(B.SValue);
  2302. EVT VT = SwitchOp.getValueType();
  2303. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2304. DAG.getConstant(B.First, dl, VT));
  2305. // Check range
  2306. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2307. SDValue RangeCmp = DAG.getSetCC(
  2308. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2309. Sub.getValueType()),
  2310. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2311. // Determine the type of the test operands.
  2312. bool UsePtrType = false;
  2313. if (!TLI.isTypeLegal(VT))
  2314. UsePtrType = true;
  2315. else {
  2316. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2317. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2318. // Switch table case range are encoded into series of masks.
  2319. // Just use pointer type, it's guaranteed to fit.
  2320. UsePtrType = true;
  2321. break;
  2322. }
  2323. }
  2324. if (UsePtrType) {
  2325. VT = TLI.getPointerTy(DAG.getDataLayout());
  2326. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2327. }
  2328. B.RegVT = VT.getSimpleVT();
  2329. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2330. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2331. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2332. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2333. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2334. SwitchBB->normalizeSuccProbs();
  2335. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2336. MVT::Other, CopyTo, RangeCmp,
  2337. DAG.getBasicBlock(B.Default));
  2338. // Avoid emitting unnecessary branches to the next block.
  2339. if (MBB != NextBlock(SwitchBB))
  2340. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2341. DAG.getBasicBlock(MBB));
  2342. DAG.setRoot(BrRange);
  2343. }
  2344. /// visitBitTestCase - this function produces one "bit test"
  2345. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2346. MachineBasicBlock* NextMBB,
  2347. BranchProbability BranchProbToNext,
  2348. unsigned Reg,
  2349. BitTestCase &B,
  2350. MachineBasicBlock *SwitchBB) {
  2351. SDLoc dl = getCurSDLoc();
  2352. MVT VT = BB.RegVT;
  2353. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2354. SDValue Cmp;
  2355. unsigned PopCount = countPopulation(B.Mask);
  2356. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2357. if (PopCount == 1) {
  2358. // Testing for a single bit; just compare the shift count with what it
  2359. // would need to be to shift a 1 bit in that position.
  2360. Cmp = DAG.getSetCC(
  2361. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2362. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2363. ISD::SETEQ);
  2364. } else if (PopCount == BB.Range) {
  2365. // There is only one zero bit in the range, test for it directly.
  2366. Cmp = DAG.getSetCC(
  2367. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2368. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2369. ISD::SETNE);
  2370. } else {
  2371. // Make desired shift
  2372. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2373. DAG.getConstant(1, dl, VT), ShiftOp);
  2374. // Emit bit tests and jumps
  2375. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2376. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2377. Cmp = DAG.getSetCC(
  2378. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2379. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2380. }
  2381. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2382. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2383. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2384. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2385. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2386. // one as they are relative probabilities (and thus work more like weights),
  2387. // and hence we need to normalize them to let the sum of them become one.
  2388. SwitchBB->normalizeSuccProbs();
  2389. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2390. MVT::Other, getControlRoot(),
  2391. Cmp, DAG.getBasicBlock(B.TargetBB));
  2392. // Avoid emitting unnecessary branches to the next block.
  2393. if (NextMBB != NextBlock(SwitchBB))
  2394. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2395. DAG.getBasicBlock(NextMBB));
  2396. DAG.setRoot(BrAnd);
  2397. }
  2398. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2399. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2400. // Retrieve successors. Look through artificial IR level blocks like
  2401. // catchswitch for successors.
  2402. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2403. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2404. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2405. // have to do anything here to lower funclet bundles.
  2406. assert(!I.hasOperandBundlesOtherThan(
  2407. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2408. "Cannot lower invokes with arbitrary operand bundles yet!");
  2409. const Value *Callee(I.getCalledValue());
  2410. const Function *Fn = dyn_cast<Function>(Callee);
  2411. if (isa<InlineAsm>(Callee))
  2412. visitInlineAsm(&I);
  2413. else if (Fn && Fn->isIntrinsic()) {
  2414. switch (Fn->getIntrinsicID()) {
  2415. default:
  2416. llvm_unreachable("Cannot invoke this intrinsic");
  2417. case Intrinsic::donothing:
  2418. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2419. break;
  2420. case Intrinsic::experimental_patchpoint_void:
  2421. case Intrinsic::experimental_patchpoint_i64:
  2422. visitPatchpoint(&I, EHPadBB);
  2423. break;
  2424. case Intrinsic::experimental_gc_statepoint:
  2425. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2426. break;
  2427. case Intrinsic::wasm_rethrow_in_catch: {
  2428. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2429. // special because it can be invoked, so we manually lower it to a DAG
  2430. // node here.
  2431. SmallVector<SDValue, 8> Ops;
  2432. Ops.push_back(getRoot()); // inchain
  2433. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2434. Ops.push_back(
  2435. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2436. TLI.getPointerTy(DAG.getDataLayout())));
  2437. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2438. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2439. break;
  2440. }
  2441. }
  2442. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2443. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2444. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2445. // intrinsic, and right now there are no plans to support other intrinsics
  2446. // with deopt state.
  2447. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2448. } else {
  2449. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2450. }
  2451. // If the value of the invoke is used outside of its defining block, make it
  2452. // available as a virtual register.
  2453. // We already took care of the exported value for the statepoint instruction
  2454. // during call to the LowerStatepoint.
  2455. if (!isStatepoint(I)) {
  2456. CopyToExportRegsIfNeeded(&I);
  2457. }
  2458. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2459. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2460. BranchProbability EHPadBBProb =
  2461. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2462. : BranchProbability::getZero();
  2463. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2464. // Update successor info.
  2465. addSuccessorWithProb(InvokeMBB, Return);
  2466. for (auto &UnwindDest : UnwindDests) {
  2467. UnwindDest.first->setIsEHPad();
  2468. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2469. }
  2470. InvokeMBB->normalizeSuccProbs();
  2471. // Drop into normal successor.
  2472. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2473. DAG.getBasicBlock(Return)));
  2474. }
  2475. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2476. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2477. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2478. // have to do anything here to lower funclet bundles.
  2479. assert(!I.hasOperandBundlesOtherThan(
  2480. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2481. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2482. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2483. "Only know how to handle inlineasm callbr");
  2484. visitInlineAsm(&I);
  2485. // Retrieve successors.
  2486. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2487. // Update successor info.
  2488. addSuccessorWithProb(CallBrMBB, Return);
  2489. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2490. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2491. addSuccessorWithProb(CallBrMBB, Target);
  2492. }
  2493. CallBrMBB->normalizeSuccProbs();
  2494. // Drop into default successor.
  2495. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2496. MVT::Other, getControlRoot(),
  2497. DAG.getBasicBlock(Return)));
  2498. }
  2499. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2500. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2501. }
  2502. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2503. assert(FuncInfo.MBB->isEHPad() &&
  2504. "Call to landingpad not in landing pad!");
  2505. // If there aren't registers to copy the values into (e.g., during SjLj
  2506. // exceptions), then don't bother to create these DAG nodes.
  2507. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2508. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2509. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2510. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2511. return;
  2512. // If landingpad's return type is token type, we don't create DAG nodes
  2513. // for its exception pointer and selector value. The extraction of exception
  2514. // pointer or selector value from token type landingpads is not currently
  2515. // supported.
  2516. if (LP.getType()->isTokenTy())
  2517. return;
  2518. SmallVector<EVT, 2> ValueVTs;
  2519. SDLoc dl = getCurSDLoc();
  2520. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2521. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2522. // Get the two live-in registers as SDValues. The physregs have already been
  2523. // copied into virtual registers.
  2524. SDValue Ops[2];
  2525. if (FuncInfo.ExceptionPointerVirtReg) {
  2526. Ops[0] = DAG.getZExtOrTrunc(
  2527. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2528. FuncInfo.ExceptionPointerVirtReg,
  2529. TLI.getPointerTy(DAG.getDataLayout())),
  2530. dl, ValueVTs[0]);
  2531. } else {
  2532. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2533. }
  2534. Ops[1] = DAG.getZExtOrTrunc(
  2535. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2536. FuncInfo.ExceptionSelectorVirtReg,
  2537. TLI.getPointerTy(DAG.getDataLayout())),
  2538. dl, ValueVTs[1]);
  2539. // Merge into one.
  2540. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2541. DAG.getVTList(ValueVTs), Ops);
  2542. setValue(&LP, Res);
  2543. }
  2544. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2545. MachineBasicBlock *Last) {
  2546. // Update JTCases.
  2547. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2548. if (SL->JTCases[i].first.HeaderBB == First)
  2549. SL->JTCases[i].first.HeaderBB = Last;
  2550. // Update BitTestCases.
  2551. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2552. if (SL->BitTestCases[i].Parent == First)
  2553. SL->BitTestCases[i].Parent = Last;
  2554. }
  2555. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2556. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2557. // Update machine-CFG edges with unique successors.
  2558. SmallSet<BasicBlock*, 32> Done;
  2559. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2560. BasicBlock *BB = I.getSuccessor(i);
  2561. bool Inserted = Done.insert(BB).second;
  2562. if (!Inserted)
  2563. continue;
  2564. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2565. addSuccessorWithProb(IndirectBrMBB, Succ);
  2566. }
  2567. IndirectBrMBB->normalizeSuccProbs();
  2568. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2569. MVT::Other, getControlRoot(),
  2570. getValue(I.getAddress())));
  2571. }
  2572. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2573. if (!DAG.getTarget().Options.TrapUnreachable)
  2574. return;
  2575. // We may be able to ignore unreachable behind a noreturn call.
  2576. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2577. const BasicBlock &BB = *I.getParent();
  2578. if (&I != &BB.front()) {
  2579. BasicBlock::const_iterator PredI =
  2580. std::prev(BasicBlock::const_iterator(&I));
  2581. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2582. if (Call->doesNotReturn())
  2583. return;
  2584. }
  2585. }
  2586. }
  2587. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2588. }
  2589. void SelectionDAGBuilder::visitFSub(const User &I) {
  2590. // -0.0 - X --> fneg
  2591. Type *Ty = I.getType();
  2592. if (isa<Constant>(I.getOperand(0)) &&
  2593. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2594. SDValue Op2 = getValue(I.getOperand(1));
  2595. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2596. Op2.getValueType(), Op2));
  2597. return;
  2598. }
  2599. visitBinary(I, ISD::FSUB);
  2600. }
  2601. /// Checks if the given instruction performs a vector reduction, in which case
  2602. /// we have the freedom to alter the elements in the result as long as the
  2603. /// reduction of them stays unchanged.
  2604. static bool isVectorReductionOp(const User *I) {
  2605. const Instruction *Inst = dyn_cast<Instruction>(I);
  2606. if (!Inst || !Inst->getType()->isVectorTy())
  2607. return false;
  2608. auto OpCode = Inst->getOpcode();
  2609. switch (OpCode) {
  2610. case Instruction::Add:
  2611. case Instruction::Mul:
  2612. case Instruction::And:
  2613. case Instruction::Or:
  2614. case Instruction::Xor:
  2615. break;
  2616. case Instruction::FAdd:
  2617. case Instruction::FMul:
  2618. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2619. if (FPOp->getFastMathFlags().isFast())
  2620. break;
  2621. LLVM_FALLTHROUGH;
  2622. default:
  2623. return false;
  2624. }
  2625. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2626. // Ensure the reduction size is a power of 2.
  2627. if (!isPowerOf2_32(ElemNum))
  2628. return false;
  2629. unsigned ElemNumToReduce = ElemNum;
  2630. // Do DFS search on the def-use chain from the given instruction. We only
  2631. // allow four kinds of operations during the search until we reach the
  2632. // instruction that extracts the first element from the vector:
  2633. //
  2634. // 1. The reduction operation of the same opcode as the given instruction.
  2635. //
  2636. // 2. PHI node.
  2637. //
  2638. // 3. ShuffleVector instruction together with a reduction operation that
  2639. // does a partial reduction.
  2640. //
  2641. // 4. ExtractElement that extracts the first element from the vector, and we
  2642. // stop searching the def-use chain here.
  2643. //
  2644. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2645. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2646. // a reduction operation if we meet any other instructions other than those
  2647. // listed above.
  2648. SmallVector<const User *, 16> UsersToVisit{Inst};
  2649. SmallPtrSet<const User *, 16> Visited;
  2650. bool ReduxExtracted = false;
  2651. while (!UsersToVisit.empty()) {
  2652. auto User = UsersToVisit.back();
  2653. UsersToVisit.pop_back();
  2654. if (!Visited.insert(User).second)
  2655. continue;
  2656. for (const auto &U : User->users()) {
  2657. auto Inst = dyn_cast<Instruction>(U);
  2658. if (!Inst)
  2659. return false;
  2660. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2661. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2662. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2663. return false;
  2664. UsersToVisit.push_back(U);
  2665. } else if (const ShuffleVectorInst *ShufInst =
  2666. dyn_cast<ShuffleVectorInst>(U)) {
  2667. // Detect the following pattern: A ShuffleVector instruction together
  2668. // with a reduction that do partial reduction on the first and second
  2669. // ElemNumToReduce / 2 elements, and store the result in
  2670. // ElemNumToReduce / 2 elements in another vector.
  2671. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2672. if (ResultElements < ElemNum)
  2673. return false;
  2674. if (ElemNumToReduce == 1)
  2675. return false;
  2676. if (!isa<UndefValue>(U->getOperand(1)))
  2677. return false;
  2678. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2679. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2680. return false;
  2681. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2682. if (ShufInst->getMaskValue(i) != -1)
  2683. return false;
  2684. // There is only one user of this ShuffleVector instruction, which
  2685. // must be a reduction operation.
  2686. if (!U->hasOneUse())
  2687. return false;
  2688. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2689. if (!U2 || U2->getOpcode() != OpCode)
  2690. return false;
  2691. // Check operands of the reduction operation.
  2692. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2693. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2694. UsersToVisit.push_back(U2);
  2695. ElemNumToReduce /= 2;
  2696. } else
  2697. return false;
  2698. } else if (isa<ExtractElementInst>(U)) {
  2699. // At this moment we should have reduced all elements in the vector.
  2700. if (ElemNumToReduce != 1)
  2701. return false;
  2702. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2703. if (!Val || !Val->isZero())
  2704. return false;
  2705. ReduxExtracted = true;
  2706. } else
  2707. return false;
  2708. }
  2709. }
  2710. return ReduxExtracted;
  2711. }
  2712. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2713. SDNodeFlags Flags;
  2714. SDValue Op = getValue(I.getOperand(0));
  2715. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2716. Op, Flags);
  2717. setValue(&I, UnNodeValue);
  2718. }
  2719. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2720. SDNodeFlags Flags;
  2721. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2722. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2723. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2724. }
  2725. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2726. Flags.setExact(ExactOp->isExact());
  2727. }
  2728. if (isVectorReductionOp(&I)) {
  2729. Flags.setVectorReduction(true);
  2730. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2731. }
  2732. SDValue Op1 = getValue(I.getOperand(0));
  2733. SDValue Op2 = getValue(I.getOperand(1));
  2734. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2735. Op1, Op2, Flags);
  2736. setValue(&I, BinNodeValue);
  2737. }
  2738. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2739. SDValue Op1 = getValue(I.getOperand(0));
  2740. SDValue Op2 = getValue(I.getOperand(1));
  2741. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2742. Op1.getValueType(), DAG.getDataLayout());
  2743. // Coerce the shift amount to the right type if we can.
  2744. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2745. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2746. unsigned Op2Size = Op2.getValueSizeInBits();
  2747. SDLoc DL = getCurSDLoc();
  2748. // If the operand is smaller than the shift count type, promote it.
  2749. if (ShiftSize > Op2Size)
  2750. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2751. // If the operand is larger than the shift count type but the shift
  2752. // count type has enough bits to represent any shift value, truncate
  2753. // it now. This is a common case and it exposes the truncate to
  2754. // optimization early.
  2755. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2756. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2757. // Otherwise we'll need to temporarily settle for some other convenient
  2758. // type. Type legalization will make adjustments once the shiftee is split.
  2759. else
  2760. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2761. }
  2762. bool nuw = false;
  2763. bool nsw = false;
  2764. bool exact = false;
  2765. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2766. if (const OverflowingBinaryOperator *OFBinOp =
  2767. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2768. nuw = OFBinOp->hasNoUnsignedWrap();
  2769. nsw = OFBinOp->hasNoSignedWrap();
  2770. }
  2771. if (const PossiblyExactOperator *ExactOp =
  2772. dyn_cast<const PossiblyExactOperator>(&I))
  2773. exact = ExactOp->isExact();
  2774. }
  2775. SDNodeFlags Flags;
  2776. Flags.setExact(exact);
  2777. Flags.setNoSignedWrap(nsw);
  2778. Flags.setNoUnsignedWrap(nuw);
  2779. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2780. Flags);
  2781. setValue(&I, Res);
  2782. }
  2783. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2784. SDValue Op1 = getValue(I.getOperand(0));
  2785. SDValue Op2 = getValue(I.getOperand(1));
  2786. SDNodeFlags Flags;
  2787. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2788. cast<PossiblyExactOperator>(&I)->isExact());
  2789. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2790. Op2, Flags));
  2791. }
  2792. void SelectionDAGBuilder::visitICmp(const User &I) {
  2793. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2794. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2795. predicate = IC->getPredicate();
  2796. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2797. predicate = ICmpInst::Predicate(IC->getPredicate());
  2798. SDValue Op1 = getValue(I.getOperand(0));
  2799. SDValue Op2 = getValue(I.getOperand(1));
  2800. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2801. auto &TLI = DAG.getTargetLoweringInfo();
  2802. EVT MemVT =
  2803. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2804. // If a pointer's DAG type is larger than its memory type then the DAG values
  2805. // are zero-extended. This breaks signed comparisons so truncate back to the
  2806. // underlying type before doing the compare.
  2807. if (Op1.getValueType() != MemVT) {
  2808. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2809. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2810. }
  2811. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2812. I.getType());
  2813. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2814. }
  2815. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2816. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2817. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2818. predicate = FC->getPredicate();
  2819. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2820. predicate = FCmpInst::Predicate(FC->getPredicate());
  2821. SDValue Op1 = getValue(I.getOperand(0));
  2822. SDValue Op2 = getValue(I.getOperand(1));
  2823. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2824. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2825. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2826. Condition = getFCmpCodeWithoutNaN(Condition);
  2827. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2828. I.getType());
  2829. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2830. }
  2831. // Check if the condition of the select has one use or two users that are both
  2832. // selects with the same condition.
  2833. static bool hasOnlySelectUsers(const Value *Cond) {
  2834. return llvm::all_of(Cond->users(), [](const Value *V) {
  2835. return isa<SelectInst>(V);
  2836. });
  2837. }
  2838. void SelectionDAGBuilder::visitSelect(const User &I) {
  2839. SmallVector<EVT, 4> ValueVTs;
  2840. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2841. ValueVTs);
  2842. unsigned NumValues = ValueVTs.size();
  2843. if (NumValues == 0) return;
  2844. SmallVector<SDValue, 4> Values(NumValues);
  2845. SDValue Cond = getValue(I.getOperand(0));
  2846. SDValue LHSVal = getValue(I.getOperand(1));
  2847. SDValue RHSVal = getValue(I.getOperand(2));
  2848. auto BaseOps = {Cond};
  2849. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2850. ISD::VSELECT : ISD::SELECT;
  2851. bool IsUnaryAbs = false;
  2852. // Min/max matching is only viable if all output VTs are the same.
  2853. if (is_splat(ValueVTs)) {
  2854. EVT VT = ValueVTs[0];
  2855. LLVMContext &Ctx = *DAG.getContext();
  2856. auto &TLI = DAG.getTargetLoweringInfo();
  2857. // We care about the legality of the operation after it has been type
  2858. // legalized.
  2859. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2860. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2861. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2862. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2863. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2864. // min/max is legal on the scalar type.
  2865. bool UseScalarMinMax = VT.isVector() &&
  2866. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2867. Value *LHS, *RHS;
  2868. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2869. ISD::NodeType Opc = ISD::DELETED_NODE;
  2870. switch (SPR.Flavor) {
  2871. case SPF_UMAX: Opc = ISD::UMAX; break;
  2872. case SPF_UMIN: Opc = ISD::UMIN; break;
  2873. case SPF_SMAX: Opc = ISD::SMAX; break;
  2874. case SPF_SMIN: Opc = ISD::SMIN; break;
  2875. case SPF_FMINNUM:
  2876. switch (SPR.NaNBehavior) {
  2877. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2878. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2879. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2880. case SPNB_RETURNS_ANY: {
  2881. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2882. Opc = ISD::FMINNUM;
  2883. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2884. Opc = ISD::FMINIMUM;
  2885. else if (UseScalarMinMax)
  2886. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2887. ISD::FMINNUM : ISD::FMINIMUM;
  2888. break;
  2889. }
  2890. }
  2891. break;
  2892. case SPF_FMAXNUM:
  2893. switch (SPR.NaNBehavior) {
  2894. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2895. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2896. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2897. case SPNB_RETURNS_ANY:
  2898. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2899. Opc = ISD::FMAXNUM;
  2900. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2901. Opc = ISD::FMAXIMUM;
  2902. else if (UseScalarMinMax)
  2903. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2904. ISD::FMAXNUM : ISD::FMAXIMUM;
  2905. break;
  2906. }
  2907. break;
  2908. case SPF_ABS:
  2909. IsUnaryAbs = true;
  2910. Opc = ISD::ABS;
  2911. break;
  2912. case SPF_NABS:
  2913. // TODO: we need to produce sub(0, abs(X)).
  2914. default: break;
  2915. }
  2916. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2917. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2918. (UseScalarMinMax &&
  2919. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2920. // If the underlying comparison instruction is used by any other
  2921. // instruction, the consumed instructions won't be destroyed, so it is
  2922. // not profitable to convert to a min/max.
  2923. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2924. OpCode = Opc;
  2925. LHSVal = getValue(LHS);
  2926. RHSVal = getValue(RHS);
  2927. BaseOps = {};
  2928. }
  2929. if (IsUnaryAbs) {
  2930. OpCode = Opc;
  2931. LHSVal = getValue(LHS);
  2932. BaseOps = {};
  2933. }
  2934. }
  2935. if (IsUnaryAbs) {
  2936. for (unsigned i = 0; i != NumValues; ++i) {
  2937. Values[i] =
  2938. DAG.getNode(OpCode, getCurSDLoc(),
  2939. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2940. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2941. }
  2942. } else {
  2943. for (unsigned i = 0; i != NumValues; ++i) {
  2944. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2945. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2946. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2947. Values[i] = DAG.getNode(
  2948. OpCode, getCurSDLoc(),
  2949. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2950. }
  2951. }
  2952. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2953. DAG.getVTList(ValueVTs), Values));
  2954. }
  2955. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2956. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2957. SDValue N = getValue(I.getOperand(0));
  2958. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2959. I.getType());
  2960. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2961. }
  2962. void SelectionDAGBuilder::visitZExt(const User &I) {
  2963. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2964. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2965. SDValue N = getValue(I.getOperand(0));
  2966. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2967. I.getType());
  2968. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2969. }
  2970. void SelectionDAGBuilder::visitSExt(const User &I) {
  2971. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2972. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2973. SDValue N = getValue(I.getOperand(0));
  2974. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2975. I.getType());
  2976. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2977. }
  2978. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2979. // FPTrunc is never a no-op cast, no need to check
  2980. SDValue N = getValue(I.getOperand(0));
  2981. SDLoc dl = getCurSDLoc();
  2982. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2983. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2984. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2985. DAG.getTargetConstant(
  2986. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2987. }
  2988. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2989. // FPExt is never a no-op cast, no need to check
  2990. SDValue N = getValue(I.getOperand(0));
  2991. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2992. I.getType());
  2993. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2994. }
  2995. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2996. // FPToUI is never a no-op cast, no need to check
  2997. SDValue N = getValue(I.getOperand(0));
  2998. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2999. I.getType());
  3000. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3001. }
  3002. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3003. // FPToSI is never a no-op cast, no need to check
  3004. SDValue N = getValue(I.getOperand(0));
  3005. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3006. I.getType());
  3007. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3008. }
  3009. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3010. // UIToFP is never a no-op cast, no need to check
  3011. SDValue N = getValue(I.getOperand(0));
  3012. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3013. I.getType());
  3014. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3015. }
  3016. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3017. // SIToFP is never a no-op cast, no need to check
  3018. SDValue N = getValue(I.getOperand(0));
  3019. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3020. I.getType());
  3021. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3022. }
  3023. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3024. // What to do depends on the size of the integer and the size of the pointer.
  3025. // We can either truncate, zero extend, or no-op, accordingly.
  3026. SDValue N = getValue(I.getOperand(0));
  3027. auto &TLI = DAG.getTargetLoweringInfo();
  3028. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3029. I.getType());
  3030. EVT PtrMemVT =
  3031. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3032. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3033. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3034. setValue(&I, N);
  3035. }
  3036. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3037. // What to do depends on the size of the integer and the size of the pointer.
  3038. // We can either truncate, zero extend, or no-op, accordingly.
  3039. SDValue N = getValue(I.getOperand(0));
  3040. auto &TLI = DAG.getTargetLoweringInfo();
  3041. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3042. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3043. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3044. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3045. setValue(&I, N);
  3046. }
  3047. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3048. SDValue N = getValue(I.getOperand(0));
  3049. SDLoc dl = getCurSDLoc();
  3050. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3051. I.getType());
  3052. // BitCast assures us that source and destination are the same size so this is
  3053. // either a BITCAST or a no-op.
  3054. if (DestVT != N.getValueType())
  3055. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3056. DestVT, N)); // convert types.
  3057. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3058. // might fold any kind of constant expression to an integer constant and that
  3059. // is not what we are looking for. Only recognize a bitcast of a genuine
  3060. // constant integer as an opaque constant.
  3061. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3062. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3063. /*isOpaque*/true));
  3064. else
  3065. setValue(&I, N); // noop cast.
  3066. }
  3067. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3068. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3069. const Value *SV = I.getOperand(0);
  3070. SDValue N = getValue(SV);
  3071. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3072. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3073. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3074. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3075. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3076. setValue(&I, N);
  3077. }
  3078. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3079. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3080. SDValue InVec = getValue(I.getOperand(0));
  3081. SDValue InVal = getValue(I.getOperand(1));
  3082. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3083. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3084. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3085. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3086. InVec, InVal, InIdx));
  3087. }
  3088. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3089. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3090. SDValue InVec = getValue(I.getOperand(0));
  3091. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3092. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3093. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3094. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3095. InVec, InIdx));
  3096. }
  3097. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3098. SDValue Src1 = getValue(I.getOperand(0));
  3099. SDValue Src2 = getValue(I.getOperand(1));
  3100. SDLoc DL = getCurSDLoc();
  3101. SmallVector<int, 8> Mask;
  3102. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3103. unsigned MaskNumElts = Mask.size();
  3104. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3105. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3106. EVT SrcVT = Src1.getValueType();
  3107. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3108. if (SrcNumElts == MaskNumElts) {
  3109. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3110. return;
  3111. }
  3112. // Normalize the shuffle vector since mask and vector length don't match.
  3113. if (SrcNumElts < MaskNumElts) {
  3114. // Mask is longer than the source vectors. We can use concatenate vector to
  3115. // make the mask and vectors lengths match.
  3116. if (MaskNumElts % SrcNumElts == 0) {
  3117. // Mask length is a multiple of the source vector length.
  3118. // Check if the shuffle is some kind of concatenation of the input
  3119. // vectors.
  3120. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3121. bool IsConcat = true;
  3122. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3123. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3124. int Idx = Mask[i];
  3125. if (Idx < 0)
  3126. continue;
  3127. // Ensure the indices in each SrcVT sized piece are sequential and that
  3128. // the same source is used for the whole piece.
  3129. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3130. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3131. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3132. IsConcat = false;
  3133. break;
  3134. }
  3135. // Remember which source this index came from.
  3136. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3137. }
  3138. // The shuffle is concatenating multiple vectors together. Just emit
  3139. // a CONCAT_VECTORS operation.
  3140. if (IsConcat) {
  3141. SmallVector<SDValue, 8> ConcatOps;
  3142. for (auto Src : ConcatSrcs) {
  3143. if (Src < 0)
  3144. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3145. else if (Src == 0)
  3146. ConcatOps.push_back(Src1);
  3147. else
  3148. ConcatOps.push_back(Src2);
  3149. }
  3150. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3151. return;
  3152. }
  3153. }
  3154. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3155. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3156. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3157. PaddedMaskNumElts);
  3158. // Pad both vectors with undefs to make them the same length as the mask.
  3159. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3160. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3161. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3162. MOps1[0] = Src1;
  3163. MOps2[0] = Src2;
  3164. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3165. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3166. // Readjust mask for new input vector length.
  3167. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3168. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3169. int Idx = Mask[i];
  3170. if (Idx >= (int)SrcNumElts)
  3171. Idx -= SrcNumElts - PaddedMaskNumElts;
  3172. MappedOps[i] = Idx;
  3173. }
  3174. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3175. // If the concatenated vector was padded, extract a subvector with the
  3176. // correct number of elements.
  3177. if (MaskNumElts != PaddedMaskNumElts)
  3178. Result = DAG.getNode(
  3179. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3180. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3181. setValue(&I, Result);
  3182. return;
  3183. }
  3184. if (SrcNumElts > MaskNumElts) {
  3185. // Analyze the access pattern of the vector to see if we can extract
  3186. // two subvectors and do the shuffle.
  3187. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3188. bool CanExtract = true;
  3189. for (int Idx : Mask) {
  3190. unsigned Input = 0;
  3191. if (Idx < 0)
  3192. continue;
  3193. if (Idx >= (int)SrcNumElts) {
  3194. Input = 1;
  3195. Idx -= SrcNumElts;
  3196. }
  3197. // If all the indices come from the same MaskNumElts sized portion of
  3198. // the sources we can use extract. Also make sure the extract wouldn't
  3199. // extract past the end of the source.
  3200. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3201. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3202. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3203. CanExtract = false;
  3204. // Make sure we always update StartIdx as we use it to track if all
  3205. // elements are undef.
  3206. StartIdx[Input] = NewStartIdx;
  3207. }
  3208. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3209. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3210. return;
  3211. }
  3212. if (CanExtract) {
  3213. // Extract appropriate subvector and generate a vector shuffle
  3214. for (unsigned Input = 0; Input < 2; ++Input) {
  3215. SDValue &Src = Input == 0 ? Src1 : Src2;
  3216. if (StartIdx[Input] < 0)
  3217. Src = DAG.getUNDEF(VT);
  3218. else {
  3219. Src = DAG.getNode(
  3220. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3221. DAG.getConstant(StartIdx[Input], DL,
  3222. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3223. }
  3224. }
  3225. // Calculate new mask.
  3226. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3227. for (int &Idx : MappedOps) {
  3228. if (Idx >= (int)SrcNumElts)
  3229. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3230. else if (Idx >= 0)
  3231. Idx -= StartIdx[0];
  3232. }
  3233. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3234. return;
  3235. }
  3236. }
  3237. // We can't use either concat vectors or extract subvectors so fall back to
  3238. // replacing the shuffle with extract and build vector.
  3239. // to insert and build vector.
  3240. EVT EltVT = VT.getVectorElementType();
  3241. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3242. SmallVector<SDValue,8> Ops;
  3243. for (int Idx : Mask) {
  3244. SDValue Res;
  3245. if (Idx < 0) {
  3246. Res = DAG.getUNDEF(EltVT);
  3247. } else {
  3248. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3249. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3250. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3251. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3252. }
  3253. Ops.push_back(Res);
  3254. }
  3255. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3256. }
  3257. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3258. ArrayRef<unsigned> Indices;
  3259. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3260. Indices = IV->getIndices();
  3261. else
  3262. Indices = cast<ConstantExpr>(&I)->getIndices();
  3263. const Value *Op0 = I.getOperand(0);
  3264. const Value *Op1 = I.getOperand(1);
  3265. Type *AggTy = I.getType();
  3266. Type *ValTy = Op1->getType();
  3267. bool IntoUndef = isa<UndefValue>(Op0);
  3268. bool FromUndef = isa<UndefValue>(Op1);
  3269. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3270. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3271. SmallVector<EVT, 4> AggValueVTs;
  3272. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3273. SmallVector<EVT, 4> ValValueVTs;
  3274. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3275. unsigned NumAggValues = AggValueVTs.size();
  3276. unsigned NumValValues = ValValueVTs.size();
  3277. SmallVector<SDValue, 4> Values(NumAggValues);
  3278. // Ignore an insertvalue that produces an empty object
  3279. if (!NumAggValues) {
  3280. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3281. return;
  3282. }
  3283. SDValue Agg = getValue(Op0);
  3284. unsigned i = 0;
  3285. // Copy the beginning value(s) from the original aggregate.
  3286. for (; i != LinearIndex; ++i)
  3287. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3288. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3289. // Copy values from the inserted value(s).
  3290. if (NumValValues) {
  3291. SDValue Val = getValue(Op1);
  3292. for (; i != LinearIndex + NumValValues; ++i)
  3293. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3294. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3295. }
  3296. // Copy remaining value(s) from the original aggregate.
  3297. for (; i != NumAggValues; ++i)
  3298. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3299. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3300. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3301. DAG.getVTList(AggValueVTs), Values));
  3302. }
  3303. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3304. ArrayRef<unsigned> Indices;
  3305. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3306. Indices = EV->getIndices();
  3307. else
  3308. Indices = cast<ConstantExpr>(&I)->getIndices();
  3309. const Value *Op0 = I.getOperand(0);
  3310. Type *AggTy = Op0->getType();
  3311. Type *ValTy = I.getType();
  3312. bool OutOfUndef = isa<UndefValue>(Op0);
  3313. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3314. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3315. SmallVector<EVT, 4> ValValueVTs;
  3316. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3317. unsigned NumValValues = ValValueVTs.size();
  3318. // Ignore a extractvalue that produces an empty object
  3319. if (!NumValValues) {
  3320. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3321. return;
  3322. }
  3323. SmallVector<SDValue, 4> Values(NumValValues);
  3324. SDValue Agg = getValue(Op0);
  3325. // Copy out the selected value(s).
  3326. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3327. Values[i - LinearIndex] =
  3328. OutOfUndef ?
  3329. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3330. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3331. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3332. DAG.getVTList(ValValueVTs), Values));
  3333. }
  3334. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3335. Value *Op0 = I.getOperand(0);
  3336. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3337. // element which holds a pointer.
  3338. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3339. SDValue N = getValue(Op0);
  3340. SDLoc dl = getCurSDLoc();
  3341. auto &TLI = DAG.getTargetLoweringInfo();
  3342. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3343. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3344. // Normalize Vector GEP - all scalar operands should be converted to the
  3345. // splat vector.
  3346. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3347. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3348. if (VectorWidth && !N.getValueType().isVector()) {
  3349. LLVMContext &Context = *DAG.getContext();
  3350. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3351. N = DAG.getSplatBuildVector(VT, dl, N);
  3352. }
  3353. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3354. GTI != E; ++GTI) {
  3355. const Value *Idx = GTI.getOperand();
  3356. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3357. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3358. if (Field) {
  3359. // N = N + Offset
  3360. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3361. // In an inbounds GEP with an offset that is nonnegative even when
  3362. // interpreted as signed, assume there is no unsigned overflow.
  3363. SDNodeFlags Flags;
  3364. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3365. Flags.setNoUnsignedWrap(true);
  3366. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3367. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3368. }
  3369. } else {
  3370. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3371. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3372. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3373. // If this is a scalar constant or a splat vector of constants,
  3374. // handle it quickly.
  3375. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3376. if (!CI && isa<ConstantDataVector>(Idx) &&
  3377. cast<ConstantDataVector>(Idx)->getSplatValue())
  3378. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3379. if (CI) {
  3380. if (CI->isZero())
  3381. continue;
  3382. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3383. LLVMContext &Context = *DAG.getContext();
  3384. SDValue OffsVal = VectorWidth ?
  3385. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3386. DAG.getConstant(Offs, dl, IdxTy);
  3387. // In an inbouds GEP with an offset that is nonnegative even when
  3388. // interpreted as signed, assume there is no unsigned overflow.
  3389. SDNodeFlags Flags;
  3390. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3391. Flags.setNoUnsignedWrap(true);
  3392. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3393. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3394. continue;
  3395. }
  3396. // N = N + Idx * ElementSize;
  3397. SDValue IdxN = getValue(Idx);
  3398. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3399. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3400. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3401. }
  3402. // If the index is smaller or larger than intptr_t, truncate or extend
  3403. // it.
  3404. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3405. // If this is a multiply by a power of two, turn it into a shl
  3406. // immediately. This is a very common case.
  3407. if (ElementSize != 1) {
  3408. if (ElementSize.isPowerOf2()) {
  3409. unsigned Amt = ElementSize.logBase2();
  3410. IdxN = DAG.getNode(ISD::SHL, dl,
  3411. N.getValueType(), IdxN,
  3412. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3413. } else {
  3414. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3415. IdxN.getValueType());
  3416. IdxN = DAG.getNode(ISD::MUL, dl,
  3417. N.getValueType(), IdxN, Scale);
  3418. }
  3419. }
  3420. N = DAG.getNode(ISD::ADD, dl,
  3421. N.getValueType(), N, IdxN);
  3422. }
  3423. }
  3424. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3425. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3426. setValue(&I, N);
  3427. }
  3428. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3429. // If this is a fixed sized alloca in the entry block of the function,
  3430. // allocate it statically on the stack.
  3431. if (FuncInfo.StaticAllocaMap.count(&I))
  3432. return; // getValue will auto-populate this.
  3433. SDLoc dl = getCurSDLoc();
  3434. Type *Ty = I.getAllocatedType();
  3435. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3436. auto &DL = DAG.getDataLayout();
  3437. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3438. unsigned Align =
  3439. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3440. SDValue AllocSize = getValue(I.getArraySize());
  3441. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3442. if (AllocSize.getValueType() != IntPtr)
  3443. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3444. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3445. AllocSize,
  3446. DAG.getConstant(TySize, dl, IntPtr));
  3447. // Handle alignment. If the requested alignment is less than or equal to
  3448. // the stack alignment, ignore it. If the size is greater than or equal to
  3449. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3450. unsigned StackAlign =
  3451. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3452. if (Align <= StackAlign)
  3453. Align = 0;
  3454. // Round the size of the allocation up to the stack alignment size
  3455. // by add SA-1 to the size. This doesn't overflow because we're computing
  3456. // an address inside an alloca.
  3457. SDNodeFlags Flags;
  3458. Flags.setNoUnsignedWrap(true);
  3459. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3460. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3461. // Mask out the low bits for alignment purposes.
  3462. AllocSize =
  3463. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3464. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3465. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3466. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3467. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3468. setValue(&I, DSA);
  3469. DAG.setRoot(DSA.getValue(1));
  3470. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3471. }
  3472. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3473. if (I.isAtomic())
  3474. return visitAtomicLoad(I);
  3475. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3476. const Value *SV = I.getOperand(0);
  3477. if (TLI.supportSwiftError()) {
  3478. // Swifterror values can come from either a function parameter with
  3479. // swifterror attribute or an alloca with swifterror attribute.
  3480. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3481. if (Arg->hasSwiftErrorAttr())
  3482. return visitLoadFromSwiftError(I);
  3483. }
  3484. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3485. if (Alloca->isSwiftError())
  3486. return visitLoadFromSwiftError(I);
  3487. }
  3488. }
  3489. SDValue Ptr = getValue(SV);
  3490. Type *Ty = I.getType();
  3491. bool isVolatile = I.isVolatile();
  3492. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3493. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3494. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3495. unsigned Alignment = I.getAlignment();
  3496. AAMDNodes AAInfo;
  3497. I.getAAMetadata(AAInfo);
  3498. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3499. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3500. SmallVector<uint64_t, 4> Offsets;
  3501. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3502. unsigned NumValues = ValueVTs.size();
  3503. if (NumValues == 0)
  3504. return;
  3505. SDValue Root;
  3506. bool ConstantMemory = false;
  3507. if (isVolatile || NumValues > MaxParallelChains)
  3508. // Serialize volatile loads with other side effects.
  3509. Root = getRoot();
  3510. else if (AA &&
  3511. AA->pointsToConstantMemory(MemoryLocation(
  3512. SV,
  3513. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3514. AAInfo))) {
  3515. // Do not serialize (non-volatile) loads of constant memory with anything.
  3516. Root = DAG.getEntryNode();
  3517. ConstantMemory = true;
  3518. } else {
  3519. // Do not serialize non-volatile loads against each other.
  3520. Root = DAG.getRoot();
  3521. }
  3522. SDLoc dl = getCurSDLoc();
  3523. if (isVolatile)
  3524. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3525. // An aggregate load cannot wrap around the address space, so offsets to its
  3526. // parts don't wrap either.
  3527. SDNodeFlags Flags;
  3528. Flags.setNoUnsignedWrap(true);
  3529. SmallVector<SDValue, 4> Values(NumValues);
  3530. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3531. EVT PtrVT = Ptr.getValueType();
  3532. unsigned ChainI = 0;
  3533. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3534. // Serializing loads here may result in excessive register pressure, and
  3535. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3536. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3537. // they are side-effect free or do not alias. The optimizer should really
  3538. // avoid this case by converting large object/array copies to llvm.memcpy
  3539. // (MaxParallelChains should always remain as failsafe).
  3540. if (ChainI == MaxParallelChains) {
  3541. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3542. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3543. makeArrayRef(Chains.data(), ChainI));
  3544. Root = Chain;
  3545. ChainI = 0;
  3546. }
  3547. SDValue A = DAG.getNode(ISD::ADD, dl,
  3548. PtrVT, Ptr,
  3549. DAG.getConstant(Offsets[i], dl, PtrVT),
  3550. Flags);
  3551. auto MMOFlags = MachineMemOperand::MONone;
  3552. if (isVolatile)
  3553. MMOFlags |= MachineMemOperand::MOVolatile;
  3554. if (isNonTemporal)
  3555. MMOFlags |= MachineMemOperand::MONonTemporal;
  3556. if (isInvariant)
  3557. MMOFlags |= MachineMemOperand::MOInvariant;
  3558. if (isDereferenceable)
  3559. MMOFlags |= MachineMemOperand::MODereferenceable;
  3560. MMOFlags |= TLI.getMMOFlags(I);
  3561. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3562. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3563. MMOFlags, AAInfo, Ranges);
  3564. Chains[ChainI] = L.getValue(1);
  3565. if (MemVTs[i] != ValueVTs[i])
  3566. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3567. Values[i] = L;
  3568. }
  3569. if (!ConstantMemory) {
  3570. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3571. makeArrayRef(Chains.data(), ChainI));
  3572. if (isVolatile)
  3573. DAG.setRoot(Chain);
  3574. else
  3575. PendingLoads.push_back(Chain);
  3576. }
  3577. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3578. DAG.getVTList(ValueVTs), Values));
  3579. }
  3580. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3581. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3582. "call visitStoreToSwiftError when backend supports swifterror");
  3583. SmallVector<EVT, 4> ValueVTs;
  3584. SmallVector<uint64_t, 4> Offsets;
  3585. const Value *SrcV = I.getOperand(0);
  3586. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3587. SrcV->getType(), ValueVTs, &Offsets);
  3588. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3589. "expect a single EVT for swifterror");
  3590. SDValue Src = getValue(SrcV);
  3591. // Create a virtual register, then update the virtual register.
  3592. unsigned VReg =
  3593. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3594. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3595. // Chain can be getRoot or getControlRoot.
  3596. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3597. SDValue(Src.getNode(), Src.getResNo()));
  3598. DAG.setRoot(CopyNode);
  3599. }
  3600. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3601. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3602. "call visitLoadFromSwiftError when backend supports swifterror");
  3603. assert(!I.isVolatile() &&
  3604. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3605. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3606. "Support volatile, non temporal, invariant for load_from_swift_error");
  3607. const Value *SV = I.getOperand(0);
  3608. Type *Ty = I.getType();
  3609. AAMDNodes AAInfo;
  3610. I.getAAMetadata(AAInfo);
  3611. assert(
  3612. (!AA ||
  3613. !AA->pointsToConstantMemory(MemoryLocation(
  3614. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3615. AAInfo))) &&
  3616. "load_from_swift_error should not be constant memory");
  3617. SmallVector<EVT, 4> ValueVTs;
  3618. SmallVector<uint64_t, 4> Offsets;
  3619. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3620. ValueVTs, &Offsets);
  3621. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3622. "expect a single EVT for swifterror");
  3623. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3624. SDValue L = DAG.getCopyFromReg(
  3625. getRoot(), getCurSDLoc(),
  3626. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3627. setValue(&I, L);
  3628. }
  3629. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3630. if (I.isAtomic())
  3631. return visitAtomicStore(I);
  3632. const Value *SrcV = I.getOperand(0);
  3633. const Value *PtrV = I.getOperand(1);
  3634. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3635. if (TLI.supportSwiftError()) {
  3636. // Swifterror values can come from either a function parameter with
  3637. // swifterror attribute or an alloca with swifterror attribute.
  3638. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3639. if (Arg->hasSwiftErrorAttr())
  3640. return visitStoreToSwiftError(I);
  3641. }
  3642. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3643. if (Alloca->isSwiftError())
  3644. return visitStoreToSwiftError(I);
  3645. }
  3646. }
  3647. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3648. SmallVector<uint64_t, 4> Offsets;
  3649. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3650. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3651. unsigned NumValues = ValueVTs.size();
  3652. if (NumValues == 0)
  3653. return;
  3654. // Get the lowered operands. Note that we do this after
  3655. // checking if NumResults is zero, because with zero results
  3656. // the operands won't have values in the map.
  3657. SDValue Src = getValue(SrcV);
  3658. SDValue Ptr = getValue(PtrV);
  3659. SDValue Root = getRoot();
  3660. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3661. SDLoc dl = getCurSDLoc();
  3662. EVT PtrVT = Ptr.getValueType();
  3663. unsigned Alignment = I.getAlignment();
  3664. AAMDNodes AAInfo;
  3665. I.getAAMetadata(AAInfo);
  3666. auto MMOFlags = MachineMemOperand::MONone;
  3667. if (I.isVolatile())
  3668. MMOFlags |= MachineMemOperand::MOVolatile;
  3669. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3670. MMOFlags |= MachineMemOperand::MONonTemporal;
  3671. MMOFlags |= TLI.getMMOFlags(I);
  3672. // An aggregate load cannot wrap around the address space, so offsets to its
  3673. // parts don't wrap either.
  3674. SDNodeFlags Flags;
  3675. Flags.setNoUnsignedWrap(true);
  3676. unsigned ChainI = 0;
  3677. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3678. // See visitLoad comments.
  3679. if (ChainI == MaxParallelChains) {
  3680. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3681. makeArrayRef(Chains.data(), ChainI));
  3682. Root = Chain;
  3683. ChainI = 0;
  3684. }
  3685. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3686. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3687. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3688. if (MemVTs[i] != ValueVTs[i])
  3689. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3690. SDValue St =
  3691. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3692. Alignment, MMOFlags, AAInfo);
  3693. Chains[ChainI] = St;
  3694. }
  3695. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3696. makeArrayRef(Chains.data(), ChainI));
  3697. DAG.setRoot(StoreNode);
  3698. }
  3699. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3700. bool IsCompressing) {
  3701. SDLoc sdl = getCurSDLoc();
  3702. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3703. unsigned& Alignment) {
  3704. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3705. Src0 = I.getArgOperand(0);
  3706. Ptr = I.getArgOperand(1);
  3707. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3708. Mask = I.getArgOperand(3);
  3709. };
  3710. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3711. unsigned& Alignment) {
  3712. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3713. Src0 = I.getArgOperand(0);
  3714. Ptr = I.getArgOperand(1);
  3715. Mask = I.getArgOperand(2);
  3716. Alignment = 0;
  3717. };
  3718. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3719. unsigned Alignment;
  3720. if (IsCompressing)
  3721. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3722. else
  3723. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3724. SDValue Ptr = getValue(PtrOperand);
  3725. SDValue Src0 = getValue(Src0Operand);
  3726. SDValue Mask = getValue(MaskOperand);
  3727. EVT VT = Src0.getValueType();
  3728. if (!Alignment)
  3729. Alignment = DAG.getEVTAlignment(VT);
  3730. AAMDNodes AAInfo;
  3731. I.getAAMetadata(AAInfo);
  3732. MachineMemOperand *MMO =
  3733. DAG.getMachineFunction().
  3734. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3735. MachineMemOperand::MOStore, VT.getStoreSize(),
  3736. Alignment, AAInfo);
  3737. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3738. MMO, false /* Truncating */,
  3739. IsCompressing);
  3740. DAG.setRoot(StoreNode);
  3741. setValue(&I, StoreNode);
  3742. }
  3743. // Get a uniform base for the Gather/Scatter intrinsic.
  3744. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3745. // We try to represent it as a base pointer + vector of indices.
  3746. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3747. // The first operand of the GEP may be a single pointer or a vector of pointers
  3748. // Example:
  3749. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3750. // or
  3751. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3752. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3753. //
  3754. // When the first GEP operand is a single pointer - it is the uniform base we
  3755. // are looking for. If first operand of the GEP is a splat vector - we
  3756. // extract the splat value and use it as a uniform base.
  3757. // In all other cases the function returns 'false'.
  3758. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3759. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3760. SelectionDAG& DAG = SDB->DAG;
  3761. LLVMContext &Context = *DAG.getContext();
  3762. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3763. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3764. if (!GEP)
  3765. return false;
  3766. const Value *GEPPtr = GEP->getPointerOperand();
  3767. if (!GEPPtr->getType()->isVectorTy())
  3768. Ptr = GEPPtr;
  3769. else if (!(Ptr = getSplatValue(GEPPtr)))
  3770. return false;
  3771. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3772. Value *IndexVal = GEP->getOperand(FinalIndex);
  3773. // Ensure all the other indices are 0.
  3774. for (unsigned i = 1; i < FinalIndex; ++i) {
  3775. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3776. if (!C || !C->isZero())
  3777. return false;
  3778. }
  3779. // The operands of the GEP may be defined in another basic block.
  3780. // In this case we'll not find nodes for the operands.
  3781. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3782. return false;
  3783. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3784. const DataLayout &DL = DAG.getDataLayout();
  3785. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3786. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3787. Base = SDB->getValue(Ptr);
  3788. Index = SDB->getValue(IndexVal);
  3789. if (!Index.getValueType().isVector()) {
  3790. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3791. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3792. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3793. }
  3794. return true;
  3795. }
  3796. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3797. SDLoc sdl = getCurSDLoc();
  3798. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3799. const Value *Ptr = I.getArgOperand(1);
  3800. SDValue Src0 = getValue(I.getArgOperand(0));
  3801. SDValue Mask = getValue(I.getArgOperand(3));
  3802. EVT VT = Src0.getValueType();
  3803. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3804. if (!Alignment)
  3805. Alignment = DAG.getEVTAlignment(VT);
  3806. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3807. AAMDNodes AAInfo;
  3808. I.getAAMetadata(AAInfo);
  3809. SDValue Base;
  3810. SDValue Index;
  3811. SDValue Scale;
  3812. const Value *BasePtr = Ptr;
  3813. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3814. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3815. MachineMemOperand *MMO = DAG.getMachineFunction().
  3816. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3817. MachineMemOperand::MOStore, VT.getStoreSize(),
  3818. Alignment, AAInfo);
  3819. if (!UniformBase) {
  3820. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3821. Index = getValue(Ptr);
  3822. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3823. }
  3824. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3825. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3826. Ops, MMO);
  3827. DAG.setRoot(Scatter);
  3828. setValue(&I, Scatter);
  3829. }
  3830. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3831. SDLoc sdl = getCurSDLoc();
  3832. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3833. unsigned& Alignment) {
  3834. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3835. Ptr = I.getArgOperand(0);
  3836. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3837. Mask = I.getArgOperand(2);
  3838. Src0 = I.getArgOperand(3);
  3839. };
  3840. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3841. unsigned& Alignment) {
  3842. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3843. Ptr = I.getArgOperand(0);
  3844. Alignment = 0;
  3845. Mask = I.getArgOperand(1);
  3846. Src0 = I.getArgOperand(2);
  3847. };
  3848. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3849. unsigned Alignment;
  3850. if (IsExpanding)
  3851. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3852. else
  3853. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3854. SDValue Ptr = getValue(PtrOperand);
  3855. SDValue Src0 = getValue(Src0Operand);
  3856. SDValue Mask = getValue(MaskOperand);
  3857. EVT VT = Src0.getValueType();
  3858. if (!Alignment)
  3859. Alignment = DAG.getEVTAlignment(VT);
  3860. AAMDNodes AAInfo;
  3861. I.getAAMetadata(AAInfo);
  3862. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3863. // Do not serialize masked loads of constant memory with anything.
  3864. bool AddToChain =
  3865. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3866. PtrOperand,
  3867. LocationSize::precise(
  3868. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3869. AAInfo));
  3870. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3871. MachineMemOperand *MMO =
  3872. DAG.getMachineFunction().
  3873. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3874. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3875. Alignment, AAInfo, Ranges);
  3876. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3877. ISD::NON_EXTLOAD, IsExpanding);
  3878. if (AddToChain)
  3879. PendingLoads.push_back(Load.getValue(1));
  3880. setValue(&I, Load);
  3881. }
  3882. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3883. SDLoc sdl = getCurSDLoc();
  3884. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3885. const Value *Ptr = I.getArgOperand(0);
  3886. SDValue Src0 = getValue(I.getArgOperand(3));
  3887. SDValue Mask = getValue(I.getArgOperand(2));
  3888. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3889. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3890. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3891. if (!Alignment)
  3892. Alignment = DAG.getEVTAlignment(VT);
  3893. AAMDNodes AAInfo;
  3894. I.getAAMetadata(AAInfo);
  3895. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3896. SDValue Root = DAG.getRoot();
  3897. SDValue Base;
  3898. SDValue Index;
  3899. SDValue Scale;
  3900. const Value *BasePtr = Ptr;
  3901. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3902. bool ConstantMemory = false;
  3903. if (UniformBase && AA &&
  3904. AA->pointsToConstantMemory(
  3905. MemoryLocation(BasePtr,
  3906. LocationSize::precise(
  3907. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3908. AAInfo))) {
  3909. // Do not serialize (non-volatile) loads of constant memory with anything.
  3910. Root = DAG.getEntryNode();
  3911. ConstantMemory = true;
  3912. }
  3913. MachineMemOperand *MMO =
  3914. DAG.getMachineFunction().
  3915. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3916. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3917. Alignment, AAInfo, Ranges);
  3918. if (!UniformBase) {
  3919. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3920. Index = getValue(Ptr);
  3921. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3922. }
  3923. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3924. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3925. Ops, MMO);
  3926. SDValue OutChain = Gather.getValue(1);
  3927. if (!ConstantMemory)
  3928. PendingLoads.push_back(OutChain);
  3929. setValue(&I, Gather);
  3930. }
  3931. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3932. SDLoc dl = getCurSDLoc();
  3933. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3934. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3935. SyncScope::ID SSID = I.getSyncScopeID();
  3936. SDValue InChain = getRoot();
  3937. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3938. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3939. auto Alignment = DAG.getEVTAlignment(MemVT);
  3940. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3941. if (I.isVolatile())
  3942. Flags |= MachineMemOperand::MOVolatile;
  3943. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3944. MachineFunction &MF = DAG.getMachineFunction();
  3945. MachineMemOperand *MMO =
  3946. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3947. Flags, MemVT.getStoreSize(), Alignment,
  3948. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3949. FailureOrdering);
  3950. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3951. dl, MemVT, VTs, InChain,
  3952. getValue(I.getPointerOperand()),
  3953. getValue(I.getCompareOperand()),
  3954. getValue(I.getNewValOperand()), MMO);
  3955. SDValue OutChain = L.getValue(2);
  3956. setValue(&I, L);
  3957. DAG.setRoot(OutChain);
  3958. }
  3959. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3960. SDLoc dl = getCurSDLoc();
  3961. ISD::NodeType NT;
  3962. switch (I.getOperation()) {
  3963. default: llvm_unreachable("Unknown atomicrmw operation");
  3964. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3965. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3966. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3967. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3968. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3969. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3970. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3971. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3972. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3973. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3974. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3975. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3976. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3977. }
  3978. AtomicOrdering Ordering = I.getOrdering();
  3979. SyncScope::ID SSID = I.getSyncScopeID();
  3980. SDValue InChain = getRoot();
  3981. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3982. auto Alignment = DAG.getEVTAlignment(MemVT);
  3983. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3984. if (I.isVolatile())
  3985. Flags |= MachineMemOperand::MOVolatile;
  3986. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3987. MachineFunction &MF = DAG.getMachineFunction();
  3988. MachineMemOperand *MMO =
  3989. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  3990. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  3991. nullptr, SSID, Ordering);
  3992. SDValue L =
  3993. DAG.getAtomic(NT, dl, MemVT, InChain,
  3994. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  3995. MMO);
  3996. SDValue OutChain = L.getValue(1);
  3997. setValue(&I, L);
  3998. DAG.setRoot(OutChain);
  3999. }
  4000. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4001. SDLoc dl = getCurSDLoc();
  4002. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4003. SDValue Ops[3];
  4004. Ops[0] = getRoot();
  4005. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4006. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4007. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4008. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4009. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4010. }
  4011. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4012. SDLoc dl = getCurSDLoc();
  4013. AtomicOrdering Order = I.getOrdering();
  4014. SyncScope::ID SSID = I.getSyncScopeID();
  4015. SDValue InChain = getRoot();
  4016. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4017. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4018. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4019. if (!TLI.supportsUnalignedAtomics() &&
  4020. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4021. report_fatal_error("Cannot generate unaligned atomic load");
  4022. auto Flags = MachineMemOperand::MOLoad;
  4023. if (I.isVolatile())
  4024. Flags |= MachineMemOperand::MOVolatile;
  4025. if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
  4026. Flags |= MachineMemOperand::MOInvariant;
  4027. if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
  4028. Flags |= MachineMemOperand::MODereferenceable;
  4029. Flags |= TLI.getMMOFlags(I);
  4030. MachineMemOperand *MMO =
  4031. DAG.getMachineFunction().
  4032. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4033. Flags, MemVT.getStoreSize(),
  4034. I.getAlignment() ? I.getAlignment() :
  4035. DAG.getEVTAlignment(MemVT),
  4036. AAMDNodes(), nullptr, SSID, Order);
  4037. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4038. SDValue L =
  4039. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4040. getValue(I.getPointerOperand()), MMO);
  4041. SDValue OutChain = L.getValue(1);
  4042. if (MemVT != VT)
  4043. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4044. setValue(&I, L);
  4045. DAG.setRoot(OutChain);
  4046. }
  4047. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4048. SDLoc dl = getCurSDLoc();
  4049. AtomicOrdering Ordering = I.getOrdering();
  4050. SyncScope::ID SSID = I.getSyncScopeID();
  4051. SDValue InChain = getRoot();
  4052. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4053. EVT MemVT =
  4054. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4055. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4056. report_fatal_error("Cannot generate unaligned atomic store");
  4057. auto Flags = MachineMemOperand::MOStore;
  4058. if (I.isVolatile())
  4059. Flags |= MachineMemOperand::MOVolatile;
  4060. Flags |= TLI.getMMOFlags(I);
  4061. MachineFunction &MF = DAG.getMachineFunction();
  4062. MachineMemOperand *MMO =
  4063. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4064. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4065. nullptr, SSID, Ordering);
  4066. SDValue Val = getValue(I.getValueOperand());
  4067. if (Val.getValueType() != MemVT)
  4068. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4069. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4070. getValue(I.getPointerOperand()), Val, MMO);
  4071. DAG.setRoot(OutChain);
  4072. }
  4073. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4074. /// node.
  4075. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4076. unsigned Intrinsic) {
  4077. // Ignore the callsite's attributes. A specific call site may be marked with
  4078. // readnone, but the lowering code will expect the chain based on the
  4079. // definition.
  4080. const Function *F = I.getCalledFunction();
  4081. bool HasChain = !F->doesNotAccessMemory();
  4082. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4083. // Build the operand list.
  4084. SmallVector<SDValue, 8> Ops;
  4085. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4086. if (OnlyLoad) {
  4087. // We don't need to serialize loads against other loads.
  4088. Ops.push_back(DAG.getRoot());
  4089. } else {
  4090. Ops.push_back(getRoot());
  4091. }
  4092. }
  4093. // Info is set by getTgtMemInstrinsic
  4094. TargetLowering::IntrinsicInfo Info;
  4095. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4096. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4097. DAG.getMachineFunction(),
  4098. Intrinsic);
  4099. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4100. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4101. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4102. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4103. TLI.getPointerTy(DAG.getDataLayout())));
  4104. // Add all operands of the call to the operand list.
  4105. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4106. SDValue Op = getValue(I.getArgOperand(i));
  4107. Ops.push_back(Op);
  4108. }
  4109. SmallVector<EVT, 4> ValueVTs;
  4110. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4111. if (HasChain)
  4112. ValueVTs.push_back(MVT::Other);
  4113. SDVTList VTs = DAG.getVTList(ValueVTs);
  4114. // Create the node.
  4115. SDValue Result;
  4116. if (IsTgtIntrinsic) {
  4117. // This is target intrinsic that touches memory
  4118. AAMDNodes AAInfo;
  4119. I.getAAMetadata(AAInfo);
  4120. Result =
  4121. DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4122. MachinePointerInfo(Info.ptrVal, Info.offset),
  4123. Info.align, Info.flags, Info.size, AAInfo);
  4124. } else if (!HasChain) {
  4125. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4126. } else if (!I.getType()->isVoidTy()) {
  4127. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4128. } else {
  4129. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4130. }
  4131. if (HasChain) {
  4132. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4133. if (OnlyLoad)
  4134. PendingLoads.push_back(Chain);
  4135. else
  4136. DAG.setRoot(Chain);
  4137. }
  4138. if (!I.getType()->isVoidTy()) {
  4139. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4140. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4141. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4142. } else
  4143. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4144. setValue(&I, Result);
  4145. }
  4146. }
  4147. /// GetSignificand - Get the significand and build it into a floating-point
  4148. /// number with exponent of 1:
  4149. ///
  4150. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4151. ///
  4152. /// where Op is the hexadecimal representation of floating point value.
  4153. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4154. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4155. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4156. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4157. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4158. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4159. }
  4160. /// GetExponent - Get the exponent:
  4161. ///
  4162. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4163. ///
  4164. /// where Op is the hexadecimal representation of floating point value.
  4165. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4166. const TargetLowering &TLI, const SDLoc &dl) {
  4167. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4168. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4169. SDValue t1 = DAG.getNode(
  4170. ISD::SRL, dl, MVT::i32, t0,
  4171. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4172. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4173. DAG.getConstant(127, dl, MVT::i32));
  4174. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4175. }
  4176. /// getF32Constant - Get 32-bit floating point constant.
  4177. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4178. const SDLoc &dl) {
  4179. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4180. MVT::f32);
  4181. }
  4182. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4183. SelectionDAG &DAG) {
  4184. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4185. // IntegerPartOfX = ((int32_t)(t0);
  4186. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4187. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4188. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4189. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4190. // IntegerPartOfX <<= 23;
  4191. IntegerPartOfX = DAG.getNode(
  4192. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4193. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4194. DAG.getDataLayout())));
  4195. SDValue TwoToFractionalPartOfX;
  4196. if (LimitFloatPrecision <= 6) {
  4197. // For floating-point precision of 6:
  4198. //
  4199. // TwoToFractionalPartOfX =
  4200. // 0.997535578f +
  4201. // (0.735607626f + 0.252464424f * x) * x;
  4202. //
  4203. // error 0.0144103317, which is 6 bits
  4204. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4205. getF32Constant(DAG, 0x3e814304, dl));
  4206. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4207. getF32Constant(DAG, 0x3f3c50c8, dl));
  4208. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4209. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4210. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4211. } else if (LimitFloatPrecision <= 12) {
  4212. // For floating-point precision of 12:
  4213. //
  4214. // TwoToFractionalPartOfX =
  4215. // 0.999892986f +
  4216. // (0.696457318f +
  4217. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4218. //
  4219. // error 0.000107046256, which is 13 to 14 bits
  4220. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4221. getF32Constant(DAG, 0x3da235e3, dl));
  4222. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4223. getF32Constant(DAG, 0x3e65b8f3, dl));
  4224. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4225. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4226. getF32Constant(DAG, 0x3f324b07, dl));
  4227. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4228. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4229. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4230. } else { // LimitFloatPrecision <= 18
  4231. // For floating-point precision of 18:
  4232. //
  4233. // TwoToFractionalPartOfX =
  4234. // 0.999999982f +
  4235. // (0.693148872f +
  4236. // (0.240227044f +
  4237. // (0.554906021e-1f +
  4238. // (0.961591928e-2f +
  4239. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4240. // error 2.47208000*10^(-7), which is better than 18 bits
  4241. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4242. getF32Constant(DAG, 0x3924b03e, dl));
  4243. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4244. getF32Constant(DAG, 0x3ab24b87, dl));
  4245. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4246. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4247. getF32Constant(DAG, 0x3c1d8c17, dl));
  4248. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4249. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4250. getF32Constant(DAG, 0x3d634a1d, dl));
  4251. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4252. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4253. getF32Constant(DAG, 0x3e75fe14, dl));
  4254. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4255. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4256. getF32Constant(DAG, 0x3f317234, dl));
  4257. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4258. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4259. getF32Constant(DAG, 0x3f800000, dl));
  4260. }
  4261. // Add the exponent into the result in integer domain.
  4262. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4263. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4264. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4265. }
  4266. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4267. /// limited-precision mode.
  4268. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4269. const TargetLowering &TLI) {
  4270. if (Op.getValueType() == MVT::f32 &&
  4271. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4272. // Put the exponent in the right bit position for later addition to the
  4273. // final result:
  4274. //
  4275. // #define LOG2OFe 1.4426950f
  4276. // t0 = Op * LOG2OFe
  4277. // TODO: What fast-math-flags should be set here?
  4278. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4279. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4280. return getLimitedPrecisionExp2(t0, dl, DAG);
  4281. }
  4282. // No special expansion.
  4283. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4284. }
  4285. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4286. /// limited-precision mode.
  4287. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4288. const TargetLowering &TLI) {
  4289. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4290. if (Op.getValueType() == MVT::f32 &&
  4291. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4292. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4293. // Scale the exponent by log(2) [0.69314718f].
  4294. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4295. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4296. getF32Constant(DAG, 0x3f317218, dl));
  4297. // Get the significand and build it into a floating-point number with
  4298. // exponent of 1.
  4299. SDValue X = GetSignificand(DAG, Op1, dl);
  4300. SDValue LogOfMantissa;
  4301. if (LimitFloatPrecision <= 6) {
  4302. // For floating-point precision of 6:
  4303. //
  4304. // LogofMantissa =
  4305. // -1.1609546f +
  4306. // (1.4034025f - 0.23903021f * x) * x;
  4307. //
  4308. // error 0.0034276066, which is better than 8 bits
  4309. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4310. getF32Constant(DAG, 0xbe74c456, dl));
  4311. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4312. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4313. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4314. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4315. getF32Constant(DAG, 0x3f949a29, dl));
  4316. } else if (LimitFloatPrecision <= 12) {
  4317. // For floating-point precision of 12:
  4318. //
  4319. // LogOfMantissa =
  4320. // -1.7417939f +
  4321. // (2.8212026f +
  4322. // (-1.4699568f +
  4323. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4324. //
  4325. // error 0.000061011436, which is 14 bits
  4326. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4327. getF32Constant(DAG, 0xbd67b6d6, dl));
  4328. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4329. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4330. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4331. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4332. getF32Constant(DAG, 0x3fbc278b, dl));
  4333. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4334. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4335. getF32Constant(DAG, 0x40348e95, dl));
  4336. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4337. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4338. getF32Constant(DAG, 0x3fdef31a, dl));
  4339. } else { // LimitFloatPrecision <= 18
  4340. // For floating-point precision of 18:
  4341. //
  4342. // LogOfMantissa =
  4343. // -2.1072184f +
  4344. // (4.2372794f +
  4345. // (-3.7029485f +
  4346. // (2.2781945f +
  4347. // (-0.87823314f +
  4348. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4349. //
  4350. // error 0.0000023660568, which is better than 18 bits
  4351. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4352. getF32Constant(DAG, 0xbc91e5ac, dl));
  4353. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4354. getF32Constant(DAG, 0x3e4350aa, dl));
  4355. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4356. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4357. getF32Constant(DAG, 0x3f60d3e3, dl));
  4358. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4359. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4360. getF32Constant(DAG, 0x4011cdf0, dl));
  4361. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4362. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4363. getF32Constant(DAG, 0x406cfd1c, dl));
  4364. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4365. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4366. getF32Constant(DAG, 0x408797cb, dl));
  4367. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4368. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4369. getF32Constant(DAG, 0x4006dcab, dl));
  4370. }
  4371. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4372. }
  4373. // No special expansion.
  4374. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4375. }
  4376. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4377. /// limited-precision mode.
  4378. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4379. const TargetLowering &TLI) {
  4380. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4381. if (Op.getValueType() == MVT::f32 &&
  4382. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4383. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4384. // Get the exponent.
  4385. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4386. // Get the significand and build it into a floating-point number with
  4387. // exponent of 1.
  4388. SDValue X = GetSignificand(DAG, Op1, dl);
  4389. // Different possible minimax approximations of significand in
  4390. // floating-point for various degrees of accuracy over [1,2].
  4391. SDValue Log2ofMantissa;
  4392. if (LimitFloatPrecision <= 6) {
  4393. // For floating-point precision of 6:
  4394. //
  4395. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4396. //
  4397. // error 0.0049451742, which is more than 7 bits
  4398. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4399. getF32Constant(DAG, 0xbeb08fe0, dl));
  4400. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4401. getF32Constant(DAG, 0x40019463, dl));
  4402. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4403. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4404. getF32Constant(DAG, 0x3fd6633d, dl));
  4405. } else if (LimitFloatPrecision <= 12) {
  4406. // For floating-point precision of 12:
  4407. //
  4408. // Log2ofMantissa =
  4409. // -2.51285454f +
  4410. // (4.07009056f +
  4411. // (-2.12067489f +
  4412. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4413. //
  4414. // error 0.0000876136000, which is better than 13 bits
  4415. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4416. getF32Constant(DAG, 0xbda7262e, dl));
  4417. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4418. getF32Constant(DAG, 0x3f25280b, dl));
  4419. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4420. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4421. getF32Constant(DAG, 0x4007b923, dl));
  4422. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4423. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4424. getF32Constant(DAG, 0x40823e2f, dl));
  4425. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4426. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4427. getF32Constant(DAG, 0x4020d29c, dl));
  4428. } else { // LimitFloatPrecision <= 18
  4429. // For floating-point precision of 18:
  4430. //
  4431. // Log2ofMantissa =
  4432. // -3.0400495f +
  4433. // (6.1129976f +
  4434. // (-5.3420409f +
  4435. // (3.2865683f +
  4436. // (-1.2669343f +
  4437. // (0.27515199f -
  4438. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4439. //
  4440. // error 0.0000018516, which is better than 18 bits
  4441. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4442. getF32Constant(DAG, 0xbcd2769e, dl));
  4443. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4444. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4445. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4446. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4447. getF32Constant(DAG, 0x3fa22ae7, dl));
  4448. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4449. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4450. getF32Constant(DAG, 0x40525723, dl));
  4451. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4452. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4453. getF32Constant(DAG, 0x40aaf200, dl));
  4454. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4455. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4456. getF32Constant(DAG, 0x40c39dad, dl));
  4457. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4458. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4459. getF32Constant(DAG, 0x4042902c, dl));
  4460. }
  4461. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4462. }
  4463. // No special expansion.
  4464. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4465. }
  4466. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4467. /// limited-precision mode.
  4468. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4469. const TargetLowering &TLI) {
  4470. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4471. if (Op.getValueType() == MVT::f32 &&
  4472. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4473. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4474. // Scale the exponent by log10(2) [0.30102999f].
  4475. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4476. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4477. getF32Constant(DAG, 0x3e9a209a, dl));
  4478. // Get the significand and build it into a floating-point number with
  4479. // exponent of 1.
  4480. SDValue X = GetSignificand(DAG, Op1, dl);
  4481. SDValue Log10ofMantissa;
  4482. if (LimitFloatPrecision <= 6) {
  4483. // For floating-point precision of 6:
  4484. //
  4485. // Log10ofMantissa =
  4486. // -0.50419619f +
  4487. // (0.60948995f - 0.10380950f * x) * x;
  4488. //
  4489. // error 0.0014886165, which is 6 bits
  4490. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4491. getF32Constant(DAG, 0xbdd49a13, dl));
  4492. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4493. getF32Constant(DAG, 0x3f1c0789, dl));
  4494. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4495. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4496. getF32Constant(DAG, 0x3f011300, dl));
  4497. } else if (LimitFloatPrecision <= 12) {
  4498. // For floating-point precision of 12:
  4499. //
  4500. // Log10ofMantissa =
  4501. // -0.64831180f +
  4502. // (0.91751397f +
  4503. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4504. //
  4505. // error 0.00019228036, which is better than 12 bits
  4506. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4507. getF32Constant(DAG, 0x3d431f31, dl));
  4508. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4509. getF32Constant(DAG, 0x3ea21fb2, dl));
  4510. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4511. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4512. getF32Constant(DAG, 0x3f6ae232, dl));
  4513. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4514. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4515. getF32Constant(DAG, 0x3f25f7c3, dl));
  4516. } else { // LimitFloatPrecision <= 18
  4517. // For floating-point precision of 18:
  4518. //
  4519. // Log10ofMantissa =
  4520. // -0.84299375f +
  4521. // (1.5327582f +
  4522. // (-1.0688956f +
  4523. // (0.49102474f +
  4524. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4525. //
  4526. // error 0.0000037995730, which is better than 18 bits
  4527. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4528. getF32Constant(DAG, 0x3c5d51ce, dl));
  4529. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4530. getF32Constant(DAG, 0x3e00685a, dl));
  4531. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4532. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4533. getF32Constant(DAG, 0x3efb6798, dl));
  4534. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4535. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4536. getF32Constant(DAG, 0x3f88d192, dl));
  4537. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4538. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4539. getF32Constant(DAG, 0x3fc4316c, dl));
  4540. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4541. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4542. getF32Constant(DAG, 0x3f57ce70, dl));
  4543. }
  4544. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4545. }
  4546. // No special expansion.
  4547. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4548. }
  4549. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4550. /// limited-precision mode.
  4551. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4552. const TargetLowering &TLI) {
  4553. if (Op.getValueType() == MVT::f32 &&
  4554. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4555. return getLimitedPrecisionExp2(Op, dl, DAG);
  4556. // No special expansion.
  4557. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4558. }
  4559. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4560. /// limited-precision mode with x == 10.0f.
  4561. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4562. SelectionDAG &DAG, const TargetLowering &TLI) {
  4563. bool IsExp10 = false;
  4564. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4565. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4566. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4567. APFloat Ten(10.0f);
  4568. IsExp10 = LHSC->isExactlyValue(Ten);
  4569. }
  4570. }
  4571. // TODO: What fast-math-flags should be set on the FMUL node?
  4572. if (IsExp10) {
  4573. // Put the exponent in the right bit position for later addition to the
  4574. // final result:
  4575. //
  4576. // #define LOG2OF10 3.3219281f
  4577. // t0 = Op * LOG2OF10;
  4578. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4579. getF32Constant(DAG, 0x40549a78, dl));
  4580. return getLimitedPrecisionExp2(t0, dl, DAG);
  4581. }
  4582. // No special expansion.
  4583. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4584. }
  4585. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4586. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4587. SelectionDAG &DAG) {
  4588. // If RHS is a constant, we can expand this out to a multiplication tree,
  4589. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4590. // optimizing for size, we only want to do this if the expansion would produce
  4591. // a small number of multiplies, otherwise we do the full expansion.
  4592. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4593. // Get the exponent as a positive value.
  4594. unsigned Val = RHSC->getSExtValue();
  4595. if ((int)Val < 0) Val = -Val;
  4596. // powi(x, 0) -> 1.0
  4597. if (Val == 0)
  4598. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4599. const Function &F = DAG.getMachineFunction().getFunction();
  4600. if (!F.hasOptSize() ||
  4601. // If optimizing for size, don't insert too many multiplies.
  4602. // This inserts up to 5 multiplies.
  4603. countPopulation(Val) + Log2_32(Val) < 7) {
  4604. // We use the simple binary decomposition method to generate the multiply
  4605. // sequence. There are more optimal ways to do this (for example,
  4606. // powi(x,15) generates one more multiply than it should), but this has
  4607. // the benefit of being both really simple and much better than a libcall.
  4608. SDValue Res; // Logically starts equal to 1.0
  4609. SDValue CurSquare = LHS;
  4610. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4611. // nodes.
  4612. while (Val) {
  4613. if (Val & 1) {
  4614. if (Res.getNode())
  4615. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4616. else
  4617. Res = CurSquare; // 1.0*CurSquare.
  4618. }
  4619. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4620. CurSquare, CurSquare);
  4621. Val >>= 1;
  4622. }
  4623. // If the original was negative, invert the result, producing 1/(x*x*x).
  4624. if (RHSC->getSExtValue() < 0)
  4625. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4626. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4627. return Res;
  4628. }
  4629. }
  4630. // Otherwise, expand to a libcall.
  4631. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4632. }
  4633. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4634. // bitcasted argument.
  4635. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4636. switch (N.getOpcode()) {
  4637. case ISD::CopyFromReg:
  4638. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4639. case ISD::BITCAST:
  4640. case ISD::AssertZext:
  4641. case ISD::AssertSext:
  4642. case ISD::TRUNCATE:
  4643. return getUnderlyingArgReg(N.getOperand(0));
  4644. default:
  4645. return 0;
  4646. }
  4647. }
  4648. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4649. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4650. /// instruction selection, they will be inserted to the entry BB.
  4651. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4652. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4653. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4654. const Argument *Arg = dyn_cast<Argument>(V);
  4655. if (!Arg)
  4656. return false;
  4657. if (!IsDbgDeclare) {
  4658. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4659. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4660. // the entry block.
  4661. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4662. if (!IsInEntryBlock)
  4663. return false;
  4664. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4665. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4666. // variable that also is a param.
  4667. //
  4668. // Although, if we are at the top of the entry block already, we can still
  4669. // emit using ArgDbgValue. This might catch some situations when the
  4670. // dbg.value refers to an argument that isn't used in the entry block, so
  4671. // any CopyToReg node would be optimized out and the only way to express
  4672. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4673. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4674. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4675. // current function, and the dbg.value intrinsic is found in the entry
  4676. // block.
  4677. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4678. !DL->getInlinedAt();
  4679. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4680. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4681. return false;
  4682. // Here we assume that a function argument on IR level only can be used to
  4683. // describe one input parameter on source level. If we for example have
  4684. // source code like this
  4685. //
  4686. // struct A { long x, y; };
  4687. // void foo(struct A a, long b) {
  4688. // ...
  4689. // b = a.x;
  4690. // ...
  4691. // }
  4692. //
  4693. // and IR like this
  4694. //
  4695. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4696. // entry:
  4697. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4698. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4699. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4700. // ...
  4701. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4702. // ...
  4703. //
  4704. // then the last dbg.value is describing a parameter "b" using a value that
  4705. // is an argument. But since we already has used %a1 to describe a parameter
  4706. // we should not handle that last dbg.value here (that would result in an
  4707. // incorrect hoisting of the DBG_VALUE to the function entry).
  4708. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4709. // for the situation with fragments above.
  4710. if (VariableIsFunctionInputArg) {
  4711. unsigned ArgNo = Arg->getArgNo();
  4712. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4713. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4714. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4715. return false;
  4716. FuncInfo.DescribedArgs.set(ArgNo);
  4717. }
  4718. }
  4719. MachineFunction &MF = DAG.getMachineFunction();
  4720. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4721. bool IsIndirect = false;
  4722. Optional<MachineOperand> Op;
  4723. // Some arguments' frame index is recorded during argument lowering.
  4724. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4725. if (FI != std::numeric_limits<int>::max())
  4726. Op = MachineOperand::CreateFI(FI);
  4727. if (!Op && N.getNode()) {
  4728. unsigned Reg = getUnderlyingArgReg(N);
  4729. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4730. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4731. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4732. if (PR)
  4733. Reg = PR;
  4734. }
  4735. if (Reg) {
  4736. Op = MachineOperand::CreateReg(Reg, false);
  4737. IsIndirect = IsDbgDeclare;
  4738. }
  4739. }
  4740. if (!Op && N.getNode()) {
  4741. // Check if frame index is available.
  4742. SDValue LCandidate = peekThroughBitcasts(N);
  4743. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4744. if (FrameIndexSDNode *FINode =
  4745. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4746. Op = MachineOperand::CreateFI(FINode->getIndex());
  4747. }
  4748. if (!Op) {
  4749. // Check if ValueMap has reg number.
  4750. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4751. if (VMI != FuncInfo.ValueMap.end()) {
  4752. const auto &TLI = DAG.getTargetLoweringInfo();
  4753. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4754. V->getType(), getABIRegCopyCC(V));
  4755. if (RFV.occupiesMultipleRegs()) {
  4756. unsigned Offset = 0;
  4757. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4758. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4759. auto FragmentExpr = DIExpression::createFragmentExpression(
  4760. Expr, Offset, RegAndSize.second);
  4761. if (!FragmentExpr)
  4762. continue;
  4763. FuncInfo.ArgDbgValues.push_back(
  4764. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4765. Op->getReg(), Variable, *FragmentExpr));
  4766. Offset += RegAndSize.second;
  4767. }
  4768. return true;
  4769. }
  4770. Op = MachineOperand::CreateReg(VMI->second, false);
  4771. IsIndirect = IsDbgDeclare;
  4772. }
  4773. }
  4774. if (!Op)
  4775. return false;
  4776. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4777. "Expected inlined-at fields to agree");
  4778. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4779. FuncInfo.ArgDbgValues.push_back(
  4780. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4781. *Op, Variable, Expr));
  4782. return true;
  4783. }
  4784. /// Return the appropriate SDDbgValue based on N.
  4785. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4786. DILocalVariable *Variable,
  4787. DIExpression *Expr,
  4788. const DebugLoc &dl,
  4789. unsigned DbgSDNodeOrder) {
  4790. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4791. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4792. // stack slot locations.
  4793. //
  4794. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4795. // debug values here after optimization:
  4796. //
  4797. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4798. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4799. //
  4800. // Both describe the direct values of their associated variables.
  4801. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4802. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4803. }
  4804. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4805. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4806. }
  4807. // VisualStudio defines setjmp as _setjmp
  4808. #if defined(_MSC_VER) && defined(setjmp) && \
  4809. !defined(setjmp_undefined_for_msvc)
  4810. # pragma push_macro("setjmp")
  4811. # undef setjmp
  4812. # define setjmp_undefined_for_msvc
  4813. #endif
  4814. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4815. switch (Intrinsic) {
  4816. case Intrinsic::smul_fix:
  4817. return ISD::SMULFIX;
  4818. case Intrinsic::umul_fix:
  4819. return ISD::UMULFIX;
  4820. default:
  4821. llvm_unreachable("Unhandled fixed point intrinsic");
  4822. }
  4823. }
  4824. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4825. const char *FunctionName) {
  4826. assert(FunctionName && "FunctionName must not be nullptr");
  4827. SDValue Callee = DAG.getExternalSymbol(
  4828. FunctionName,
  4829. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4830. LowerCallTo(&I, Callee, I.isTailCall());
  4831. }
  4832. /// Lower the call to the specified intrinsic function.
  4833. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4834. unsigned Intrinsic) {
  4835. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4836. SDLoc sdl = getCurSDLoc();
  4837. DebugLoc dl = getCurDebugLoc();
  4838. SDValue Res;
  4839. switch (Intrinsic) {
  4840. default:
  4841. // By default, turn this into a target intrinsic node.
  4842. visitTargetIntrinsic(I, Intrinsic);
  4843. return;
  4844. case Intrinsic::vastart: visitVAStart(I); return;
  4845. case Intrinsic::vaend: visitVAEnd(I); return;
  4846. case Intrinsic::vacopy: visitVACopy(I); return;
  4847. case Intrinsic::returnaddress:
  4848. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4849. TLI.getPointerTy(DAG.getDataLayout()),
  4850. getValue(I.getArgOperand(0))));
  4851. return;
  4852. case Intrinsic::addressofreturnaddress:
  4853. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4854. TLI.getPointerTy(DAG.getDataLayout())));
  4855. return;
  4856. case Intrinsic::sponentry:
  4857. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4858. TLI.getPointerTy(DAG.getDataLayout())));
  4859. return;
  4860. case Intrinsic::frameaddress:
  4861. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4862. TLI.getPointerTy(DAG.getDataLayout()),
  4863. getValue(I.getArgOperand(0))));
  4864. return;
  4865. case Intrinsic::read_register: {
  4866. Value *Reg = I.getArgOperand(0);
  4867. SDValue Chain = getRoot();
  4868. SDValue RegName =
  4869. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4870. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4871. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4872. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4873. setValue(&I, Res);
  4874. DAG.setRoot(Res.getValue(1));
  4875. return;
  4876. }
  4877. case Intrinsic::write_register: {
  4878. Value *Reg = I.getArgOperand(0);
  4879. Value *RegValue = I.getArgOperand(1);
  4880. SDValue Chain = getRoot();
  4881. SDValue RegName =
  4882. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4883. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4884. RegName, getValue(RegValue)));
  4885. return;
  4886. }
  4887. case Intrinsic::setjmp:
  4888. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4889. return;
  4890. case Intrinsic::longjmp:
  4891. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4892. return;
  4893. case Intrinsic::memcpy: {
  4894. const auto &MCI = cast<MemCpyInst>(I);
  4895. SDValue Op1 = getValue(I.getArgOperand(0));
  4896. SDValue Op2 = getValue(I.getArgOperand(1));
  4897. SDValue Op3 = getValue(I.getArgOperand(2));
  4898. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4899. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4900. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4901. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4902. bool isVol = MCI.isVolatile();
  4903. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4904. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4905. // node.
  4906. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4907. false, isTC,
  4908. MachinePointerInfo(I.getArgOperand(0)),
  4909. MachinePointerInfo(I.getArgOperand(1)));
  4910. updateDAGForMaybeTailCall(MC);
  4911. return;
  4912. }
  4913. case Intrinsic::memset: {
  4914. const auto &MSI = cast<MemSetInst>(I);
  4915. SDValue Op1 = getValue(I.getArgOperand(0));
  4916. SDValue Op2 = getValue(I.getArgOperand(1));
  4917. SDValue Op3 = getValue(I.getArgOperand(2));
  4918. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4919. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4920. bool isVol = MSI.isVolatile();
  4921. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4922. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4923. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4924. updateDAGForMaybeTailCall(MS);
  4925. return;
  4926. }
  4927. case Intrinsic::memmove: {
  4928. const auto &MMI = cast<MemMoveInst>(I);
  4929. SDValue Op1 = getValue(I.getArgOperand(0));
  4930. SDValue Op2 = getValue(I.getArgOperand(1));
  4931. SDValue Op3 = getValue(I.getArgOperand(2));
  4932. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4933. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4934. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4935. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4936. bool isVol = MMI.isVolatile();
  4937. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4938. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4939. // node.
  4940. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4941. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4942. MachinePointerInfo(I.getArgOperand(1)));
  4943. updateDAGForMaybeTailCall(MM);
  4944. return;
  4945. }
  4946. case Intrinsic::memcpy_element_unordered_atomic: {
  4947. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4948. SDValue Dst = getValue(MI.getRawDest());
  4949. SDValue Src = getValue(MI.getRawSource());
  4950. SDValue Length = getValue(MI.getLength());
  4951. unsigned DstAlign = MI.getDestAlignment();
  4952. unsigned SrcAlign = MI.getSourceAlignment();
  4953. Type *LengthTy = MI.getLength()->getType();
  4954. unsigned ElemSz = MI.getElementSizeInBytes();
  4955. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4956. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4957. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4958. MachinePointerInfo(MI.getRawDest()),
  4959. MachinePointerInfo(MI.getRawSource()));
  4960. updateDAGForMaybeTailCall(MC);
  4961. return;
  4962. }
  4963. case Intrinsic::memmove_element_unordered_atomic: {
  4964. auto &MI = cast<AtomicMemMoveInst>(I);
  4965. SDValue Dst = getValue(MI.getRawDest());
  4966. SDValue Src = getValue(MI.getRawSource());
  4967. SDValue Length = getValue(MI.getLength());
  4968. unsigned DstAlign = MI.getDestAlignment();
  4969. unsigned SrcAlign = MI.getSourceAlignment();
  4970. Type *LengthTy = MI.getLength()->getType();
  4971. unsigned ElemSz = MI.getElementSizeInBytes();
  4972. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4973. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4974. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4975. MachinePointerInfo(MI.getRawDest()),
  4976. MachinePointerInfo(MI.getRawSource()));
  4977. updateDAGForMaybeTailCall(MC);
  4978. return;
  4979. }
  4980. case Intrinsic::memset_element_unordered_atomic: {
  4981. auto &MI = cast<AtomicMemSetInst>(I);
  4982. SDValue Dst = getValue(MI.getRawDest());
  4983. SDValue Val = getValue(MI.getValue());
  4984. SDValue Length = getValue(MI.getLength());
  4985. unsigned DstAlign = MI.getDestAlignment();
  4986. Type *LengthTy = MI.getLength()->getType();
  4987. unsigned ElemSz = MI.getElementSizeInBytes();
  4988. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4989. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  4990. LengthTy, ElemSz, isTC,
  4991. MachinePointerInfo(MI.getRawDest()));
  4992. updateDAGForMaybeTailCall(MC);
  4993. return;
  4994. }
  4995. case Intrinsic::dbg_addr:
  4996. case Intrinsic::dbg_declare: {
  4997. const auto &DI = cast<DbgVariableIntrinsic>(I);
  4998. DILocalVariable *Variable = DI.getVariable();
  4999. DIExpression *Expression = DI.getExpression();
  5000. dropDanglingDebugInfo(Variable, Expression);
  5001. assert(Variable && "Missing variable");
  5002. // Check if address has undef value.
  5003. const Value *Address = DI.getVariableLocation();
  5004. if (!Address || isa<UndefValue>(Address) ||
  5005. (Address->use_empty() && !isa<Argument>(Address))) {
  5006. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5007. return;
  5008. }
  5009. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5010. // Check if this variable can be described by a frame index, typically
  5011. // either as a static alloca or a byval parameter.
  5012. int FI = std::numeric_limits<int>::max();
  5013. if (const auto *AI =
  5014. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5015. if (AI->isStaticAlloca()) {
  5016. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5017. if (I != FuncInfo.StaticAllocaMap.end())
  5018. FI = I->second;
  5019. }
  5020. } else if (const auto *Arg = dyn_cast<Argument>(
  5021. Address->stripInBoundsConstantOffsets())) {
  5022. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5023. }
  5024. // llvm.dbg.addr is control dependent and always generates indirect
  5025. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5026. // the MachineFunction variable table.
  5027. if (FI != std::numeric_limits<int>::max()) {
  5028. if (Intrinsic == Intrinsic::dbg_addr) {
  5029. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5030. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5031. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5032. }
  5033. return;
  5034. }
  5035. SDValue &N = NodeMap[Address];
  5036. if (!N.getNode() && isa<Argument>(Address))
  5037. // Check unused arguments map.
  5038. N = UnusedArgNodeMap[Address];
  5039. SDDbgValue *SDV;
  5040. if (N.getNode()) {
  5041. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5042. Address = BCI->getOperand(0);
  5043. // Parameters are handled specially.
  5044. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5045. if (isParameter && FINode) {
  5046. // Byval parameter. We have a frame index at this point.
  5047. SDV =
  5048. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5049. /*IsIndirect*/ true, dl, SDNodeOrder);
  5050. } else if (isa<Argument>(Address)) {
  5051. // Address is an argument, so try to emit its dbg value using
  5052. // virtual register info from the FuncInfo.ValueMap.
  5053. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5054. return;
  5055. } else {
  5056. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5057. true, dl, SDNodeOrder);
  5058. }
  5059. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5060. } else {
  5061. // If Address is an argument then try to emit its dbg value using
  5062. // virtual register info from the FuncInfo.ValueMap.
  5063. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5064. N)) {
  5065. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5066. }
  5067. }
  5068. return;
  5069. }
  5070. case Intrinsic::dbg_label: {
  5071. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5072. DILabel *Label = DI.getLabel();
  5073. assert(Label && "Missing label");
  5074. SDDbgLabel *SDV;
  5075. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5076. DAG.AddDbgLabel(SDV);
  5077. return;
  5078. }
  5079. case Intrinsic::dbg_value: {
  5080. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5081. assert(DI.getVariable() && "Missing variable");
  5082. DILocalVariable *Variable = DI.getVariable();
  5083. DIExpression *Expression = DI.getExpression();
  5084. dropDanglingDebugInfo(Variable, Expression);
  5085. const Value *V = DI.getValue();
  5086. if (!V)
  5087. return;
  5088. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5089. SDNodeOrder))
  5090. return;
  5091. // TODO: Dangling debug info will eventually either be resolved or produce
  5092. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5093. // between the original dbg.value location and its resolved DBG_VALUE, which
  5094. // we should ideally fill with an extra Undef DBG_VALUE.
  5095. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5096. return;
  5097. }
  5098. case Intrinsic::eh_typeid_for: {
  5099. // Find the type id for the given typeinfo.
  5100. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5101. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5102. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5103. setValue(&I, Res);
  5104. return;
  5105. }
  5106. case Intrinsic::eh_return_i32:
  5107. case Intrinsic::eh_return_i64:
  5108. DAG.getMachineFunction().setCallsEHReturn(true);
  5109. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5110. MVT::Other,
  5111. getControlRoot(),
  5112. getValue(I.getArgOperand(0)),
  5113. getValue(I.getArgOperand(1))));
  5114. return;
  5115. case Intrinsic::eh_unwind_init:
  5116. DAG.getMachineFunction().setCallsUnwindInit(true);
  5117. return;
  5118. case Intrinsic::eh_dwarf_cfa:
  5119. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5120. TLI.getPointerTy(DAG.getDataLayout()),
  5121. getValue(I.getArgOperand(0))));
  5122. return;
  5123. case Intrinsic::eh_sjlj_callsite: {
  5124. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5125. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5126. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5127. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5128. MMI.setCurrentCallSite(CI->getZExtValue());
  5129. return;
  5130. }
  5131. case Intrinsic::eh_sjlj_functioncontext: {
  5132. // Get and store the index of the function context.
  5133. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5134. AllocaInst *FnCtx =
  5135. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5136. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5137. MFI.setFunctionContextIndex(FI);
  5138. return;
  5139. }
  5140. case Intrinsic::eh_sjlj_setjmp: {
  5141. SDValue Ops[2];
  5142. Ops[0] = getRoot();
  5143. Ops[1] = getValue(I.getArgOperand(0));
  5144. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5145. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5146. setValue(&I, Op.getValue(0));
  5147. DAG.setRoot(Op.getValue(1));
  5148. return;
  5149. }
  5150. case Intrinsic::eh_sjlj_longjmp:
  5151. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5152. getRoot(), getValue(I.getArgOperand(0))));
  5153. return;
  5154. case Intrinsic::eh_sjlj_setup_dispatch:
  5155. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5156. getRoot()));
  5157. return;
  5158. case Intrinsic::masked_gather:
  5159. visitMaskedGather(I);
  5160. return;
  5161. case Intrinsic::masked_load:
  5162. visitMaskedLoad(I);
  5163. return;
  5164. case Intrinsic::masked_scatter:
  5165. visitMaskedScatter(I);
  5166. return;
  5167. case Intrinsic::masked_store:
  5168. visitMaskedStore(I);
  5169. return;
  5170. case Intrinsic::masked_expandload:
  5171. visitMaskedLoad(I, true /* IsExpanding */);
  5172. return;
  5173. case Intrinsic::masked_compressstore:
  5174. visitMaskedStore(I, true /* IsCompressing */);
  5175. return;
  5176. case Intrinsic::x86_mmx_pslli_w:
  5177. case Intrinsic::x86_mmx_pslli_d:
  5178. case Intrinsic::x86_mmx_pslli_q:
  5179. case Intrinsic::x86_mmx_psrli_w:
  5180. case Intrinsic::x86_mmx_psrli_d:
  5181. case Intrinsic::x86_mmx_psrli_q:
  5182. case Intrinsic::x86_mmx_psrai_w:
  5183. case Intrinsic::x86_mmx_psrai_d: {
  5184. SDValue ShAmt = getValue(I.getArgOperand(1));
  5185. if (isa<ConstantSDNode>(ShAmt)) {
  5186. visitTargetIntrinsic(I, Intrinsic);
  5187. return;
  5188. }
  5189. unsigned NewIntrinsic = 0;
  5190. EVT ShAmtVT = MVT::v2i32;
  5191. switch (Intrinsic) {
  5192. case Intrinsic::x86_mmx_pslli_w:
  5193. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5194. break;
  5195. case Intrinsic::x86_mmx_pslli_d:
  5196. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5197. break;
  5198. case Intrinsic::x86_mmx_pslli_q:
  5199. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5200. break;
  5201. case Intrinsic::x86_mmx_psrli_w:
  5202. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5203. break;
  5204. case Intrinsic::x86_mmx_psrli_d:
  5205. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5206. break;
  5207. case Intrinsic::x86_mmx_psrli_q:
  5208. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5209. break;
  5210. case Intrinsic::x86_mmx_psrai_w:
  5211. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5212. break;
  5213. case Intrinsic::x86_mmx_psrai_d:
  5214. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5215. break;
  5216. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5217. }
  5218. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5219. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5220. // to be zero.
  5221. // We must do this early because v2i32 is not a legal type.
  5222. SDValue ShOps[2];
  5223. ShOps[0] = ShAmt;
  5224. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5225. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5226. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5227. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5228. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5229. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5230. getValue(I.getArgOperand(0)), ShAmt);
  5231. setValue(&I, Res);
  5232. return;
  5233. }
  5234. case Intrinsic::powi:
  5235. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5236. getValue(I.getArgOperand(1)), DAG));
  5237. return;
  5238. case Intrinsic::log:
  5239. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5240. return;
  5241. case Intrinsic::log2:
  5242. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5243. return;
  5244. case Intrinsic::log10:
  5245. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5246. return;
  5247. case Intrinsic::exp:
  5248. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5249. return;
  5250. case Intrinsic::exp2:
  5251. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5252. return;
  5253. case Intrinsic::pow:
  5254. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5255. getValue(I.getArgOperand(1)), DAG, TLI));
  5256. return;
  5257. case Intrinsic::sqrt:
  5258. case Intrinsic::fabs:
  5259. case Intrinsic::sin:
  5260. case Intrinsic::cos:
  5261. case Intrinsic::floor:
  5262. case Intrinsic::ceil:
  5263. case Intrinsic::trunc:
  5264. case Intrinsic::rint:
  5265. case Intrinsic::nearbyint:
  5266. case Intrinsic::round:
  5267. case Intrinsic::canonicalize: {
  5268. unsigned Opcode;
  5269. switch (Intrinsic) {
  5270. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5271. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5272. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5273. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5274. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5275. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5276. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5277. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5278. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5279. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5280. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5281. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5282. }
  5283. setValue(&I, DAG.getNode(Opcode, sdl,
  5284. getValue(I.getArgOperand(0)).getValueType(),
  5285. getValue(I.getArgOperand(0))));
  5286. return;
  5287. }
  5288. case Intrinsic::lround:
  5289. case Intrinsic::llround:
  5290. case Intrinsic::lrint:
  5291. case Intrinsic::llrint: {
  5292. unsigned Opcode;
  5293. switch (Intrinsic) {
  5294. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5295. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5296. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5297. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5298. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5299. }
  5300. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5301. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5302. getValue(I.getArgOperand(0))));
  5303. return;
  5304. }
  5305. case Intrinsic::minnum:
  5306. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5307. getValue(I.getArgOperand(0)).getValueType(),
  5308. getValue(I.getArgOperand(0)),
  5309. getValue(I.getArgOperand(1))));
  5310. return;
  5311. case Intrinsic::maxnum:
  5312. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5313. getValue(I.getArgOperand(0)).getValueType(),
  5314. getValue(I.getArgOperand(0)),
  5315. getValue(I.getArgOperand(1))));
  5316. return;
  5317. case Intrinsic::minimum:
  5318. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5319. getValue(I.getArgOperand(0)).getValueType(),
  5320. getValue(I.getArgOperand(0)),
  5321. getValue(I.getArgOperand(1))));
  5322. return;
  5323. case Intrinsic::maximum:
  5324. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5325. getValue(I.getArgOperand(0)).getValueType(),
  5326. getValue(I.getArgOperand(0)),
  5327. getValue(I.getArgOperand(1))));
  5328. return;
  5329. case Intrinsic::copysign:
  5330. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5331. getValue(I.getArgOperand(0)).getValueType(),
  5332. getValue(I.getArgOperand(0)),
  5333. getValue(I.getArgOperand(1))));
  5334. return;
  5335. case Intrinsic::fma:
  5336. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5337. getValue(I.getArgOperand(0)).getValueType(),
  5338. getValue(I.getArgOperand(0)),
  5339. getValue(I.getArgOperand(1)),
  5340. getValue(I.getArgOperand(2))));
  5341. return;
  5342. case Intrinsic::experimental_constrained_fadd:
  5343. case Intrinsic::experimental_constrained_fsub:
  5344. case Intrinsic::experimental_constrained_fmul:
  5345. case Intrinsic::experimental_constrained_fdiv:
  5346. case Intrinsic::experimental_constrained_frem:
  5347. case Intrinsic::experimental_constrained_fma:
  5348. case Intrinsic::experimental_constrained_fptrunc:
  5349. case Intrinsic::experimental_constrained_fpext:
  5350. case Intrinsic::experimental_constrained_sqrt:
  5351. case Intrinsic::experimental_constrained_pow:
  5352. case Intrinsic::experimental_constrained_powi:
  5353. case Intrinsic::experimental_constrained_sin:
  5354. case Intrinsic::experimental_constrained_cos:
  5355. case Intrinsic::experimental_constrained_exp:
  5356. case Intrinsic::experimental_constrained_exp2:
  5357. case Intrinsic::experimental_constrained_log:
  5358. case Intrinsic::experimental_constrained_log10:
  5359. case Intrinsic::experimental_constrained_log2:
  5360. case Intrinsic::experimental_constrained_rint:
  5361. case Intrinsic::experimental_constrained_nearbyint:
  5362. case Intrinsic::experimental_constrained_maxnum:
  5363. case Intrinsic::experimental_constrained_minnum:
  5364. case Intrinsic::experimental_constrained_ceil:
  5365. case Intrinsic::experimental_constrained_floor:
  5366. case Intrinsic::experimental_constrained_round:
  5367. case Intrinsic::experimental_constrained_trunc:
  5368. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5369. return;
  5370. case Intrinsic::fmuladd: {
  5371. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5372. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5373. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5374. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5375. getValue(I.getArgOperand(0)).getValueType(),
  5376. getValue(I.getArgOperand(0)),
  5377. getValue(I.getArgOperand(1)),
  5378. getValue(I.getArgOperand(2))));
  5379. } else {
  5380. // TODO: Intrinsic calls should have fast-math-flags.
  5381. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5382. getValue(I.getArgOperand(0)).getValueType(),
  5383. getValue(I.getArgOperand(0)),
  5384. getValue(I.getArgOperand(1)));
  5385. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5386. getValue(I.getArgOperand(0)).getValueType(),
  5387. Mul,
  5388. getValue(I.getArgOperand(2)));
  5389. setValue(&I, Add);
  5390. }
  5391. return;
  5392. }
  5393. case Intrinsic::convert_to_fp16:
  5394. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5395. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5396. getValue(I.getArgOperand(0)),
  5397. DAG.getTargetConstant(0, sdl,
  5398. MVT::i32))));
  5399. return;
  5400. case Intrinsic::convert_from_fp16:
  5401. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5402. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5403. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5404. getValue(I.getArgOperand(0)))));
  5405. return;
  5406. case Intrinsic::pcmarker: {
  5407. SDValue Tmp = getValue(I.getArgOperand(0));
  5408. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5409. return;
  5410. }
  5411. case Intrinsic::readcyclecounter: {
  5412. SDValue Op = getRoot();
  5413. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5414. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5415. setValue(&I, Res);
  5416. DAG.setRoot(Res.getValue(1));
  5417. return;
  5418. }
  5419. case Intrinsic::bitreverse:
  5420. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5421. getValue(I.getArgOperand(0)).getValueType(),
  5422. getValue(I.getArgOperand(0))));
  5423. return;
  5424. case Intrinsic::bswap:
  5425. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5426. getValue(I.getArgOperand(0)).getValueType(),
  5427. getValue(I.getArgOperand(0))));
  5428. return;
  5429. case Intrinsic::cttz: {
  5430. SDValue Arg = getValue(I.getArgOperand(0));
  5431. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5432. EVT Ty = Arg.getValueType();
  5433. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5434. sdl, Ty, Arg));
  5435. return;
  5436. }
  5437. case Intrinsic::ctlz: {
  5438. SDValue Arg = getValue(I.getArgOperand(0));
  5439. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5440. EVT Ty = Arg.getValueType();
  5441. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5442. sdl, Ty, Arg));
  5443. return;
  5444. }
  5445. case Intrinsic::ctpop: {
  5446. SDValue Arg = getValue(I.getArgOperand(0));
  5447. EVT Ty = Arg.getValueType();
  5448. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5449. return;
  5450. }
  5451. case Intrinsic::fshl:
  5452. case Intrinsic::fshr: {
  5453. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5454. SDValue X = getValue(I.getArgOperand(0));
  5455. SDValue Y = getValue(I.getArgOperand(1));
  5456. SDValue Z = getValue(I.getArgOperand(2));
  5457. EVT VT = X.getValueType();
  5458. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5459. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5460. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5461. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5462. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5463. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5464. return;
  5465. }
  5466. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5467. // avoid the select that is necessary in the general case to filter out
  5468. // the 0-shift possibility that leads to UB.
  5469. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5470. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5471. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5472. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5473. return;
  5474. }
  5475. // Some targets only rotate one way. Try the opposite direction.
  5476. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5477. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5478. // Negate the shift amount because it is safe to ignore the high bits.
  5479. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5480. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5481. return;
  5482. }
  5483. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5484. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5485. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5486. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5487. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5488. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5489. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5490. return;
  5491. }
  5492. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5493. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5494. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5495. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5496. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5497. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5498. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5499. // and that is undefined. We must compare and select to avoid UB.
  5500. EVT CCVT = MVT::i1;
  5501. if (VT.isVector())
  5502. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5503. // For fshl, 0-shift returns the 1st arg (X).
  5504. // For fshr, 0-shift returns the 2nd arg (Y).
  5505. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5506. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5507. return;
  5508. }
  5509. case Intrinsic::sadd_sat: {
  5510. SDValue Op1 = getValue(I.getArgOperand(0));
  5511. SDValue Op2 = getValue(I.getArgOperand(1));
  5512. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5513. return;
  5514. }
  5515. case Intrinsic::uadd_sat: {
  5516. SDValue Op1 = getValue(I.getArgOperand(0));
  5517. SDValue Op2 = getValue(I.getArgOperand(1));
  5518. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5519. return;
  5520. }
  5521. case Intrinsic::ssub_sat: {
  5522. SDValue Op1 = getValue(I.getArgOperand(0));
  5523. SDValue Op2 = getValue(I.getArgOperand(1));
  5524. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5525. return;
  5526. }
  5527. case Intrinsic::usub_sat: {
  5528. SDValue Op1 = getValue(I.getArgOperand(0));
  5529. SDValue Op2 = getValue(I.getArgOperand(1));
  5530. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5531. return;
  5532. }
  5533. case Intrinsic::smul_fix:
  5534. case Intrinsic::umul_fix: {
  5535. SDValue Op1 = getValue(I.getArgOperand(0));
  5536. SDValue Op2 = getValue(I.getArgOperand(1));
  5537. SDValue Op3 = getValue(I.getArgOperand(2));
  5538. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5539. Op1.getValueType(), Op1, Op2, Op3));
  5540. return;
  5541. }
  5542. case Intrinsic::smul_fix_sat: {
  5543. SDValue Op1 = getValue(I.getArgOperand(0));
  5544. SDValue Op2 = getValue(I.getArgOperand(1));
  5545. SDValue Op3 = getValue(I.getArgOperand(2));
  5546. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5547. Op3));
  5548. return;
  5549. }
  5550. case Intrinsic::stacksave: {
  5551. SDValue Op = getRoot();
  5552. Res = DAG.getNode(
  5553. ISD::STACKSAVE, sdl,
  5554. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5555. setValue(&I, Res);
  5556. DAG.setRoot(Res.getValue(1));
  5557. return;
  5558. }
  5559. case Intrinsic::stackrestore:
  5560. Res = getValue(I.getArgOperand(0));
  5561. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5562. return;
  5563. case Intrinsic::get_dynamic_area_offset: {
  5564. SDValue Op = getRoot();
  5565. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5566. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5567. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5568. // target.
  5569. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5570. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5571. " intrinsic!");
  5572. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5573. Op);
  5574. DAG.setRoot(Op);
  5575. setValue(&I, Res);
  5576. return;
  5577. }
  5578. case Intrinsic::stackguard: {
  5579. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5580. MachineFunction &MF = DAG.getMachineFunction();
  5581. const Module &M = *MF.getFunction().getParent();
  5582. SDValue Chain = getRoot();
  5583. if (TLI.useLoadStackGuardNode()) {
  5584. Res = getLoadStackGuard(DAG, sdl, Chain);
  5585. } else {
  5586. const Value *Global = TLI.getSDagStackGuard(M);
  5587. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5588. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5589. MachinePointerInfo(Global, 0), Align,
  5590. MachineMemOperand::MOVolatile);
  5591. }
  5592. if (TLI.useStackGuardXorFP())
  5593. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5594. DAG.setRoot(Chain);
  5595. setValue(&I, Res);
  5596. return;
  5597. }
  5598. case Intrinsic::stackprotector: {
  5599. // Emit code into the DAG to store the stack guard onto the stack.
  5600. MachineFunction &MF = DAG.getMachineFunction();
  5601. MachineFrameInfo &MFI = MF.getFrameInfo();
  5602. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5603. SDValue Src, Chain = getRoot();
  5604. if (TLI.useLoadStackGuardNode())
  5605. Src = getLoadStackGuard(DAG, sdl, Chain);
  5606. else
  5607. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5608. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5609. int FI = FuncInfo.StaticAllocaMap[Slot];
  5610. MFI.setStackProtectorIndex(FI);
  5611. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5612. // Store the stack protector onto the stack.
  5613. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5614. DAG.getMachineFunction(), FI),
  5615. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5616. setValue(&I, Res);
  5617. DAG.setRoot(Res);
  5618. return;
  5619. }
  5620. case Intrinsic::objectsize: {
  5621. // If we don't know by now, we're never going to know.
  5622. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5623. assert(CI && "Non-constant type in __builtin_object_size?");
  5624. SDValue Arg = getValue(I.getCalledValue());
  5625. EVT Ty = Arg.getValueType();
  5626. if (CI->isZero())
  5627. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5628. else
  5629. Res = DAG.getConstant(0, sdl, Ty);
  5630. setValue(&I, Res);
  5631. return;
  5632. }
  5633. case Intrinsic::is_constant:
  5634. // If this wasn't constant-folded away by now, then it's not a
  5635. // constant.
  5636. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5637. return;
  5638. case Intrinsic::annotation:
  5639. case Intrinsic::ptr_annotation:
  5640. case Intrinsic::launder_invariant_group:
  5641. case Intrinsic::strip_invariant_group:
  5642. // Drop the intrinsic, but forward the value
  5643. setValue(&I, getValue(I.getOperand(0)));
  5644. return;
  5645. case Intrinsic::assume:
  5646. case Intrinsic::var_annotation:
  5647. case Intrinsic::sideeffect:
  5648. // Discard annotate attributes, assumptions, and artificial side-effects.
  5649. return;
  5650. case Intrinsic::codeview_annotation: {
  5651. // Emit a label associated with this metadata.
  5652. MachineFunction &MF = DAG.getMachineFunction();
  5653. MCSymbol *Label =
  5654. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5655. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5656. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5657. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5658. DAG.setRoot(Res);
  5659. return;
  5660. }
  5661. case Intrinsic::init_trampoline: {
  5662. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5663. SDValue Ops[6];
  5664. Ops[0] = getRoot();
  5665. Ops[1] = getValue(I.getArgOperand(0));
  5666. Ops[2] = getValue(I.getArgOperand(1));
  5667. Ops[3] = getValue(I.getArgOperand(2));
  5668. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5669. Ops[5] = DAG.getSrcValue(F);
  5670. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5671. DAG.setRoot(Res);
  5672. return;
  5673. }
  5674. case Intrinsic::adjust_trampoline:
  5675. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5676. TLI.getPointerTy(DAG.getDataLayout()),
  5677. getValue(I.getArgOperand(0))));
  5678. return;
  5679. case Intrinsic::gcroot: {
  5680. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5681. "only valid in functions with gc specified, enforced by Verifier");
  5682. assert(GFI && "implied by previous");
  5683. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5684. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5685. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5686. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5687. return;
  5688. }
  5689. case Intrinsic::gcread:
  5690. case Intrinsic::gcwrite:
  5691. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5692. case Intrinsic::flt_rounds:
  5693. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5694. return;
  5695. case Intrinsic::expect:
  5696. // Just replace __builtin_expect(exp, c) with EXP.
  5697. setValue(&I, getValue(I.getArgOperand(0)));
  5698. return;
  5699. case Intrinsic::debugtrap:
  5700. case Intrinsic::trap: {
  5701. StringRef TrapFuncName =
  5702. I.getAttributes()
  5703. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5704. .getValueAsString();
  5705. if (TrapFuncName.empty()) {
  5706. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5707. ISD::TRAP : ISD::DEBUGTRAP;
  5708. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5709. return;
  5710. }
  5711. TargetLowering::ArgListTy Args;
  5712. TargetLowering::CallLoweringInfo CLI(DAG);
  5713. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5714. CallingConv::C, I.getType(),
  5715. DAG.getExternalSymbol(TrapFuncName.data(),
  5716. TLI.getPointerTy(DAG.getDataLayout())),
  5717. std::move(Args));
  5718. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5719. DAG.setRoot(Result.second);
  5720. return;
  5721. }
  5722. case Intrinsic::uadd_with_overflow:
  5723. case Intrinsic::sadd_with_overflow:
  5724. case Intrinsic::usub_with_overflow:
  5725. case Intrinsic::ssub_with_overflow:
  5726. case Intrinsic::umul_with_overflow:
  5727. case Intrinsic::smul_with_overflow: {
  5728. ISD::NodeType Op;
  5729. switch (Intrinsic) {
  5730. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5731. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5732. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5733. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5734. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5735. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5736. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5737. }
  5738. SDValue Op1 = getValue(I.getArgOperand(0));
  5739. SDValue Op2 = getValue(I.getArgOperand(1));
  5740. EVT ResultVT = Op1.getValueType();
  5741. EVT OverflowVT = MVT::i1;
  5742. if (ResultVT.isVector())
  5743. OverflowVT = EVT::getVectorVT(
  5744. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5745. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5746. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5747. return;
  5748. }
  5749. case Intrinsic::prefetch: {
  5750. SDValue Ops[5];
  5751. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5752. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5753. Ops[0] = DAG.getRoot();
  5754. Ops[1] = getValue(I.getArgOperand(0));
  5755. Ops[2] = getValue(I.getArgOperand(1));
  5756. Ops[3] = getValue(I.getArgOperand(2));
  5757. Ops[4] = getValue(I.getArgOperand(3));
  5758. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5759. DAG.getVTList(MVT::Other), Ops,
  5760. EVT::getIntegerVT(*Context, 8),
  5761. MachinePointerInfo(I.getArgOperand(0)),
  5762. 0, /* align */
  5763. Flags);
  5764. // Chain the prefetch in parallell with any pending loads, to stay out of
  5765. // the way of later optimizations.
  5766. PendingLoads.push_back(Result);
  5767. Result = getRoot();
  5768. DAG.setRoot(Result);
  5769. return;
  5770. }
  5771. case Intrinsic::lifetime_start:
  5772. case Intrinsic::lifetime_end: {
  5773. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5774. // Stack coloring is not enabled in O0, discard region information.
  5775. if (TM.getOptLevel() == CodeGenOpt::None)
  5776. return;
  5777. const int64_t ObjectSize =
  5778. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5779. Value *const ObjectPtr = I.getArgOperand(1);
  5780. SmallVector<const Value *, 4> Allocas;
  5781. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5782. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5783. E = Allocas.end(); Object != E; ++Object) {
  5784. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5785. // Could not find an Alloca.
  5786. if (!LifetimeObject)
  5787. continue;
  5788. // First check that the Alloca is static, otherwise it won't have a
  5789. // valid frame index.
  5790. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5791. if (SI == FuncInfo.StaticAllocaMap.end())
  5792. return;
  5793. const int FrameIndex = SI->second;
  5794. int64_t Offset;
  5795. if (GetPointerBaseWithConstantOffset(
  5796. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5797. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5798. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5799. Offset);
  5800. DAG.setRoot(Res);
  5801. }
  5802. return;
  5803. }
  5804. case Intrinsic::invariant_start:
  5805. // Discard region information.
  5806. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5807. return;
  5808. case Intrinsic::invariant_end:
  5809. // Discard region information.
  5810. return;
  5811. case Intrinsic::clear_cache:
  5812. /// FunctionName may be null.
  5813. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5814. lowerCallToExternalSymbol(I, FunctionName);
  5815. return;
  5816. case Intrinsic::donothing:
  5817. // ignore
  5818. return;
  5819. case Intrinsic::experimental_stackmap:
  5820. visitStackmap(I);
  5821. return;
  5822. case Intrinsic::experimental_patchpoint_void:
  5823. case Intrinsic::experimental_patchpoint_i64:
  5824. visitPatchpoint(&I);
  5825. return;
  5826. case Intrinsic::experimental_gc_statepoint:
  5827. LowerStatepoint(ImmutableStatepoint(&I));
  5828. return;
  5829. case Intrinsic::experimental_gc_result:
  5830. visitGCResult(cast<GCResultInst>(I));
  5831. return;
  5832. case Intrinsic::experimental_gc_relocate:
  5833. visitGCRelocate(cast<GCRelocateInst>(I));
  5834. return;
  5835. case Intrinsic::instrprof_increment:
  5836. llvm_unreachable("instrprof failed to lower an increment");
  5837. case Intrinsic::instrprof_value_profile:
  5838. llvm_unreachable("instrprof failed to lower a value profiling call");
  5839. case Intrinsic::localescape: {
  5840. MachineFunction &MF = DAG.getMachineFunction();
  5841. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5842. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5843. // is the same on all targets.
  5844. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5845. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5846. if (isa<ConstantPointerNull>(Arg))
  5847. continue; // Skip null pointers. They represent a hole in index space.
  5848. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5849. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5850. "can only escape static allocas");
  5851. int FI = FuncInfo.StaticAllocaMap[Slot];
  5852. MCSymbol *FrameAllocSym =
  5853. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5854. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5855. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5856. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5857. .addSym(FrameAllocSym)
  5858. .addFrameIndex(FI);
  5859. }
  5860. return;
  5861. }
  5862. case Intrinsic::localrecover: {
  5863. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5864. MachineFunction &MF = DAG.getMachineFunction();
  5865. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5866. // Get the symbol that defines the frame offset.
  5867. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5868. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5869. unsigned IdxVal =
  5870. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5871. MCSymbol *FrameAllocSym =
  5872. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5873. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5874. // Create a MCSymbol for the label to avoid any target lowering
  5875. // that would make this PC relative.
  5876. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5877. SDValue OffsetVal =
  5878. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5879. // Add the offset to the FP.
  5880. Value *FP = I.getArgOperand(1);
  5881. SDValue FPVal = getValue(FP);
  5882. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5883. setValue(&I, Add);
  5884. return;
  5885. }
  5886. case Intrinsic::eh_exceptionpointer:
  5887. case Intrinsic::eh_exceptioncode: {
  5888. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5889. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5890. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5891. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5892. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5893. SDValue N =
  5894. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5895. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5896. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5897. setValue(&I, N);
  5898. return;
  5899. }
  5900. case Intrinsic::xray_customevent: {
  5901. // Here we want to make sure that the intrinsic behaves as if it has a
  5902. // specific calling convention, and only for x86_64.
  5903. // FIXME: Support other platforms later.
  5904. const auto &Triple = DAG.getTarget().getTargetTriple();
  5905. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5906. return;
  5907. SDLoc DL = getCurSDLoc();
  5908. SmallVector<SDValue, 8> Ops;
  5909. // We want to say that we always want the arguments in registers.
  5910. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5911. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5912. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5913. SDValue Chain = getRoot();
  5914. Ops.push_back(LogEntryVal);
  5915. Ops.push_back(StrSizeVal);
  5916. Ops.push_back(Chain);
  5917. // We need to enforce the calling convention for the callsite, so that
  5918. // argument ordering is enforced correctly, and that register allocation can
  5919. // see that some registers may be assumed clobbered and have to preserve
  5920. // them across calls to the intrinsic.
  5921. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5922. DL, NodeTys, Ops);
  5923. SDValue patchableNode = SDValue(MN, 0);
  5924. DAG.setRoot(patchableNode);
  5925. setValue(&I, patchableNode);
  5926. return;
  5927. }
  5928. case Intrinsic::xray_typedevent: {
  5929. // Here we want to make sure that the intrinsic behaves as if it has a
  5930. // specific calling convention, and only for x86_64.
  5931. // FIXME: Support other platforms later.
  5932. const auto &Triple = DAG.getTarget().getTargetTriple();
  5933. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5934. return;
  5935. SDLoc DL = getCurSDLoc();
  5936. SmallVector<SDValue, 8> Ops;
  5937. // We want to say that we always want the arguments in registers.
  5938. // It's unclear to me how manipulating the selection DAG here forces callers
  5939. // to provide arguments in registers instead of on the stack.
  5940. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5941. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5942. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5943. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5944. SDValue Chain = getRoot();
  5945. Ops.push_back(LogTypeId);
  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(
  5954. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5955. SDValue patchableNode = SDValue(MN, 0);
  5956. DAG.setRoot(patchableNode);
  5957. setValue(&I, patchableNode);
  5958. return;
  5959. }
  5960. case Intrinsic::experimental_deoptimize:
  5961. LowerDeoptimizeCall(&I);
  5962. return;
  5963. case Intrinsic::experimental_vector_reduce_v2_fadd:
  5964. case Intrinsic::experimental_vector_reduce_v2_fmul:
  5965. case Intrinsic::experimental_vector_reduce_add:
  5966. case Intrinsic::experimental_vector_reduce_mul:
  5967. case Intrinsic::experimental_vector_reduce_and:
  5968. case Intrinsic::experimental_vector_reduce_or:
  5969. case Intrinsic::experimental_vector_reduce_xor:
  5970. case Intrinsic::experimental_vector_reduce_smax:
  5971. case Intrinsic::experimental_vector_reduce_smin:
  5972. case Intrinsic::experimental_vector_reduce_umax:
  5973. case Intrinsic::experimental_vector_reduce_umin:
  5974. case Intrinsic::experimental_vector_reduce_fmax:
  5975. case Intrinsic::experimental_vector_reduce_fmin:
  5976. visitVectorReduce(I, Intrinsic);
  5977. return;
  5978. case Intrinsic::icall_branch_funnel: {
  5979. SmallVector<SDValue, 16> Ops;
  5980. Ops.push_back(DAG.getRoot());
  5981. Ops.push_back(getValue(I.getArgOperand(0)));
  5982. int64_t Offset;
  5983. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5984. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  5985. if (!Base)
  5986. report_fatal_error(
  5987. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5988. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  5989. struct BranchFunnelTarget {
  5990. int64_t Offset;
  5991. SDValue Target;
  5992. };
  5993. SmallVector<BranchFunnelTarget, 8> Targets;
  5994. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  5995. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5996. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  5997. if (ElemBase != Base)
  5998. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  5999. "to the same GlobalValue");
  6000. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6001. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6002. if (!GA)
  6003. report_fatal_error(
  6004. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6005. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6006. GA->getGlobal(), getCurSDLoc(),
  6007. Val.getValueType(), GA->getOffset())});
  6008. }
  6009. llvm::sort(Targets,
  6010. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6011. return T1.Offset < T2.Offset;
  6012. });
  6013. for (auto &T : Targets) {
  6014. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6015. Ops.push_back(T.Target);
  6016. }
  6017. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6018. getCurSDLoc(), MVT::Other, Ops),
  6019. 0);
  6020. DAG.setRoot(N);
  6021. setValue(&I, N);
  6022. HasTailCall = true;
  6023. return;
  6024. }
  6025. case Intrinsic::wasm_landingpad_index:
  6026. // Information this intrinsic contained has been transferred to
  6027. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6028. // delete it now.
  6029. return;
  6030. }
  6031. }
  6032. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6033. const ConstrainedFPIntrinsic &FPI) {
  6034. SDLoc sdl = getCurSDLoc();
  6035. unsigned Opcode;
  6036. switch (FPI.getIntrinsicID()) {
  6037. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6038. case Intrinsic::experimental_constrained_fadd:
  6039. Opcode = ISD::STRICT_FADD;
  6040. break;
  6041. case Intrinsic::experimental_constrained_fsub:
  6042. Opcode = ISD::STRICT_FSUB;
  6043. break;
  6044. case Intrinsic::experimental_constrained_fmul:
  6045. Opcode = ISD::STRICT_FMUL;
  6046. break;
  6047. case Intrinsic::experimental_constrained_fdiv:
  6048. Opcode = ISD::STRICT_FDIV;
  6049. break;
  6050. case Intrinsic::experimental_constrained_frem:
  6051. Opcode = ISD::STRICT_FREM;
  6052. break;
  6053. case Intrinsic::experimental_constrained_fma:
  6054. Opcode = ISD::STRICT_FMA;
  6055. break;
  6056. case Intrinsic::experimental_constrained_fptrunc:
  6057. Opcode = ISD::STRICT_FP_ROUND;
  6058. break;
  6059. case Intrinsic::experimental_constrained_fpext:
  6060. Opcode = ISD::STRICT_FP_EXTEND;
  6061. break;
  6062. case Intrinsic::experimental_constrained_sqrt:
  6063. Opcode = ISD::STRICT_FSQRT;
  6064. break;
  6065. case Intrinsic::experimental_constrained_pow:
  6066. Opcode = ISD::STRICT_FPOW;
  6067. break;
  6068. case Intrinsic::experimental_constrained_powi:
  6069. Opcode = ISD::STRICT_FPOWI;
  6070. break;
  6071. case Intrinsic::experimental_constrained_sin:
  6072. Opcode = ISD::STRICT_FSIN;
  6073. break;
  6074. case Intrinsic::experimental_constrained_cos:
  6075. Opcode = ISD::STRICT_FCOS;
  6076. break;
  6077. case Intrinsic::experimental_constrained_exp:
  6078. Opcode = ISD::STRICT_FEXP;
  6079. break;
  6080. case Intrinsic::experimental_constrained_exp2:
  6081. Opcode = ISD::STRICT_FEXP2;
  6082. break;
  6083. case Intrinsic::experimental_constrained_log:
  6084. Opcode = ISD::STRICT_FLOG;
  6085. break;
  6086. case Intrinsic::experimental_constrained_log10:
  6087. Opcode = ISD::STRICT_FLOG10;
  6088. break;
  6089. case Intrinsic::experimental_constrained_log2:
  6090. Opcode = ISD::STRICT_FLOG2;
  6091. break;
  6092. case Intrinsic::experimental_constrained_rint:
  6093. Opcode = ISD::STRICT_FRINT;
  6094. break;
  6095. case Intrinsic::experimental_constrained_nearbyint:
  6096. Opcode = ISD::STRICT_FNEARBYINT;
  6097. break;
  6098. case Intrinsic::experimental_constrained_maxnum:
  6099. Opcode = ISD::STRICT_FMAXNUM;
  6100. break;
  6101. case Intrinsic::experimental_constrained_minnum:
  6102. Opcode = ISD::STRICT_FMINNUM;
  6103. break;
  6104. case Intrinsic::experimental_constrained_ceil:
  6105. Opcode = ISD::STRICT_FCEIL;
  6106. break;
  6107. case Intrinsic::experimental_constrained_floor:
  6108. Opcode = ISD::STRICT_FFLOOR;
  6109. break;
  6110. case Intrinsic::experimental_constrained_round:
  6111. Opcode = ISD::STRICT_FROUND;
  6112. break;
  6113. case Intrinsic::experimental_constrained_trunc:
  6114. Opcode = ISD::STRICT_FTRUNC;
  6115. break;
  6116. }
  6117. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6118. SDValue Chain = getRoot();
  6119. SmallVector<EVT, 4> ValueVTs;
  6120. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6121. ValueVTs.push_back(MVT::Other); // Out chain
  6122. SDVTList VTs = DAG.getVTList(ValueVTs);
  6123. SDValue Result;
  6124. if (Opcode == ISD::STRICT_FP_ROUND)
  6125. Result = DAG.getNode(Opcode, sdl, VTs,
  6126. { Chain, getValue(FPI.getArgOperand(0)),
  6127. DAG.getTargetConstant(0, sdl,
  6128. TLI.getPointerTy(DAG.getDataLayout())) });
  6129. else if (FPI.isUnaryOp())
  6130. Result = DAG.getNode(Opcode, sdl, VTs,
  6131. { Chain, getValue(FPI.getArgOperand(0)) });
  6132. else if (FPI.isTernaryOp())
  6133. Result = DAG.getNode(Opcode, sdl, VTs,
  6134. { Chain, getValue(FPI.getArgOperand(0)),
  6135. getValue(FPI.getArgOperand(1)),
  6136. getValue(FPI.getArgOperand(2)) });
  6137. else
  6138. Result = DAG.getNode(Opcode, sdl, VTs,
  6139. { Chain, getValue(FPI.getArgOperand(0)),
  6140. getValue(FPI.getArgOperand(1)) });
  6141. if (FPI.getExceptionBehavior() !=
  6142. ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
  6143. SDNodeFlags Flags;
  6144. Flags.setFPExcept(true);
  6145. Result->setFlags(Flags);
  6146. }
  6147. assert(Result.getNode()->getNumValues() == 2);
  6148. SDValue OutChain = Result.getValue(1);
  6149. DAG.setRoot(OutChain);
  6150. SDValue FPResult = Result.getValue(0);
  6151. setValue(&FPI, FPResult);
  6152. }
  6153. std::pair<SDValue, SDValue>
  6154. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6155. const BasicBlock *EHPadBB) {
  6156. MachineFunction &MF = DAG.getMachineFunction();
  6157. MachineModuleInfo &MMI = MF.getMMI();
  6158. MCSymbol *BeginLabel = nullptr;
  6159. if (EHPadBB) {
  6160. // Insert a label before the invoke call to mark the try range. This can be
  6161. // used to detect deletion of the invoke via the MachineModuleInfo.
  6162. BeginLabel = MMI.getContext().createTempSymbol();
  6163. // For SjLj, keep track of which landing pads go with which invokes
  6164. // so as to maintain the ordering of pads in the LSDA.
  6165. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6166. if (CallSiteIndex) {
  6167. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6168. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6169. // Now that the call site is handled, stop tracking it.
  6170. MMI.setCurrentCallSite(0);
  6171. }
  6172. // Both PendingLoads and PendingExports must be flushed here;
  6173. // this call might not return.
  6174. (void)getRoot();
  6175. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6176. CLI.setChain(getRoot());
  6177. }
  6178. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6179. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6180. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6181. "Non-null chain expected with non-tail call!");
  6182. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6183. "Null value expected with tail call!");
  6184. if (!Result.second.getNode()) {
  6185. // As a special case, a null chain means that a tail call has been emitted
  6186. // and the DAG root is already updated.
  6187. HasTailCall = true;
  6188. // Since there's no actual continuation from this block, nothing can be
  6189. // relying on us setting vregs for them.
  6190. PendingExports.clear();
  6191. } else {
  6192. DAG.setRoot(Result.second);
  6193. }
  6194. if (EHPadBB) {
  6195. // Insert a label at the end of the invoke call to mark the try range. This
  6196. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6197. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6198. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6199. // Inform MachineModuleInfo of range.
  6200. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6201. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6202. // actually use outlined funclets and their LSDA info style.
  6203. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6204. assert(CLI.CS);
  6205. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6206. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6207. BeginLabel, EndLabel);
  6208. } else if (!isScopedEHPersonality(Pers)) {
  6209. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6210. }
  6211. }
  6212. return Result;
  6213. }
  6214. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6215. bool isTailCall,
  6216. const BasicBlock *EHPadBB) {
  6217. auto &DL = DAG.getDataLayout();
  6218. FunctionType *FTy = CS.getFunctionType();
  6219. Type *RetTy = CS.getType();
  6220. TargetLowering::ArgListTy Args;
  6221. Args.reserve(CS.arg_size());
  6222. const Value *SwiftErrorVal = nullptr;
  6223. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6224. // We can't tail call inside a function with a swifterror argument. Lowering
  6225. // does not support this yet. It would have to move into the swifterror
  6226. // register before the call.
  6227. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6228. if (TLI.supportSwiftError() &&
  6229. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6230. isTailCall = false;
  6231. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6232. i != e; ++i) {
  6233. TargetLowering::ArgListEntry Entry;
  6234. const Value *V = *i;
  6235. // Skip empty types
  6236. if (V->getType()->isEmptyTy())
  6237. continue;
  6238. SDValue ArgNode = getValue(V);
  6239. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6240. Entry.setAttributes(&CS, i - CS.arg_begin());
  6241. // Use swifterror virtual register as input to the call.
  6242. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6243. SwiftErrorVal = V;
  6244. // We find the virtual register for the actual swifterror argument.
  6245. // Instead of using the Value, we use the virtual register instead.
  6246. Entry.Node = DAG.getRegister(
  6247. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6248. EVT(TLI.getPointerTy(DL)));
  6249. }
  6250. Args.push_back(Entry);
  6251. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6252. // might point to function-local memory), we can't meaningfully tail-call.
  6253. if (Entry.IsSRet && isa<Instruction>(V))
  6254. isTailCall = false;
  6255. }
  6256. // Check if target-independent constraints permit a tail call here.
  6257. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6258. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6259. isTailCall = false;
  6260. // Disable tail calls if there is an swifterror argument. Targets have not
  6261. // been updated to support tail calls.
  6262. if (TLI.supportSwiftError() && SwiftErrorVal)
  6263. isTailCall = false;
  6264. TargetLowering::CallLoweringInfo CLI(DAG);
  6265. CLI.setDebugLoc(getCurSDLoc())
  6266. .setChain(getRoot())
  6267. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6268. .setTailCall(isTailCall)
  6269. .setConvergent(CS.isConvergent());
  6270. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6271. if (Result.first.getNode()) {
  6272. const Instruction *Inst = CS.getInstruction();
  6273. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6274. setValue(Inst, Result.first);
  6275. }
  6276. // The last element of CLI.InVals has the SDValue for swifterror return.
  6277. // Here we copy it to a virtual register and update SwiftErrorMap for
  6278. // book-keeping.
  6279. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6280. // Get the last element of InVals.
  6281. SDValue Src = CLI.InVals.back();
  6282. unsigned VReg = SwiftError.getOrCreateVRegDefAt(
  6283. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6284. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6285. DAG.setRoot(CopyNode);
  6286. }
  6287. }
  6288. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6289. SelectionDAGBuilder &Builder) {
  6290. // Check to see if this load can be trivially constant folded, e.g. if the
  6291. // input is from a string literal.
  6292. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6293. // Cast pointer to the type we really want to load.
  6294. Type *LoadTy =
  6295. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6296. if (LoadVT.isVector())
  6297. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6298. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6299. PointerType::getUnqual(LoadTy));
  6300. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6301. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6302. return Builder.getValue(LoadCst);
  6303. }
  6304. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6305. // still constant memory, the input chain can be the entry node.
  6306. SDValue Root;
  6307. bool ConstantMemory = false;
  6308. // Do not serialize (non-volatile) loads of constant memory with anything.
  6309. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6310. Root = Builder.DAG.getEntryNode();
  6311. ConstantMemory = true;
  6312. } else {
  6313. // Do not serialize non-volatile loads against each other.
  6314. Root = Builder.DAG.getRoot();
  6315. }
  6316. SDValue Ptr = Builder.getValue(PtrVal);
  6317. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6318. Ptr, MachinePointerInfo(PtrVal),
  6319. /* Alignment = */ 1);
  6320. if (!ConstantMemory)
  6321. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6322. return LoadVal;
  6323. }
  6324. /// Record the value for an instruction that produces an integer result,
  6325. /// converting the type where necessary.
  6326. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6327. SDValue Value,
  6328. bool IsSigned) {
  6329. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6330. I.getType(), true);
  6331. if (IsSigned)
  6332. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6333. else
  6334. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6335. setValue(&I, Value);
  6336. }
  6337. /// See if we can lower a memcmp call into an optimized form. If so, return
  6338. /// true and lower it. Otherwise return false, and it will be lowered like a
  6339. /// normal call.
  6340. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6341. /// correct prototype.
  6342. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6343. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6344. const Value *Size = I.getArgOperand(2);
  6345. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6346. if (CSize && CSize->getZExtValue() == 0) {
  6347. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6348. I.getType(), true);
  6349. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6350. return true;
  6351. }
  6352. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6353. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6354. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6355. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6356. if (Res.first.getNode()) {
  6357. processIntegerCallValue(I, Res.first, true);
  6358. PendingLoads.push_back(Res.second);
  6359. return true;
  6360. }
  6361. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6362. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6363. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6364. return false;
  6365. // If the target has a fast compare for the given size, it will return a
  6366. // preferred load type for that size. Require that the load VT is legal and
  6367. // that the target supports unaligned loads of that type. Otherwise, return
  6368. // INVALID.
  6369. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6370. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6371. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6372. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6373. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6374. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6375. // TODO: Check alignment of src and dest ptrs.
  6376. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6377. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6378. if (!TLI.isTypeLegal(LVT) ||
  6379. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6380. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6381. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6382. }
  6383. return LVT;
  6384. };
  6385. // This turns into unaligned loads. We only do this if the target natively
  6386. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6387. // we'll only produce a small number of byte loads.
  6388. MVT LoadVT;
  6389. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6390. switch (NumBitsToCompare) {
  6391. default:
  6392. return false;
  6393. case 16:
  6394. LoadVT = MVT::i16;
  6395. break;
  6396. case 32:
  6397. LoadVT = MVT::i32;
  6398. break;
  6399. case 64:
  6400. case 128:
  6401. case 256:
  6402. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6403. break;
  6404. }
  6405. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6406. return false;
  6407. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6408. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6409. // Bitcast to a wide integer type if the loads are vectors.
  6410. if (LoadVT.isVector()) {
  6411. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6412. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6413. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6414. }
  6415. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6416. processIntegerCallValue(I, Cmp, false);
  6417. return true;
  6418. }
  6419. /// See if we can lower a memchr call into an optimized form. If so, return
  6420. /// true and lower it. Otherwise return false, and it will be lowered like a
  6421. /// normal call.
  6422. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6423. /// correct prototype.
  6424. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6425. const Value *Src = I.getArgOperand(0);
  6426. const Value *Char = I.getArgOperand(1);
  6427. const Value *Length = I.getArgOperand(2);
  6428. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6429. std::pair<SDValue, SDValue> Res =
  6430. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6431. getValue(Src), getValue(Char), getValue(Length),
  6432. MachinePointerInfo(Src));
  6433. if (Res.first.getNode()) {
  6434. setValue(&I, Res.first);
  6435. PendingLoads.push_back(Res.second);
  6436. return true;
  6437. }
  6438. return false;
  6439. }
  6440. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6441. /// true and lower it. Otherwise return false, and it will be lowered like a
  6442. /// normal call.
  6443. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6444. /// correct prototype.
  6445. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6446. SDValue Dst = getValue(I.getArgOperand(0));
  6447. SDValue Src = getValue(I.getArgOperand(1));
  6448. SDValue Size = getValue(I.getArgOperand(2));
  6449. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6450. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6451. unsigned Align = std::min(DstAlign, SrcAlign);
  6452. if (Align == 0) // Alignment of one or both could not be inferred.
  6453. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6454. bool isVol = false;
  6455. SDLoc sdl = getCurSDLoc();
  6456. // In the mempcpy context we need to pass in a false value for isTailCall
  6457. // because the return pointer needs to be adjusted by the size of
  6458. // the copied memory.
  6459. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6460. false, /*isTailCall=*/false,
  6461. MachinePointerInfo(I.getArgOperand(0)),
  6462. MachinePointerInfo(I.getArgOperand(1)));
  6463. assert(MC.getNode() != nullptr &&
  6464. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6465. DAG.setRoot(MC);
  6466. // Check if Size needs to be truncated or extended.
  6467. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6468. // Adjust return pointer to point just past the last dst byte.
  6469. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6470. Dst, Size);
  6471. setValue(&I, DstPlusSize);
  6472. return true;
  6473. }
  6474. /// See if we can lower a strcpy call into an optimized form. If so, return
  6475. /// true and lower it, otherwise return false and it will be lowered like a
  6476. /// normal call.
  6477. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6478. /// correct prototype.
  6479. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6480. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6481. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6482. std::pair<SDValue, SDValue> Res =
  6483. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6484. getValue(Arg0), getValue(Arg1),
  6485. MachinePointerInfo(Arg0),
  6486. MachinePointerInfo(Arg1), isStpcpy);
  6487. if (Res.first.getNode()) {
  6488. setValue(&I, Res.first);
  6489. DAG.setRoot(Res.second);
  6490. return true;
  6491. }
  6492. return false;
  6493. }
  6494. /// See if we can lower a strcmp call into an optimized form. If so, return
  6495. /// true and lower it, otherwise return false and it will be lowered like a
  6496. /// normal call.
  6497. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6498. /// correct prototype.
  6499. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6500. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6501. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6502. std::pair<SDValue, SDValue> Res =
  6503. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6504. getValue(Arg0), getValue(Arg1),
  6505. MachinePointerInfo(Arg0),
  6506. MachinePointerInfo(Arg1));
  6507. if (Res.first.getNode()) {
  6508. processIntegerCallValue(I, Res.first, true);
  6509. PendingLoads.push_back(Res.second);
  6510. return true;
  6511. }
  6512. return false;
  6513. }
  6514. /// See if we can lower a strlen call into an optimized form. If so, return
  6515. /// true and lower it, otherwise return false and it will be lowered like a
  6516. /// normal call.
  6517. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6518. /// correct prototype.
  6519. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6520. const Value *Arg0 = I.getArgOperand(0);
  6521. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6522. std::pair<SDValue, SDValue> Res =
  6523. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6524. getValue(Arg0), MachinePointerInfo(Arg0));
  6525. if (Res.first.getNode()) {
  6526. processIntegerCallValue(I, Res.first, false);
  6527. PendingLoads.push_back(Res.second);
  6528. return true;
  6529. }
  6530. return false;
  6531. }
  6532. /// See if we can lower a strnlen call into an optimized form. If so, return
  6533. /// true and lower it, otherwise return false and it will be lowered like a
  6534. /// normal call.
  6535. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6536. /// correct prototype.
  6537. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6538. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6539. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6540. std::pair<SDValue, SDValue> Res =
  6541. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6542. getValue(Arg0), getValue(Arg1),
  6543. MachinePointerInfo(Arg0));
  6544. if (Res.first.getNode()) {
  6545. processIntegerCallValue(I, Res.first, false);
  6546. PendingLoads.push_back(Res.second);
  6547. return true;
  6548. }
  6549. return false;
  6550. }
  6551. /// See if we can lower a unary floating-point operation into an SDNode with
  6552. /// the specified Opcode. If so, return true and lower it, otherwise return
  6553. /// false and it will be lowered like a normal call.
  6554. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6555. /// correct prototype.
  6556. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6557. unsigned Opcode) {
  6558. // We already checked this call's prototype; verify it doesn't modify errno.
  6559. if (!I.onlyReadsMemory())
  6560. return false;
  6561. SDValue Tmp = getValue(I.getArgOperand(0));
  6562. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6563. return true;
  6564. }
  6565. /// See if we can lower a binary floating-point operation into an SDNode with
  6566. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6567. /// false, and it will be lowered like a normal call.
  6568. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6569. /// correct prototype.
  6570. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6571. unsigned Opcode) {
  6572. // We already checked this call's prototype; verify it doesn't modify errno.
  6573. if (!I.onlyReadsMemory())
  6574. return false;
  6575. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6576. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6577. EVT VT = Tmp0.getValueType();
  6578. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6579. return true;
  6580. }
  6581. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6582. // Handle inline assembly differently.
  6583. if (isa<InlineAsm>(I.getCalledValue())) {
  6584. visitInlineAsm(&I);
  6585. return;
  6586. }
  6587. if (Function *F = I.getCalledFunction()) {
  6588. if (F->isDeclaration()) {
  6589. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6590. unsigned IID = F->getIntrinsicID();
  6591. if (!IID)
  6592. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6593. IID = II->getIntrinsicID(F);
  6594. if (IID) {
  6595. visitIntrinsicCall(I, IID);
  6596. return;
  6597. }
  6598. }
  6599. // Check for well-known libc/libm calls. If the function is internal, it
  6600. // can't be a library call. Don't do the check if marked as nobuiltin for
  6601. // some reason or the call site requires strict floating point semantics.
  6602. LibFunc Func;
  6603. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6604. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6605. LibInfo->hasOptimizedCodeGen(Func)) {
  6606. switch (Func) {
  6607. default: break;
  6608. case LibFunc_copysign:
  6609. case LibFunc_copysignf:
  6610. case LibFunc_copysignl:
  6611. // We already checked this call's prototype; verify it doesn't modify
  6612. // errno.
  6613. if (I.onlyReadsMemory()) {
  6614. SDValue LHS = getValue(I.getArgOperand(0));
  6615. SDValue RHS = getValue(I.getArgOperand(1));
  6616. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6617. LHS.getValueType(), LHS, RHS));
  6618. return;
  6619. }
  6620. break;
  6621. case LibFunc_fabs:
  6622. case LibFunc_fabsf:
  6623. case LibFunc_fabsl:
  6624. if (visitUnaryFloatCall(I, ISD::FABS))
  6625. return;
  6626. break;
  6627. case LibFunc_fmin:
  6628. case LibFunc_fminf:
  6629. case LibFunc_fminl:
  6630. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6631. return;
  6632. break;
  6633. case LibFunc_fmax:
  6634. case LibFunc_fmaxf:
  6635. case LibFunc_fmaxl:
  6636. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6637. return;
  6638. break;
  6639. case LibFunc_sin:
  6640. case LibFunc_sinf:
  6641. case LibFunc_sinl:
  6642. if (visitUnaryFloatCall(I, ISD::FSIN))
  6643. return;
  6644. break;
  6645. case LibFunc_cos:
  6646. case LibFunc_cosf:
  6647. case LibFunc_cosl:
  6648. if (visitUnaryFloatCall(I, ISD::FCOS))
  6649. return;
  6650. break;
  6651. case LibFunc_sqrt:
  6652. case LibFunc_sqrtf:
  6653. case LibFunc_sqrtl:
  6654. case LibFunc_sqrt_finite:
  6655. case LibFunc_sqrtf_finite:
  6656. case LibFunc_sqrtl_finite:
  6657. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6658. return;
  6659. break;
  6660. case LibFunc_floor:
  6661. case LibFunc_floorf:
  6662. case LibFunc_floorl:
  6663. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6664. return;
  6665. break;
  6666. case LibFunc_nearbyint:
  6667. case LibFunc_nearbyintf:
  6668. case LibFunc_nearbyintl:
  6669. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6670. return;
  6671. break;
  6672. case LibFunc_ceil:
  6673. case LibFunc_ceilf:
  6674. case LibFunc_ceill:
  6675. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6676. return;
  6677. break;
  6678. case LibFunc_rint:
  6679. case LibFunc_rintf:
  6680. case LibFunc_rintl:
  6681. if (visitUnaryFloatCall(I, ISD::FRINT))
  6682. return;
  6683. break;
  6684. case LibFunc_round:
  6685. case LibFunc_roundf:
  6686. case LibFunc_roundl:
  6687. if (visitUnaryFloatCall(I, ISD::FROUND))
  6688. return;
  6689. break;
  6690. case LibFunc_trunc:
  6691. case LibFunc_truncf:
  6692. case LibFunc_truncl:
  6693. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6694. return;
  6695. break;
  6696. case LibFunc_log2:
  6697. case LibFunc_log2f:
  6698. case LibFunc_log2l:
  6699. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6700. return;
  6701. break;
  6702. case LibFunc_exp2:
  6703. case LibFunc_exp2f:
  6704. case LibFunc_exp2l:
  6705. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6706. return;
  6707. break;
  6708. case LibFunc_memcmp:
  6709. if (visitMemCmpCall(I))
  6710. return;
  6711. break;
  6712. case LibFunc_mempcpy:
  6713. if (visitMemPCpyCall(I))
  6714. return;
  6715. break;
  6716. case LibFunc_memchr:
  6717. if (visitMemChrCall(I))
  6718. return;
  6719. break;
  6720. case LibFunc_strcpy:
  6721. if (visitStrCpyCall(I, false))
  6722. return;
  6723. break;
  6724. case LibFunc_stpcpy:
  6725. if (visitStrCpyCall(I, true))
  6726. return;
  6727. break;
  6728. case LibFunc_strcmp:
  6729. if (visitStrCmpCall(I))
  6730. return;
  6731. break;
  6732. case LibFunc_strlen:
  6733. if (visitStrLenCall(I))
  6734. return;
  6735. break;
  6736. case LibFunc_strnlen:
  6737. if (visitStrNLenCall(I))
  6738. return;
  6739. break;
  6740. }
  6741. }
  6742. }
  6743. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6744. // have to do anything here to lower funclet bundles.
  6745. assert(!I.hasOperandBundlesOtherThan(
  6746. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6747. "Cannot lower calls with arbitrary operand bundles!");
  6748. SDValue Callee = getValue(I.getCalledValue());
  6749. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6750. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6751. else
  6752. // Check if we can potentially perform a tail call. More detailed checking
  6753. // is be done within LowerCallTo, after more information about the call is
  6754. // known.
  6755. LowerCallTo(&I, Callee, I.isTailCall());
  6756. }
  6757. namespace {
  6758. /// AsmOperandInfo - This contains information for each constraint that we are
  6759. /// lowering.
  6760. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6761. public:
  6762. /// CallOperand - If this is the result output operand or a clobber
  6763. /// this is null, otherwise it is the incoming operand to the CallInst.
  6764. /// This gets modified as the asm is processed.
  6765. SDValue CallOperand;
  6766. /// AssignedRegs - If this is a register or register class operand, this
  6767. /// contains the set of register corresponding to the operand.
  6768. RegsForValue AssignedRegs;
  6769. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6770. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6771. }
  6772. /// Whether or not this operand accesses memory
  6773. bool hasMemory(const TargetLowering &TLI) const {
  6774. // Indirect operand accesses access memory.
  6775. if (isIndirect)
  6776. return true;
  6777. for (const auto &Code : Codes)
  6778. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6779. return true;
  6780. return false;
  6781. }
  6782. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6783. /// corresponds to. If there is no Value* for this operand, it returns
  6784. /// MVT::Other.
  6785. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6786. const DataLayout &DL) const {
  6787. if (!CallOperandVal) return MVT::Other;
  6788. if (isa<BasicBlock>(CallOperandVal))
  6789. return TLI.getPointerTy(DL);
  6790. llvm::Type *OpTy = CallOperandVal->getType();
  6791. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6792. // If this is an indirect operand, the operand is a pointer to the
  6793. // accessed type.
  6794. if (isIndirect) {
  6795. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6796. if (!PtrTy)
  6797. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6798. OpTy = PtrTy->getElementType();
  6799. }
  6800. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6801. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6802. if (STy->getNumElements() == 1)
  6803. OpTy = STy->getElementType(0);
  6804. // If OpTy is not a single value, it may be a struct/union that we
  6805. // can tile with integers.
  6806. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6807. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6808. switch (BitSize) {
  6809. default: break;
  6810. case 1:
  6811. case 8:
  6812. case 16:
  6813. case 32:
  6814. case 64:
  6815. case 128:
  6816. OpTy = IntegerType::get(Context, BitSize);
  6817. break;
  6818. }
  6819. }
  6820. return TLI.getValueType(DL, OpTy, true);
  6821. }
  6822. };
  6823. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6824. } // end anonymous namespace
  6825. /// Make sure that the output operand \p OpInfo and its corresponding input
  6826. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6827. /// out).
  6828. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6829. SDISelAsmOperandInfo &MatchingOpInfo,
  6830. SelectionDAG &DAG) {
  6831. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6832. return;
  6833. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6834. const auto &TLI = DAG.getTargetLoweringInfo();
  6835. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6836. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6837. OpInfo.ConstraintVT);
  6838. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6839. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6840. MatchingOpInfo.ConstraintVT);
  6841. if ((OpInfo.ConstraintVT.isInteger() !=
  6842. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6843. (MatchRC.second != InputRC.second)) {
  6844. // FIXME: error out in a more elegant fashion
  6845. report_fatal_error("Unsupported asm: input constraint"
  6846. " with a matching output constraint of"
  6847. " incompatible type!");
  6848. }
  6849. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6850. }
  6851. /// Get a direct memory input to behave well as an indirect operand.
  6852. /// This may introduce stores, hence the need for a \p Chain.
  6853. /// \return The (possibly updated) chain.
  6854. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6855. SDISelAsmOperandInfo &OpInfo,
  6856. SelectionDAG &DAG) {
  6857. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6858. // If we don't have an indirect input, put it in the constpool if we can,
  6859. // otherwise spill it to a stack slot.
  6860. // TODO: This isn't quite right. We need to handle these according to
  6861. // the addressing mode that the constraint wants. Also, this may take
  6862. // an additional register for the computation and we don't want that
  6863. // either.
  6864. // If the operand is a float, integer, or vector constant, spill to a
  6865. // constant pool entry to get its address.
  6866. const Value *OpVal = OpInfo.CallOperandVal;
  6867. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6868. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6869. OpInfo.CallOperand = DAG.getConstantPool(
  6870. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6871. return Chain;
  6872. }
  6873. // Otherwise, create a stack slot and emit a store to it before the asm.
  6874. Type *Ty = OpVal->getType();
  6875. auto &DL = DAG.getDataLayout();
  6876. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6877. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6878. MachineFunction &MF = DAG.getMachineFunction();
  6879. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6880. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6881. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6882. MachinePointerInfo::getFixedStack(MF, SSFI),
  6883. TLI.getMemValueType(DL, Ty));
  6884. OpInfo.CallOperand = StackSlot;
  6885. return Chain;
  6886. }
  6887. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6888. /// specified operand. We prefer to assign virtual registers, to allow the
  6889. /// register allocator to handle the assignment process. However, if the asm
  6890. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6891. /// allocation. This produces generally horrible, but correct, code.
  6892. ///
  6893. /// OpInfo describes the operand
  6894. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6895. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6896. SDISelAsmOperandInfo &OpInfo,
  6897. SDISelAsmOperandInfo &RefOpInfo) {
  6898. LLVMContext &Context = *DAG.getContext();
  6899. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6900. MachineFunction &MF = DAG.getMachineFunction();
  6901. SmallVector<unsigned, 4> Regs;
  6902. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6903. // No work to do for memory operations.
  6904. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6905. return;
  6906. // If this is a constraint for a single physreg, or a constraint for a
  6907. // register class, find it.
  6908. unsigned AssignedReg;
  6909. const TargetRegisterClass *RC;
  6910. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6911. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6912. // RC is unset only on failure. Return immediately.
  6913. if (!RC)
  6914. return;
  6915. // Get the actual register value type. This is important, because the user
  6916. // may have asked for (e.g.) the AX register in i32 type. We need to
  6917. // remember that AX is actually i16 to get the right extension.
  6918. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6919. if (OpInfo.ConstraintVT != MVT::Other) {
  6920. // If this is an FP operand in an integer register (or visa versa), or more
  6921. // generally if the operand value disagrees with the register class we plan
  6922. // to stick it in, fix the operand type.
  6923. //
  6924. // If this is an input value, the bitcast to the new type is done now.
  6925. // Bitcast for output value is done at the end of visitInlineAsm().
  6926. if ((OpInfo.Type == InlineAsm::isOutput ||
  6927. OpInfo.Type == InlineAsm::isInput) &&
  6928. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6929. // Try to convert to the first EVT that the reg class contains. If the
  6930. // types are identical size, use a bitcast to convert (e.g. two differing
  6931. // vector types). Note: output bitcast is done at the end of
  6932. // visitInlineAsm().
  6933. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6934. // Exclude indirect inputs while they are unsupported because the code
  6935. // to perform the load is missing and thus OpInfo.CallOperand still
  6936. // refers to the input address rather than the pointed-to value.
  6937. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6938. OpInfo.CallOperand =
  6939. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6940. OpInfo.ConstraintVT = RegVT;
  6941. // If the operand is an FP value and we want it in integer registers,
  6942. // use the corresponding integer type. This turns an f64 value into
  6943. // i64, which can be passed with two i32 values on a 32-bit machine.
  6944. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6945. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6946. if (OpInfo.Type == InlineAsm::isInput)
  6947. OpInfo.CallOperand =
  6948. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  6949. OpInfo.ConstraintVT = VT;
  6950. }
  6951. }
  6952. }
  6953. // No need to allocate a matching input constraint since the constraint it's
  6954. // matching to has already been allocated.
  6955. if (OpInfo.isMatchingInputConstraint())
  6956. return;
  6957. EVT ValueVT = OpInfo.ConstraintVT;
  6958. if (OpInfo.ConstraintVT == MVT::Other)
  6959. ValueVT = RegVT;
  6960. // Initialize NumRegs.
  6961. unsigned NumRegs = 1;
  6962. if (OpInfo.ConstraintVT != MVT::Other)
  6963. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6964. // If this is a constraint for a specific physical register, like {r17},
  6965. // assign it now.
  6966. // If this associated to a specific register, initialize iterator to correct
  6967. // place. If virtual, make sure we have enough registers
  6968. // Initialize iterator if necessary
  6969. TargetRegisterClass::iterator I = RC->begin();
  6970. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6971. // Do not check for single registers.
  6972. if (AssignedReg) {
  6973. for (; *I != AssignedReg; ++I)
  6974. assert(I != RC->end() && "AssignedReg should be member of RC");
  6975. }
  6976. for (; NumRegs; --NumRegs, ++I) {
  6977. assert(I != RC->end() && "Ran out of registers to allocate!");
  6978. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  6979. Regs.push_back(R);
  6980. }
  6981. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6982. }
  6983. static unsigned
  6984. findMatchingInlineAsmOperand(unsigned OperandNo,
  6985. const std::vector<SDValue> &AsmNodeOperands) {
  6986. // Scan until we find the definition we already emitted of this operand.
  6987. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6988. for (; OperandNo; --OperandNo) {
  6989. // Advance to the next operand.
  6990. unsigned OpFlag =
  6991. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6992. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6993. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6994. InlineAsm::isMemKind(OpFlag)) &&
  6995. "Skipped past definitions?");
  6996. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6997. }
  6998. return CurOp;
  6999. }
  7000. namespace {
  7001. class ExtraFlags {
  7002. unsigned Flags = 0;
  7003. public:
  7004. explicit ExtraFlags(ImmutableCallSite CS) {
  7005. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7006. if (IA->hasSideEffects())
  7007. Flags |= InlineAsm::Extra_HasSideEffects;
  7008. if (IA->isAlignStack())
  7009. Flags |= InlineAsm::Extra_IsAlignStack;
  7010. if (CS.isConvergent())
  7011. Flags |= InlineAsm::Extra_IsConvergent;
  7012. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7013. }
  7014. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7015. // Ideally, we would only check against memory constraints. However, the
  7016. // meaning of an Other constraint can be target-specific and we can't easily
  7017. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7018. // for Other constraints as well.
  7019. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7020. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7021. if (OpInfo.Type == InlineAsm::isInput)
  7022. Flags |= InlineAsm::Extra_MayLoad;
  7023. else if (OpInfo.Type == InlineAsm::isOutput)
  7024. Flags |= InlineAsm::Extra_MayStore;
  7025. else if (OpInfo.Type == InlineAsm::isClobber)
  7026. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7027. }
  7028. }
  7029. unsigned get() const { return Flags; }
  7030. };
  7031. } // end anonymous namespace
  7032. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7033. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7034. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7035. /// ConstraintOperands - Information about all of the constraints.
  7036. SDISelAsmOperandInfoVector ConstraintOperands;
  7037. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7038. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7039. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7040. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7041. // AsmDialect, MayLoad, MayStore).
  7042. bool HasSideEffect = IA->hasSideEffects();
  7043. ExtraFlags ExtraInfo(CS);
  7044. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7045. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7046. for (auto &T : TargetConstraints) {
  7047. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7048. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7049. // Compute the value type for each operand.
  7050. if (OpInfo.Type == InlineAsm::isInput ||
  7051. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7052. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7053. // Process the call argument. BasicBlocks are labels, currently appearing
  7054. // only in asm's.
  7055. const Instruction *I = CS.getInstruction();
  7056. if (isa<CallBrInst>(I) &&
  7057. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7058. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7059. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7060. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7061. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7062. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7063. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7064. } else {
  7065. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7066. }
  7067. OpInfo.ConstraintVT =
  7068. OpInfo
  7069. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7070. .getSimpleVT();
  7071. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7072. // The return value of the call is this value. As such, there is no
  7073. // corresponding argument.
  7074. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7075. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7076. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7077. DAG.getDataLayout(), STy->getElementType(ResNo));
  7078. } else {
  7079. assert(ResNo == 0 && "Asm only has one result!");
  7080. OpInfo.ConstraintVT =
  7081. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7082. }
  7083. ++ResNo;
  7084. } else {
  7085. OpInfo.ConstraintVT = MVT::Other;
  7086. }
  7087. if (!HasSideEffect)
  7088. HasSideEffect = OpInfo.hasMemory(TLI);
  7089. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7090. // FIXME: Could we compute this on OpInfo rather than T?
  7091. // Compute the constraint code and ConstraintType to use.
  7092. TLI.ComputeConstraintToUse(T, SDValue());
  7093. ExtraInfo.update(T);
  7094. }
  7095. // We won't need to flush pending loads if this asm doesn't touch
  7096. // memory and is nonvolatile.
  7097. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7098. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7099. if (IsCallBr) {
  7100. // If this is a callbr we need to flush pending exports since inlineasm_br
  7101. // is a terminator. We need to do this before nodes are glued to
  7102. // the inlineasm_br node.
  7103. Chain = getControlRoot();
  7104. }
  7105. // Second pass over the constraints: compute which constraint option to use.
  7106. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7107. // If this is an output operand with a matching input operand, look up the
  7108. // matching input. If their types mismatch, e.g. one is an integer, the
  7109. // other is floating point, or their sizes are different, flag it as an
  7110. // error.
  7111. if (OpInfo.hasMatchingInput()) {
  7112. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7113. patchMatchingInput(OpInfo, Input, DAG);
  7114. }
  7115. // Compute the constraint code and ConstraintType to use.
  7116. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7117. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7118. OpInfo.Type == InlineAsm::isClobber)
  7119. continue;
  7120. // If this is a memory input, and if the operand is not indirect, do what we
  7121. // need to provide an address for the memory input.
  7122. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7123. !OpInfo.isIndirect) {
  7124. assert((OpInfo.isMultipleAlternative ||
  7125. (OpInfo.Type == InlineAsm::isInput)) &&
  7126. "Can only indirectify direct input operands!");
  7127. // Memory operands really want the address of the value.
  7128. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7129. // There is no longer a Value* corresponding to this operand.
  7130. OpInfo.CallOperandVal = nullptr;
  7131. // It is now an indirect operand.
  7132. OpInfo.isIndirect = true;
  7133. }
  7134. }
  7135. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7136. std::vector<SDValue> AsmNodeOperands;
  7137. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7138. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7139. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7140. // If we have a !srcloc metadata node associated with it, we want to attach
  7141. // this to the ultimately generated inline asm machineinstr. To do this, we
  7142. // pass in the third operand as this (potentially null) inline asm MDNode.
  7143. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7144. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7145. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7146. // bits as operand 3.
  7147. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7148. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7149. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7150. // this, assign virtual and physical registers for inputs and otput.
  7151. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7152. // Assign Registers.
  7153. SDISelAsmOperandInfo &RefOpInfo =
  7154. OpInfo.isMatchingInputConstraint()
  7155. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7156. : OpInfo;
  7157. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7158. switch (OpInfo.Type) {
  7159. case InlineAsm::isOutput:
  7160. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7161. (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7162. OpInfo.isIndirect)) {
  7163. unsigned ConstraintID =
  7164. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7165. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7166. "Failed to convert memory constraint code to constraint id.");
  7167. // Add information to the INLINEASM node to know about this output.
  7168. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7169. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7170. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7171. MVT::i32));
  7172. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7173. break;
  7174. } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
  7175. !OpInfo.isIndirect) ||
  7176. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7177. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7178. // Otherwise, this outputs to a register (directly for C_Register /
  7179. // C_RegisterClass, and a target-defined fashion for C_Other). Find a
  7180. // register that we can use.
  7181. if (OpInfo.AssignedRegs.Regs.empty()) {
  7182. emitInlineAsmError(
  7183. CS, "couldn't allocate output register for constraint '" +
  7184. Twine(OpInfo.ConstraintCode) + "'");
  7185. return;
  7186. }
  7187. // Add information to the INLINEASM node to know that this register is
  7188. // set.
  7189. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7190. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7191. : InlineAsm::Kind_RegDef,
  7192. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7193. }
  7194. break;
  7195. case InlineAsm::isInput: {
  7196. SDValue InOperandVal = OpInfo.CallOperand;
  7197. if (OpInfo.isMatchingInputConstraint()) {
  7198. // If this is required to match an output register we have already set,
  7199. // just use its register.
  7200. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7201. AsmNodeOperands);
  7202. unsigned OpFlag =
  7203. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7204. if (InlineAsm::isRegDefKind(OpFlag) ||
  7205. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7206. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7207. if (OpInfo.isIndirect) {
  7208. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7209. emitInlineAsmError(CS, "inline asm not supported yet:"
  7210. " don't know how to handle tied "
  7211. "indirect register inputs");
  7212. return;
  7213. }
  7214. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7215. SmallVector<unsigned, 4> Regs;
  7216. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7217. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7218. MachineRegisterInfo &RegInfo =
  7219. DAG.getMachineFunction().getRegInfo();
  7220. for (unsigned i = 0; i != NumRegs; ++i)
  7221. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7222. } else {
  7223. emitInlineAsmError(CS, "inline asm error: This value type register "
  7224. "class is not natively supported!");
  7225. return;
  7226. }
  7227. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7228. SDLoc dl = getCurSDLoc();
  7229. // Use the produced MatchedRegs object to
  7230. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7231. CS.getInstruction());
  7232. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7233. true, OpInfo.getMatchedOperand(), dl,
  7234. DAG, AsmNodeOperands);
  7235. break;
  7236. }
  7237. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7238. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7239. "Unexpected number of operands");
  7240. // Add information to the INLINEASM node to know about this input.
  7241. // See InlineAsm.h isUseOperandTiedToDef.
  7242. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7243. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7244. OpInfo.getMatchedOperand());
  7245. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7246. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7247. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7248. break;
  7249. }
  7250. // Treat indirect 'X' constraint as memory.
  7251. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7252. OpInfo.isIndirect)
  7253. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7254. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  7255. std::vector<SDValue> Ops;
  7256. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7257. Ops, DAG);
  7258. if (Ops.empty()) {
  7259. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7260. Twine(OpInfo.ConstraintCode) + "'");
  7261. return;
  7262. }
  7263. // Add information to the INLINEASM node to know about this input.
  7264. unsigned ResOpType =
  7265. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7266. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7267. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7268. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7269. break;
  7270. }
  7271. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7272. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7273. assert(InOperandVal.getValueType() ==
  7274. TLI.getPointerTy(DAG.getDataLayout()) &&
  7275. "Memory operands expect pointer values");
  7276. unsigned ConstraintID =
  7277. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7278. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7279. "Failed to convert memory constraint code to constraint id.");
  7280. // Add information to the INLINEASM node to know about this input.
  7281. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7282. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7283. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7284. getCurSDLoc(),
  7285. MVT::i32));
  7286. AsmNodeOperands.push_back(InOperandVal);
  7287. break;
  7288. }
  7289. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7290. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7291. "Unknown constraint type!");
  7292. // TODO: Support this.
  7293. if (OpInfo.isIndirect) {
  7294. emitInlineAsmError(
  7295. CS, "Don't know how to handle indirect register inputs yet "
  7296. "for constraint '" +
  7297. Twine(OpInfo.ConstraintCode) + "'");
  7298. return;
  7299. }
  7300. // Copy the input into the appropriate registers.
  7301. if (OpInfo.AssignedRegs.Regs.empty()) {
  7302. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7303. Twine(OpInfo.ConstraintCode) + "'");
  7304. return;
  7305. }
  7306. SDLoc dl = getCurSDLoc();
  7307. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7308. Chain, &Flag, CS.getInstruction());
  7309. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7310. dl, DAG, AsmNodeOperands);
  7311. break;
  7312. }
  7313. case InlineAsm::isClobber:
  7314. // Add the clobbered value to the operand list, so that the register
  7315. // allocator is aware that the physreg got clobbered.
  7316. if (!OpInfo.AssignedRegs.Regs.empty())
  7317. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7318. false, 0, getCurSDLoc(), DAG,
  7319. AsmNodeOperands);
  7320. break;
  7321. }
  7322. }
  7323. // Finish up input operands. Set the input chain and add the flag last.
  7324. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7325. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7326. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7327. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7328. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7329. Flag = Chain.getValue(1);
  7330. // Do additional work to generate outputs.
  7331. SmallVector<EVT, 1> ResultVTs;
  7332. SmallVector<SDValue, 1> ResultValues;
  7333. SmallVector<SDValue, 8> OutChains;
  7334. llvm::Type *CSResultType = CS.getType();
  7335. ArrayRef<Type *> ResultTypes;
  7336. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7337. ResultTypes = StructResult->elements();
  7338. else if (!CSResultType->isVoidTy())
  7339. ResultTypes = makeArrayRef(CSResultType);
  7340. auto CurResultType = ResultTypes.begin();
  7341. auto handleRegAssign = [&](SDValue V) {
  7342. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7343. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7344. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7345. ++CurResultType;
  7346. // If the type of the inline asm call site return value is different but has
  7347. // same size as the type of the asm output bitcast it. One example of this
  7348. // is for vectors with different width / number of elements. This can
  7349. // happen for register classes that can contain multiple different value
  7350. // types. The preg or vreg allocated may not have the same VT as was
  7351. // expected.
  7352. //
  7353. // This can also happen for a return value that disagrees with the register
  7354. // class it is put in, eg. a double in a general-purpose register on a
  7355. // 32-bit machine.
  7356. if (ResultVT != V.getValueType() &&
  7357. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7358. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7359. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7360. V.getValueType().isInteger()) {
  7361. // If a result value was tied to an input value, the computed result
  7362. // may have a wider width than the expected result. Extract the
  7363. // relevant portion.
  7364. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7365. }
  7366. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7367. ResultVTs.push_back(ResultVT);
  7368. ResultValues.push_back(V);
  7369. };
  7370. // Deal with output operands.
  7371. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7372. if (OpInfo.Type == InlineAsm::isOutput) {
  7373. SDValue Val;
  7374. // Skip trivial output operands.
  7375. if (OpInfo.AssignedRegs.Regs.empty())
  7376. continue;
  7377. switch (OpInfo.ConstraintType) {
  7378. case TargetLowering::C_Register:
  7379. case TargetLowering::C_RegisterClass:
  7380. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7381. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7382. break;
  7383. case TargetLowering::C_Other:
  7384. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7385. OpInfo, DAG);
  7386. break;
  7387. case TargetLowering::C_Memory:
  7388. break; // Already handled.
  7389. case TargetLowering::C_Unknown:
  7390. assert(false && "Unexpected unknown constraint");
  7391. }
  7392. // Indirect output manifest as stores. Record output chains.
  7393. if (OpInfo.isIndirect) {
  7394. const Value *Ptr = OpInfo.CallOperandVal;
  7395. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7396. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7397. MachinePointerInfo(Ptr));
  7398. OutChains.push_back(Store);
  7399. } else {
  7400. // generate CopyFromRegs to associated registers.
  7401. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7402. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7403. for (const SDValue &V : Val->op_values())
  7404. handleRegAssign(V);
  7405. } else
  7406. handleRegAssign(Val);
  7407. }
  7408. }
  7409. }
  7410. // Set results.
  7411. if (!ResultValues.empty()) {
  7412. assert(CurResultType == ResultTypes.end() &&
  7413. "Mismatch in number of ResultTypes");
  7414. assert(ResultValues.size() == ResultTypes.size() &&
  7415. "Mismatch in number of output operands in asm result");
  7416. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7417. DAG.getVTList(ResultVTs), ResultValues);
  7418. setValue(CS.getInstruction(), V);
  7419. }
  7420. // Collect store chains.
  7421. if (!OutChains.empty())
  7422. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7423. // Only Update Root if inline assembly has a memory effect.
  7424. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7425. DAG.setRoot(Chain);
  7426. }
  7427. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7428. const Twine &Message) {
  7429. LLVMContext &Ctx = *DAG.getContext();
  7430. Ctx.emitError(CS.getInstruction(), Message);
  7431. // Make sure we leave the DAG in a valid state
  7432. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7433. SmallVector<EVT, 1> ValueVTs;
  7434. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7435. if (ValueVTs.empty())
  7436. return;
  7437. SmallVector<SDValue, 1> Ops;
  7438. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7439. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7440. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7441. }
  7442. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7443. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7444. MVT::Other, getRoot(),
  7445. getValue(I.getArgOperand(0)),
  7446. DAG.getSrcValue(I.getArgOperand(0))));
  7447. }
  7448. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7449. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7450. const DataLayout &DL = DAG.getDataLayout();
  7451. SDValue V = DAG.getVAArg(
  7452. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7453. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7454. DL.getABITypeAlignment(I.getType()));
  7455. DAG.setRoot(V.getValue(1));
  7456. if (I.getType()->isPointerTy())
  7457. V = DAG.getPtrExtOrTrunc(
  7458. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7459. setValue(&I, V);
  7460. }
  7461. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7462. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7463. MVT::Other, getRoot(),
  7464. getValue(I.getArgOperand(0)),
  7465. DAG.getSrcValue(I.getArgOperand(0))));
  7466. }
  7467. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7468. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7469. MVT::Other, getRoot(),
  7470. getValue(I.getArgOperand(0)),
  7471. getValue(I.getArgOperand(1)),
  7472. DAG.getSrcValue(I.getArgOperand(0)),
  7473. DAG.getSrcValue(I.getArgOperand(1))));
  7474. }
  7475. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7476. const Instruction &I,
  7477. SDValue Op) {
  7478. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7479. if (!Range)
  7480. return Op;
  7481. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7482. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7483. return Op;
  7484. APInt Lo = CR.getUnsignedMin();
  7485. if (!Lo.isMinValue())
  7486. return Op;
  7487. APInt Hi = CR.getUnsignedMax();
  7488. unsigned Bits = std::max(Hi.getActiveBits(),
  7489. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7490. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7491. SDLoc SL = getCurSDLoc();
  7492. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7493. DAG.getValueType(SmallVT));
  7494. unsigned NumVals = Op.getNode()->getNumValues();
  7495. if (NumVals == 1)
  7496. return ZExt;
  7497. SmallVector<SDValue, 4> Ops;
  7498. Ops.push_back(ZExt);
  7499. for (unsigned I = 1; I != NumVals; ++I)
  7500. Ops.push_back(Op.getValue(I));
  7501. return DAG.getMergeValues(Ops, SL);
  7502. }
  7503. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7504. /// the call being lowered.
  7505. ///
  7506. /// This is a helper for lowering intrinsics that follow a target calling
  7507. /// convention or require stack pointer adjustment. Only a subset of the
  7508. /// intrinsic's operands need to participate in the calling convention.
  7509. void SelectionDAGBuilder::populateCallLoweringInfo(
  7510. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7511. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7512. bool IsPatchPoint) {
  7513. TargetLowering::ArgListTy Args;
  7514. Args.reserve(NumArgs);
  7515. // Populate the argument list.
  7516. // Attributes for args start at offset 1, after the return attribute.
  7517. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7518. ArgI != ArgE; ++ArgI) {
  7519. const Value *V = Call->getOperand(ArgI);
  7520. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7521. TargetLowering::ArgListEntry Entry;
  7522. Entry.Node = getValue(V);
  7523. Entry.Ty = V->getType();
  7524. Entry.setAttributes(Call, ArgI);
  7525. Args.push_back(Entry);
  7526. }
  7527. CLI.setDebugLoc(getCurSDLoc())
  7528. .setChain(getRoot())
  7529. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7530. .setDiscardResult(Call->use_empty())
  7531. .setIsPatchPoint(IsPatchPoint);
  7532. }
  7533. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7534. /// or patchpoint target node's operand list.
  7535. ///
  7536. /// Constants are converted to TargetConstants purely as an optimization to
  7537. /// avoid constant materialization and register allocation.
  7538. ///
  7539. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7540. /// generate addess computation nodes, and so FinalizeISel can convert the
  7541. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7542. /// address materialization and register allocation, but may also be required
  7543. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7544. /// alloca in the entry block, then the runtime may assume that the alloca's
  7545. /// StackMap location can be read immediately after compilation and that the
  7546. /// location is valid at any point during execution (this is similar to the
  7547. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7548. /// only available in a register, then the runtime would need to trap when
  7549. /// execution reaches the StackMap in order to read the alloca's location.
  7550. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7551. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7552. SelectionDAGBuilder &Builder) {
  7553. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7554. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7555. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7556. Ops.push_back(
  7557. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7558. Ops.push_back(
  7559. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7560. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7561. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7562. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7563. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7564. } else
  7565. Ops.push_back(OpVal);
  7566. }
  7567. }
  7568. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7569. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7570. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7571. // [live variables...])
  7572. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7573. SDValue Chain, InFlag, Callee, NullPtr;
  7574. SmallVector<SDValue, 32> Ops;
  7575. SDLoc DL = getCurSDLoc();
  7576. Callee = getValue(CI.getCalledValue());
  7577. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7578. // The stackmap intrinsic only records the live variables (the arguemnts
  7579. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7580. // intrinsic, this won't be lowered to a function call. This means we don't
  7581. // have to worry about calling conventions and target specific lowering code.
  7582. // Instead we perform the call lowering right here.
  7583. //
  7584. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7585. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7586. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7587. //
  7588. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7589. InFlag = Chain.getValue(1);
  7590. // Add the <id> and <numBytes> constants.
  7591. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7592. Ops.push_back(DAG.getTargetConstant(
  7593. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7594. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7595. Ops.push_back(DAG.getTargetConstant(
  7596. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7597. MVT::i32));
  7598. // Push live variables for the stack map.
  7599. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7600. // We are not pushing any register mask info here on the operands list,
  7601. // because the stackmap doesn't clobber anything.
  7602. // Push the chain and the glue flag.
  7603. Ops.push_back(Chain);
  7604. Ops.push_back(InFlag);
  7605. // Create the STACKMAP node.
  7606. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7607. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7608. Chain = SDValue(SM, 0);
  7609. InFlag = Chain.getValue(1);
  7610. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7611. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7612. // Set the root to the target-lowered call chain.
  7613. DAG.setRoot(Chain);
  7614. // Inform the Frame Information that we have a stackmap in this function.
  7615. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7616. }
  7617. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7618. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7619. const BasicBlock *EHPadBB) {
  7620. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7621. // i32 <numBytes>,
  7622. // i8* <target>,
  7623. // i32 <numArgs>,
  7624. // [Args...],
  7625. // [live variables...])
  7626. CallingConv::ID CC = CS.getCallingConv();
  7627. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7628. bool HasDef = !CS->getType()->isVoidTy();
  7629. SDLoc dl = getCurSDLoc();
  7630. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7631. // Handle immediate and symbolic callees.
  7632. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7633. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7634. /*isTarget=*/true);
  7635. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7636. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7637. SDLoc(SymbolicCallee),
  7638. SymbolicCallee->getValueType(0));
  7639. // Get the real number of arguments participating in the call <numArgs>
  7640. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7641. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7642. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7643. // Intrinsics include all meta-operands up to but not including CC.
  7644. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7645. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7646. "Not enough arguments provided to the patchpoint intrinsic");
  7647. // For AnyRegCC the arguments are lowered later on manually.
  7648. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7649. Type *ReturnTy =
  7650. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7651. TargetLowering::CallLoweringInfo CLI(DAG);
  7652. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7653. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7654. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7655. SDNode *CallEnd = Result.second.getNode();
  7656. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7657. CallEnd = CallEnd->getOperand(0).getNode();
  7658. /// Get a call instruction from the call sequence chain.
  7659. /// Tail calls are not allowed.
  7660. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7661. "Expected a callseq node.");
  7662. SDNode *Call = CallEnd->getOperand(0).getNode();
  7663. bool HasGlue = Call->getGluedNode();
  7664. // Replace the target specific call node with the patchable intrinsic.
  7665. SmallVector<SDValue, 8> Ops;
  7666. // Add the <id> and <numBytes> constants.
  7667. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7668. Ops.push_back(DAG.getTargetConstant(
  7669. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7670. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7671. Ops.push_back(DAG.getTargetConstant(
  7672. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7673. MVT::i32));
  7674. // Add the callee.
  7675. Ops.push_back(Callee);
  7676. // Adjust <numArgs> to account for any arguments that have been passed on the
  7677. // stack instead.
  7678. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7679. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7680. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7681. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7682. // Add the calling convention
  7683. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7684. // Add the arguments we omitted previously. The register allocator should
  7685. // place these in any free register.
  7686. if (IsAnyRegCC)
  7687. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7688. Ops.push_back(getValue(CS.getArgument(i)));
  7689. // Push the arguments from the call instruction up to the register mask.
  7690. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7691. Ops.append(Call->op_begin() + 2, e);
  7692. // Push live variables for the stack map.
  7693. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7694. // Push the register mask info.
  7695. if (HasGlue)
  7696. Ops.push_back(*(Call->op_end()-2));
  7697. else
  7698. Ops.push_back(*(Call->op_end()-1));
  7699. // Push the chain (this is originally the first operand of the call, but
  7700. // becomes now the last or second to last operand).
  7701. Ops.push_back(*(Call->op_begin()));
  7702. // Push the glue flag (last operand).
  7703. if (HasGlue)
  7704. Ops.push_back(*(Call->op_end()-1));
  7705. SDVTList NodeTys;
  7706. if (IsAnyRegCC && HasDef) {
  7707. // Create the return types based on the intrinsic definition
  7708. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7709. SmallVector<EVT, 3> ValueVTs;
  7710. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7711. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7712. // There is always a chain and a glue type at the end
  7713. ValueVTs.push_back(MVT::Other);
  7714. ValueVTs.push_back(MVT::Glue);
  7715. NodeTys = DAG.getVTList(ValueVTs);
  7716. } else
  7717. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7718. // Replace the target specific call node with a PATCHPOINT node.
  7719. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7720. dl, NodeTys, Ops);
  7721. // Update the NodeMap.
  7722. if (HasDef) {
  7723. if (IsAnyRegCC)
  7724. setValue(CS.getInstruction(), SDValue(MN, 0));
  7725. else
  7726. setValue(CS.getInstruction(), Result.first);
  7727. }
  7728. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7729. // call sequence. Furthermore the location of the chain and glue can change
  7730. // when the AnyReg calling convention is used and the intrinsic returns a
  7731. // value.
  7732. if (IsAnyRegCC && HasDef) {
  7733. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7734. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7735. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7736. } else
  7737. DAG.ReplaceAllUsesWith(Call, MN);
  7738. DAG.DeleteNode(Call);
  7739. // Inform the Frame Information that we have a patchpoint in this function.
  7740. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7741. }
  7742. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7743. unsigned Intrinsic) {
  7744. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7745. SDValue Op1 = getValue(I.getArgOperand(0));
  7746. SDValue Op2;
  7747. if (I.getNumArgOperands() > 1)
  7748. Op2 = getValue(I.getArgOperand(1));
  7749. SDLoc dl = getCurSDLoc();
  7750. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7751. SDValue Res;
  7752. FastMathFlags FMF;
  7753. if (isa<FPMathOperator>(I))
  7754. FMF = I.getFastMathFlags();
  7755. switch (Intrinsic) {
  7756. case Intrinsic::experimental_vector_reduce_v2_fadd:
  7757. if (FMF.allowReassoc())
  7758. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  7759. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
  7760. else
  7761. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7762. break;
  7763. case Intrinsic::experimental_vector_reduce_v2_fmul:
  7764. if (FMF.allowReassoc())
  7765. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  7766. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
  7767. else
  7768. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7769. break;
  7770. case Intrinsic::experimental_vector_reduce_add:
  7771. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7772. break;
  7773. case Intrinsic::experimental_vector_reduce_mul:
  7774. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7775. break;
  7776. case Intrinsic::experimental_vector_reduce_and:
  7777. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7778. break;
  7779. case Intrinsic::experimental_vector_reduce_or:
  7780. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7781. break;
  7782. case Intrinsic::experimental_vector_reduce_xor:
  7783. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7784. break;
  7785. case Intrinsic::experimental_vector_reduce_smax:
  7786. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7787. break;
  7788. case Intrinsic::experimental_vector_reduce_smin:
  7789. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7790. break;
  7791. case Intrinsic::experimental_vector_reduce_umax:
  7792. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7793. break;
  7794. case Intrinsic::experimental_vector_reduce_umin:
  7795. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7796. break;
  7797. case Intrinsic::experimental_vector_reduce_fmax:
  7798. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7799. break;
  7800. case Intrinsic::experimental_vector_reduce_fmin:
  7801. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7802. break;
  7803. default:
  7804. llvm_unreachable("Unhandled vector reduce intrinsic");
  7805. }
  7806. setValue(&I, Res);
  7807. }
  7808. /// Returns an AttributeList representing the attributes applied to the return
  7809. /// value of the given call.
  7810. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7811. SmallVector<Attribute::AttrKind, 2> Attrs;
  7812. if (CLI.RetSExt)
  7813. Attrs.push_back(Attribute::SExt);
  7814. if (CLI.RetZExt)
  7815. Attrs.push_back(Attribute::ZExt);
  7816. if (CLI.IsInReg)
  7817. Attrs.push_back(Attribute::InReg);
  7818. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7819. Attrs);
  7820. }
  7821. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7822. /// implementation, which just calls LowerCall.
  7823. /// FIXME: When all targets are
  7824. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7825. std::pair<SDValue, SDValue>
  7826. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7827. // Handle the incoming return values from the call.
  7828. CLI.Ins.clear();
  7829. Type *OrigRetTy = CLI.RetTy;
  7830. SmallVector<EVT, 4> RetTys;
  7831. SmallVector<uint64_t, 4> Offsets;
  7832. auto &DL = CLI.DAG.getDataLayout();
  7833. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7834. if (CLI.IsPostTypeLegalization) {
  7835. // If we are lowering a libcall after legalization, split the return type.
  7836. SmallVector<EVT, 4> OldRetTys;
  7837. SmallVector<uint64_t, 4> OldOffsets;
  7838. RetTys.swap(OldRetTys);
  7839. Offsets.swap(OldOffsets);
  7840. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7841. EVT RetVT = OldRetTys[i];
  7842. uint64_t Offset = OldOffsets[i];
  7843. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7844. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7845. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7846. RetTys.append(NumRegs, RegisterVT);
  7847. for (unsigned j = 0; j != NumRegs; ++j)
  7848. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7849. }
  7850. }
  7851. SmallVector<ISD::OutputArg, 4> Outs;
  7852. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7853. bool CanLowerReturn =
  7854. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7855. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7856. SDValue DemoteStackSlot;
  7857. int DemoteStackIdx = -100;
  7858. if (!CanLowerReturn) {
  7859. // FIXME: equivalent assert?
  7860. // assert(!CS.hasInAllocaArgument() &&
  7861. // "sret demotion is incompatible with inalloca");
  7862. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7863. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7864. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7865. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7866. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7867. DL.getAllocaAddrSpace());
  7868. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7869. ArgListEntry Entry;
  7870. Entry.Node = DemoteStackSlot;
  7871. Entry.Ty = StackSlotPtrType;
  7872. Entry.IsSExt = false;
  7873. Entry.IsZExt = false;
  7874. Entry.IsInReg = false;
  7875. Entry.IsSRet = true;
  7876. Entry.IsNest = false;
  7877. Entry.IsByVal = false;
  7878. Entry.IsReturned = false;
  7879. Entry.IsSwiftSelf = false;
  7880. Entry.IsSwiftError = false;
  7881. Entry.Alignment = Align;
  7882. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7883. CLI.NumFixedArgs += 1;
  7884. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7885. // sret demotion isn't compatible with tail-calls, since the sret argument
  7886. // points into the callers stack frame.
  7887. CLI.IsTailCall = false;
  7888. } else {
  7889. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7890. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7891. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7892. ISD::ArgFlagsTy Flags;
  7893. if (NeedsRegBlock) {
  7894. Flags.setInConsecutiveRegs();
  7895. if (I == RetTys.size() - 1)
  7896. Flags.setInConsecutiveRegsLast();
  7897. }
  7898. EVT VT = RetTys[I];
  7899. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7900. CLI.CallConv, VT);
  7901. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7902. CLI.CallConv, VT);
  7903. for (unsigned i = 0; i != NumRegs; ++i) {
  7904. ISD::InputArg MyFlags;
  7905. MyFlags.Flags = Flags;
  7906. MyFlags.VT = RegisterVT;
  7907. MyFlags.ArgVT = VT;
  7908. MyFlags.Used = CLI.IsReturnValueUsed;
  7909. if (CLI.RetTy->isPointerTy()) {
  7910. MyFlags.Flags.setPointer();
  7911. MyFlags.Flags.setPointerAddrSpace(
  7912. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  7913. }
  7914. if (CLI.RetSExt)
  7915. MyFlags.Flags.setSExt();
  7916. if (CLI.RetZExt)
  7917. MyFlags.Flags.setZExt();
  7918. if (CLI.IsInReg)
  7919. MyFlags.Flags.setInReg();
  7920. CLI.Ins.push_back(MyFlags);
  7921. }
  7922. }
  7923. }
  7924. // We push in swifterror return as the last element of CLI.Ins.
  7925. ArgListTy &Args = CLI.getArgs();
  7926. if (supportSwiftError()) {
  7927. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7928. if (Args[i].IsSwiftError) {
  7929. ISD::InputArg MyFlags;
  7930. MyFlags.VT = getPointerTy(DL);
  7931. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7932. MyFlags.Flags.setSwiftError();
  7933. CLI.Ins.push_back(MyFlags);
  7934. }
  7935. }
  7936. }
  7937. // Handle all of the outgoing arguments.
  7938. CLI.Outs.clear();
  7939. CLI.OutVals.clear();
  7940. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7941. SmallVector<EVT, 4> ValueVTs;
  7942. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7943. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7944. Type *FinalType = Args[i].Ty;
  7945. if (Args[i].IsByVal)
  7946. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7947. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7948. FinalType, CLI.CallConv, CLI.IsVarArg);
  7949. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7950. ++Value) {
  7951. EVT VT = ValueVTs[Value];
  7952. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7953. SDValue Op = SDValue(Args[i].Node.getNode(),
  7954. Args[i].Node.getResNo() + Value);
  7955. ISD::ArgFlagsTy Flags;
  7956. // Certain targets (such as MIPS), may have a different ABI alignment
  7957. // for a type depending on the context. Give the target a chance to
  7958. // specify the alignment it wants.
  7959. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7960. if (Args[i].Ty->isPointerTy()) {
  7961. Flags.setPointer();
  7962. Flags.setPointerAddrSpace(
  7963. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  7964. }
  7965. if (Args[i].IsZExt)
  7966. Flags.setZExt();
  7967. if (Args[i].IsSExt)
  7968. Flags.setSExt();
  7969. if (Args[i].IsInReg) {
  7970. // If we are using vectorcall calling convention, a structure that is
  7971. // passed InReg - is surely an HVA
  7972. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7973. isa<StructType>(FinalType)) {
  7974. // The first value of a structure is marked
  7975. if (0 == Value)
  7976. Flags.setHvaStart();
  7977. Flags.setHva();
  7978. }
  7979. // Set InReg Flag
  7980. Flags.setInReg();
  7981. }
  7982. if (Args[i].IsSRet)
  7983. Flags.setSRet();
  7984. if (Args[i].IsSwiftSelf)
  7985. Flags.setSwiftSelf();
  7986. if (Args[i].IsSwiftError)
  7987. Flags.setSwiftError();
  7988. if (Args[i].IsByVal)
  7989. Flags.setByVal();
  7990. if (Args[i].IsInAlloca) {
  7991. Flags.setInAlloca();
  7992. // Set the byval flag for CCAssignFn callbacks that don't know about
  7993. // inalloca. This way we can know how many bytes we should've allocated
  7994. // and how many bytes a callee cleanup function will pop. If we port
  7995. // inalloca to more targets, we'll have to add custom inalloca handling
  7996. // in the various CC lowering callbacks.
  7997. Flags.setByVal();
  7998. }
  7999. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8000. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8001. Type *ElementTy = Ty->getElementType();
  8002. unsigned FrameSize = DL.getTypeAllocSize(
  8003. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8004. Flags.setByValSize(FrameSize);
  8005. // info is not there but there are cases it cannot get right.
  8006. unsigned FrameAlign;
  8007. if (Args[i].Alignment)
  8008. FrameAlign = Args[i].Alignment;
  8009. else
  8010. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8011. Flags.setByValAlign(FrameAlign);
  8012. }
  8013. if (Args[i].IsNest)
  8014. Flags.setNest();
  8015. if (NeedsRegBlock)
  8016. Flags.setInConsecutiveRegs();
  8017. Flags.setOrigAlign(OriginalAlignment);
  8018. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8019. CLI.CallConv, VT);
  8020. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8021. CLI.CallConv, VT);
  8022. SmallVector<SDValue, 4> Parts(NumParts);
  8023. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8024. if (Args[i].IsSExt)
  8025. ExtendKind = ISD::SIGN_EXTEND;
  8026. else if (Args[i].IsZExt)
  8027. ExtendKind = ISD::ZERO_EXTEND;
  8028. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8029. // for now.
  8030. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8031. CanLowerReturn) {
  8032. assert((CLI.RetTy == Args[i].Ty ||
  8033. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8034. CLI.RetTy->getPointerAddressSpace() ==
  8035. Args[i].Ty->getPointerAddressSpace())) &&
  8036. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8037. // Before passing 'returned' to the target lowering code, ensure that
  8038. // either the register MVT and the actual EVT are the same size or that
  8039. // the return value and argument are extended in the same way; in these
  8040. // cases it's safe to pass the argument register value unchanged as the
  8041. // return register value (although it's at the target's option whether
  8042. // to do so)
  8043. // TODO: allow code generation to take advantage of partially preserved
  8044. // registers rather than clobbering the entire register when the
  8045. // parameter extension method is not compatible with the return
  8046. // extension method
  8047. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8048. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8049. CLI.RetZExt == Args[i].IsZExt))
  8050. Flags.setReturned();
  8051. }
  8052. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8053. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8054. for (unsigned j = 0; j != NumParts; ++j) {
  8055. // if it isn't first piece, alignment must be 1
  8056. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8057. i < CLI.NumFixedArgs,
  8058. i, j*Parts[j].getValueType().getStoreSize());
  8059. if (NumParts > 1 && j == 0)
  8060. MyFlags.Flags.setSplit();
  8061. else if (j != 0) {
  8062. MyFlags.Flags.setOrigAlign(1);
  8063. if (j == NumParts - 1)
  8064. MyFlags.Flags.setSplitEnd();
  8065. }
  8066. CLI.Outs.push_back(MyFlags);
  8067. CLI.OutVals.push_back(Parts[j]);
  8068. }
  8069. if (NeedsRegBlock && Value == NumValues - 1)
  8070. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8071. }
  8072. }
  8073. SmallVector<SDValue, 4> InVals;
  8074. CLI.Chain = LowerCall(CLI, InVals);
  8075. // Update CLI.InVals to use outside of this function.
  8076. CLI.InVals = InVals;
  8077. // Verify that the target's LowerCall behaved as expected.
  8078. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8079. "LowerCall didn't return a valid chain!");
  8080. assert((!CLI.IsTailCall || InVals.empty()) &&
  8081. "LowerCall emitted a return value for a tail call!");
  8082. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8083. "LowerCall didn't emit the correct number of values!");
  8084. // For a tail call, the return value is merely live-out and there aren't
  8085. // any nodes in the DAG representing it. Return a special value to
  8086. // indicate that a tail call has been emitted and no more Instructions
  8087. // should be processed in the current block.
  8088. if (CLI.IsTailCall) {
  8089. CLI.DAG.setRoot(CLI.Chain);
  8090. return std::make_pair(SDValue(), SDValue());
  8091. }
  8092. #ifndef NDEBUG
  8093. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8094. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8095. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8096. "LowerCall emitted a value with the wrong type!");
  8097. }
  8098. #endif
  8099. SmallVector<SDValue, 4> ReturnValues;
  8100. if (!CanLowerReturn) {
  8101. // The instruction result is the result of loading from the
  8102. // hidden sret parameter.
  8103. SmallVector<EVT, 1> PVTs;
  8104. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8105. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8106. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8107. EVT PtrVT = PVTs[0];
  8108. unsigned NumValues = RetTys.size();
  8109. ReturnValues.resize(NumValues);
  8110. SmallVector<SDValue, 4> Chains(NumValues);
  8111. // An aggregate return value cannot wrap around the address space, so
  8112. // offsets to its parts don't wrap either.
  8113. SDNodeFlags Flags;
  8114. Flags.setNoUnsignedWrap(true);
  8115. for (unsigned i = 0; i < NumValues; ++i) {
  8116. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8117. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8118. PtrVT), Flags);
  8119. SDValue L = CLI.DAG.getLoad(
  8120. RetTys[i], CLI.DL, CLI.Chain, Add,
  8121. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8122. DemoteStackIdx, Offsets[i]),
  8123. /* Alignment = */ 1);
  8124. ReturnValues[i] = L;
  8125. Chains[i] = L.getValue(1);
  8126. }
  8127. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8128. } else {
  8129. // Collect the legal value parts into potentially illegal values
  8130. // that correspond to the original function's return values.
  8131. Optional<ISD::NodeType> AssertOp;
  8132. if (CLI.RetSExt)
  8133. AssertOp = ISD::AssertSext;
  8134. else if (CLI.RetZExt)
  8135. AssertOp = ISD::AssertZext;
  8136. unsigned CurReg = 0;
  8137. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8138. EVT VT = RetTys[I];
  8139. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8140. CLI.CallConv, VT);
  8141. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8142. CLI.CallConv, VT);
  8143. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8144. NumRegs, RegisterVT, VT, nullptr,
  8145. CLI.CallConv, AssertOp));
  8146. CurReg += NumRegs;
  8147. }
  8148. // For a function returning void, there is no return value. We can't create
  8149. // such a node, so we just return a null return value in that case. In
  8150. // that case, nothing will actually look at the value.
  8151. if (ReturnValues.empty())
  8152. return std::make_pair(SDValue(), CLI.Chain);
  8153. }
  8154. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8155. CLI.DAG.getVTList(RetTys), ReturnValues);
  8156. return std::make_pair(Res, CLI.Chain);
  8157. }
  8158. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8159. SmallVectorImpl<SDValue> &Results,
  8160. SelectionDAG &DAG) const {
  8161. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8162. Results.push_back(Res);
  8163. }
  8164. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8165. llvm_unreachable("LowerOperation not implemented for this target!");
  8166. }
  8167. void
  8168. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8169. SDValue Op = getNonRegisterValue(V);
  8170. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8171. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8172. "Copy from a reg to the same reg!");
  8173. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  8174. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8175. // If this is an InlineAsm we have to match the registers required, not the
  8176. // notional registers required by the type.
  8177. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8178. None); // This is not an ABI copy.
  8179. SDValue Chain = DAG.getEntryNode();
  8180. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8181. FuncInfo.PreferredExtendType.end())
  8182. ? ISD::ANY_EXTEND
  8183. : FuncInfo.PreferredExtendType[V];
  8184. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8185. PendingExports.push_back(Chain);
  8186. }
  8187. #include "llvm/CodeGen/SelectionDAGISel.h"
  8188. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8189. /// entry block, return true. This includes arguments used by switches, since
  8190. /// the switch may expand into multiple basic blocks.
  8191. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8192. // With FastISel active, we may be splitting blocks, so force creation
  8193. // of virtual registers for all non-dead arguments.
  8194. if (FastISel)
  8195. return A->use_empty();
  8196. const BasicBlock &Entry = A->getParent()->front();
  8197. for (const User *U : A->users())
  8198. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8199. return false; // Use not in entry block.
  8200. return true;
  8201. }
  8202. using ArgCopyElisionMapTy =
  8203. DenseMap<const Argument *,
  8204. std::pair<const AllocaInst *, const StoreInst *>>;
  8205. /// Scan the entry block of the function in FuncInfo for arguments that look
  8206. /// like copies into a local alloca. Record any copied arguments in
  8207. /// ArgCopyElisionCandidates.
  8208. static void
  8209. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8210. FunctionLoweringInfo *FuncInfo,
  8211. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8212. // Record the state of every static alloca used in the entry block. Argument
  8213. // allocas are all used in the entry block, so we need approximately as many
  8214. // entries as we have arguments.
  8215. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8216. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8217. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8218. StaticAllocas.reserve(NumArgs * 2);
  8219. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8220. if (!V)
  8221. return nullptr;
  8222. V = V->stripPointerCasts();
  8223. const auto *AI = dyn_cast<AllocaInst>(V);
  8224. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8225. return nullptr;
  8226. auto Iter = StaticAllocas.insert({AI, Unknown});
  8227. return &Iter.first->second;
  8228. };
  8229. // Look for stores of arguments to static allocas. Look through bitcasts and
  8230. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8231. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8232. // unanalyzed store might write it.
  8233. // FIXME: Handle structs initialized with multiple stores.
  8234. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8235. // Look for stores, and handle non-store uses conservatively.
  8236. const auto *SI = dyn_cast<StoreInst>(&I);
  8237. if (!SI) {
  8238. // We will look through cast uses, so ignore them completely.
  8239. if (I.isCast())
  8240. continue;
  8241. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8242. if (isa<DbgInfoIntrinsic>(I))
  8243. continue;
  8244. // This is an unknown instruction. Assume it escapes or writes to all
  8245. // static alloca operands.
  8246. for (const Use &U : I.operands()) {
  8247. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8248. *Info = StaticAllocaInfo::Clobbered;
  8249. }
  8250. continue;
  8251. }
  8252. // If the stored value is a static alloca, mark it as escaped.
  8253. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8254. *Info = StaticAllocaInfo::Clobbered;
  8255. // Check if the destination is a static alloca.
  8256. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8257. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8258. if (!Info)
  8259. continue;
  8260. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8261. // Skip allocas that have been initialized or clobbered.
  8262. if (*Info != StaticAllocaInfo::Unknown)
  8263. continue;
  8264. // Check if the stored value is an argument, and that this store fully
  8265. // initializes the alloca. Don't elide copies from the same argument twice.
  8266. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8267. const auto *Arg = dyn_cast<Argument>(Val);
  8268. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8269. Arg->getType()->isEmptyTy() ||
  8270. DL.getTypeStoreSize(Arg->getType()) !=
  8271. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8272. ArgCopyElisionCandidates.count(Arg)) {
  8273. *Info = StaticAllocaInfo::Clobbered;
  8274. continue;
  8275. }
  8276. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8277. << '\n');
  8278. // Mark this alloca and store for argument copy elision.
  8279. *Info = StaticAllocaInfo::Elidable;
  8280. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8281. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8282. // builds, which is useful, because -O0 builds have large entry blocks and
  8283. // many allocas.
  8284. if (ArgCopyElisionCandidates.size() == NumArgs)
  8285. break;
  8286. }
  8287. }
  8288. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8289. /// ArgVal is a load from a suitable fixed stack object.
  8290. static void tryToElideArgumentCopy(
  8291. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8292. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8293. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8294. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8295. SDValue ArgVal, bool &ArgHasUses) {
  8296. // Check if this is a load from a fixed stack object.
  8297. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8298. if (!LNode)
  8299. return;
  8300. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8301. if (!FINode)
  8302. return;
  8303. // Check that the fixed stack object is the right size and alignment.
  8304. // Look at the alignment that the user wrote on the alloca instead of looking
  8305. // at the stack object.
  8306. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8307. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8308. const AllocaInst *AI = ArgCopyIter->second.first;
  8309. int FixedIndex = FINode->getIndex();
  8310. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8311. int OldIndex = AllocaIndex;
  8312. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8313. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8314. LLVM_DEBUG(
  8315. dbgs() << " argument copy elision failed due to bad fixed stack "
  8316. "object size\n");
  8317. return;
  8318. }
  8319. unsigned RequiredAlignment = AI->getAlignment();
  8320. if (!RequiredAlignment) {
  8321. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8322. AI->getAllocatedType());
  8323. }
  8324. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8325. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8326. "greater than stack argument alignment ("
  8327. << RequiredAlignment << " vs "
  8328. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8329. return;
  8330. }
  8331. // Perform the elision. Delete the old stack object and replace its only use
  8332. // in the variable info map. Mark the stack object as mutable.
  8333. LLVM_DEBUG({
  8334. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8335. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8336. << '\n';
  8337. });
  8338. MFI.RemoveStackObject(OldIndex);
  8339. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8340. AllocaIndex = FixedIndex;
  8341. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8342. Chains.push_back(ArgVal.getValue(1));
  8343. // Avoid emitting code for the store implementing the copy.
  8344. const StoreInst *SI = ArgCopyIter->second.second;
  8345. ElidedArgCopyInstrs.insert(SI);
  8346. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8347. // if it is't used by anything other than the store.
  8348. for (const Value *U : Arg.users()) {
  8349. if (U != SI) {
  8350. ArgHasUses = true;
  8351. break;
  8352. }
  8353. }
  8354. }
  8355. void SelectionDAGISel::LowerArguments(const Function &F) {
  8356. SelectionDAG &DAG = SDB->DAG;
  8357. SDLoc dl = SDB->getCurSDLoc();
  8358. const DataLayout &DL = DAG.getDataLayout();
  8359. SmallVector<ISD::InputArg, 16> Ins;
  8360. if (!FuncInfo->CanLowerReturn) {
  8361. // Put in an sret pointer parameter before all the other parameters.
  8362. SmallVector<EVT, 1> ValueVTs;
  8363. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8364. F.getReturnType()->getPointerTo(
  8365. DAG.getDataLayout().getAllocaAddrSpace()),
  8366. ValueVTs);
  8367. // NOTE: Assuming that a pointer will never break down to more than one VT
  8368. // or one register.
  8369. ISD::ArgFlagsTy Flags;
  8370. Flags.setSRet();
  8371. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8372. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8373. ISD::InputArg::NoArgIndex, 0);
  8374. Ins.push_back(RetArg);
  8375. }
  8376. // Look for stores of arguments to static allocas. Mark such arguments with a
  8377. // flag to ask the target to give us the memory location of that argument if
  8378. // available.
  8379. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8380. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8381. // Set up the incoming argument description vector.
  8382. for (const Argument &Arg : F.args()) {
  8383. unsigned ArgNo = Arg.getArgNo();
  8384. SmallVector<EVT, 4> ValueVTs;
  8385. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8386. bool isArgValueUsed = !Arg.use_empty();
  8387. unsigned PartBase = 0;
  8388. Type *FinalType = Arg.getType();
  8389. if (Arg.hasAttribute(Attribute::ByVal))
  8390. FinalType = cast<PointerType>(FinalType)->getElementType();
  8391. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8392. FinalType, F.getCallingConv(), F.isVarArg());
  8393. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8394. Value != NumValues; ++Value) {
  8395. EVT VT = ValueVTs[Value];
  8396. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8397. ISD::ArgFlagsTy Flags;
  8398. // Certain targets (such as MIPS), may have a different ABI alignment
  8399. // for a type depending on the context. Give the target a chance to
  8400. // specify the alignment it wants.
  8401. unsigned OriginalAlignment =
  8402. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8403. if (Arg.getType()->isPointerTy()) {
  8404. Flags.setPointer();
  8405. Flags.setPointerAddrSpace(
  8406. cast<PointerType>(Arg.getType())->getAddressSpace());
  8407. }
  8408. if (Arg.hasAttribute(Attribute::ZExt))
  8409. Flags.setZExt();
  8410. if (Arg.hasAttribute(Attribute::SExt))
  8411. Flags.setSExt();
  8412. if (Arg.hasAttribute(Attribute::InReg)) {
  8413. // If we are using vectorcall calling convention, a structure that is
  8414. // passed InReg - is surely an HVA
  8415. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8416. isa<StructType>(Arg.getType())) {
  8417. // The first value of a structure is marked
  8418. if (0 == Value)
  8419. Flags.setHvaStart();
  8420. Flags.setHva();
  8421. }
  8422. // Set InReg Flag
  8423. Flags.setInReg();
  8424. }
  8425. if (Arg.hasAttribute(Attribute::StructRet))
  8426. Flags.setSRet();
  8427. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8428. Flags.setSwiftSelf();
  8429. if (Arg.hasAttribute(Attribute::SwiftError))
  8430. Flags.setSwiftError();
  8431. if (Arg.hasAttribute(Attribute::ByVal))
  8432. Flags.setByVal();
  8433. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8434. Flags.setInAlloca();
  8435. // Set the byval flag for CCAssignFn callbacks that don't know about
  8436. // inalloca. This way we can know how many bytes we should've allocated
  8437. // and how many bytes a callee cleanup function will pop. If we port
  8438. // inalloca to more targets, we'll have to add custom inalloca handling
  8439. // in the various CC lowering callbacks.
  8440. Flags.setByVal();
  8441. }
  8442. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8443. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8444. if (ArgNo == 0)
  8445. Flags.setByVal();
  8446. }
  8447. if (Flags.isByVal() || Flags.isInAlloca()) {
  8448. PointerType *Ty = cast<PointerType>(Arg.getType());
  8449. Type *ElementTy = Ty->getElementType();
  8450. // For ByVal, size and alignment should be passed from FE. BE will
  8451. // guess if this info is not there but there are cases it cannot get
  8452. // right.
  8453. unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
  8454. Flags.setByValSize(FrameSize);
  8455. unsigned FrameAlign;
  8456. if (Arg.getParamAlignment())
  8457. FrameAlign = Arg.getParamAlignment();
  8458. else
  8459. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8460. Flags.setByValAlign(FrameAlign);
  8461. }
  8462. if (Arg.hasAttribute(Attribute::Nest))
  8463. Flags.setNest();
  8464. if (NeedsRegBlock)
  8465. Flags.setInConsecutiveRegs();
  8466. Flags.setOrigAlign(OriginalAlignment);
  8467. if (ArgCopyElisionCandidates.count(&Arg))
  8468. Flags.setCopyElisionCandidate();
  8469. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8470. *CurDAG->getContext(), F.getCallingConv(), VT);
  8471. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8472. *CurDAG->getContext(), F.getCallingConv(), VT);
  8473. for (unsigned i = 0; i != NumRegs; ++i) {
  8474. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8475. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8476. if (NumRegs > 1 && i == 0)
  8477. MyFlags.Flags.setSplit();
  8478. // if it isn't first piece, alignment must be 1
  8479. else if (i > 0) {
  8480. MyFlags.Flags.setOrigAlign(1);
  8481. if (i == NumRegs - 1)
  8482. MyFlags.Flags.setSplitEnd();
  8483. }
  8484. Ins.push_back(MyFlags);
  8485. }
  8486. if (NeedsRegBlock && Value == NumValues - 1)
  8487. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8488. PartBase += VT.getStoreSize();
  8489. }
  8490. }
  8491. // Call the target to set up the argument values.
  8492. SmallVector<SDValue, 8> InVals;
  8493. SDValue NewRoot = TLI->LowerFormalArguments(
  8494. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8495. // Verify that the target's LowerFormalArguments behaved as expected.
  8496. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8497. "LowerFormalArguments didn't return a valid chain!");
  8498. assert(InVals.size() == Ins.size() &&
  8499. "LowerFormalArguments didn't emit the correct number of values!");
  8500. LLVM_DEBUG({
  8501. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8502. assert(InVals[i].getNode() &&
  8503. "LowerFormalArguments emitted a null value!");
  8504. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8505. "LowerFormalArguments emitted a value with the wrong type!");
  8506. }
  8507. });
  8508. // Update the DAG with the new chain value resulting from argument lowering.
  8509. DAG.setRoot(NewRoot);
  8510. // Set up the argument values.
  8511. unsigned i = 0;
  8512. if (!FuncInfo->CanLowerReturn) {
  8513. // Create a virtual register for the sret pointer, and put in a copy
  8514. // from the sret argument into it.
  8515. SmallVector<EVT, 1> ValueVTs;
  8516. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8517. F.getReturnType()->getPointerTo(
  8518. DAG.getDataLayout().getAllocaAddrSpace()),
  8519. ValueVTs);
  8520. MVT VT = ValueVTs[0].getSimpleVT();
  8521. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8522. Optional<ISD::NodeType> AssertOp = None;
  8523. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8524. nullptr, F.getCallingConv(), AssertOp);
  8525. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8526. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8527. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8528. FuncInfo->DemoteRegister = SRetReg;
  8529. NewRoot =
  8530. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8531. DAG.setRoot(NewRoot);
  8532. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8533. ++i;
  8534. }
  8535. SmallVector<SDValue, 4> Chains;
  8536. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8537. for (const Argument &Arg : F.args()) {
  8538. SmallVector<SDValue, 4> ArgValues;
  8539. SmallVector<EVT, 4> ValueVTs;
  8540. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8541. unsigned NumValues = ValueVTs.size();
  8542. if (NumValues == 0)
  8543. continue;
  8544. bool ArgHasUses = !Arg.use_empty();
  8545. // Elide the copying store if the target loaded this argument from a
  8546. // suitable fixed stack object.
  8547. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8548. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8549. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8550. InVals[i], ArgHasUses);
  8551. }
  8552. // If this argument is unused then remember its value. It is used to generate
  8553. // debugging information.
  8554. bool isSwiftErrorArg =
  8555. TLI->supportSwiftError() &&
  8556. Arg.hasAttribute(Attribute::SwiftError);
  8557. if (!ArgHasUses && !isSwiftErrorArg) {
  8558. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8559. // Also remember any frame index for use in FastISel.
  8560. if (FrameIndexSDNode *FI =
  8561. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8562. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8563. }
  8564. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8565. EVT VT = ValueVTs[Val];
  8566. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8567. F.getCallingConv(), VT);
  8568. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8569. *CurDAG->getContext(), F.getCallingConv(), VT);
  8570. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8571. // we do generate a copy for it that can be used on return from the
  8572. // function.
  8573. if (ArgHasUses || isSwiftErrorArg) {
  8574. Optional<ISD::NodeType> AssertOp;
  8575. if (Arg.hasAttribute(Attribute::SExt))
  8576. AssertOp = ISD::AssertSext;
  8577. else if (Arg.hasAttribute(Attribute::ZExt))
  8578. AssertOp = ISD::AssertZext;
  8579. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8580. PartVT, VT, nullptr,
  8581. F.getCallingConv(), AssertOp));
  8582. }
  8583. i += NumParts;
  8584. }
  8585. // We don't need to do anything else for unused arguments.
  8586. if (ArgValues.empty())
  8587. continue;
  8588. // Note down frame index.
  8589. if (FrameIndexSDNode *FI =
  8590. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8591. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8592. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8593. SDB->getCurSDLoc());
  8594. SDB->setValue(&Arg, Res);
  8595. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8596. // We want to associate the argument with the frame index, among
  8597. // involved operands, that correspond to the lowest address. The
  8598. // getCopyFromParts function, called earlier, is swapping the order of
  8599. // the operands to BUILD_PAIR depending on endianness. The result of
  8600. // that swapping is that the least significant bits of the argument will
  8601. // be in the first operand of the BUILD_PAIR node, and the most
  8602. // significant bits will be in the second operand.
  8603. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8604. if (LoadSDNode *LNode =
  8605. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8606. if (FrameIndexSDNode *FI =
  8607. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8608. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8609. }
  8610. // Update the SwiftErrorVRegDefMap.
  8611. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8612. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8613. if (TargetRegisterInfo::isVirtualRegister(Reg))
  8614. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8615. Reg);
  8616. }
  8617. // If this argument is live outside of the entry block, insert a copy from
  8618. // wherever we got it to the vreg that other BB's will reference it as.
  8619. if (Res.getOpcode() == ISD::CopyFromReg) {
  8620. // If we can, though, try to skip creating an unnecessary vreg.
  8621. // FIXME: This isn't very clean... it would be nice to make this more
  8622. // general.
  8623. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8624. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  8625. FuncInfo->ValueMap[&Arg] = Reg;
  8626. continue;
  8627. }
  8628. }
  8629. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8630. FuncInfo->InitializeRegForValue(&Arg);
  8631. SDB->CopyToExportRegsIfNeeded(&Arg);
  8632. }
  8633. }
  8634. if (!Chains.empty()) {
  8635. Chains.push_back(NewRoot);
  8636. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8637. }
  8638. DAG.setRoot(NewRoot);
  8639. assert(i == InVals.size() && "Argument register count mismatch!");
  8640. // If any argument copy elisions occurred and we have debug info, update the
  8641. // stale frame indices used in the dbg.declare variable info table.
  8642. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8643. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8644. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8645. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8646. if (I != ArgCopyElisionFrameIndexMap.end())
  8647. VI.Slot = I->second;
  8648. }
  8649. }
  8650. // Finally, if the target has anything special to do, allow it to do so.
  8651. EmitFunctionEntryCode();
  8652. }
  8653. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8654. /// ensure constants are generated when needed. Remember the virtual registers
  8655. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8656. /// directly add them, because expansion might result in multiple MBB's for one
  8657. /// BB. As such, the start of the BB might correspond to a different MBB than
  8658. /// the end.
  8659. void
  8660. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8661. const Instruction *TI = LLVMBB->getTerminator();
  8662. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8663. // Check PHI nodes in successors that expect a value to be available from this
  8664. // block.
  8665. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8666. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8667. if (!isa<PHINode>(SuccBB->begin())) continue;
  8668. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8669. // If this terminator has multiple identical successors (common for
  8670. // switches), only handle each succ once.
  8671. if (!SuccsHandled.insert(SuccMBB).second)
  8672. continue;
  8673. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8674. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8675. // nodes and Machine PHI nodes, but the incoming operands have not been
  8676. // emitted yet.
  8677. for (const PHINode &PN : SuccBB->phis()) {
  8678. // Ignore dead phi's.
  8679. if (PN.use_empty())
  8680. continue;
  8681. // Skip empty types
  8682. if (PN.getType()->isEmptyTy())
  8683. continue;
  8684. unsigned Reg;
  8685. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8686. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8687. unsigned &RegOut = ConstantsOut[C];
  8688. if (RegOut == 0) {
  8689. RegOut = FuncInfo.CreateRegs(C);
  8690. CopyValueToVirtualRegister(C, RegOut);
  8691. }
  8692. Reg = RegOut;
  8693. } else {
  8694. DenseMap<const Value *, unsigned>::iterator I =
  8695. FuncInfo.ValueMap.find(PHIOp);
  8696. if (I != FuncInfo.ValueMap.end())
  8697. Reg = I->second;
  8698. else {
  8699. assert(isa<AllocaInst>(PHIOp) &&
  8700. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8701. "Didn't codegen value into a register!??");
  8702. Reg = FuncInfo.CreateRegs(PHIOp);
  8703. CopyValueToVirtualRegister(PHIOp, Reg);
  8704. }
  8705. }
  8706. // Remember that this register needs to added to the machine PHI node as
  8707. // the input for this MBB.
  8708. SmallVector<EVT, 4> ValueVTs;
  8709. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8710. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8711. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8712. EVT VT = ValueVTs[vti];
  8713. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8714. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8715. FuncInfo.PHINodesToUpdate.push_back(
  8716. std::make_pair(&*MBBI++, Reg + i));
  8717. Reg += NumRegisters;
  8718. }
  8719. }
  8720. }
  8721. ConstantsOut.clear();
  8722. }
  8723. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8724. /// is 0.
  8725. MachineBasicBlock *
  8726. SelectionDAGBuilder::StackProtectorDescriptor::
  8727. AddSuccessorMBB(const BasicBlock *BB,
  8728. MachineBasicBlock *ParentMBB,
  8729. bool IsLikely,
  8730. MachineBasicBlock *SuccMBB) {
  8731. // If SuccBB has not been created yet, create it.
  8732. if (!SuccMBB) {
  8733. MachineFunction *MF = ParentMBB->getParent();
  8734. MachineFunction::iterator BBI(ParentMBB);
  8735. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8736. MF->insert(++BBI, SuccMBB);
  8737. }
  8738. // Add it as a successor of ParentMBB.
  8739. ParentMBB->addSuccessor(
  8740. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8741. return SuccMBB;
  8742. }
  8743. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8744. MachineFunction::iterator I(MBB);
  8745. if (++I == FuncInfo.MF->end())
  8746. return nullptr;
  8747. return &*I;
  8748. }
  8749. /// During lowering new call nodes can be created (such as memset, etc.).
  8750. /// Those will become new roots of the current DAG, but complications arise
  8751. /// when they are tail calls. In such cases, the call lowering will update
  8752. /// the root, but the builder still needs to know that a tail call has been
  8753. /// lowered in order to avoid generating an additional return.
  8754. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8755. // If the node is null, we do have a tail call.
  8756. if (MaybeTC.getNode() != nullptr)
  8757. DAG.setRoot(MaybeTC);
  8758. else
  8759. HasTailCall = true;
  8760. }
  8761. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8762. MachineBasicBlock *SwitchMBB,
  8763. MachineBasicBlock *DefaultMBB) {
  8764. MachineFunction *CurMF = FuncInfo.MF;
  8765. MachineBasicBlock *NextMBB = nullptr;
  8766. MachineFunction::iterator BBI(W.MBB);
  8767. if (++BBI != FuncInfo.MF->end())
  8768. NextMBB = &*BBI;
  8769. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8770. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8771. if (Size == 2 && W.MBB == SwitchMBB) {
  8772. // If any two of the cases has the same destination, and if one value
  8773. // is the same as the other, but has one bit unset that the other has set,
  8774. // use bit manipulation to do two compares at once. For example:
  8775. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8776. // TODO: This could be extended to merge any 2 cases in switches with 3
  8777. // cases.
  8778. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8779. CaseCluster &Small = *W.FirstCluster;
  8780. CaseCluster &Big = *W.LastCluster;
  8781. if (Small.Low == Small.High && Big.Low == Big.High &&
  8782. Small.MBB == Big.MBB) {
  8783. const APInt &SmallValue = Small.Low->getValue();
  8784. const APInt &BigValue = Big.Low->getValue();
  8785. // Check that there is only one bit different.
  8786. APInt CommonBit = BigValue ^ SmallValue;
  8787. if (CommonBit.isPowerOf2()) {
  8788. SDValue CondLHS = getValue(Cond);
  8789. EVT VT = CondLHS.getValueType();
  8790. SDLoc DL = getCurSDLoc();
  8791. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8792. DAG.getConstant(CommonBit, DL, VT));
  8793. SDValue Cond = DAG.getSetCC(
  8794. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8795. ISD::SETEQ);
  8796. // Update successor info.
  8797. // Both Small and Big will jump to Small.BB, so we sum up the
  8798. // probabilities.
  8799. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8800. if (BPI)
  8801. addSuccessorWithProb(
  8802. SwitchMBB, DefaultMBB,
  8803. // The default destination is the first successor in IR.
  8804. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8805. else
  8806. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8807. // Insert the true branch.
  8808. SDValue BrCond =
  8809. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8810. DAG.getBasicBlock(Small.MBB));
  8811. // Insert the false branch.
  8812. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8813. DAG.getBasicBlock(DefaultMBB));
  8814. DAG.setRoot(BrCond);
  8815. return;
  8816. }
  8817. }
  8818. }
  8819. if (TM.getOptLevel() != CodeGenOpt::None) {
  8820. // Here, we order cases by probability so the most likely case will be
  8821. // checked first. However, two clusters can have the same probability in
  8822. // which case their relative ordering is non-deterministic. So we use Low
  8823. // as a tie-breaker as clusters are guaranteed to never overlap.
  8824. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8825. [](const CaseCluster &a, const CaseCluster &b) {
  8826. return a.Prob != b.Prob ?
  8827. a.Prob > b.Prob :
  8828. a.Low->getValue().slt(b.Low->getValue());
  8829. });
  8830. // Rearrange the case blocks so that the last one falls through if possible
  8831. // without changing the order of probabilities.
  8832. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8833. --I;
  8834. if (I->Prob > W.LastCluster->Prob)
  8835. break;
  8836. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8837. std::swap(*I, *W.LastCluster);
  8838. break;
  8839. }
  8840. }
  8841. }
  8842. // Compute total probability.
  8843. BranchProbability DefaultProb = W.DefaultProb;
  8844. BranchProbability UnhandledProbs = DefaultProb;
  8845. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8846. UnhandledProbs += I->Prob;
  8847. MachineBasicBlock *CurMBB = W.MBB;
  8848. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8849. bool FallthroughUnreachable = false;
  8850. MachineBasicBlock *Fallthrough;
  8851. if (I == W.LastCluster) {
  8852. // For the last cluster, fall through to the default destination.
  8853. Fallthrough = DefaultMBB;
  8854. FallthroughUnreachable = isa<UnreachableInst>(
  8855. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  8856. } else {
  8857. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8858. CurMF->insert(BBI, Fallthrough);
  8859. // Put Cond in a virtual register to make it available from the new blocks.
  8860. ExportFromCurrentBlock(Cond);
  8861. }
  8862. UnhandledProbs -= I->Prob;
  8863. switch (I->Kind) {
  8864. case CC_JumpTable: {
  8865. // FIXME: Optimize away range check based on pivot comparisons.
  8866. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  8867. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  8868. // The jump block hasn't been inserted yet; insert it here.
  8869. MachineBasicBlock *JumpMBB = JT->MBB;
  8870. CurMF->insert(BBI, JumpMBB);
  8871. auto JumpProb = I->Prob;
  8872. auto FallthroughProb = UnhandledProbs;
  8873. // If the default statement is a target of the jump table, we evenly
  8874. // distribute the default probability to successors of CurMBB. Also
  8875. // update the probability on the edge from JumpMBB to Fallthrough.
  8876. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8877. SE = JumpMBB->succ_end();
  8878. SI != SE; ++SI) {
  8879. if (*SI == DefaultMBB) {
  8880. JumpProb += DefaultProb / 2;
  8881. FallthroughProb -= DefaultProb / 2;
  8882. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8883. JumpMBB->normalizeSuccProbs();
  8884. break;
  8885. }
  8886. }
  8887. if (FallthroughUnreachable) {
  8888. // Skip the range check if the fallthrough block is unreachable.
  8889. JTH->OmitRangeCheck = true;
  8890. }
  8891. if (!JTH->OmitRangeCheck)
  8892. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8893. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8894. CurMBB->normalizeSuccProbs();
  8895. // The jump table header will be inserted in our current block, do the
  8896. // range check, and fall through to our fallthrough block.
  8897. JTH->HeaderBB = CurMBB;
  8898. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8899. // If we're in the right place, emit the jump table header right now.
  8900. if (CurMBB == SwitchMBB) {
  8901. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8902. JTH->Emitted = true;
  8903. }
  8904. break;
  8905. }
  8906. case CC_BitTests: {
  8907. // FIXME: If Fallthrough is unreachable, skip the range check.
  8908. // FIXME: Optimize away range check based on pivot comparisons.
  8909. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  8910. // The bit test blocks haven't been inserted yet; insert them here.
  8911. for (BitTestCase &BTC : BTB->Cases)
  8912. CurMF->insert(BBI, BTC.ThisBB);
  8913. // Fill in fields of the BitTestBlock.
  8914. BTB->Parent = CurMBB;
  8915. BTB->Default = Fallthrough;
  8916. BTB->DefaultProb = UnhandledProbs;
  8917. // If the cases in bit test don't form a contiguous range, we evenly
  8918. // distribute the probability on the edge to Fallthrough to two
  8919. // successors of CurMBB.
  8920. if (!BTB->ContiguousRange) {
  8921. BTB->Prob += DefaultProb / 2;
  8922. BTB->DefaultProb -= DefaultProb / 2;
  8923. }
  8924. // If we're in the right place, emit the bit test header right now.
  8925. if (CurMBB == SwitchMBB) {
  8926. visitBitTestHeader(*BTB, SwitchMBB);
  8927. BTB->Emitted = true;
  8928. }
  8929. break;
  8930. }
  8931. case CC_Range: {
  8932. const Value *RHS, *LHS, *MHS;
  8933. ISD::CondCode CC;
  8934. if (I->Low == I->High) {
  8935. // Check Cond == I->Low.
  8936. CC = ISD::SETEQ;
  8937. LHS = Cond;
  8938. RHS=I->Low;
  8939. MHS = nullptr;
  8940. } else {
  8941. // Check I->Low <= Cond <= I->High.
  8942. CC = ISD::SETLE;
  8943. LHS = I->Low;
  8944. MHS = Cond;
  8945. RHS = I->High;
  8946. }
  8947. // If Fallthrough is unreachable, fold away the comparison.
  8948. if (FallthroughUnreachable)
  8949. CC = ISD::SETTRUE;
  8950. // The false probability is the sum of all unhandled cases.
  8951. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  8952. getCurSDLoc(), I->Prob, UnhandledProbs);
  8953. if (CurMBB == SwitchMBB)
  8954. visitSwitchCase(CB, SwitchMBB);
  8955. else
  8956. SL->SwitchCases.push_back(CB);
  8957. break;
  8958. }
  8959. }
  8960. CurMBB = Fallthrough;
  8961. }
  8962. }
  8963. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  8964. CaseClusterIt First,
  8965. CaseClusterIt Last) {
  8966. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  8967. if (X.Prob != CC.Prob)
  8968. return X.Prob > CC.Prob;
  8969. // Ties are broken by comparing the case value.
  8970. return X.Low->getValue().slt(CC.Low->getValue());
  8971. });
  8972. }
  8973. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  8974. const SwitchWorkListItem &W,
  8975. Value *Cond,
  8976. MachineBasicBlock *SwitchMBB) {
  8977. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  8978. "Clusters not sorted?");
  8979. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  8980. // Balance the tree based on branch probabilities to create a near-optimal (in
  8981. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  8982. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  8983. CaseClusterIt LastLeft = W.FirstCluster;
  8984. CaseClusterIt FirstRight = W.LastCluster;
  8985. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  8986. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  8987. // Move LastLeft and FirstRight towards each other from opposite directions to
  8988. // find a partitioning of the clusters which balances the probability on both
  8989. // sides. If LeftProb and RightProb are equal, alternate which side is
  8990. // taken to ensure 0-probability nodes are distributed evenly.
  8991. unsigned I = 0;
  8992. while (LastLeft + 1 < FirstRight) {
  8993. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  8994. LeftProb += (++LastLeft)->Prob;
  8995. else
  8996. RightProb += (--FirstRight)->Prob;
  8997. I++;
  8998. }
  8999. while (true) {
  9000. // Our binary search tree differs from a typical BST in that ours can have up
  9001. // to three values in each leaf. The pivot selection above doesn't take that
  9002. // into account, which means the tree might require more nodes and be less
  9003. // efficient. We compensate for this here.
  9004. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9005. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9006. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9007. // If one side has less than 3 clusters, and the other has more than 3,
  9008. // consider taking a cluster from the other side.
  9009. if (NumLeft < NumRight) {
  9010. // Consider moving the first cluster on the right to the left side.
  9011. CaseCluster &CC = *FirstRight;
  9012. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9013. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9014. if (LeftSideRank <= RightSideRank) {
  9015. // Moving the cluster to the left does not demote it.
  9016. ++LastLeft;
  9017. ++FirstRight;
  9018. continue;
  9019. }
  9020. } else {
  9021. assert(NumRight < NumLeft);
  9022. // Consider moving the last element on the left to the right side.
  9023. CaseCluster &CC = *LastLeft;
  9024. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9025. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9026. if (RightSideRank <= LeftSideRank) {
  9027. // Moving the cluster to the right does not demot it.
  9028. --LastLeft;
  9029. --FirstRight;
  9030. continue;
  9031. }
  9032. }
  9033. }
  9034. break;
  9035. }
  9036. assert(LastLeft + 1 == FirstRight);
  9037. assert(LastLeft >= W.FirstCluster);
  9038. assert(FirstRight <= W.LastCluster);
  9039. // Use the first element on the right as pivot since we will make less-than
  9040. // comparisons against it.
  9041. CaseClusterIt PivotCluster = FirstRight;
  9042. assert(PivotCluster > W.FirstCluster);
  9043. assert(PivotCluster <= W.LastCluster);
  9044. CaseClusterIt FirstLeft = W.FirstCluster;
  9045. CaseClusterIt LastRight = W.LastCluster;
  9046. const ConstantInt *Pivot = PivotCluster->Low;
  9047. // New blocks will be inserted immediately after the current one.
  9048. MachineFunction::iterator BBI(W.MBB);
  9049. ++BBI;
  9050. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9051. // we can branch to its destination directly if it's squeezed exactly in
  9052. // between the known lower bound and Pivot - 1.
  9053. MachineBasicBlock *LeftMBB;
  9054. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9055. FirstLeft->Low == W.GE &&
  9056. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9057. LeftMBB = FirstLeft->MBB;
  9058. } else {
  9059. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9060. FuncInfo.MF->insert(BBI, LeftMBB);
  9061. WorkList.push_back(
  9062. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9063. // Put Cond in a virtual register to make it available from the new blocks.
  9064. ExportFromCurrentBlock(Cond);
  9065. }
  9066. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9067. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9068. // directly if RHS.High equals the current upper bound.
  9069. MachineBasicBlock *RightMBB;
  9070. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9071. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9072. RightMBB = FirstRight->MBB;
  9073. } else {
  9074. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9075. FuncInfo.MF->insert(BBI, RightMBB);
  9076. WorkList.push_back(
  9077. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9078. // Put Cond in a virtual register to make it available from the new blocks.
  9079. ExportFromCurrentBlock(Cond);
  9080. }
  9081. // Create the CaseBlock record that will be used to lower the branch.
  9082. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9083. getCurSDLoc(), LeftProb, RightProb);
  9084. if (W.MBB == SwitchMBB)
  9085. visitSwitchCase(CB, SwitchMBB);
  9086. else
  9087. SL->SwitchCases.push_back(CB);
  9088. }
  9089. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9090. // from the swith statement.
  9091. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9092. BranchProbability PeeledCaseProb) {
  9093. if (PeeledCaseProb == BranchProbability::getOne())
  9094. return BranchProbability::getZero();
  9095. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9096. uint32_t Numerator = CaseProb.getNumerator();
  9097. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9098. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9099. }
  9100. // Try to peel the top probability case if it exceeds the threshold.
  9101. // Return current MachineBasicBlock for the switch statement if the peeling
  9102. // does not occur.
  9103. // If the peeling is performed, return the newly created MachineBasicBlock
  9104. // for the peeled switch statement. Also update Clusters to remove the peeled
  9105. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9106. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9107. const SwitchInst &SI, CaseClusterVector &Clusters,
  9108. BranchProbability &PeeledCaseProb) {
  9109. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9110. // Don't perform if there is only one cluster or optimizing for size.
  9111. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9112. TM.getOptLevel() == CodeGenOpt::None ||
  9113. SwitchMBB->getParent()->getFunction().hasMinSize())
  9114. return SwitchMBB;
  9115. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9116. unsigned PeeledCaseIndex = 0;
  9117. bool SwitchPeeled = false;
  9118. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9119. CaseCluster &CC = Clusters[Index];
  9120. if (CC.Prob < TopCaseProb)
  9121. continue;
  9122. TopCaseProb = CC.Prob;
  9123. PeeledCaseIndex = Index;
  9124. SwitchPeeled = true;
  9125. }
  9126. if (!SwitchPeeled)
  9127. return SwitchMBB;
  9128. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9129. << TopCaseProb << "\n");
  9130. // Record the MBB for the peeled switch statement.
  9131. MachineFunction::iterator BBI(SwitchMBB);
  9132. ++BBI;
  9133. MachineBasicBlock *PeeledSwitchMBB =
  9134. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9135. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9136. ExportFromCurrentBlock(SI.getCondition());
  9137. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9138. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9139. nullptr, nullptr, TopCaseProb.getCompl()};
  9140. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9141. Clusters.erase(PeeledCaseIt);
  9142. for (CaseCluster &CC : Clusters) {
  9143. LLVM_DEBUG(
  9144. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9145. << CC.Prob << "\n");
  9146. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9147. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9148. }
  9149. PeeledCaseProb = TopCaseProb;
  9150. return PeeledSwitchMBB;
  9151. }
  9152. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9153. // Extract cases from the switch.
  9154. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9155. CaseClusterVector Clusters;
  9156. Clusters.reserve(SI.getNumCases());
  9157. for (auto I : SI.cases()) {
  9158. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9159. const ConstantInt *CaseVal = I.getCaseValue();
  9160. BranchProbability Prob =
  9161. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9162. : BranchProbability(1, SI.getNumCases() + 1);
  9163. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9164. }
  9165. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9166. // Cluster adjacent cases with the same destination. We do this at all
  9167. // optimization levels because it's cheap to do and will make codegen faster
  9168. // if there are many clusters.
  9169. sortAndRangeify(Clusters);
  9170. // The branch probablity of the peeled case.
  9171. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9172. MachineBasicBlock *PeeledSwitchMBB =
  9173. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9174. // If there is only the default destination, jump there directly.
  9175. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9176. if (Clusters.empty()) {
  9177. assert(PeeledSwitchMBB == SwitchMBB);
  9178. SwitchMBB->addSuccessor(DefaultMBB);
  9179. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9180. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9181. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9182. }
  9183. return;
  9184. }
  9185. SL->findJumpTables(Clusters, &SI, DefaultMBB);
  9186. SL->findBitTestClusters(Clusters, &SI);
  9187. LLVM_DEBUG({
  9188. dbgs() << "Case clusters: ";
  9189. for (const CaseCluster &C : Clusters) {
  9190. if (C.Kind == CC_JumpTable)
  9191. dbgs() << "JT:";
  9192. if (C.Kind == CC_BitTests)
  9193. dbgs() << "BT:";
  9194. C.Low->getValue().print(dbgs(), true);
  9195. if (C.Low != C.High) {
  9196. dbgs() << '-';
  9197. C.High->getValue().print(dbgs(), true);
  9198. }
  9199. dbgs() << ' ';
  9200. }
  9201. dbgs() << '\n';
  9202. });
  9203. assert(!Clusters.empty());
  9204. SwitchWorkList WorkList;
  9205. CaseClusterIt First = Clusters.begin();
  9206. CaseClusterIt Last = Clusters.end() - 1;
  9207. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9208. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9209. // DefaultMBB is not replaced.
  9210. if (PeeledCaseProb != BranchProbability::getZero() &&
  9211. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9212. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9213. WorkList.push_back(
  9214. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9215. while (!WorkList.empty()) {
  9216. SwitchWorkListItem W = WorkList.back();
  9217. WorkList.pop_back();
  9218. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9219. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9220. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9221. // For optimized builds, lower large range as a balanced binary tree.
  9222. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9223. continue;
  9224. }
  9225. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9226. }
  9227. }