SelectionDAGBuilder.cpp 422 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827
  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/BitVector.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/BlockFrequencyInfo.h"
  27. #include "llvm/Analysis/BranchProbabilityInfo.h"
  28. #include "llvm/Analysis/ConstantFolding.h"
  29. #include "llvm/Analysis/EHPersonalities.h"
  30. #include "llvm/Analysis/Loads.h"
  31. #include "llvm/Analysis/MemoryLocation.h"
  32. #include "llvm/Analysis/ProfileSummaryInfo.h"
  33. #include "llvm/Analysis/TargetLibraryInfo.h"
  34. #include "llvm/Analysis/ValueTracking.h"
  35. #include "llvm/Analysis/VectorUtils.h"
  36. #include "llvm/CodeGen/Analysis.h"
  37. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  38. #include "llvm/CodeGen/GCMetadata.h"
  39. #include "llvm/CodeGen/MachineBasicBlock.h"
  40. #include "llvm/CodeGen/MachineFrameInfo.h"
  41. #include "llvm/CodeGen/MachineFunction.h"
  42. #include "llvm/CodeGen/MachineInstr.h"
  43. #include "llvm/CodeGen/MachineInstrBuilder.h"
  44. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  45. #include "llvm/CodeGen/MachineMemOperand.h"
  46. #include "llvm/CodeGen/MachineModuleInfo.h"
  47. #include "llvm/CodeGen/MachineOperand.h"
  48. #include "llvm/CodeGen/MachineRegisterInfo.h"
  49. #include "llvm/CodeGen/RuntimeLibcalls.h"
  50. #include "llvm/CodeGen/SelectionDAG.h"
  51. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  52. #include "llvm/CodeGen/StackMaps.h"
  53. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  54. #include "llvm/CodeGen/TargetFrameLowering.h"
  55. #include "llvm/CodeGen/TargetInstrInfo.h"
  56. #include "llvm/CodeGen/TargetOpcodes.h"
  57. #include "llvm/CodeGen/TargetRegisterInfo.h"
  58. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  59. #include "llvm/CodeGen/WinEHFuncInfo.h"
  60. #include "llvm/IR/Argument.h"
  61. #include "llvm/IR/Attributes.h"
  62. #include "llvm/IR/BasicBlock.h"
  63. #include "llvm/IR/CFG.h"
  64. #include "llvm/IR/CallingConv.h"
  65. #include "llvm/IR/Constant.h"
  66. #include "llvm/IR/ConstantRange.h"
  67. #include "llvm/IR/Constants.h"
  68. #include "llvm/IR/DataLayout.h"
  69. #include "llvm/IR/DebugInfoMetadata.h"
  70. #include "llvm/IR/DerivedTypes.h"
  71. #include "llvm/IR/Function.h"
  72. #include "llvm/IR/GetElementPtrTypeIterator.h"
  73. #include "llvm/IR/InlineAsm.h"
  74. #include "llvm/IR/InstrTypes.h"
  75. #include "llvm/IR/Instructions.h"
  76. #include "llvm/IR/IntrinsicInst.h"
  77. #include "llvm/IR/Intrinsics.h"
  78. #include "llvm/IR/IntrinsicsAArch64.h"
  79. #include "llvm/IR/IntrinsicsWebAssembly.h"
  80. #include "llvm/IR/LLVMContext.h"
  81. #include "llvm/IR/Metadata.h"
  82. #include "llvm/IR/Module.h"
  83. #include "llvm/IR/Operator.h"
  84. #include "llvm/IR/PatternMatch.h"
  85. #include "llvm/IR/Statepoint.h"
  86. #include "llvm/IR/Type.h"
  87. #include "llvm/IR/User.h"
  88. #include "llvm/IR/Value.h"
  89. #include "llvm/MC/MCContext.h"
  90. #include "llvm/MC/MCSymbol.h"
  91. #include "llvm/Support/AtomicOrdering.h"
  92. #include "llvm/Support/Casting.h"
  93. #include "llvm/Support/CommandLine.h"
  94. #include "llvm/Support/Compiler.h"
  95. #include "llvm/Support/Debug.h"
  96. #include "llvm/Support/MathExtras.h"
  97. #include "llvm/Support/raw_ostream.h"
  98. #include "llvm/Target/TargetIntrinsicInfo.h"
  99. #include "llvm/Target/TargetMachine.h"
  100. #include "llvm/Target/TargetOptions.h"
  101. #include "llvm/Transforms/Utils/Local.h"
  102. #include <cstddef>
  103. #include <cstring>
  104. #include <iterator>
  105. #include <limits>
  106. #include <numeric>
  107. #include <tuple>
  108. using namespace llvm;
  109. using namespace PatternMatch;
  110. using namespace SwitchCG;
  111. #define DEBUG_TYPE "isel"
  112. /// LimitFloatPrecision - Generate low-precision inline sequences for
  113. /// some float libcalls (6, 8 or 12 bits).
  114. static unsigned LimitFloatPrecision;
  115. static cl::opt<bool>
  116. InsertAssertAlign("insert-assert-align", cl::init(true),
  117. cl::desc("Insert the experimental `assertalign` node."),
  118. cl::ReallyHidden);
  119. static cl::opt<unsigned, true>
  120. LimitFPPrecision("limit-float-precision",
  121. cl::desc("Generate low-precision inline sequences "
  122. "for some float libcalls"),
  123. cl::location(LimitFloatPrecision), cl::Hidden,
  124. cl::init(0));
  125. static cl::opt<unsigned> SwitchPeelThreshold(
  126. "switch-peel-threshold", cl::Hidden, cl::init(66),
  127. cl::desc("Set the case probability threshold for peeling the case from a "
  128. "switch statement. A value greater than 100 will void this "
  129. "optimization"));
  130. // Limit the width of DAG chains. This is important in general to prevent
  131. // DAG-based analysis from blowing up. For example, alias analysis and
  132. // load clustering may not complete in reasonable time. It is difficult to
  133. // recognize and avoid this situation within each individual analysis, and
  134. // future analyses are likely to have the same behavior. Limiting DAG width is
  135. // the safe approach and will be especially important with global DAGs.
  136. //
  137. // MaxParallelChains default is arbitrarily high to avoid affecting
  138. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  139. // sequence over this should have been converted to llvm.memcpy by the
  140. // frontend. It is easy to induce this behavior with .ll code such as:
  141. // %buffer = alloca [4096 x i8]
  142. // %data = load [4096 x i8]* %argPtr
  143. // store [4096 x i8] %data, [4096 x i8]* %buffer
  144. static const unsigned MaxParallelChains = 64;
  145. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  146. const SDValue *Parts, unsigned NumParts,
  147. MVT PartVT, EVT ValueVT, const Value *V,
  148. Optional<CallingConv::ID> CC);
  149. /// getCopyFromParts - Create a value that contains the specified legal parts
  150. /// combined into the value they represent. If the parts combine to a type
  151. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  152. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  153. /// (ISD::AssertSext).
  154. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  155. const SDValue *Parts, unsigned NumParts,
  156. MVT PartVT, EVT ValueVT, const Value *V,
  157. Optional<CallingConv::ID> CC = None,
  158. Optional<ISD::NodeType> AssertOp = None) {
  159. // Let the target assemble the parts if it wants to
  160. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  161. if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
  162. PartVT, ValueVT, CC))
  163. return Val;
  164. if (ValueVT.isVector())
  165. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  166. CC);
  167. assert(NumParts > 0 && "No parts to assemble!");
  168. SDValue Val = Parts[0];
  169. if (NumParts > 1) {
  170. // Assemble the value from multiple parts.
  171. if (ValueVT.isInteger()) {
  172. unsigned PartBits = PartVT.getSizeInBits();
  173. unsigned ValueBits = ValueVT.getSizeInBits();
  174. // Assemble the power of 2 part.
  175. unsigned RoundParts =
  176. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  177. unsigned RoundBits = PartBits * RoundParts;
  178. EVT RoundVT = RoundBits == ValueBits ?
  179. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  180. SDValue Lo, Hi;
  181. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  182. if (RoundParts > 2) {
  183. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  184. PartVT, HalfVT, V);
  185. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  186. RoundParts / 2, PartVT, HalfVT, V);
  187. } else {
  188. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  189. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  190. }
  191. if (DAG.getDataLayout().isBigEndian())
  192. std::swap(Lo, Hi);
  193. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  194. if (RoundParts < NumParts) {
  195. // Assemble the trailing non-power-of-2 part.
  196. unsigned OddParts = NumParts - RoundParts;
  197. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  198. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  199. OddVT, V, CC);
  200. // Combine the round and odd parts.
  201. Lo = Val;
  202. if (DAG.getDataLayout().isBigEndian())
  203. std::swap(Lo, Hi);
  204. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  205. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  206. Hi =
  207. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  208. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  209. TLI.getPointerTy(DAG.getDataLayout())));
  210. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  211. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  212. }
  213. } else if (PartVT.isFloatingPoint()) {
  214. // FP split into multiple FP parts (for ppcf128)
  215. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  216. "Unexpected split");
  217. SDValue Lo, Hi;
  218. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  219. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  220. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  221. std::swap(Lo, Hi);
  222. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  223. } else {
  224. // FP split into integer parts (soft fp)
  225. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  226. !PartVT.isVector() && "Unexpected split");
  227. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  228. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  229. }
  230. }
  231. // There is now one part, held in Val. Correct it to match ValueVT.
  232. // PartEVT is the type of the register class that holds the value.
  233. // ValueVT is the type of the inline asm operation.
  234. EVT PartEVT = Val.getValueType();
  235. if (PartEVT == ValueVT)
  236. return Val;
  237. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  238. ValueVT.bitsLT(PartEVT)) {
  239. // For an FP value in an integer part, we need to truncate to the right
  240. // width first.
  241. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  242. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  243. }
  244. // Handle types that have the same size.
  245. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  246. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  247. // Handle types with different sizes.
  248. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  249. if (ValueVT.bitsLT(PartEVT)) {
  250. // For a truncate, see if we have any information to
  251. // indicate whether the truncated bits will always be
  252. // zero or sign-extension.
  253. if (AssertOp.hasValue())
  254. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  255. DAG.getValueType(ValueVT));
  256. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  257. }
  258. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  259. }
  260. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  261. // FP_ROUND's are always exact here.
  262. if (ValueVT.bitsLT(Val.getValueType()))
  263. return DAG.getNode(
  264. ISD::FP_ROUND, DL, ValueVT, Val,
  265. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  266. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  267. }
  268. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  269. // then truncating.
  270. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  271. ValueVT.bitsLT(PartEVT)) {
  272. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  273. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  274. }
  275. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  276. }
  277. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  278. const Twine &ErrMsg) {
  279. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  280. if (!V)
  281. return Ctx.emitError(ErrMsg);
  282. const char *AsmError = ", possible invalid constraint for vector type";
  283. if (const CallInst *CI = dyn_cast<CallInst>(I))
  284. if (CI->isInlineAsm())
  285. return Ctx.emitError(I, ErrMsg + AsmError);
  286. return Ctx.emitError(I, ErrMsg);
  287. }
  288. /// getCopyFromPartsVector - Create a value that contains the specified legal
  289. /// parts combined into the value they represent. If the parts combine to a
  290. /// type larger than ValueVT then AssertOp can be used to specify whether the
  291. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  292. /// ValueVT (ISD::AssertSext).
  293. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  294. const SDValue *Parts, unsigned NumParts,
  295. MVT PartVT, EVT ValueVT, const Value *V,
  296. Optional<CallingConv::ID> CallConv) {
  297. assert(ValueVT.isVector() && "Not a vector value");
  298. assert(NumParts > 0 && "No parts to assemble!");
  299. const bool IsABIRegCopy = CallConv.hasValue();
  300. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  301. SDValue Val = Parts[0];
  302. // Handle a multi-element vector.
  303. if (NumParts > 1) {
  304. EVT IntermediateVT;
  305. MVT RegisterVT;
  306. unsigned NumIntermediates;
  307. unsigned NumRegs;
  308. if (IsABIRegCopy) {
  309. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  310. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  311. NumIntermediates, RegisterVT);
  312. } else {
  313. NumRegs =
  314. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  315. NumIntermediates, RegisterVT);
  316. }
  317. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  318. NumParts = NumRegs; // Silence a compiler warning.
  319. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  320. assert(RegisterVT.getSizeInBits() ==
  321. Parts[0].getSimpleValueType().getSizeInBits() &&
  322. "Part type sizes don't match!");
  323. // Assemble the parts into intermediate operands.
  324. SmallVector<SDValue, 8> Ops(NumIntermediates);
  325. if (NumIntermediates == NumParts) {
  326. // If the register was not expanded, truncate or copy the value,
  327. // as appropriate.
  328. for (unsigned i = 0; i != NumParts; ++i)
  329. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  330. PartVT, IntermediateVT, V, CallConv);
  331. } else if (NumParts > 0) {
  332. // If the intermediate type was expanded, build the intermediate
  333. // operands from the parts.
  334. assert(NumParts % NumIntermediates == 0 &&
  335. "Must expand into a divisible number of parts!");
  336. unsigned Factor = NumParts / NumIntermediates;
  337. for (unsigned i = 0; i != NumIntermediates; ++i)
  338. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  339. PartVT, IntermediateVT, V, CallConv);
  340. }
  341. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  342. // intermediate operands.
  343. EVT BuiltVectorTy =
  344. IntermediateVT.isVector()
  345. ? EVT::getVectorVT(
  346. *DAG.getContext(), IntermediateVT.getScalarType(),
  347. IntermediateVT.getVectorElementCount() * NumParts)
  348. : EVT::getVectorVT(*DAG.getContext(),
  349. IntermediateVT.getScalarType(),
  350. NumIntermediates);
  351. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  352. : ISD::BUILD_VECTOR,
  353. DL, BuiltVectorTy, Ops);
  354. }
  355. // There is now one part, held in Val. Correct it to match ValueVT.
  356. EVT PartEVT = Val.getValueType();
  357. if (PartEVT == ValueVT)
  358. return Val;
  359. if (PartEVT.isVector()) {
  360. // If the element type of the source/dest vectors are the same, but the
  361. // parts vector has more elements than the value vector, then we have a
  362. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  363. // elements we want.
  364. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  365. assert((PartEVT.getVectorElementCount().getKnownMinValue() >
  366. ValueVT.getVectorElementCount().getKnownMinValue()) &&
  367. (PartEVT.getVectorElementCount().isScalable() ==
  368. ValueVT.getVectorElementCount().isScalable()) &&
  369. "Cannot narrow, it would be a lossy transformation");
  370. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  371. DAG.getVectorIdxConstant(0, DL));
  372. }
  373. // Vector/Vector bitcast.
  374. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  375. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  376. assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
  377. "Cannot handle this kind of promotion");
  378. // Promoted vector extract
  379. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  380. }
  381. // Trivial bitcast if the types are the same size and the destination
  382. // vector type is legal.
  383. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  384. TLI.isTypeLegal(ValueVT))
  385. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  386. if (ValueVT.getVectorNumElements() != 1) {
  387. // Certain ABIs require that vectors are passed as integers. For vectors
  388. // are the same size, this is an obvious bitcast.
  389. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  390. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  391. } else if (ValueVT.bitsLT(PartEVT)) {
  392. // Bitcast Val back the original type and extract the corresponding
  393. // vector we want.
  394. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  395. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  396. ValueVT.getVectorElementType(), Elts);
  397. Val = DAG.getBitcast(WiderVecType, Val);
  398. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  399. DAG.getVectorIdxConstant(0, DL));
  400. }
  401. diagnosePossiblyInvalidConstraint(
  402. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  403. return DAG.getUNDEF(ValueVT);
  404. }
  405. // Handle cases such as i8 -> <1 x i1>
  406. EVT ValueSVT = ValueVT.getVectorElementType();
  407. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
  408. if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
  409. Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
  410. else
  411. Val = ValueVT.isFloatingPoint()
  412. ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  413. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  414. }
  415. return DAG.getBuildVector(ValueVT, DL, Val);
  416. }
  417. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  418. SDValue Val, SDValue *Parts, unsigned NumParts,
  419. MVT PartVT, const Value *V,
  420. Optional<CallingConv::ID> CallConv);
  421. /// getCopyToParts - Create a series of nodes that contain the specified value
  422. /// split into legal parts. If the parts contain more bits than Val, then, for
  423. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  424. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  425. SDValue *Parts, unsigned NumParts, MVT PartVT,
  426. const Value *V,
  427. Optional<CallingConv::ID> CallConv = None,
  428. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  429. // Let the target split the parts if it wants to
  430. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  431. if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
  432. CallConv))
  433. return;
  434. EVT ValueVT = Val.getValueType();
  435. // Handle the vector case separately.
  436. if (ValueVT.isVector())
  437. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  438. CallConv);
  439. unsigned PartBits = PartVT.getSizeInBits();
  440. unsigned OrigNumParts = NumParts;
  441. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  442. "Copying to an illegal type!");
  443. if (NumParts == 0)
  444. return;
  445. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  446. EVT PartEVT = PartVT;
  447. if (PartEVT == ValueVT) {
  448. assert(NumParts == 1 && "No-op copy with multiple parts!");
  449. Parts[0] = Val;
  450. return;
  451. }
  452. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  453. // If the parts cover more bits than the value has, promote the value.
  454. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  455. assert(NumParts == 1 && "Do not know what to promote to!");
  456. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  457. } else {
  458. if (ValueVT.isFloatingPoint()) {
  459. // FP values need to be bitcast, then extended if they are being put
  460. // into a larger container.
  461. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  462. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  463. }
  464. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  465. ValueVT.isInteger() &&
  466. "Unknown mismatch!");
  467. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  468. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  469. if (PartVT == MVT::x86mmx)
  470. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  471. }
  472. } else if (PartBits == ValueVT.getSizeInBits()) {
  473. // Different types of the same size.
  474. assert(NumParts == 1 && PartEVT != ValueVT);
  475. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  476. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  477. // If the parts cover less bits than value has, truncate the value.
  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(ISD::TRUNCATE, DL, ValueVT, Val);
  483. if (PartVT == MVT::x86mmx)
  484. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  485. }
  486. // The value may have changed - recompute ValueVT.
  487. ValueVT = Val.getValueType();
  488. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  489. "Failed to tile the value with PartVT!");
  490. if (NumParts == 1) {
  491. if (PartEVT != ValueVT) {
  492. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  493. "scalar-to-vector conversion failed");
  494. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  495. }
  496. Parts[0] = Val;
  497. return;
  498. }
  499. // Expand the value into multiple parts.
  500. if (NumParts & (NumParts - 1)) {
  501. // The number of parts is not a power of 2. Split off and copy the tail.
  502. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  503. "Do not know what to expand to!");
  504. unsigned RoundParts = 1 << Log2_32(NumParts);
  505. unsigned RoundBits = RoundParts * PartBits;
  506. unsigned OddParts = NumParts - RoundParts;
  507. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  508. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  509. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  510. CallConv);
  511. if (DAG.getDataLayout().isBigEndian())
  512. // The odd parts were reversed by getCopyToParts - unreverse them.
  513. std::reverse(Parts + RoundParts, Parts + NumParts);
  514. NumParts = RoundParts;
  515. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  516. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  517. }
  518. // The number of parts is a power of 2. Repeatedly bisect the value using
  519. // EXTRACT_ELEMENT.
  520. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  521. EVT::getIntegerVT(*DAG.getContext(),
  522. ValueVT.getSizeInBits()),
  523. Val);
  524. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  525. for (unsigned i = 0; i < NumParts; i += StepSize) {
  526. unsigned ThisBits = StepSize * PartBits / 2;
  527. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  528. SDValue &Part0 = Parts[i];
  529. SDValue &Part1 = Parts[i+StepSize/2];
  530. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  531. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  532. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  533. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  534. if (ThisBits == PartBits && ThisVT != PartVT) {
  535. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  536. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  537. }
  538. }
  539. }
  540. if (DAG.getDataLayout().isBigEndian())
  541. std::reverse(Parts, Parts + OrigNumParts);
  542. }
  543. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  544. SDValue Val, const SDLoc &DL, EVT PartVT) {
  545. if (!PartVT.isFixedLengthVector())
  546. return SDValue();
  547. EVT ValueVT = Val.getValueType();
  548. unsigned PartNumElts = PartVT.getVectorNumElements();
  549. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  550. if (PartNumElts > ValueNumElts &&
  551. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  552. EVT ElementVT = PartVT.getVectorElementType();
  553. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  554. // undef elements.
  555. SmallVector<SDValue, 16> Ops;
  556. DAG.ExtractVectorElements(Val, Ops);
  557. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  558. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  559. Ops.push_back(EltUndef);
  560. // FIXME: Use CONCAT for 2x -> 4x.
  561. return DAG.getBuildVector(PartVT, DL, Ops);
  562. }
  563. return SDValue();
  564. }
  565. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  566. /// value split into legal parts.
  567. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  568. SDValue Val, SDValue *Parts, unsigned NumParts,
  569. MVT PartVT, const Value *V,
  570. Optional<CallingConv::ID> CallConv) {
  571. EVT ValueVT = Val.getValueType();
  572. assert(ValueVT.isVector() && "Not a vector");
  573. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  574. const bool IsABIRegCopy = CallConv.hasValue();
  575. if (NumParts == 1) {
  576. EVT PartEVT = PartVT;
  577. if (PartEVT == ValueVT) {
  578. // Nothing to do.
  579. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  580. // Bitconvert vector->vector case.
  581. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  582. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  583. Val = Widened;
  584. } else if (PartVT.isVector() &&
  585. PartEVT.getVectorElementType().bitsGE(
  586. ValueVT.getVectorElementType()) &&
  587. PartEVT.getVectorElementCount() ==
  588. ValueVT.getVectorElementCount()) {
  589. // Promoted vector extract
  590. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  591. } else {
  592. if (ValueVT.getVectorElementCount().isScalar()) {
  593. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  594. DAG.getVectorIdxConstant(0, DL));
  595. } else {
  596. uint64_t ValueSize = ValueVT.getFixedSizeInBits();
  597. assert(PartVT.getFixedSizeInBits() > ValueSize &&
  598. "lossy conversion of vector to scalar type");
  599. EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
  600. Val = DAG.getBitcast(IntermediateType, Val);
  601. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  602. }
  603. }
  604. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  605. Parts[0] = Val;
  606. return;
  607. }
  608. // Handle a multi-element vector.
  609. EVT IntermediateVT;
  610. MVT RegisterVT;
  611. unsigned NumIntermediates;
  612. unsigned NumRegs;
  613. if (IsABIRegCopy) {
  614. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  615. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  616. NumIntermediates, RegisterVT);
  617. } else {
  618. NumRegs =
  619. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  620. NumIntermediates, RegisterVT);
  621. }
  622. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  623. NumParts = NumRegs; // Silence a compiler warning.
  624. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  625. assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
  626. "Mixing scalable and fixed vectors when copying in parts");
  627. Optional<ElementCount> DestEltCnt;
  628. if (IntermediateVT.isVector())
  629. DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
  630. else
  631. DestEltCnt = ElementCount::getFixed(NumIntermediates);
  632. EVT BuiltVectorTy = EVT::getVectorVT(
  633. *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
  634. if (ValueVT != BuiltVectorTy) {
  635. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  636. Val = Widened;
  637. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  638. }
  639. // Split the vector into intermediate operands.
  640. SmallVector<SDValue, 8> Ops(NumIntermediates);
  641. for (unsigned i = 0; i != NumIntermediates; ++i) {
  642. if (IntermediateVT.isVector()) {
  643. // This does something sensible for scalable vectors - see the
  644. // definition of EXTRACT_SUBVECTOR for further details.
  645. unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
  646. Ops[i] =
  647. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  648. DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
  649. } else {
  650. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  651. DAG.getVectorIdxConstant(i, DL));
  652. }
  653. }
  654. // Split the intermediate operands into legal parts.
  655. if (NumParts == NumIntermediates) {
  656. // If the register was not expanded, promote or copy the value,
  657. // as appropriate.
  658. for (unsigned i = 0; i != NumParts; ++i)
  659. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  660. } else if (NumParts > 0) {
  661. // If the intermediate type was expanded, split each the value into
  662. // legal parts.
  663. assert(NumIntermediates != 0 && "division by zero");
  664. assert(NumParts % NumIntermediates == 0 &&
  665. "Must expand into a divisible number of parts!");
  666. unsigned Factor = NumParts / NumIntermediates;
  667. for (unsigned i = 0; i != NumIntermediates; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  669. CallConv);
  670. }
  671. }
  672. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  673. EVT valuevt, Optional<CallingConv::ID> CC)
  674. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  675. RegCount(1, regs.size()), CallConv(CC) {}
  676. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  677. const DataLayout &DL, unsigned Reg, Type *Ty,
  678. Optional<CallingConv::ID> CC) {
  679. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  680. CallConv = CC;
  681. for (EVT ValueVT : ValueVTs) {
  682. unsigned NumRegs =
  683. isABIMangled()
  684. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  685. : TLI.getNumRegisters(Context, ValueVT);
  686. MVT RegisterVT =
  687. isABIMangled()
  688. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  689. : TLI.getRegisterType(Context, ValueVT);
  690. for (unsigned i = 0; i != NumRegs; ++i)
  691. Regs.push_back(Reg + i);
  692. RegVTs.push_back(RegisterVT);
  693. RegCount.push_back(NumRegs);
  694. Reg += NumRegs;
  695. }
  696. }
  697. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  698. FunctionLoweringInfo &FuncInfo,
  699. const SDLoc &dl, SDValue &Chain,
  700. SDValue *Flag, const Value *V) const {
  701. // A Value with type {} or [0 x %t] needs no registers.
  702. if (ValueVTs.empty())
  703. return SDValue();
  704. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  705. // Assemble the legal parts into the final values.
  706. SmallVector<SDValue, 4> Values(ValueVTs.size());
  707. SmallVector<SDValue, 8> Parts;
  708. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  709. // Copy the legal parts from the registers.
  710. EVT ValueVT = ValueVTs[Value];
  711. unsigned NumRegs = RegCount[Value];
  712. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  713. *DAG.getContext(),
  714. CallConv.getValue(), RegVTs[Value])
  715. : RegVTs[Value];
  716. Parts.resize(NumRegs);
  717. for (unsigned i = 0; i != NumRegs; ++i) {
  718. SDValue P;
  719. if (!Flag) {
  720. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  721. } else {
  722. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  723. *Flag = P.getValue(2);
  724. }
  725. Chain = P.getValue(1);
  726. Parts[i] = P;
  727. // If the source register was virtual and if we know something about it,
  728. // add an assert node.
  729. if (!Register::isVirtualRegister(Regs[Part + i]) ||
  730. !RegisterVT.isInteger())
  731. continue;
  732. const FunctionLoweringInfo::LiveOutInfo *LOI =
  733. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  734. if (!LOI)
  735. continue;
  736. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  737. unsigned NumSignBits = LOI->NumSignBits;
  738. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  739. if (NumZeroBits == RegSize) {
  740. // The current value is a zero.
  741. // Explicitly express that as it would be easier for
  742. // optimizations to kick in.
  743. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  744. continue;
  745. }
  746. // FIXME: We capture more information than the dag can represent. For
  747. // now, just use the tightest assertzext/assertsext possible.
  748. bool isSExt;
  749. EVT FromVT(MVT::Other);
  750. if (NumZeroBits) {
  751. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  752. isSExt = false;
  753. } else if (NumSignBits > 1) {
  754. FromVT =
  755. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  756. isSExt = true;
  757. } else {
  758. continue;
  759. }
  760. // Add an assertion node.
  761. assert(FromVT != MVT::Other);
  762. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  763. RegisterVT, P, DAG.getValueType(FromVT));
  764. }
  765. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  766. RegisterVT, ValueVT, V, CallConv);
  767. Part += NumRegs;
  768. Parts.clear();
  769. }
  770. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  771. }
  772. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  773. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  774. const Value *V,
  775. ISD::NodeType PreferredExtendType) const {
  776. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  777. ISD::NodeType ExtendKind = PreferredExtendType;
  778. // Get the list of the values's legal parts.
  779. unsigned NumRegs = Regs.size();
  780. SmallVector<SDValue, 8> Parts(NumRegs);
  781. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  782. unsigned NumParts = RegCount[Value];
  783. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  784. *DAG.getContext(),
  785. CallConv.getValue(), RegVTs[Value])
  786. : RegVTs[Value];
  787. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  788. ExtendKind = ISD::ZERO_EXTEND;
  789. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  790. NumParts, RegisterVT, V, CallConv, ExtendKind);
  791. Part += NumParts;
  792. }
  793. // Copy the parts into the registers.
  794. SmallVector<SDValue, 8> Chains(NumRegs);
  795. for (unsigned i = 0; i != NumRegs; ++i) {
  796. SDValue Part;
  797. if (!Flag) {
  798. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  799. } else {
  800. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  801. *Flag = Part.getValue(1);
  802. }
  803. Chains[i] = Part.getValue(0);
  804. }
  805. if (NumRegs == 1 || Flag)
  806. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  807. // flagged to it. That is the CopyToReg nodes and the user are considered
  808. // a single scheduling unit. If we create a TokenFactor and return it as
  809. // chain, then the TokenFactor is both a predecessor (operand) of the
  810. // user as well as a successor (the TF operands are flagged to the user).
  811. // c1, f1 = CopyToReg
  812. // c2, f2 = CopyToReg
  813. // c3 = TokenFactor c1, c2
  814. // ...
  815. // = op c3, ..., f2
  816. Chain = Chains[NumRegs-1];
  817. else
  818. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  819. }
  820. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  821. unsigned MatchingIdx, const SDLoc &dl,
  822. SelectionDAG &DAG,
  823. std::vector<SDValue> &Ops) const {
  824. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  825. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  826. if (HasMatching)
  827. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  828. else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
  829. // Put the register class of the virtual registers in the flag word. That
  830. // way, later passes can recompute register class constraints for inline
  831. // assembly as well as normal instructions.
  832. // Don't do this for tied operands that can use the regclass information
  833. // from the def.
  834. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  835. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  836. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  837. }
  838. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  839. Ops.push_back(Res);
  840. if (Code == InlineAsm::Kind_Clobber) {
  841. // Clobbers should always have a 1:1 mapping with registers, and may
  842. // reference registers that have illegal (e.g. vector) types. Hence, we
  843. // shouldn't try to apply any sort of splitting logic to them.
  844. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  845. "No 1:1 mapping from clobbers to regs?");
  846. Register SP = TLI.getStackPointerRegisterToSaveRestore();
  847. (void)SP;
  848. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  849. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  850. assert(
  851. (Regs[I] != SP ||
  852. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  853. "If we clobbered the stack pointer, MFI should know about it.");
  854. }
  855. return;
  856. }
  857. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  858. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  859. MVT RegisterVT = RegVTs[Value];
  860. for (unsigned i = 0; i != NumRegs; ++i) {
  861. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  862. unsigned TheReg = Regs[Reg++];
  863. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  864. }
  865. }
  866. }
  867. SmallVector<std::pair<unsigned, TypeSize>, 4>
  868. RegsForValue::getRegsAndSizes() const {
  869. SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
  870. unsigned I = 0;
  871. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  872. unsigned RegCount = std::get<0>(CountAndVT);
  873. MVT RegisterVT = std::get<1>(CountAndVT);
  874. TypeSize RegisterSize = RegisterVT.getSizeInBits();
  875. for (unsigned E = I + RegCount; I != E; ++I)
  876. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  877. }
  878. return OutVec;
  879. }
  880. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  881. const TargetLibraryInfo *li) {
  882. AA = aa;
  883. GFI = gfi;
  884. LibInfo = li;
  885. DL = &DAG.getDataLayout();
  886. Context = DAG.getContext();
  887. LPadToCallSiteMap.clear();
  888. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  889. }
  890. void SelectionDAGBuilder::clear() {
  891. NodeMap.clear();
  892. UnusedArgNodeMap.clear();
  893. PendingLoads.clear();
  894. PendingExports.clear();
  895. PendingConstrainedFP.clear();
  896. PendingConstrainedFPStrict.clear();
  897. CurInst = nullptr;
  898. HasTailCall = false;
  899. SDNodeOrder = LowestSDNodeOrder;
  900. StatepointLowering.clear();
  901. }
  902. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  903. DanglingDebugInfoMap.clear();
  904. }
  905. // Update DAG root to include dependencies on Pending chains.
  906. SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
  907. SDValue Root = DAG.getRoot();
  908. if (Pending.empty())
  909. return Root;
  910. // Add current root to PendingChains, unless we already indirectly
  911. // depend on it.
  912. if (Root.getOpcode() != ISD::EntryToken) {
  913. unsigned i = 0, e = Pending.size();
  914. for (; i != e; ++i) {
  915. assert(Pending[i].getNode()->getNumOperands() > 1);
  916. if (Pending[i].getNode()->getOperand(0) == Root)
  917. break; // Don't add the root if we already indirectly depend on it.
  918. }
  919. if (i == e)
  920. Pending.push_back(Root);
  921. }
  922. if (Pending.size() == 1)
  923. Root = Pending[0];
  924. else
  925. Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
  926. DAG.setRoot(Root);
  927. Pending.clear();
  928. return Root;
  929. }
  930. SDValue SelectionDAGBuilder::getMemoryRoot() {
  931. return updateRoot(PendingLoads);
  932. }
  933. SDValue SelectionDAGBuilder::getRoot() {
  934. // Chain up all pending constrained intrinsics together with all
  935. // pending loads, by simply appending them to PendingLoads and
  936. // then calling getMemoryRoot().
  937. PendingLoads.reserve(PendingLoads.size() +
  938. PendingConstrainedFP.size() +
  939. PendingConstrainedFPStrict.size());
  940. PendingLoads.append(PendingConstrainedFP.begin(),
  941. PendingConstrainedFP.end());
  942. PendingLoads.append(PendingConstrainedFPStrict.begin(),
  943. PendingConstrainedFPStrict.end());
  944. PendingConstrainedFP.clear();
  945. PendingConstrainedFPStrict.clear();
  946. return getMemoryRoot();
  947. }
  948. SDValue SelectionDAGBuilder::getControlRoot() {
  949. // We need to emit pending fpexcept.strict constrained intrinsics,
  950. // so append them to the PendingExports list.
  951. PendingExports.append(PendingConstrainedFPStrict.begin(),
  952. PendingConstrainedFPStrict.end());
  953. PendingConstrainedFPStrict.clear();
  954. return updateRoot(PendingExports);
  955. }
  956. void SelectionDAGBuilder::visit(const Instruction &I) {
  957. // Set up outgoing PHI node register values before emitting the terminator.
  958. if (I.isTerminator()) {
  959. HandlePHINodesInSuccessorBlocks(I.getParent());
  960. }
  961. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  962. if (!isa<DbgInfoIntrinsic>(I))
  963. ++SDNodeOrder;
  964. CurInst = &I;
  965. visit(I.getOpcode(), I);
  966. if (!I.isTerminator() && !HasTailCall &&
  967. !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
  968. CopyToExportRegsIfNeeded(&I);
  969. CurInst = nullptr;
  970. }
  971. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  972. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  973. }
  974. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  975. // Note: this doesn't use InstVisitor, because it has to work with
  976. // ConstantExpr's in addition to instructions.
  977. switch (Opcode) {
  978. default: llvm_unreachable("Unknown instruction type encountered!");
  979. // Build the switch statement using the Instruction.def file.
  980. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  981. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  982. #include "llvm/IR/Instruction.def"
  983. }
  984. }
  985. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  986. const DIExpression *Expr) {
  987. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  988. const DbgValueInst *DI = DDI.getDI();
  989. DIVariable *DanglingVariable = DI->getVariable();
  990. DIExpression *DanglingExpr = DI->getExpression();
  991. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  992. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  993. return true;
  994. }
  995. return false;
  996. };
  997. for (auto &DDIMI : DanglingDebugInfoMap) {
  998. DanglingDebugInfoVector &DDIV = DDIMI.second;
  999. // If debug info is to be dropped, run it through final checks to see
  1000. // whether it can be salvaged.
  1001. for (auto &DDI : DDIV)
  1002. if (isMatchingDbgValue(DDI))
  1003. salvageUnresolvedDbgValue(DDI);
  1004. erase_if(DDIV, isMatchingDbgValue);
  1005. }
  1006. }
  1007. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1008. // generate the debug data structures now that we've seen its definition.
  1009. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1010. SDValue Val) {
  1011. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1012. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1013. return;
  1014. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1015. for (auto &DDI : DDIV) {
  1016. const DbgValueInst *DI = DDI.getDI();
  1017. assert(DI && "Ill-formed DanglingDebugInfo");
  1018. DebugLoc dl = DDI.getdl();
  1019. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1020. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1021. DILocalVariable *Variable = DI->getVariable();
  1022. DIExpression *Expr = DI->getExpression();
  1023. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1024. "Expected inlined-at fields to agree");
  1025. SDDbgValue *SDV;
  1026. if (Val.getNode()) {
  1027. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1028. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1029. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1030. // in the first place we should not be more successful here). Unless we
  1031. // have some test case that prove this to be correct we should avoid
  1032. // calling EmitFuncArgumentDbgValue here.
  1033. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1034. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1035. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1036. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1037. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1038. // inserted after the definition of Val when emitting the instructions
  1039. // after ISel. An alternative could be to teach
  1040. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1041. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1042. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1043. << ValSDNodeOrder << "\n");
  1044. SDV = getDbgValue(Val, Variable, Expr, dl,
  1045. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1046. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1047. } else
  1048. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1049. << "in EmitFuncArgumentDbgValue\n");
  1050. } else {
  1051. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1052. auto Undef =
  1053. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1054. auto SDV =
  1055. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1056. DAG.AddDbgValue(SDV, nullptr, false);
  1057. }
  1058. }
  1059. DDIV.clear();
  1060. }
  1061. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1062. Value *V = DDI.getDI()->getValue();
  1063. DILocalVariable *Var = DDI.getDI()->getVariable();
  1064. DIExpression *Expr = DDI.getDI()->getExpression();
  1065. DebugLoc DL = DDI.getdl();
  1066. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1067. unsigned SDOrder = DDI.getSDNodeOrder();
  1068. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1069. // that DW_OP_stack_value is desired.
  1070. assert(isa<DbgValueInst>(DDI.getDI()));
  1071. bool StackValue = true;
  1072. // Can this Value can be encoded without any further work?
  1073. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1074. return;
  1075. // Attempt to salvage back through as many instructions as possible. Bail if
  1076. // a non-instruction is seen, such as a constant expression or global
  1077. // variable. FIXME: Further work could recover those too.
  1078. while (isa<Instruction>(V)) {
  1079. Instruction &VAsInst = *cast<Instruction>(V);
  1080. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1081. // If we cannot salvage any further, and haven't yet found a suitable debug
  1082. // expression, bail out.
  1083. if (!NewExpr)
  1084. break;
  1085. // New value and expr now represent this debuginfo.
  1086. V = VAsInst.getOperand(0);
  1087. Expr = NewExpr;
  1088. // Some kind of simplification occurred: check whether the operand of the
  1089. // salvaged debug expression can be encoded in this DAG.
  1090. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1091. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1092. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1093. return;
  1094. }
  1095. }
  1096. // This was the final opportunity to salvage this debug information, and it
  1097. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1098. // any earlier variable location.
  1099. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1100. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1101. DAG.AddDbgValue(SDV, nullptr, false);
  1102. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1103. << "\n");
  1104. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1105. << "\n");
  1106. }
  1107. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1108. DIExpression *Expr, DebugLoc dl,
  1109. DebugLoc InstDL, unsigned Order) {
  1110. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1111. SDDbgValue *SDV;
  1112. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1113. isa<ConstantPointerNull>(V)) {
  1114. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1115. DAG.AddDbgValue(SDV, nullptr, false);
  1116. return true;
  1117. }
  1118. // If the Value is a frame index, we can create a FrameIndex debug value
  1119. // without relying on the DAG at all.
  1120. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1121. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1122. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1123. auto SDV =
  1124. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1125. /*IsIndirect*/ false, dl, SDNodeOrder);
  1126. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1127. // is still available even if the SDNode gets optimized out.
  1128. DAG.AddDbgValue(SDV, nullptr, false);
  1129. return true;
  1130. }
  1131. }
  1132. // Do not use getValue() in here; we don't want to generate code at
  1133. // this point if it hasn't been done yet.
  1134. SDValue N = NodeMap[V];
  1135. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1136. N = UnusedArgNodeMap[V];
  1137. if (N.getNode()) {
  1138. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1139. return true;
  1140. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1141. DAG.AddDbgValue(SDV, N.getNode(), false);
  1142. return true;
  1143. }
  1144. // Special rules apply for the first dbg.values of parameter variables in a
  1145. // function. Identify them by the fact they reference Argument Values, that
  1146. // they're parameters, and they are parameters of the current function. We
  1147. // need to let them dangle until they get an SDNode.
  1148. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1149. !InstDL.getInlinedAt();
  1150. if (!IsParamOfFunc) {
  1151. // The value is not used in this block yet (or it would have an SDNode).
  1152. // We still want the value to appear for the user if possible -- if it has
  1153. // an associated VReg, we can refer to that instead.
  1154. auto VMI = FuncInfo.ValueMap.find(V);
  1155. if (VMI != FuncInfo.ValueMap.end()) {
  1156. unsigned Reg = VMI->second;
  1157. // If this is a PHI node, it may be split up into several MI PHI nodes
  1158. // (in FunctionLoweringInfo::set).
  1159. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1160. V->getType(), None);
  1161. if (RFV.occupiesMultipleRegs()) {
  1162. unsigned Offset = 0;
  1163. unsigned BitsToDescribe = 0;
  1164. if (auto VarSize = Var->getSizeInBits())
  1165. BitsToDescribe = *VarSize;
  1166. if (auto Fragment = Expr->getFragmentInfo())
  1167. BitsToDescribe = Fragment->SizeInBits;
  1168. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1169. unsigned RegisterSize = RegAndSize.second;
  1170. // Bail out if all bits are described already.
  1171. if (Offset >= BitsToDescribe)
  1172. break;
  1173. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1174. ? BitsToDescribe - Offset
  1175. : RegisterSize;
  1176. auto FragmentExpr = DIExpression::createFragmentExpression(
  1177. Expr, Offset, FragmentSize);
  1178. if (!FragmentExpr)
  1179. continue;
  1180. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1181. false, dl, SDNodeOrder);
  1182. DAG.AddDbgValue(SDV, nullptr, false);
  1183. Offset += RegisterSize;
  1184. }
  1185. } else {
  1186. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1187. DAG.AddDbgValue(SDV, nullptr, false);
  1188. }
  1189. return true;
  1190. }
  1191. }
  1192. return false;
  1193. }
  1194. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1195. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1196. for (auto &Pair : DanglingDebugInfoMap)
  1197. for (auto &DDI : Pair.second)
  1198. salvageUnresolvedDbgValue(DDI);
  1199. clearDanglingDebugInfo();
  1200. }
  1201. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1202. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1203. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1204. DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
  1205. SDValue Result;
  1206. if (It != FuncInfo.ValueMap.end()) {
  1207. Register InReg = It->second;
  1208. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1209. DAG.getDataLayout(), InReg, Ty,
  1210. None); // This is not an ABI copy.
  1211. SDValue Chain = DAG.getEntryNode();
  1212. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1213. V);
  1214. resolveDanglingDebugInfo(V, Result);
  1215. }
  1216. return Result;
  1217. }
  1218. /// getValue - Return an SDValue for the given Value.
  1219. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1220. // If we already have an SDValue for this value, use it. It's important
  1221. // to do this first, so that we don't create a CopyFromReg if we already
  1222. // have a regular SDValue.
  1223. SDValue &N = NodeMap[V];
  1224. if (N.getNode()) return N;
  1225. // If there's a virtual register allocated and initialized for this
  1226. // value, use it.
  1227. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1228. return copyFromReg;
  1229. // Otherwise create a new SDValue and remember it.
  1230. SDValue Val = getValueImpl(V);
  1231. NodeMap[V] = Val;
  1232. resolveDanglingDebugInfo(V, Val);
  1233. return Val;
  1234. }
  1235. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1236. /// don't look in FuncInfo.ValueMap for a virtual register.
  1237. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1238. // If we already have an SDValue for this value, use it.
  1239. SDValue &N = NodeMap[V];
  1240. if (N.getNode()) {
  1241. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1242. // Remove the debug location from the node as the node is about to be used
  1243. // in a location which may differ from the original debug location. This
  1244. // is relevant to Constant and ConstantFP nodes because they can appear
  1245. // as constant expressions inside PHI nodes.
  1246. N->setDebugLoc(DebugLoc());
  1247. }
  1248. return N;
  1249. }
  1250. // Otherwise create a new SDValue and remember it.
  1251. SDValue Val = getValueImpl(V);
  1252. NodeMap[V] = Val;
  1253. resolveDanglingDebugInfo(V, Val);
  1254. return Val;
  1255. }
  1256. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1257. /// Create an SDValue for the given value.
  1258. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1259. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1260. if (const Constant *C = dyn_cast<Constant>(V)) {
  1261. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1262. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1263. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1264. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1265. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1266. if (isa<ConstantPointerNull>(C)) {
  1267. unsigned AS = V->getType()->getPointerAddressSpace();
  1268. return DAG.getConstant(0, getCurSDLoc(),
  1269. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1270. }
  1271. if (match(C, m_VScale(DAG.getDataLayout())))
  1272. return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
  1273. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1274. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1275. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1276. return DAG.getUNDEF(VT);
  1277. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1278. visit(CE->getOpcode(), *CE);
  1279. SDValue N1 = NodeMap[V];
  1280. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1281. return N1;
  1282. }
  1283. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1284. SmallVector<SDValue, 4> Constants;
  1285. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1286. OI != OE; ++OI) {
  1287. SDNode *Val = getValue(*OI).getNode();
  1288. // If the operand is an empty aggregate, there are no values.
  1289. if (!Val) continue;
  1290. // Add each leaf value from the operand to the Constants list
  1291. // to form a flattened list of all the values.
  1292. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1293. Constants.push_back(SDValue(Val, i));
  1294. }
  1295. return DAG.getMergeValues(Constants, getCurSDLoc());
  1296. }
  1297. if (const ConstantDataSequential *CDS =
  1298. dyn_cast<ConstantDataSequential>(C)) {
  1299. SmallVector<SDValue, 4> Ops;
  1300. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1301. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1302. // Add each leaf value from the operand to the Constants list
  1303. // to form a flattened list of all the values.
  1304. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1305. Ops.push_back(SDValue(Val, i));
  1306. }
  1307. if (isa<ArrayType>(CDS->getType()))
  1308. return DAG.getMergeValues(Ops, getCurSDLoc());
  1309. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1310. }
  1311. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1312. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1313. "Unknown struct or array constant!");
  1314. SmallVector<EVT, 4> ValueVTs;
  1315. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1316. unsigned NumElts = ValueVTs.size();
  1317. if (NumElts == 0)
  1318. return SDValue(); // empty struct
  1319. SmallVector<SDValue, 4> Constants(NumElts);
  1320. for (unsigned i = 0; i != NumElts; ++i) {
  1321. EVT EltVT = ValueVTs[i];
  1322. if (isa<UndefValue>(C))
  1323. Constants[i] = DAG.getUNDEF(EltVT);
  1324. else if (EltVT.isFloatingPoint())
  1325. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1326. else
  1327. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1328. }
  1329. return DAG.getMergeValues(Constants, getCurSDLoc());
  1330. }
  1331. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1332. return DAG.getBlockAddress(BA, VT);
  1333. if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
  1334. return getValue(Equiv->getGlobalValue());
  1335. VectorType *VecTy = cast<VectorType>(V->getType());
  1336. // Now that we know the number and type of the elements, get that number of
  1337. // elements into the Ops array based on what kind of constant it is.
  1338. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1339. SmallVector<SDValue, 16> Ops;
  1340. unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
  1341. for (unsigned i = 0; i != NumElements; ++i)
  1342. Ops.push_back(getValue(CV->getOperand(i)));
  1343. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1344. } else if (isa<ConstantAggregateZero>(C)) {
  1345. EVT EltVT =
  1346. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1347. SDValue Op;
  1348. if (EltVT.isFloatingPoint())
  1349. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1350. else
  1351. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1352. if (isa<ScalableVectorType>(VecTy))
  1353. return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
  1354. else {
  1355. SmallVector<SDValue, 16> Ops;
  1356. Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
  1357. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1358. }
  1359. }
  1360. llvm_unreachable("Unknown vector constant");
  1361. }
  1362. // If this is a static alloca, generate it as the frameindex instead of
  1363. // computation.
  1364. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1365. DenseMap<const AllocaInst*, int>::iterator SI =
  1366. FuncInfo.StaticAllocaMap.find(AI);
  1367. if (SI != FuncInfo.StaticAllocaMap.end())
  1368. return DAG.getFrameIndex(SI->second,
  1369. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1370. }
  1371. // If this is an instruction which fast-isel has deferred, select it now.
  1372. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1373. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1374. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1375. Inst->getType(), None);
  1376. SDValue Chain = DAG.getEntryNode();
  1377. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1378. }
  1379. if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
  1380. return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
  1381. }
  1382. llvm_unreachable("Can't get register for value!");
  1383. }
  1384. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1385. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1386. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1387. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1388. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1389. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1390. if (!IsSEH)
  1391. CatchPadMBB->setIsEHScopeEntry();
  1392. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1393. if (IsMSVCCXX || IsCoreCLR)
  1394. CatchPadMBB->setIsEHFuncletEntry();
  1395. }
  1396. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1397. // Update machine-CFG edge.
  1398. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1399. FuncInfo.MBB->addSuccessor(TargetMBB);
  1400. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1401. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1402. if (IsSEH) {
  1403. // If this is not a fall-through branch or optimizations are switched off,
  1404. // emit the branch.
  1405. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1406. TM.getOptLevel() == CodeGenOpt::None)
  1407. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1408. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1409. return;
  1410. }
  1411. // Figure out the funclet membership for the catchret's successor.
  1412. // This will be used by the FuncletLayout pass to determine how to order the
  1413. // BB's.
  1414. // A 'catchret' returns to the outer scope's color.
  1415. Value *ParentPad = I.getCatchSwitchParentPad();
  1416. const BasicBlock *SuccessorColor;
  1417. if (isa<ConstantTokenNone>(ParentPad))
  1418. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1419. else
  1420. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1421. assert(SuccessorColor && "No parent funclet for catchret!");
  1422. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1423. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1424. // Create the terminator node.
  1425. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1426. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1427. DAG.getBasicBlock(SuccessorColorMBB));
  1428. DAG.setRoot(Ret);
  1429. }
  1430. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1431. // Don't emit any special code for the cleanuppad instruction. It just marks
  1432. // the start of an EH scope/funclet.
  1433. FuncInfo.MBB->setIsEHScopeEntry();
  1434. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1435. if (Pers != EHPersonality::Wasm_CXX) {
  1436. FuncInfo.MBB->setIsEHFuncletEntry();
  1437. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1438. }
  1439. }
  1440. // In wasm EH, even though a catchpad may not catch an exception if a tag does
  1441. // not match, it is OK to add only the first unwind destination catchpad to the
  1442. // successors, because there will be at least one invoke instruction within the
  1443. // catch scope that points to the next unwind destination, if one exists, so
  1444. // CFGSort cannot mess up with BB sorting order.
  1445. // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
  1446. // call within them, and catchpads only consisting of 'catch (...)' have a
  1447. // '__cxa_end_catch' call within them, both of which generate invokes in case
  1448. // the next unwind destination exists, i.e., the next unwind destination is not
  1449. // the caller.)
  1450. //
  1451. // Having at most one EH pad successor is also simpler and helps later
  1452. // transformations.
  1453. //
  1454. // For example,
  1455. // current:
  1456. // invoke void @foo to ... unwind label %catch.dispatch
  1457. // catch.dispatch:
  1458. // %0 = catchswitch within ... [label %catch.start] unwind label %next
  1459. // catch.start:
  1460. // ...
  1461. // ... in this BB or some other child BB dominated by this BB there will be an
  1462. // invoke that points to 'next' BB as an unwind destination
  1463. //
  1464. // next: ; We don't need to add this to 'current' BB's successor
  1465. // ...
  1466. static void findWasmUnwindDestinations(
  1467. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1468. BranchProbability Prob,
  1469. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1470. &UnwindDests) {
  1471. while (EHPadBB) {
  1472. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1473. if (isa<CleanupPadInst>(Pad)) {
  1474. // Stop on cleanup pads.
  1475. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1476. UnwindDests.back().first->setIsEHScopeEntry();
  1477. break;
  1478. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1479. // Add the catchpad handlers to the possible destinations. We don't
  1480. // continue to the unwind destination of the catchswitch for wasm.
  1481. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1482. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1483. UnwindDests.back().first->setIsEHScopeEntry();
  1484. }
  1485. break;
  1486. } else {
  1487. continue;
  1488. }
  1489. }
  1490. }
  1491. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1492. /// many places it could ultimately go. In the IR, we have a single unwind
  1493. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1494. /// This function skips over imaginary basic blocks that hold catchswitch
  1495. /// instructions, and finds all the "real" machine
  1496. /// basic block destinations. As those destinations may not be successors of
  1497. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1498. /// The passed-in Prob is the edge probability to EHPadBB.
  1499. static void findUnwindDestinations(
  1500. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1501. BranchProbability Prob,
  1502. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1503. &UnwindDests) {
  1504. EHPersonality Personality =
  1505. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1506. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1507. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1508. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1509. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1510. if (IsWasmCXX) {
  1511. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1512. assert(UnwindDests.size() <= 1 &&
  1513. "There should be at most one unwind destination for wasm");
  1514. return;
  1515. }
  1516. while (EHPadBB) {
  1517. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1518. BasicBlock *NewEHPadBB = nullptr;
  1519. if (isa<LandingPadInst>(Pad)) {
  1520. // Stop on landingpads. They are not funclets.
  1521. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1522. break;
  1523. } else if (isa<CleanupPadInst>(Pad)) {
  1524. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1525. // personalities.
  1526. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1527. UnwindDests.back().first->setIsEHScopeEntry();
  1528. UnwindDests.back().first->setIsEHFuncletEntry();
  1529. break;
  1530. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1531. // Add the catchpad handlers to the possible destinations.
  1532. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1533. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1534. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1535. if (IsMSVCCXX || IsCoreCLR)
  1536. UnwindDests.back().first->setIsEHFuncletEntry();
  1537. if (!IsSEH)
  1538. UnwindDests.back().first->setIsEHScopeEntry();
  1539. }
  1540. NewEHPadBB = CatchSwitch->getUnwindDest();
  1541. } else {
  1542. continue;
  1543. }
  1544. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1545. if (BPI && NewEHPadBB)
  1546. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1547. EHPadBB = NewEHPadBB;
  1548. }
  1549. }
  1550. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1551. // Update successor info.
  1552. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1553. auto UnwindDest = I.getUnwindDest();
  1554. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1555. BranchProbability UnwindDestProb =
  1556. (BPI && UnwindDest)
  1557. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1558. : BranchProbability::getZero();
  1559. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1560. for (auto &UnwindDest : UnwindDests) {
  1561. UnwindDest.first->setIsEHPad();
  1562. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1563. }
  1564. FuncInfo.MBB->normalizeSuccProbs();
  1565. // Create the terminator node.
  1566. SDValue Ret =
  1567. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1568. DAG.setRoot(Ret);
  1569. }
  1570. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1571. report_fatal_error("visitCatchSwitch not yet implemented!");
  1572. }
  1573. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1574. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1575. auto &DL = DAG.getDataLayout();
  1576. SDValue Chain = getControlRoot();
  1577. SmallVector<ISD::OutputArg, 8> Outs;
  1578. SmallVector<SDValue, 8> OutVals;
  1579. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1580. // lower
  1581. //
  1582. // %val = call <ty> @llvm.experimental.deoptimize()
  1583. // ret <ty> %val
  1584. //
  1585. // differently.
  1586. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1587. LowerDeoptimizingReturn();
  1588. return;
  1589. }
  1590. if (!FuncInfo.CanLowerReturn) {
  1591. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1592. const Function *F = I.getParent()->getParent();
  1593. // Emit a store of the return value through the virtual register.
  1594. // Leave Outs empty so that LowerReturn won't try to load return
  1595. // registers the usual way.
  1596. SmallVector<EVT, 1> PtrValueVTs;
  1597. ComputeValueVTs(TLI, DL,
  1598. F->getReturnType()->getPointerTo(
  1599. DAG.getDataLayout().getAllocaAddrSpace()),
  1600. PtrValueVTs);
  1601. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1602. DemoteReg, PtrValueVTs[0]);
  1603. SDValue RetOp = getValue(I.getOperand(0));
  1604. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1605. SmallVector<uint64_t, 4> Offsets;
  1606. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1607. &Offsets);
  1608. unsigned NumValues = ValueVTs.size();
  1609. SmallVector<SDValue, 4> Chains(NumValues);
  1610. Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
  1611. for (unsigned i = 0; i != NumValues; ++i) {
  1612. // An aggregate return value cannot wrap around the address space, so
  1613. // offsets to its parts don't wrap either.
  1614. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
  1615. TypeSize::Fixed(Offsets[i]));
  1616. SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
  1617. if (MemVTs[i] != ValueVTs[i])
  1618. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1619. Chains[i] = DAG.getStore(
  1620. Chain, getCurSDLoc(), Val,
  1621. // FIXME: better loc info would be nice.
  1622. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
  1623. commonAlignment(BaseAlign, Offsets[i]));
  1624. }
  1625. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1626. MVT::Other, Chains);
  1627. } else if (I.getNumOperands() != 0) {
  1628. SmallVector<EVT, 4> ValueVTs;
  1629. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1630. unsigned NumValues = ValueVTs.size();
  1631. if (NumValues) {
  1632. SDValue RetOp = getValue(I.getOperand(0));
  1633. const Function *F = I.getParent()->getParent();
  1634. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1635. I.getOperand(0)->getType(), F->getCallingConv(),
  1636. /*IsVarArg*/ false);
  1637. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1638. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1639. Attribute::SExt))
  1640. ExtendKind = ISD::SIGN_EXTEND;
  1641. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1642. Attribute::ZExt))
  1643. ExtendKind = ISD::ZERO_EXTEND;
  1644. LLVMContext &Context = F->getContext();
  1645. bool RetInReg = F->getAttributes().hasAttribute(
  1646. AttributeList::ReturnIndex, Attribute::InReg);
  1647. for (unsigned j = 0; j != NumValues; ++j) {
  1648. EVT VT = ValueVTs[j];
  1649. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1650. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1651. CallingConv::ID CC = F->getCallingConv();
  1652. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1653. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1654. SmallVector<SDValue, 4> Parts(NumParts);
  1655. getCopyToParts(DAG, getCurSDLoc(),
  1656. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1657. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1658. // 'inreg' on function refers to return value
  1659. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1660. if (RetInReg)
  1661. Flags.setInReg();
  1662. if (I.getOperand(0)->getType()->isPointerTy()) {
  1663. Flags.setPointer();
  1664. Flags.setPointerAddrSpace(
  1665. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1666. }
  1667. if (NeedsRegBlock) {
  1668. Flags.setInConsecutiveRegs();
  1669. if (j == NumValues - 1)
  1670. Flags.setInConsecutiveRegsLast();
  1671. }
  1672. // Propagate extension type if any
  1673. if (ExtendKind == ISD::SIGN_EXTEND)
  1674. Flags.setSExt();
  1675. else if (ExtendKind == ISD::ZERO_EXTEND)
  1676. Flags.setZExt();
  1677. for (unsigned i = 0; i < NumParts; ++i) {
  1678. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1679. VT, /*isfixed=*/true, 0, 0));
  1680. OutVals.push_back(Parts[i]);
  1681. }
  1682. }
  1683. }
  1684. }
  1685. // Push in swifterror virtual register as the last element of Outs. This makes
  1686. // sure swifterror virtual register will be returned in the swifterror
  1687. // physical register.
  1688. const Function *F = I.getParent()->getParent();
  1689. if (TLI.supportSwiftError() &&
  1690. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1691. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1692. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1693. Flags.setSwiftError();
  1694. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1695. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1696. true /*isfixed*/, 1 /*origidx*/,
  1697. 0 /*partOffs*/));
  1698. // Create SDNode for the swifterror virtual register.
  1699. OutVals.push_back(
  1700. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1701. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1702. EVT(TLI.getPointerTy(DL))));
  1703. }
  1704. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1705. CallingConv::ID CallConv =
  1706. DAG.getMachineFunction().getFunction().getCallingConv();
  1707. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1708. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1709. // Verify that the target's LowerReturn behaved as expected.
  1710. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1711. "LowerReturn didn't return a valid chain!");
  1712. // Update the DAG with the new chain value resulting from return lowering.
  1713. DAG.setRoot(Chain);
  1714. }
  1715. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1716. /// created for it, emit nodes to copy the value into the virtual
  1717. /// registers.
  1718. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1719. // Skip empty types
  1720. if (V->getType()->isEmptyTy())
  1721. return;
  1722. DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
  1723. if (VMI != FuncInfo.ValueMap.end()) {
  1724. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1725. CopyValueToVirtualRegister(V, VMI->second);
  1726. }
  1727. }
  1728. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1729. /// the current basic block, add it to ValueMap now so that we'll get a
  1730. /// CopyTo/FromReg.
  1731. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1732. // No need to export constants.
  1733. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1734. // Already exported?
  1735. if (FuncInfo.isExportedInst(V)) return;
  1736. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1737. CopyValueToVirtualRegister(V, Reg);
  1738. }
  1739. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1740. const BasicBlock *FromBB) {
  1741. // The operands of the setcc have to be in this block. We don't know
  1742. // how to export them from some other block.
  1743. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1744. // Can export from current BB.
  1745. if (VI->getParent() == FromBB)
  1746. return true;
  1747. // Is already exported, noop.
  1748. return FuncInfo.isExportedInst(V);
  1749. }
  1750. // If this is an argument, we can export it if the BB is the entry block or
  1751. // if it is already exported.
  1752. if (isa<Argument>(V)) {
  1753. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1754. return true;
  1755. // Otherwise, can only export this if it is already exported.
  1756. return FuncInfo.isExportedInst(V);
  1757. }
  1758. // Otherwise, constants can always be exported.
  1759. return true;
  1760. }
  1761. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1762. BranchProbability
  1763. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1764. const MachineBasicBlock *Dst) const {
  1765. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1766. const BasicBlock *SrcBB = Src->getBasicBlock();
  1767. const BasicBlock *DstBB = Dst->getBasicBlock();
  1768. if (!BPI) {
  1769. // If BPI is not available, set the default probability as 1 / N, where N is
  1770. // the number of successors.
  1771. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1772. return BranchProbability(1, SuccSize);
  1773. }
  1774. return BPI->getEdgeProbability(SrcBB, DstBB);
  1775. }
  1776. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1777. MachineBasicBlock *Dst,
  1778. BranchProbability Prob) {
  1779. if (!FuncInfo.BPI)
  1780. Src->addSuccessorWithoutProb(Dst);
  1781. else {
  1782. if (Prob.isUnknown())
  1783. Prob = getEdgeProbability(Src, Dst);
  1784. Src->addSuccessor(Dst, Prob);
  1785. }
  1786. }
  1787. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1788. if (const Instruction *I = dyn_cast<Instruction>(V))
  1789. return I->getParent() == BB;
  1790. return true;
  1791. }
  1792. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1793. /// This function emits a branch and is used at the leaves of an OR or an
  1794. /// AND operator tree.
  1795. void
  1796. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1797. MachineBasicBlock *TBB,
  1798. MachineBasicBlock *FBB,
  1799. MachineBasicBlock *CurBB,
  1800. MachineBasicBlock *SwitchBB,
  1801. BranchProbability TProb,
  1802. BranchProbability FProb,
  1803. bool InvertCond) {
  1804. const BasicBlock *BB = CurBB->getBasicBlock();
  1805. // If the leaf of the tree is a comparison, merge the condition into
  1806. // the caseblock.
  1807. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1808. // The operands of the cmp have to be in this block. We don't know
  1809. // how to export them from some other block. If this is the first block
  1810. // of the sequence, no exporting is needed.
  1811. if (CurBB == SwitchBB ||
  1812. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1813. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1814. ISD::CondCode Condition;
  1815. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1816. ICmpInst::Predicate Pred =
  1817. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1818. Condition = getICmpCondCode(Pred);
  1819. } else {
  1820. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1821. FCmpInst::Predicate Pred =
  1822. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1823. Condition = getFCmpCondCode(Pred);
  1824. if (TM.Options.NoNaNsFPMath)
  1825. Condition = getFCmpCodeWithoutNaN(Condition);
  1826. }
  1827. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1828. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1829. SL->SwitchCases.push_back(CB);
  1830. return;
  1831. }
  1832. }
  1833. // Create a CaseBlock record representing this branch.
  1834. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1835. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1836. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1837. SL->SwitchCases.push_back(CB);
  1838. }
  1839. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1840. MachineBasicBlock *TBB,
  1841. MachineBasicBlock *FBB,
  1842. MachineBasicBlock *CurBB,
  1843. MachineBasicBlock *SwitchBB,
  1844. Instruction::BinaryOps Opc,
  1845. BranchProbability TProb,
  1846. BranchProbability FProb,
  1847. bool InvertCond) {
  1848. // Skip over not part of the tree and remember to invert op and operands at
  1849. // next level.
  1850. Value *NotCond;
  1851. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1852. InBlock(NotCond, CurBB->getBasicBlock())) {
  1853. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1854. !InvertCond);
  1855. return;
  1856. }
  1857. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1858. const Value *BOpOp0, *BOpOp1;
  1859. // Compute the effective opcode for Cond, taking into account whether it needs
  1860. // to be inverted, e.g.
  1861. // and (not (or A, B)), C
  1862. // gets lowered as
  1863. // and (and (not A, not B), C)
  1864. Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
  1865. if (BOp) {
  1866. BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
  1867. ? Instruction::And
  1868. : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
  1869. ? Instruction::Or
  1870. : (Instruction::BinaryOps)0);
  1871. if (InvertCond) {
  1872. if (BOpc == Instruction::And)
  1873. BOpc = Instruction::Or;
  1874. else if (BOpc == Instruction::Or)
  1875. BOpc = Instruction::And;
  1876. }
  1877. }
  1878. // If this node is not part of the or/and tree, emit it as a branch.
  1879. // Note that all nodes in the tree should have same opcode.
  1880. bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
  1881. if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
  1882. !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
  1883. !InBlock(BOpOp1, CurBB->getBasicBlock())) {
  1884. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1885. TProb, FProb, InvertCond);
  1886. return;
  1887. }
  1888. // Create TmpBB after CurBB.
  1889. MachineFunction::iterator BBI(CurBB);
  1890. MachineFunction &MF = DAG.getMachineFunction();
  1891. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1892. CurBB->getParent()->insert(++BBI, TmpBB);
  1893. if (Opc == Instruction::Or) {
  1894. // Codegen X | Y as:
  1895. // BB1:
  1896. // jmp_if_X TBB
  1897. // jmp TmpBB
  1898. // TmpBB:
  1899. // jmp_if_Y TBB
  1900. // jmp FBB
  1901. //
  1902. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1903. // The requirement is that
  1904. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1905. // = TrueProb for original BB.
  1906. // Assuming the original probabilities are A and B, one choice is to set
  1907. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1908. // A/(1+B) and 2B/(1+B). This choice assumes that
  1909. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1910. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1911. // TmpBB, but the math is more complicated.
  1912. auto NewTrueProb = TProb / 2;
  1913. auto NewFalseProb = TProb / 2 + FProb;
  1914. // Emit the LHS condition.
  1915. FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
  1916. NewFalseProb, InvertCond);
  1917. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1918. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1919. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1920. // Emit the RHS condition into TmpBB.
  1921. FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  1922. Probs[1], InvertCond);
  1923. } else {
  1924. assert(Opc == Instruction::And && "Unknown merge op!");
  1925. // Codegen X & Y as:
  1926. // BB1:
  1927. // jmp_if_X TmpBB
  1928. // jmp FBB
  1929. // TmpBB:
  1930. // jmp_if_Y TBB
  1931. // jmp FBB
  1932. //
  1933. // This requires creation of TmpBB after CurBB.
  1934. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1935. // The requirement is that
  1936. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1937. // = FalseProb for original BB.
  1938. // Assuming the original probabilities are A and B, one choice is to set
  1939. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1940. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1941. // TrueProb for BB1 * FalseProb for TmpBB.
  1942. auto NewTrueProb = TProb + FProb / 2;
  1943. auto NewFalseProb = FProb / 2;
  1944. // Emit the LHS condition.
  1945. FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
  1946. NewFalseProb, InvertCond);
  1947. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1948. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1949. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1950. // Emit the RHS condition into TmpBB.
  1951. FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  1952. Probs[1], InvertCond);
  1953. }
  1954. }
  1955. /// If the set of cases should be emitted as a series of branches, return true.
  1956. /// If we should emit this as a bunch of and/or'd together conditions, return
  1957. /// false.
  1958. bool
  1959. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1960. if (Cases.size() != 2) return true;
  1961. // If this is two comparisons of the same values or'd or and'd together, they
  1962. // will get folded into a single comparison, so don't emit two blocks.
  1963. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1964. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1965. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1966. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1967. return false;
  1968. }
  1969. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1970. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1971. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1972. Cases[0].CC == Cases[1].CC &&
  1973. isa<Constant>(Cases[0].CmpRHS) &&
  1974. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1975. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1976. return false;
  1977. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1978. return false;
  1979. }
  1980. return true;
  1981. }
  1982. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1983. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1984. // Update machine-CFG edges.
  1985. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1986. if (I.isUnconditional()) {
  1987. // Update machine-CFG edges.
  1988. BrMBB->addSuccessor(Succ0MBB);
  1989. // If this is not a fall-through branch or optimizations are switched off,
  1990. // emit the branch.
  1991. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1992. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1993. MVT::Other, getControlRoot(),
  1994. DAG.getBasicBlock(Succ0MBB)));
  1995. return;
  1996. }
  1997. // If this condition is one of the special cases we handle, do special stuff
  1998. // now.
  1999. const Value *CondVal = I.getCondition();
  2000. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  2001. // If this is a series of conditions that are or'd or and'd together, emit
  2002. // this as a sequence of branches instead of setcc's with and/or operations.
  2003. // As long as jumps are not expensive (exceptions for multi-use logic ops,
  2004. // unpredictable branches, and vector extracts because those jumps are likely
  2005. // expensive for any target), this should improve performance.
  2006. // For example, instead of something like:
  2007. // cmp A, B
  2008. // C = seteq
  2009. // cmp D, E
  2010. // F = setle
  2011. // or C, F
  2012. // jnz foo
  2013. // Emit:
  2014. // cmp A, B
  2015. // je foo
  2016. // cmp D, E
  2017. // jle foo
  2018. const Instruction *BOp = dyn_cast<Instruction>(CondVal);
  2019. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
  2020. BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
  2021. Value *Vec;
  2022. const Value *BOp0, *BOp1;
  2023. Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
  2024. if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
  2025. Opcode = Instruction::And;
  2026. else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
  2027. Opcode = Instruction::Or;
  2028. if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
  2029. match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
  2030. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
  2031. getEdgeProbability(BrMBB, Succ0MBB),
  2032. getEdgeProbability(BrMBB, Succ1MBB),
  2033. /*InvertCond=*/false);
  2034. // If the compares in later blocks need to use values not currently
  2035. // exported from this block, export them now. This block should always
  2036. // be the first entry.
  2037. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2038. // Allow some cases to be rejected.
  2039. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2040. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2041. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2042. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2043. }
  2044. // Emit the branch for this block.
  2045. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2046. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2047. return;
  2048. }
  2049. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2050. // SwitchCases.
  2051. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2052. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2053. SL->SwitchCases.clear();
  2054. }
  2055. }
  2056. // Create a CaseBlock record representing this branch.
  2057. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2058. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2059. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2060. // cond branch.
  2061. visitSwitchCase(CB, BrMBB);
  2062. }
  2063. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2064. /// the binary search tree resulting from lowering a switch instruction.
  2065. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2066. MachineBasicBlock *SwitchBB) {
  2067. SDValue Cond;
  2068. SDValue CondLHS = getValue(CB.CmpLHS);
  2069. SDLoc dl = CB.DL;
  2070. if (CB.CC == ISD::SETTRUE) {
  2071. // Branch or fall through to TrueBB.
  2072. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2073. SwitchBB->normalizeSuccProbs();
  2074. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2075. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2076. DAG.getBasicBlock(CB.TrueBB)));
  2077. }
  2078. return;
  2079. }
  2080. auto &TLI = DAG.getTargetLoweringInfo();
  2081. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2082. // Build the setcc now.
  2083. if (!CB.CmpMHS) {
  2084. // Fold "(X == true)" to X and "(X == false)" to !X to
  2085. // handle common cases produced by branch lowering.
  2086. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2087. CB.CC == ISD::SETEQ)
  2088. Cond = CondLHS;
  2089. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2090. CB.CC == ISD::SETEQ) {
  2091. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2092. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2093. } else {
  2094. SDValue CondRHS = getValue(CB.CmpRHS);
  2095. // If a pointer's DAG type is larger than its memory type then the DAG
  2096. // values are zero-extended. This breaks signed comparisons so truncate
  2097. // back to the underlying type before doing the compare.
  2098. if (CondLHS.getValueType() != MemVT) {
  2099. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2100. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2101. }
  2102. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2103. }
  2104. } else {
  2105. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2106. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2107. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2108. SDValue CmpOp = getValue(CB.CmpMHS);
  2109. EVT VT = CmpOp.getValueType();
  2110. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2111. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2112. ISD::SETLE);
  2113. } else {
  2114. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2115. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2116. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2117. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2118. }
  2119. }
  2120. // Update successor info
  2121. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2122. // TrueBB and FalseBB are always different unless the incoming IR is
  2123. // degenerate. This only happens when running llc on weird IR.
  2124. if (CB.TrueBB != CB.FalseBB)
  2125. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2126. SwitchBB->normalizeSuccProbs();
  2127. // If the lhs block is the next block, invert the condition so that we can
  2128. // fall through to the lhs instead of the rhs block.
  2129. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2130. std::swap(CB.TrueBB, CB.FalseBB);
  2131. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2132. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2133. }
  2134. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2135. MVT::Other, getControlRoot(), Cond,
  2136. DAG.getBasicBlock(CB.TrueBB));
  2137. // Insert the false branch. Do this even if it's a fall through branch,
  2138. // this makes it easier to do DAG optimizations which require inverting
  2139. // the branch condition.
  2140. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2141. DAG.getBasicBlock(CB.FalseBB));
  2142. DAG.setRoot(BrCond);
  2143. }
  2144. /// visitJumpTable - Emit JumpTable node in the current MBB
  2145. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2146. // Emit the code for the jump table
  2147. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2148. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2149. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2150. JT.Reg, PTy);
  2151. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2152. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2153. MVT::Other, Index.getValue(1),
  2154. Table, Index);
  2155. DAG.setRoot(BrJumpTable);
  2156. }
  2157. /// visitJumpTableHeader - This function emits necessary code to produce index
  2158. /// in the JumpTable from switch case.
  2159. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2160. JumpTableHeader &JTH,
  2161. MachineBasicBlock *SwitchBB) {
  2162. SDLoc dl = getCurSDLoc();
  2163. // Subtract the lowest switch case value from the value being switched on.
  2164. SDValue SwitchOp = getValue(JTH.SValue);
  2165. EVT VT = SwitchOp.getValueType();
  2166. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2167. DAG.getConstant(JTH.First, dl, VT));
  2168. // The SDNode we just created, which holds the value being switched on minus
  2169. // the smallest case value, needs to be copied to a virtual register so it
  2170. // can be used as an index into the jump table in a subsequent basic block.
  2171. // This value may be smaller or larger than the target's pointer type, and
  2172. // therefore require extension or truncating.
  2173. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2174. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2175. unsigned JumpTableReg =
  2176. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2177. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2178. JumpTableReg, SwitchOp);
  2179. JT.Reg = JumpTableReg;
  2180. if (!JTH.OmitRangeCheck) {
  2181. // Emit the range check for the jump table, and branch to the default block
  2182. // for the switch statement if the value being switched on exceeds the
  2183. // largest case in the switch.
  2184. SDValue CMP = DAG.getSetCC(
  2185. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2186. Sub.getValueType()),
  2187. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2188. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2189. MVT::Other, CopyTo, CMP,
  2190. DAG.getBasicBlock(JT.Default));
  2191. // Avoid emitting unnecessary branches to the next block.
  2192. if (JT.MBB != NextBlock(SwitchBB))
  2193. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2194. DAG.getBasicBlock(JT.MBB));
  2195. DAG.setRoot(BrCond);
  2196. } else {
  2197. // Avoid emitting unnecessary branches to the next block.
  2198. if (JT.MBB != NextBlock(SwitchBB))
  2199. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2200. DAG.getBasicBlock(JT.MBB)));
  2201. else
  2202. DAG.setRoot(CopyTo);
  2203. }
  2204. }
  2205. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2206. /// variable if there exists one.
  2207. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2208. SDValue &Chain) {
  2209. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2210. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2211. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2212. MachineFunction &MF = DAG.getMachineFunction();
  2213. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2214. MachineSDNode *Node =
  2215. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2216. if (Global) {
  2217. MachinePointerInfo MPInfo(Global);
  2218. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2219. MachineMemOperand::MODereferenceable;
  2220. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2221. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
  2222. DAG.setNodeMemRefs(Node, {MemRef});
  2223. }
  2224. if (PtrTy != PtrMemTy)
  2225. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2226. return SDValue(Node, 0);
  2227. }
  2228. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2229. /// tail spliced into a stack protector check success bb.
  2230. ///
  2231. /// For a high level explanation of how this fits into the stack protector
  2232. /// generation see the comment on the declaration of class
  2233. /// StackProtectorDescriptor.
  2234. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2235. MachineBasicBlock *ParentBB) {
  2236. // First create the loads to the guard/stack slot for the comparison.
  2237. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2238. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2239. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2240. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2241. int FI = MFI.getStackProtectorIndex();
  2242. SDValue Guard;
  2243. SDLoc dl = getCurSDLoc();
  2244. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2245. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2246. Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
  2247. // Generate code to load the content of the guard slot.
  2248. SDValue GuardVal = DAG.getLoad(
  2249. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2250. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2251. MachineMemOperand::MOVolatile);
  2252. if (TLI.useStackGuardXorFP())
  2253. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2254. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2255. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2256. // The target provides a guard check function to validate the guard value.
  2257. // Generate a call to that function with the content of the guard slot as
  2258. // argument.
  2259. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2260. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2261. TargetLowering::ArgListTy Args;
  2262. TargetLowering::ArgListEntry Entry;
  2263. Entry.Node = GuardVal;
  2264. Entry.Ty = FnTy->getParamType(0);
  2265. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2266. Entry.IsInReg = true;
  2267. Args.push_back(Entry);
  2268. TargetLowering::CallLoweringInfo CLI(DAG);
  2269. CLI.setDebugLoc(getCurSDLoc())
  2270. .setChain(DAG.getEntryNode())
  2271. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2272. getValue(GuardCheckFn), std::move(Args));
  2273. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2274. DAG.setRoot(Result.second);
  2275. return;
  2276. }
  2277. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2278. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2279. SDValue Chain = DAG.getEntryNode();
  2280. if (TLI.useLoadStackGuardNode()) {
  2281. Guard = getLoadStackGuard(DAG, dl, Chain);
  2282. } else {
  2283. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2284. SDValue GuardPtr = getValue(IRGuard);
  2285. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2286. MachinePointerInfo(IRGuard, 0), Align,
  2287. MachineMemOperand::MOVolatile);
  2288. }
  2289. // Perform the comparison via a getsetcc.
  2290. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2291. *DAG.getContext(),
  2292. Guard.getValueType()),
  2293. Guard, GuardVal, ISD::SETNE);
  2294. // If the guard/stackslot do not equal, branch to failure MBB.
  2295. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2296. MVT::Other, GuardVal.getOperand(0),
  2297. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2298. // Otherwise branch to success MBB.
  2299. SDValue Br = DAG.getNode(ISD::BR, dl,
  2300. MVT::Other, BrCond,
  2301. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2302. DAG.setRoot(Br);
  2303. }
  2304. /// Codegen the failure basic block for a stack protector check.
  2305. ///
  2306. /// A failure stack protector machine basic block consists simply of a call to
  2307. /// __stack_chk_fail().
  2308. ///
  2309. /// For a high level explanation of how this fits into the stack protector
  2310. /// generation see the comment on the declaration of class
  2311. /// StackProtectorDescriptor.
  2312. void
  2313. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2314. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2315. TargetLowering::MakeLibCallOptions CallOptions;
  2316. CallOptions.setDiscardResult(true);
  2317. SDValue Chain =
  2318. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2319. None, CallOptions, getCurSDLoc()).second;
  2320. // On PS4, the "return address" must still be within the calling function,
  2321. // even if it's at the very end, so emit an explicit TRAP here.
  2322. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2323. if (TM.getTargetTriple().isPS4CPU())
  2324. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2325. // WebAssembly needs an unreachable instruction after a non-returning call,
  2326. // because the function return type can be different from __stack_chk_fail's
  2327. // return type (void).
  2328. if (TM.getTargetTriple().isWasm())
  2329. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2330. DAG.setRoot(Chain);
  2331. }
  2332. /// visitBitTestHeader - This function emits necessary code to produce value
  2333. /// suitable for "bit tests"
  2334. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2335. MachineBasicBlock *SwitchBB) {
  2336. SDLoc dl = getCurSDLoc();
  2337. // Subtract the minimum value.
  2338. SDValue SwitchOp = getValue(B.SValue);
  2339. EVT VT = SwitchOp.getValueType();
  2340. SDValue RangeSub =
  2341. DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
  2342. // Determine the type of the test operands.
  2343. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2344. bool UsePtrType = false;
  2345. if (!TLI.isTypeLegal(VT)) {
  2346. UsePtrType = true;
  2347. } else {
  2348. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2349. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2350. // Switch table case range are encoded into series of masks.
  2351. // Just use pointer type, it's guaranteed to fit.
  2352. UsePtrType = true;
  2353. break;
  2354. }
  2355. }
  2356. SDValue Sub = RangeSub;
  2357. if (UsePtrType) {
  2358. VT = TLI.getPointerTy(DAG.getDataLayout());
  2359. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2360. }
  2361. B.RegVT = VT.getSimpleVT();
  2362. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2363. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2364. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2365. if (!B.OmitRangeCheck)
  2366. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2367. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2368. SwitchBB->normalizeSuccProbs();
  2369. SDValue Root = CopyTo;
  2370. if (!B.OmitRangeCheck) {
  2371. // Conditional branch to the default block.
  2372. SDValue RangeCmp = DAG.getSetCC(dl,
  2373. TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2374. RangeSub.getValueType()),
  2375. RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
  2376. ISD::SETUGT);
  2377. Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
  2378. DAG.getBasicBlock(B.Default));
  2379. }
  2380. // Avoid emitting unnecessary branches to the next block.
  2381. if (MBB != NextBlock(SwitchBB))
  2382. Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
  2383. DAG.setRoot(Root);
  2384. }
  2385. /// visitBitTestCase - this function produces one "bit test"
  2386. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2387. MachineBasicBlock* NextMBB,
  2388. BranchProbability BranchProbToNext,
  2389. unsigned Reg,
  2390. BitTestCase &B,
  2391. MachineBasicBlock *SwitchBB) {
  2392. SDLoc dl = getCurSDLoc();
  2393. MVT VT = BB.RegVT;
  2394. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2395. SDValue Cmp;
  2396. unsigned PopCount = countPopulation(B.Mask);
  2397. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2398. if (PopCount == 1) {
  2399. // Testing for a single bit; just compare the shift count with what it
  2400. // would need to be to shift a 1 bit in that position.
  2401. Cmp = DAG.getSetCC(
  2402. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2403. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2404. ISD::SETEQ);
  2405. } else if (PopCount == BB.Range) {
  2406. // There is only one zero bit in the range, test for it directly.
  2407. Cmp = DAG.getSetCC(
  2408. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2409. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2410. ISD::SETNE);
  2411. } else {
  2412. // Make desired shift
  2413. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2414. DAG.getConstant(1, dl, VT), ShiftOp);
  2415. // Emit bit tests and jumps
  2416. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2417. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2418. Cmp = DAG.getSetCC(
  2419. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2420. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2421. }
  2422. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2423. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2424. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2425. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2426. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2427. // one as they are relative probabilities (and thus work more like weights),
  2428. // and hence we need to normalize them to let the sum of them become one.
  2429. SwitchBB->normalizeSuccProbs();
  2430. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2431. MVT::Other, getControlRoot(),
  2432. Cmp, DAG.getBasicBlock(B.TargetBB));
  2433. // Avoid emitting unnecessary branches to the next block.
  2434. if (NextMBB != NextBlock(SwitchBB))
  2435. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2436. DAG.getBasicBlock(NextMBB));
  2437. DAG.setRoot(BrAnd);
  2438. }
  2439. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2440. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2441. // Retrieve successors. Look through artificial IR level blocks like
  2442. // catchswitch for successors.
  2443. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2444. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2445. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2446. // have to do anything here to lower funclet bundles.
  2447. assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
  2448. LLVMContext::OB_gc_transition,
  2449. LLVMContext::OB_gc_live,
  2450. LLVMContext::OB_funclet,
  2451. LLVMContext::OB_cfguardtarget}) &&
  2452. "Cannot lower invokes with arbitrary operand bundles yet!");
  2453. const Value *Callee(I.getCalledOperand());
  2454. const Function *Fn = dyn_cast<Function>(Callee);
  2455. if (isa<InlineAsm>(Callee))
  2456. visitInlineAsm(I);
  2457. else if (Fn && Fn->isIntrinsic()) {
  2458. switch (Fn->getIntrinsicID()) {
  2459. default:
  2460. llvm_unreachable("Cannot invoke this intrinsic");
  2461. case Intrinsic::donothing:
  2462. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2463. break;
  2464. case Intrinsic::experimental_patchpoint_void:
  2465. case Intrinsic::experimental_patchpoint_i64:
  2466. visitPatchpoint(I, EHPadBB);
  2467. break;
  2468. case Intrinsic::experimental_gc_statepoint:
  2469. LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
  2470. break;
  2471. case Intrinsic::wasm_rethrow: {
  2472. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2473. // special because it can be invoked, so we manually lower it to a DAG
  2474. // node here.
  2475. SmallVector<SDValue, 8> Ops;
  2476. Ops.push_back(getRoot()); // inchain
  2477. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2478. Ops.push_back(
  2479. DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
  2480. TLI.getPointerTy(DAG.getDataLayout())));
  2481. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2482. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2483. break;
  2484. }
  2485. }
  2486. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2487. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2488. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2489. // intrinsic, and right now there are no plans to support other intrinsics
  2490. // with deopt state.
  2491. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2492. } else {
  2493. LowerCallTo(I, getValue(Callee), false, EHPadBB);
  2494. }
  2495. // If the value of the invoke is used outside of its defining block, make it
  2496. // available as a virtual register.
  2497. // We already took care of the exported value for the statepoint instruction
  2498. // during call to the LowerStatepoint.
  2499. if (!isa<GCStatepointInst>(I)) {
  2500. CopyToExportRegsIfNeeded(&I);
  2501. }
  2502. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2503. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2504. BranchProbability EHPadBBProb =
  2505. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2506. : BranchProbability::getZero();
  2507. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2508. // Update successor info.
  2509. addSuccessorWithProb(InvokeMBB, Return);
  2510. for (auto &UnwindDest : UnwindDests) {
  2511. UnwindDest.first->setIsEHPad();
  2512. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2513. }
  2514. InvokeMBB->normalizeSuccProbs();
  2515. // Drop into normal successor.
  2516. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2517. DAG.getBasicBlock(Return)));
  2518. }
  2519. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2520. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2521. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2522. // have to do anything here to lower funclet bundles.
  2523. assert(!I.hasOperandBundlesOtherThan(
  2524. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2525. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2526. assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
  2527. visitInlineAsm(I);
  2528. CopyToExportRegsIfNeeded(&I);
  2529. // Retrieve successors.
  2530. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2531. // Update successor info.
  2532. addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
  2533. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2534. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2535. addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
  2536. Target->setIsInlineAsmBrIndirectTarget();
  2537. }
  2538. CallBrMBB->normalizeSuccProbs();
  2539. // Drop into default successor.
  2540. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2541. MVT::Other, getControlRoot(),
  2542. DAG.getBasicBlock(Return)));
  2543. }
  2544. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2545. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2546. }
  2547. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2548. assert(FuncInfo.MBB->isEHPad() &&
  2549. "Call to landingpad not in landing pad!");
  2550. // If there aren't registers to copy the values into (e.g., during SjLj
  2551. // exceptions), then don't bother to create these DAG nodes.
  2552. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2553. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2554. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2555. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2556. return;
  2557. // If landingpad's return type is token type, we don't create DAG nodes
  2558. // for its exception pointer and selector value. The extraction of exception
  2559. // pointer or selector value from token type landingpads is not currently
  2560. // supported.
  2561. if (LP.getType()->isTokenTy())
  2562. return;
  2563. SmallVector<EVT, 2> ValueVTs;
  2564. SDLoc dl = getCurSDLoc();
  2565. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2566. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2567. // Get the two live-in registers as SDValues. The physregs have already been
  2568. // copied into virtual registers.
  2569. SDValue Ops[2];
  2570. if (FuncInfo.ExceptionPointerVirtReg) {
  2571. Ops[0] = DAG.getZExtOrTrunc(
  2572. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2573. FuncInfo.ExceptionPointerVirtReg,
  2574. TLI.getPointerTy(DAG.getDataLayout())),
  2575. dl, ValueVTs[0]);
  2576. } else {
  2577. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2578. }
  2579. Ops[1] = DAG.getZExtOrTrunc(
  2580. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2581. FuncInfo.ExceptionSelectorVirtReg,
  2582. TLI.getPointerTy(DAG.getDataLayout())),
  2583. dl, ValueVTs[1]);
  2584. // Merge into one.
  2585. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2586. DAG.getVTList(ValueVTs), Ops);
  2587. setValue(&LP, Res);
  2588. }
  2589. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2590. MachineBasicBlock *Last) {
  2591. // Update JTCases.
  2592. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2593. if (SL->JTCases[i].first.HeaderBB == First)
  2594. SL->JTCases[i].first.HeaderBB = Last;
  2595. // Update BitTestCases.
  2596. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2597. if (SL->BitTestCases[i].Parent == First)
  2598. SL->BitTestCases[i].Parent = Last;
  2599. }
  2600. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2601. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2602. // Update machine-CFG edges with unique successors.
  2603. SmallSet<BasicBlock*, 32> Done;
  2604. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2605. BasicBlock *BB = I.getSuccessor(i);
  2606. bool Inserted = Done.insert(BB).second;
  2607. if (!Inserted)
  2608. continue;
  2609. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2610. addSuccessorWithProb(IndirectBrMBB, Succ);
  2611. }
  2612. IndirectBrMBB->normalizeSuccProbs();
  2613. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2614. MVT::Other, getControlRoot(),
  2615. getValue(I.getAddress())));
  2616. }
  2617. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2618. if (!DAG.getTarget().Options.TrapUnreachable)
  2619. return;
  2620. // We may be able to ignore unreachable behind a noreturn call.
  2621. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2622. const BasicBlock &BB = *I.getParent();
  2623. if (&I != &BB.front()) {
  2624. BasicBlock::const_iterator PredI =
  2625. std::prev(BasicBlock::const_iterator(&I));
  2626. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2627. if (Call->doesNotReturn())
  2628. return;
  2629. }
  2630. }
  2631. }
  2632. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2633. }
  2634. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2635. SDNodeFlags Flags;
  2636. SDValue Op = getValue(I.getOperand(0));
  2637. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2638. Op, Flags);
  2639. setValue(&I, UnNodeValue);
  2640. }
  2641. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2642. SDNodeFlags Flags;
  2643. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2644. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2645. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2646. }
  2647. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
  2648. Flags.setExact(ExactOp->isExact());
  2649. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2650. Flags.copyFMF(*FPOp);
  2651. SDValue Op1 = getValue(I.getOperand(0));
  2652. SDValue Op2 = getValue(I.getOperand(1));
  2653. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2654. Op1, Op2, Flags);
  2655. setValue(&I, BinNodeValue);
  2656. }
  2657. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2658. SDValue Op1 = getValue(I.getOperand(0));
  2659. SDValue Op2 = getValue(I.getOperand(1));
  2660. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2661. Op1.getValueType(), DAG.getDataLayout());
  2662. // Coerce the shift amount to the right type if we can.
  2663. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2664. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2665. unsigned Op2Size = Op2.getValueSizeInBits();
  2666. SDLoc DL = getCurSDLoc();
  2667. // If the operand is smaller than the shift count type, promote it.
  2668. if (ShiftSize > Op2Size)
  2669. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2670. // If the operand is larger than the shift count type but the shift
  2671. // count type has enough bits to represent any shift value, truncate
  2672. // it now. This is a common case and it exposes the truncate to
  2673. // optimization early.
  2674. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2675. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2676. // Otherwise we'll need to temporarily settle for some other convenient
  2677. // type. Type legalization will make adjustments once the shiftee is split.
  2678. else
  2679. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2680. }
  2681. bool nuw = false;
  2682. bool nsw = false;
  2683. bool exact = false;
  2684. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2685. if (const OverflowingBinaryOperator *OFBinOp =
  2686. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2687. nuw = OFBinOp->hasNoUnsignedWrap();
  2688. nsw = OFBinOp->hasNoSignedWrap();
  2689. }
  2690. if (const PossiblyExactOperator *ExactOp =
  2691. dyn_cast<const PossiblyExactOperator>(&I))
  2692. exact = ExactOp->isExact();
  2693. }
  2694. SDNodeFlags Flags;
  2695. Flags.setExact(exact);
  2696. Flags.setNoSignedWrap(nsw);
  2697. Flags.setNoUnsignedWrap(nuw);
  2698. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2699. Flags);
  2700. setValue(&I, Res);
  2701. }
  2702. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2703. SDValue Op1 = getValue(I.getOperand(0));
  2704. SDValue Op2 = getValue(I.getOperand(1));
  2705. SDNodeFlags Flags;
  2706. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2707. cast<PossiblyExactOperator>(&I)->isExact());
  2708. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2709. Op2, Flags));
  2710. }
  2711. void SelectionDAGBuilder::visitICmp(const User &I) {
  2712. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2713. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2714. predicate = IC->getPredicate();
  2715. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2716. predicate = ICmpInst::Predicate(IC->getPredicate());
  2717. SDValue Op1 = getValue(I.getOperand(0));
  2718. SDValue Op2 = getValue(I.getOperand(1));
  2719. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2720. auto &TLI = DAG.getTargetLoweringInfo();
  2721. EVT MemVT =
  2722. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2723. // If a pointer's DAG type is larger than its memory type then the DAG values
  2724. // are zero-extended. This breaks signed comparisons so truncate back to the
  2725. // underlying type before doing the compare.
  2726. if (Op1.getValueType() != MemVT) {
  2727. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2728. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2729. }
  2730. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2731. I.getType());
  2732. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2733. }
  2734. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2735. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2736. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2737. predicate = FC->getPredicate();
  2738. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2739. predicate = FCmpInst::Predicate(FC->getPredicate());
  2740. SDValue Op1 = getValue(I.getOperand(0));
  2741. SDValue Op2 = getValue(I.getOperand(1));
  2742. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2743. auto *FPMO = cast<FPMathOperator>(&I);
  2744. if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
  2745. Condition = getFCmpCodeWithoutNaN(Condition);
  2746. SDNodeFlags Flags;
  2747. Flags.copyFMF(*FPMO);
  2748. SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
  2749. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2750. I.getType());
  2751. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2752. }
  2753. // Check if the condition of the select has one use or two users that are both
  2754. // selects with the same condition.
  2755. static bool hasOnlySelectUsers(const Value *Cond) {
  2756. return llvm::all_of(Cond->users(), [](const Value *V) {
  2757. return isa<SelectInst>(V);
  2758. });
  2759. }
  2760. void SelectionDAGBuilder::visitSelect(const User &I) {
  2761. SmallVector<EVT, 4> ValueVTs;
  2762. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2763. ValueVTs);
  2764. unsigned NumValues = ValueVTs.size();
  2765. if (NumValues == 0) return;
  2766. SmallVector<SDValue, 4> Values(NumValues);
  2767. SDValue Cond = getValue(I.getOperand(0));
  2768. SDValue LHSVal = getValue(I.getOperand(1));
  2769. SDValue RHSVal = getValue(I.getOperand(2));
  2770. SmallVector<SDValue, 1> BaseOps(1, Cond);
  2771. ISD::NodeType OpCode =
  2772. Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
  2773. bool IsUnaryAbs = false;
  2774. bool Negate = false;
  2775. SDNodeFlags Flags;
  2776. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2777. Flags.copyFMF(*FPOp);
  2778. // Min/max matching is only viable if all output VTs are the same.
  2779. if (is_splat(ValueVTs)) {
  2780. EVT VT = ValueVTs[0];
  2781. LLVMContext &Ctx = *DAG.getContext();
  2782. auto &TLI = DAG.getTargetLoweringInfo();
  2783. // We care about the legality of the operation after it has been type
  2784. // legalized.
  2785. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
  2786. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2787. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2788. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2789. // min/max is legal on the scalar type.
  2790. bool UseScalarMinMax = VT.isVector() &&
  2791. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2792. Value *LHS, *RHS;
  2793. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2794. ISD::NodeType Opc = ISD::DELETED_NODE;
  2795. switch (SPR.Flavor) {
  2796. case SPF_UMAX: Opc = ISD::UMAX; break;
  2797. case SPF_UMIN: Opc = ISD::UMIN; break;
  2798. case SPF_SMAX: Opc = ISD::SMAX; break;
  2799. case SPF_SMIN: Opc = ISD::SMIN; break;
  2800. case SPF_FMINNUM:
  2801. switch (SPR.NaNBehavior) {
  2802. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2803. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2804. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2805. case SPNB_RETURNS_ANY: {
  2806. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2807. Opc = ISD::FMINNUM;
  2808. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2809. Opc = ISD::FMINIMUM;
  2810. else if (UseScalarMinMax)
  2811. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2812. ISD::FMINNUM : ISD::FMINIMUM;
  2813. break;
  2814. }
  2815. }
  2816. break;
  2817. case SPF_FMAXNUM:
  2818. switch (SPR.NaNBehavior) {
  2819. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2820. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2821. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2822. case SPNB_RETURNS_ANY:
  2823. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2824. Opc = ISD::FMAXNUM;
  2825. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2826. Opc = ISD::FMAXIMUM;
  2827. else if (UseScalarMinMax)
  2828. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2829. ISD::FMAXNUM : ISD::FMAXIMUM;
  2830. break;
  2831. }
  2832. break;
  2833. case SPF_NABS:
  2834. Negate = true;
  2835. LLVM_FALLTHROUGH;
  2836. case SPF_ABS:
  2837. IsUnaryAbs = true;
  2838. Opc = ISD::ABS;
  2839. break;
  2840. default: break;
  2841. }
  2842. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2843. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2844. (UseScalarMinMax &&
  2845. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2846. // If the underlying comparison instruction is used by any other
  2847. // instruction, the consumed instructions won't be destroyed, so it is
  2848. // not profitable to convert to a min/max.
  2849. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2850. OpCode = Opc;
  2851. LHSVal = getValue(LHS);
  2852. RHSVal = getValue(RHS);
  2853. BaseOps.clear();
  2854. }
  2855. if (IsUnaryAbs) {
  2856. OpCode = Opc;
  2857. LHSVal = getValue(LHS);
  2858. BaseOps.clear();
  2859. }
  2860. }
  2861. if (IsUnaryAbs) {
  2862. for (unsigned i = 0; i != NumValues; ++i) {
  2863. SDLoc dl = getCurSDLoc();
  2864. EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
  2865. Values[i] =
  2866. DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
  2867. if (Negate)
  2868. Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
  2869. Values[i]);
  2870. }
  2871. } else {
  2872. for (unsigned i = 0; i != NumValues; ++i) {
  2873. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2874. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2875. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2876. Values[i] = DAG.getNode(
  2877. OpCode, getCurSDLoc(),
  2878. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
  2879. }
  2880. }
  2881. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2882. DAG.getVTList(ValueVTs), Values));
  2883. }
  2884. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2885. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2886. SDValue N = getValue(I.getOperand(0));
  2887. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2888. I.getType());
  2889. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2890. }
  2891. void SelectionDAGBuilder::visitZExt(const User &I) {
  2892. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2893. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2894. SDValue N = getValue(I.getOperand(0));
  2895. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2896. I.getType());
  2897. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2898. }
  2899. void SelectionDAGBuilder::visitSExt(const User &I) {
  2900. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2901. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2902. SDValue N = getValue(I.getOperand(0));
  2903. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2904. I.getType());
  2905. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2906. }
  2907. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2908. // FPTrunc is never a no-op cast, no need to check
  2909. SDValue N = getValue(I.getOperand(0));
  2910. SDLoc dl = getCurSDLoc();
  2911. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2912. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2913. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2914. DAG.getTargetConstant(
  2915. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2916. }
  2917. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2918. // FPExt is never a no-op cast, no need to check
  2919. SDValue N = getValue(I.getOperand(0));
  2920. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2921. I.getType());
  2922. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2923. }
  2924. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2925. // FPToUI is never a no-op cast, no need to check
  2926. SDValue N = getValue(I.getOperand(0));
  2927. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2928. I.getType());
  2929. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2930. }
  2931. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2932. // FPToSI is never a no-op cast, no need to check
  2933. SDValue N = getValue(I.getOperand(0));
  2934. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2935. I.getType());
  2936. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2937. }
  2938. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2939. // UIToFP is never a no-op cast, no need to check
  2940. SDValue N = getValue(I.getOperand(0));
  2941. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2942. I.getType());
  2943. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2944. }
  2945. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2946. // SIToFP is never a no-op cast, no need to check
  2947. SDValue N = getValue(I.getOperand(0));
  2948. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2949. I.getType());
  2950. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2951. }
  2952. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2953. // What to do depends on the size of the integer and the size of the pointer.
  2954. // We can either truncate, zero extend, or no-op, accordingly.
  2955. SDValue N = getValue(I.getOperand(0));
  2956. auto &TLI = DAG.getTargetLoweringInfo();
  2957. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2958. I.getType());
  2959. EVT PtrMemVT =
  2960. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2961. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  2962. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  2963. setValue(&I, N);
  2964. }
  2965. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2966. // What to do depends on the size of the integer and the size of the pointer.
  2967. // We can either truncate, zero extend, or no-op, accordingly.
  2968. SDValue N = getValue(I.getOperand(0));
  2969. auto &TLI = DAG.getTargetLoweringInfo();
  2970. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2971. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  2972. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  2973. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  2974. setValue(&I, N);
  2975. }
  2976. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2977. SDValue N = getValue(I.getOperand(0));
  2978. SDLoc dl = getCurSDLoc();
  2979. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2980. I.getType());
  2981. // BitCast assures us that source and destination are the same size so this is
  2982. // either a BITCAST or a no-op.
  2983. if (DestVT != N.getValueType())
  2984. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2985. DestVT, N)); // convert types.
  2986. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2987. // might fold any kind of constant expression to an integer constant and that
  2988. // is not what we are looking for. Only recognize a bitcast of a genuine
  2989. // constant integer as an opaque constant.
  2990. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2991. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2992. /*isOpaque*/true));
  2993. else
  2994. setValue(&I, N); // noop cast.
  2995. }
  2996. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2997. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2998. const Value *SV = I.getOperand(0);
  2999. SDValue N = getValue(SV);
  3000. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3001. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3002. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3003. if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
  3004. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3005. setValue(&I, N);
  3006. }
  3007. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3008. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3009. SDValue InVec = getValue(I.getOperand(0));
  3010. SDValue InVal = getValue(I.getOperand(1));
  3011. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3012. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3013. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3014. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3015. InVec, InVal, InIdx));
  3016. }
  3017. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3018. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3019. SDValue InVec = getValue(I.getOperand(0));
  3020. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3021. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3022. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3023. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3024. InVec, InIdx));
  3025. }
  3026. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3027. SDValue Src1 = getValue(I.getOperand(0));
  3028. SDValue Src2 = getValue(I.getOperand(1));
  3029. ArrayRef<int> Mask;
  3030. if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
  3031. Mask = SVI->getShuffleMask();
  3032. else
  3033. Mask = cast<ConstantExpr>(I).getShuffleMask();
  3034. SDLoc DL = getCurSDLoc();
  3035. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3036. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3037. EVT SrcVT = Src1.getValueType();
  3038. if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
  3039. VT.isScalableVector()) {
  3040. // Canonical splat form of first element of first input vector.
  3041. SDValue FirstElt =
  3042. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
  3043. DAG.getVectorIdxConstant(0, DL));
  3044. setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
  3045. return;
  3046. }
  3047. // For now, we only handle splats for scalable vectors.
  3048. // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
  3049. // for targets that support a SPLAT_VECTOR for non-scalable vector types.
  3050. assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
  3051. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3052. unsigned MaskNumElts = Mask.size();
  3053. if (SrcNumElts == MaskNumElts) {
  3054. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3055. return;
  3056. }
  3057. // Normalize the shuffle vector since mask and vector length don't match.
  3058. if (SrcNumElts < MaskNumElts) {
  3059. // Mask is longer than the source vectors. We can use concatenate vector to
  3060. // make the mask and vectors lengths match.
  3061. if (MaskNumElts % SrcNumElts == 0) {
  3062. // Mask length is a multiple of the source vector length.
  3063. // Check if the shuffle is some kind of concatenation of the input
  3064. // vectors.
  3065. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3066. bool IsConcat = true;
  3067. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3068. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3069. int Idx = Mask[i];
  3070. if (Idx < 0)
  3071. continue;
  3072. // Ensure the indices in each SrcVT sized piece are sequential and that
  3073. // the same source is used for the whole piece.
  3074. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3075. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3076. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3077. IsConcat = false;
  3078. break;
  3079. }
  3080. // Remember which source this index came from.
  3081. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3082. }
  3083. // The shuffle is concatenating multiple vectors together. Just emit
  3084. // a CONCAT_VECTORS operation.
  3085. if (IsConcat) {
  3086. SmallVector<SDValue, 8> ConcatOps;
  3087. for (auto Src : ConcatSrcs) {
  3088. if (Src < 0)
  3089. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3090. else if (Src == 0)
  3091. ConcatOps.push_back(Src1);
  3092. else
  3093. ConcatOps.push_back(Src2);
  3094. }
  3095. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3096. return;
  3097. }
  3098. }
  3099. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3100. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3101. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3102. PaddedMaskNumElts);
  3103. // Pad both vectors with undefs to make them the same length as the mask.
  3104. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3105. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3106. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3107. MOps1[0] = Src1;
  3108. MOps2[0] = Src2;
  3109. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3110. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3111. // Readjust mask for new input vector length.
  3112. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3113. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3114. int Idx = Mask[i];
  3115. if (Idx >= (int)SrcNumElts)
  3116. Idx -= SrcNumElts - PaddedMaskNumElts;
  3117. MappedOps[i] = Idx;
  3118. }
  3119. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3120. // If the concatenated vector was padded, extract a subvector with the
  3121. // correct number of elements.
  3122. if (MaskNumElts != PaddedMaskNumElts)
  3123. Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3124. DAG.getVectorIdxConstant(0, DL));
  3125. setValue(&I, Result);
  3126. return;
  3127. }
  3128. if (SrcNumElts > MaskNumElts) {
  3129. // Analyze the access pattern of the vector to see if we can extract
  3130. // two subvectors and do the shuffle.
  3131. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3132. bool CanExtract = true;
  3133. for (int Idx : Mask) {
  3134. unsigned Input = 0;
  3135. if (Idx < 0)
  3136. continue;
  3137. if (Idx >= (int)SrcNumElts) {
  3138. Input = 1;
  3139. Idx -= SrcNumElts;
  3140. }
  3141. // If all the indices come from the same MaskNumElts sized portion of
  3142. // the sources we can use extract. Also make sure the extract wouldn't
  3143. // extract past the end of the source.
  3144. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3145. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3146. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3147. CanExtract = false;
  3148. // Make sure we always update StartIdx as we use it to track if all
  3149. // elements are undef.
  3150. StartIdx[Input] = NewStartIdx;
  3151. }
  3152. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3153. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3154. return;
  3155. }
  3156. if (CanExtract) {
  3157. // Extract appropriate subvector and generate a vector shuffle
  3158. for (unsigned Input = 0; Input < 2; ++Input) {
  3159. SDValue &Src = Input == 0 ? Src1 : Src2;
  3160. if (StartIdx[Input] < 0)
  3161. Src = DAG.getUNDEF(VT);
  3162. else {
  3163. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3164. DAG.getVectorIdxConstant(StartIdx[Input], DL));
  3165. }
  3166. }
  3167. // Calculate new mask.
  3168. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3169. for (int &Idx : MappedOps) {
  3170. if (Idx >= (int)SrcNumElts)
  3171. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3172. else if (Idx >= 0)
  3173. Idx -= StartIdx[0];
  3174. }
  3175. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3176. return;
  3177. }
  3178. }
  3179. // We can't use either concat vectors or extract subvectors so fall back to
  3180. // replacing the shuffle with extract and build vector.
  3181. // to insert and build vector.
  3182. EVT EltVT = VT.getVectorElementType();
  3183. SmallVector<SDValue,8> Ops;
  3184. for (int Idx : Mask) {
  3185. SDValue Res;
  3186. if (Idx < 0) {
  3187. Res = DAG.getUNDEF(EltVT);
  3188. } else {
  3189. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3190. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3191. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
  3192. DAG.getVectorIdxConstant(Idx, DL));
  3193. }
  3194. Ops.push_back(Res);
  3195. }
  3196. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3197. }
  3198. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3199. ArrayRef<unsigned> Indices;
  3200. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3201. Indices = IV->getIndices();
  3202. else
  3203. Indices = cast<ConstantExpr>(&I)->getIndices();
  3204. const Value *Op0 = I.getOperand(0);
  3205. const Value *Op1 = I.getOperand(1);
  3206. Type *AggTy = I.getType();
  3207. Type *ValTy = Op1->getType();
  3208. bool IntoUndef = isa<UndefValue>(Op0);
  3209. bool FromUndef = isa<UndefValue>(Op1);
  3210. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3211. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3212. SmallVector<EVT, 4> AggValueVTs;
  3213. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3214. SmallVector<EVT, 4> ValValueVTs;
  3215. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3216. unsigned NumAggValues = AggValueVTs.size();
  3217. unsigned NumValValues = ValValueVTs.size();
  3218. SmallVector<SDValue, 4> Values(NumAggValues);
  3219. // Ignore an insertvalue that produces an empty object
  3220. if (!NumAggValues) {
  3221. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3222. return;
  3223. }
  3224. SDValue Agg = getValue(Op0);
  3225. unsigned i = 0;
  3226. // Copy the beginning value(s) from the original aggregate.
  3227. for (; i != LinearIndex; ++i)
  3228. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3229. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3230. // Copy values from the inserted value(s).
  3231. if (NumValValues) {
  3232. SDValue Val = getValue(Op1);
  3233. for (; i != LinearIndex + NumValValues; ++i)
  3234. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3235. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3236. }
  3237. // Copy remaining value(s) from the original aggregate.
  3238. for (; i != NumAggValues; ++i)
  3239. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3240. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3241. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3242. DAG.getVTList(AggValueVTs), Values));
  3243. }
  3244. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3245. ArrayRef<unsigned> Indices;
  3246. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3247. Indices = EV->getIndices();
  3248. else
  3249. Indices = cast<ConstantExpr>(&I)->getIndices();
  3250. const Value *Op0 = I.getOperand(0);
  3251. Type *AggTy = Op0->getType();
  3252. Type *ValTy = I.getType();
  3253. bool OutOfUndef = isa<UndefValue>(Op0);
  3254. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3255. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3256. SmallVector<EVT, 4> ValValueVTs;
  3257. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3258. unsigned NumValValues = ValValueVTs.size();
  3259. // Ignore a extractvalue that produces an empty object
  3260. if (!NumValValues) {
  3261. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3262. return;
  3263. }
  3264. SmallVector<SDValue, 4> Values(NumValValues);
  3265. SDValue Agg = getValue(Op0);
  3266. // Copy out the selected value(s).
  3267. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3268. Values[i - LinearIndex] =
  3269. OutOfUndef ?
  3270. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3271. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3272. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3273. DAG.getVTList(ValValueVTs), Values));
  3274. }
  3275. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3276. Value *Op0 = I.getOperand(0);
  3277. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3278. // element which holds a pointer.
  3279. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3280. SDValue N = getValue(Op0);
  3281. SDLoc dl = getCurSDLoc();
  3282. auto &TLI = DAG.getTargetLoweringInfo();
  3283. // Normalize Vector GEP - all scalar operands should be converted to the
  3284. // splat vector.
  3285. bool IsVectorGEP = I.getType()->isVectorTy();
  3286. ElementCount VectorElementCount =
  3287. IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
  3288. : ElementCount::getFixed(0);
  3289. if (IsVectorGEP && !N.getValueType().isVector()) {
  3290. LLVMContext &Context = *DAG.getContext();
  3291. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
  3292. if (VectorElementCount.isScalable())
  3293. N = DAG.getSplatVector(VT, dl, N);
  3294. else
  3295. N = DAG.getSplatBuildVector(VT, dl, N);
  3296. }
  3297. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3298. GTI != E; ++GTI) {
  3299. const Value *Idx = GTI.getOperand();
  3300. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3301. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3302. if (Field) {
  3303. // N = N + Offset
  3304. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3305. // In an inbounds GEP with an offset that is nonnegative even when
  3306. // interpreted as signed, assume there is no unsigned overflow.
  3307. SDNodeFlags Flags;
  3308. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3309. Flags.setNoUnsignedWrap(true);
  3310. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3311. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3312. }
  3313. } else {
  3314. // IdxSize is the width of the arithmetic according to IR semantics.
  3315. // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
  3316. // (and fix up the result later).
  3317. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3318. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3319. TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
  3320. // We intentionally mask away the high bits here; ElementSize may not
  3321. // fit in IdxTy.
  3322. APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
  3323. bool ElementScalable = ElementSize.isScalable();
  3324. // If this is a scalar constant or a splat vector of constants,
  3325. // handle it quickly.
  3326. const auto *C = dyn_cast<Constant>(Idx);
  3327. if (C && isa<VectorType>(C->getType()))
  3328. C = C->getSplatValue();
  3329. const auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3330. if (CI && CI->isZero())
  3331. continue;
  3332. if (CI && !ElementScalable) {
  3333. APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
  3334. LLVMContext &Context = *DAG.getContext();
  3335. SDValue OffsVal;
  3336. if (IsVectorGEP)
  3337. OffsVal = DAG.getConstant(
  3338. Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
  3339. else
  3340. OffsVal = DAG.getConstant(Offs, dl, IdxTy);
  3341. // In an inbounds GEP with an offset that is nonnegative even when
  3342. // interpreted as signed, assume there is no unsigned overflow.
  3343. SDNodeFlags Flags;
  3344. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3345. Flags.setNoUnsignedWrap(true);
  3346. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3347. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3348. continue;
  3349. }
  3350. // N = N + Idx * ElementMul;
  3351. SDValue IdxN = getValue(Idx);
  3352. if (!IdxN.getValueType().isVector() && IsVectorGEP) {
  3353. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
  3354. VectorElementCount);
  3355. if (VectorElementCount.isScalable())
  3356. IdxN = DAG.getSplatVector(VT, dl, IdxN);
  3357. else
  3358. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3359. }
  3360. // If the index is smaller or larger than intptr_t, truncate or extend
  3361. // it.
  3362. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3363. if (ElementScalable) {
  3364. EVT VScaleTy = N.getValueType().getScalarType();
  3365. SDValue VScale = DAG.getNode(
  3366. ISD::VSCALE, dl, VScaleTy,
  3367. DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
  3368. if (IsVectorGEP)
  3369. VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
  3370. IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
  3371. } else {
  3372. // If this is a multiply by a power of two, turn it into a shl
  3373. // immediately. This is a very common case.
  3374. if (ElementMul != 1) {
  3375. if (ElementMul.isPowerOf2()) {
  3376. unsigned Amt = ElementMul.logBase2();
  3377. IdxN = DAG.getNode(ISD::SHL, dl,
  3378. N.getValueType(), IdxN,
  3379. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3380. } else {
  3381. SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
  3382. IdxN.getValueType());
  3383. IdxN = DAG.getNode(ISD::MUL, dl,
  3384. N.getValueType(), IdxN, Scale);
  3385. }
  3386. }
  3387. }
  3388. N = DAG.getNode(ISD::ADD, dl,
  3389. N.getValueType(), N, IdxN);
  3390. }
  3391. }
  3392. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3393. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3394. if (IsVectorGEP) {
  3395. PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
  3396. PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
  3397. }
  3398. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3399. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3400. setValue(&I, N);
  3401. }
  3402. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3403. // If this is a fixed sized alloca in the entry block of the function,
  3404. // allocate it statically on the stack.
  3405. if (FuncInfo.StaticAllocaMap.count(&I))
  3406. return; // getValue will auto-populate this.
  3407. SDLoc dl = getCurSDLoc();
  3408. Type *Ty = I.getAllocatedType();
  3409. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3410. auto &DL = DAG.getDataLayout();
  3411. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3412. MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
  3413. SDValue AllocSize = getValue(I.getArraySize());
  3414. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3415. if (AllocSize.getValueType() != IntPtr)
  3416. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3417. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3418. AllocSize,
  3419. DAG.getConstant(TySize, dl, IntPtr));
  3420. // Handle alignment. If the requested alignment is less than or equal to
  3421. // the stack alignment, ignore it. If the size is greater than or equal to
  3422. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3423. Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
  3424. if (*Alignment <= StackAlign)
  3425. Alignment = None;
  3426. const uint64_t StackAlignMask = StackAlign.value() - 1U;
  3427. // Round the size of the allocation up to the stack alignment size
  3428. // by add SA-1 to the size. This doesn't overflow because we're computing
  3429. // an address inside an alloca.
  3430. SDNodeFlags Flags;
  3431. Flags.setNoUnsignedWrap(true);
  3432. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3433. DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
  3434. // Mask out the low bits for alignment purposes.
  3435. AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3436. DAG.getConstant(~StackAlignMask, dl, IntPtr));
  3437. SDValue Ops[] = {
  3438. getRoot(), AllocSize,
  3439. DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
  3440. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3441. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3442. setValue(&I, DSA);
  3443. DAG.setRoot(DSA.getValue(1));
  3444. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3445. }
  3446. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3447. if (I.isAtomic())
  3448. return visitAtomicLoad(I);
  3449. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3450. const Value *SV = I.getOperand(0);
  3451. if (TLI.supportSwiftError()) {
  3452. // Swifterror values can come from either a function parameter with
  3453. // swifterror attribute or an alloca with swifterror attribute.
  3454. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3455. if (Arg->hasSwiftErrorAttr())
  3456. return visitLoadFromSwiftError(I);
  3457. }
  3458. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3459. if (Alloca->isSwiftError())
  3460. return visitLoadFromSwiftError(I);
  3461. }
  3462. }
  3463. SDValue Ptr = getValue(SV);
  3464. Type *Ty = I.getType();
  3465. Align Alignment = I.getAlign();
  3466. AAMDNodes AAInfo;
  3467. I.getAAMetadata(AAInfo);
  3468. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3469. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3470. SmallVector<uint64_t, 4> Offsets;
  3471. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3472. unsigned NumValues = ValueVTs.size();
  3473. if (NumValues == 0)
  3474. return;
  3475. bool isVolatile = I.isVolatile();
  3476. SDValue Root;
  3477. bool ConstantMemory = false;
  3478. if (isVolatile)
  3479. // Serialize volatile loads with other side effects.
  3480. Root = getRoot();
  3481. else if (NumValues > MaxParallelChains)
  3482. Root = getMemoryRoot();
  3483. else if (AA &&
  3484. AA->pointsToConstantMemory(MemoryLocation(
  3485. SV,
  3486. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3487. AAInfo))) {
  3488. // Do not serialize (non-volatile) loads of constant memory with anything.
  3489. Root = DAG.getEntryNode();
  3490. ConstantMemory = true;
  3491. } else {
  3492. // Do not serialize non-volatile loads against each other.
  3493. Root = DAG.getRoot();
  3494. }
  3495. SDLoc dl = getCurSDLoc();
  3496. if (isVolatile)
  3497. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3498. // An aggregate load cannot wrap around the address space, so offsets to its
  3499. // parts don't wrap either.
  3500. SDNodeFlags Flags;
  3501. Flags.setNoUnsignedWrap(true);
  3502. SmallVector<SDValue, 4> Values(NumValues);
  3503. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3504. EVT PtrVT = Ptr.getValueType();
  3505. MachineMemOperand::Flags MMOFlags
  3506. = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
  3507. unsigned ChainI = 0;
  3508. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3509. // Serializing loads here may result in excessive register pressure, and
  3510. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3511. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3512. // they are side-effect free or do not alias. The optimizer should really
  3513. // avoid this case by converting large object/array copies to llvm.memcpy
  3514. // (MaxParallelChains should always remain as failsafe).
  3515. if (ChainI == MaxParallelChains) {
  3516. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3517. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3518. makeArrayRef(Chains.data(), ChainI));
  3519. Root = Chain;
  3520. ChainI = 0;
  3521. }
  3522. SDValue A = DAG.getNode(ISD::ADD, dl,
  3523. PtrVT, Ptr,
  3524. DAG.getConstant(Offsets[i], dl, PtrVT),
  3525. Flags);
  3526. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3527. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3528. MMOFlags, AAInfo, Ranges);
  3529. Chains[ChainI] = L.getValue(1);
  3530. if (MemVTs[i] != ValueVTs[i])
  3531. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3532. Values[i] = L;
  3533. }
  3534. if (!ConstantMemory) {
  3535. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3536. makeArrayRef(Chains.data(), ChainI));
  3537. if (isVolatile)
  3538. DAG.setRoot(Chain);
  3539. else
  3540. PendingLoads.push_back(Chain);
  3541. }
  3542. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3543. DAG.getVTList(ValueVTs), Values));
  3544. }
  3545. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3546. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3547. "call visitStoreToSwiftError when backend supports swifterror");
  3548. SmallVector<EVT, 4> ValueVTs;
  3549. SmallVector<uint64_t, 4> Offsets;
  3550. const Value *SrcV = I.getOperand(0);
  3551. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3552. SrcV->getType(), ValueVTs, &Offsets);
  3553. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3554. "expect a single EVT for swifterror");
  3555. SDValue Src = getValue(SrcV);
  3556. // Create a virtual register, then update the virtual register.
  3557. Register VReg =
  3558. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3559. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3560. // Chain can be getRoot or getControlRoot.
  3561. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3562. SDValue(Src.getNode(), Src.getResNo()));
  3563. DAG.setRoot(CopyNode);
  3564. }
  3565. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3566. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3567. "call visitLoadFromSwiftError when backend supports swifterror");
  3568. assert(!I.isVolatile() &&
  3569. !I.hasMetadata(LLVMContext::MD_nontemporal) &&
  3570. !I.hasMetadata(LLVMContext::MD_invariant_load) &&
  3571. "Support volatile, non temporal, invariant for load_from_swift_error");
  3572. const Value *SV = I.getOperand(0);
  3573. Type *Ty = I.getType();
  3574. AAMDNodes AAInfo;
  3575. I.getAAMetadata(AAInfo);
  3576. assert(
  3577. (!AA ||
  3578. !AA->pointsToConstantMemory(MemoryLocation(
  3579. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3580. AAInfo))) &&
  3581. "load_from_swift_error should not be constant memory");
  3582. SmallVector<EVT, 4> ValueVTs;
  3583. SmallVector<uint64_t, 4> Offsets;
  3584. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3585. ValueVTs, &Offsets);
  3586. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3587. "expect a single EVT for swifterror");
  3588. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3589. SDValue L = DAG.getCopyFromReg(
  3590. getRoot(), getCurSDLoc(),
  3591. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3592. setValue(&I, L);
  3593. }
  3594. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3595. if (I.isAtomic())
  3596. return visitAtomicStore(I);
  3597. const Value *SrcV = I.getOperand(0);
  3598. const Value *PtrV = I.getOperand(1);
  3599. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3600. if (TLI.supportSwiftError()) {
  3601. // Swifterror values can come from either a function parameter with
  3602. // swifterror attribute or an alloca with swifterror attribute.
  3603. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3604. if (Arg->hasSwiftErrorAttr())
  3605. return visitStoreToSwiftError(I);
  3606. }
  3607. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3608. if (Alloca->isSwiftError())
  3609. return visitStoreToSwiftError(I);
  3610. }
  3611. }
  3612. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3613. SmallVector<uint64_t, 4> Offsets;
  3614. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3615. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3616. unsigned NumValues = ValueVTs.size();
  3617. if (NumValues == 0)
  3618. return;
  3619. // Get the lowered operands. Note that we do this after
  3620. // checking if NumResults is zero, because with zero results
  3621. // the operands won't have values in the map.
  3622. SDValue Src = getValue(SrcV);
  3623. SDValue Ptr = getValue(PtrV);
  3624. SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
  3625. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3626. SDLoc dl = getCurSDLoc();
  3627. Align Alignment = I.getAlign();
  3628. AAMDNodes AAInfo;
  3629. I.getAAMetadata(AAInfo);
  3630. auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
  3631. // An aggregate load cannot wrap around the address space, so offsets to its
  3632. // parts don't wrap either.
  3633. SDNodeFlags Flags;
  3634. Flags.setNoUnsignedWrap(true);
  3635. unsigned ChainI = 0;
  3636. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3637. // See visitLoad comments.
  3638. if (ChainI == MaxParallelChains) {
  3639. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3640. makeArrayRef(Chains.data(), ChainI));
  3641. Root = Chain;
  3642. ChainI = 0;
  3643. }
  3644. SDValue Add =
  3645. DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
  3646. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3647. if (MemVTs[i] != ValueVTs[i])
  3648. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3649. SDValue St =
  3650. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3651. Alignment, MMOFlags, AAInfo);
  3652. Chains[ChainI] = St;
  3653. }
  3654. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3655. makeArrayRef(Chains.data(), ChainI));
  3656. DAG.setRoot(StoreNode);
  3657. }
  3658. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3659. bool IsCompressing) {
  3660. SDLoc sdl = getCurSDLoc();
  3661. auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3662. MaybeAlign &Alignment) {
  3663. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3664. Src0 = I.getArgOperand(0);
  3665. Ptr = I.getArgOperand(1);
  3666. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
  3667. Mask = I.getArgOperand(3);
  3668. };
  3669. auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3670. MaybeAlign &Alignment) {
  3671. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3672. Src0 = I.getArgOperand(0);
  3673. Ptr = I.getArgOperand(1);
  3674. Mask = I.getArgOperand(2);
  3675. Alignment = None;
  3676. };
  3677. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3678. MaybeAlign Alignment;
  3679. if (IsCompressing)
  3680. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3681. else
  3682. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3683. SDValue Ptr = getValue(PtrOperand);
  3684. SDValue Src0 = getValue(Src0Operand);
  3685. SDValue Mask = getValue(MaskOperand);
  3686. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  3687. EVT VT = Src0.getValueType();
  3688. if (!Alignment)
  3689. Alignment = DAG.getEVTAlign(VT);
  3690. AAMDNodes AAInfo;
  3691. I.getAAMetadata(AAInfo);
  3692. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3693. MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
  3694. // TODO: Make MachineMemOperands aware of scalable
  3695. // vectors.
  3696. VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
  3697. SDValue StoreNode =
  3698. DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
  3699. ISD::UNINDEXED, false /* Truncating */, IsCompressing);
  3700. DAG.setRoot(StoreNode);
  3701. setValue(&I, StoreNode);
  3702. }
  3703. // Get a uniform base for the Gather/Scatter intrinsic.
  3704. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3705. // We try to represent it as a base pointer + vector of indices.
  3706. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3707. // The first operand of the GEP may be a single pointer or a vector of pointers
  3708. // Example:
  3709. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3710. // or
  3711. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3712. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3713. //
  3714. // When the first GEP operand is a single pointer - it is the uniform base we
  3715. // are looking for. If first operand of the GEP is a splat vector - we
  3716. // extract the splat value and use it as a uniform base.
  3717. // In all other cases the function returns 'false'.
  3718. static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
  3719. ISD::MemIndexType &IndexType, SDValue &Scale,
  3720. SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
  3721. SelectionDAG& DAG = SDB->DAG;
  3722. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3723. const DataLayout &DL = DAG.getDataLayout();
  3724. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3725. // Handle splat constant pointer.
  3726. if (auto *C = dyn_cast<Constant>(Ptr)) {
  3727. C = C->getSplatValue();
  3728. if (!C)
  3729. return false;
  3730. Base = SDB->getValue(C);
  3731. unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
  3732. EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
  3733. Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
  3734. IndexType = ISD::SIGNED_SCALED;
  3735. Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3736. return true;
  3737. }
  3738. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3739. if (!GEP || GEP->getParent() != CurBB)
  3740. return false;
  3741. if (GEP->getNumOperands() != 2)
  3742. return false;
  3743. const Value *BasePtr = GEP->getPointerOperand();
  3744. const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
  3745. // Make sure the base is scalar and the index is a vector.
  3746. if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
  3747. return false;
  3748. Base = SDB->getValue(BasePtr);
  3749. Index = SDB->getValue(IndexVal);
  3750. IndexType = ISD::SIGNED_SCALED;
  3751. Scale = DAG.getTargetConstant(
  3752. DL.getTypeAllocSize(GEP->getResultElementType()),
  3753. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3754. return true;
  3755. }
  3756. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3757. SDLoc sdl = getCurSDLoc();
  3758. // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
  3759. const Value *Ptr = I.getArgOperand(1);
  3760. SDValue Src0 = getValue(I.getArgOperand(0));
  3761. SDValue Mask = getValue(I.getArgOperand(3));
  3762. EVT VT = Src0.getValueType();
  3763. Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
  3764. ->getMaybeAlignValue()
  3765. .getValueOr(DAG.getEVTAlign(VT));
  3766. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3767. AAMDNodes AAInfo;
  3768. I.getAAMetadata(AAInfo);
  3769. SDValue Base;
  3770. SDValue Index;
  3771. ISD::MemIndexType IndexType;
  3772. SDValue Scale;
  3773. bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
  3774. I.getParent());
  3775. unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
  3776. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3777. MachinePointerInfo(AS), MachineMemOperand::MOStore,
  3778. // TODO: Make MachineMemOperands aware of scalable
  3779. // vectors.
  3780. MemoryLocation::UnknownSize, Alignment, AAInfo);
  3781. if (!UniformBase) {
  3782. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3783. Index = getValue(Ptr);
  3784. IndexType = ISD::SIGNED_UNSCALED;
  3785. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3786. }
  3787. SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
  3788. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3789. Ops, MMO, IndexType, false);
  3790. DAG.setRoot(Scatter);
  3791. setValue(&I, Scatter);
  3792. }
  3793. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3794. SDLoc sdl = getCurSDLoc();
  3795. auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3796. MaybeAlign &Alignment) {
  3797. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3798. Ptr = I.getArgOperand(0);
  3799. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
  3800. Mask = I.getArgOperand(2);
  3801. Src0 = I.getArgOperand(3);
  3802. };
  3803. auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3804. MaybeAlign &Alignment) {
  3805. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3806. Ptr = I.getArgOperand(0);
  3807. Alignment = None;
  3808. Mask = I.getArgOperand(1);
  3809. Src0 = I.getArgOperand(2);
  3810. };
  3811. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3812. MaybeAlign Alignment;
  3813. if (IsExpanding)
  3814. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3815. else
  3816. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3817. SDValue Ptr = getValue(PtrOperand);
  3818. SDValue Src0 = getValue(Src0Operand);
  3819. SDValue Mask = getValue(MaskOperand);
  3820. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  3821. EVT VT = Src0.getValueType();
  3822. if (!Alignment)
  3823. Alignment = DAG.getEVTAlign(VT);
  3824. AAMDNodes AAInfo;
  3825. I.getAAMetadata(AAInfo);
  3826. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3827. // Do not serialize masked loads of constant memory with anything.
  3828. MemoryLocation ML;
  3829. if (VT.isScalableVector())
  3830. ML = MemoryLocation::getAfter(PtrOperand);
  3831. else
  3832. ML = MemoryLocation(PtrOperand, LocationSize::precise(
  3833. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3834. AAInfo);
  3835. bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
  3836. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3837. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3838. MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
  3839. // TODO: Make MachineMemOperands aware of scalable
  3840. // vectors.
  3841. VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
  3842. SDValue Load =
  3843. DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
  3844. ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
  3845. if (AddToChain)
  3846. PendingLoads.push_back(Load.getValue(1));
  3847. setValue(&I, Load);
  3848. }
  3849. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3850. SDLoc sdl = getCurSDLoc();
  3851. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3852. const Value *Ptr = I.getArgOperand(0);
  3853. SDValue Src0 = getValue(I.getArgOperand(3));
  3854. SDValue Mask = getValue(I.getArgOperand(2));
  3855. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3856. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3857. Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
  3858. ->getMaybeAlignValue()
  3859. .getValueOr(DAG.getEVTAlign(VT));
  3860. AAMDNodes AAInfo;
  3861. I.getAAMetadata(AAInfo);
  3862. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3863. SDValue Root = DAG.getRoot();
  3864. SDValue Base;
  3865. SDValue Index;
  3866. ISD::MemIndexType IndexType;
  3867. SDValue Scale;
  3868. bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
  3869. I.getParent());
  3870. unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
  3871. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3872. MachinePointerInfo(AS), MachineMemOperand::MOLoad,
  3873. // TODO: Make MachineMemOperands aware of scalable
  3874. // vectors.
  3875. MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
  3876. if (!UniformBase) {
  3877. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3878. Index = getValue(Ptr);
  3879. IndexType = ISD::SIGNED_UNSCALED;
  3880. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3881. }
  3882. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3883. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3884. Ops, MMO, IndexType, ISD::NON_EXTLOAD);
  3885. PendingLoads.push_back(Gather.getValue(1));
  3886. setValue(&I, Gather);
  3887. }
  3888. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3889. SDLoc dl = getCurSDLoc();
  3890. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3891. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3892. SyncScope::ID SSID = I.getSyncScopeID();
  3893. SDValue InChain = getRoot();
  3894. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3895. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3896. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3897. auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
  3898. MachineFunction &MF = DAG.getMachineFunction();
  3899. MachineMemOperand *MMO = MF.getMachineMemOperand(
  3900. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  3901. DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3902. FailureOrdering);
  3903. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3904. dl, MemVT, VTs, InChain,
  3905. getValue(I.getPointerOperand()),
  3906. getValue(I.getCompareOperand()),
  3907. getValue(I.getNewValOperand()), MMO);
  3908. SDValue OutChain = L.getValue(2);
  3909. setValue(&I, L);
  3910. DAG.setRoot(OutChain);
  3911. }
  3912. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3913. SDLoc dl = getCurSDLoc();
  3914. ISD::NodeType NT;
  3915. switch (I.getOperation()) {
  3916. default: llvm_unreachable("Unknown atomicrmw operation");
  3917. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3918. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3919. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3920. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3921. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3922. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3923. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3924. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3925. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3926. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3927. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3928. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3929. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3930. }
  3931. AtomicOrdering Ordering = I.getOrdering();
  3932. SyncScope::ID SSID = I.getSyncScopeID();
  3933. SDValue InChain = getRoot();
  3934. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3935. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3936. auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
  3937. MachineFunction &MF = DAG.getMachineFunction();
  3938. MachineMemOperand *MMO = MF.getMachineMemOperand(
  3939. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  3940. DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
  3941. SDValue L =
  3942. DAG.getAtomic(NT, dl, MemVT, InChain,
  3943. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  3944. MMO);
  3945. SDValue OutChain = L.getValue(1);
  3946. setValue(&I, L);
  3947. DAG.setRoot(OutChain);
  3948. }
  3949. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3950. SDLoc dl = getCurSDLoc();
  3951. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3952. SDValue Ops[3];
  3953. Ops[0] = getRoot();
  3954. Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
  3955. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3956. Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
  3957. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3958. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3959. }
  3960. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3961. SDLoc dl = getCurSDLoc();
  3962. AtomicOrdering Order = I.getOrdering();
  3963. SyncScope::ID SSID = I.getSyncScopeID();
  3964. SDValue InChain = getRoot();
  3965. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3966. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3967. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3968. if (!TLI.supportsUnalignedAtomics() &&
  3969. I.getAlignment() < MemVT.getSizeInBits() / 8)
  3970. report_fatal_error("Cannot generate unaligned atomic load");
  3971. auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
  3972. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3973. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  3974. I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
  3975. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3976. SDValue Ptr = getValue(I.getPointerOperand());
  3977. if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
  3978. // TODO: Once this is better exercised by tests, it should be merged with
  3979. // the normal path for loads to prevent future divergence.
  3980. SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
  3981. if (MemVT != VT)
  3982. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  3983. setValue(&I, L);
  3984. SDValue OutChain = L.getValue(1);
  3985. if (!I.isUnordered())
  3986. DAG.setRoot(OutChain);
  3987. else
  3988. PendingLoads.push_back(OutChain);
  3989. return;
  3990. }
  3991. SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  3992. Ptr, MMO);
  3993. SDValue OutChain = L.getValue(1);
  3994. if (MemVT != VT)
  3995. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  3996. setValue(&I, L);
  3997. DAG.setRoot(OutChain);
  3998. }
  3999. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4000. SDLoc dl = getCurSDLoc();
  4001. AtomicOrdering Ordering = I.getOrdering();
  4002. SyncScope::ID SSID = I.getSyncScopeID();
  4003. SDValue InChain = getRoot();
  4004. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4005. EVT MemVT =
  4006. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4007. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4008. report_fatal_error("Cannot generate unaligned atomic store");
  4009. auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
  4010. MachineFunction &MF = DAG.getMachineFunction();
  4011. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4012. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4013. I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
  4014. SDValue Val = getValue(I.getValueOperand());
  4015. if (Val.getValueType() != MemVT)
  4016. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4017. SDValue Ptr = getValue(I.getPointerOperand());
  4018. if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
  4019. // TODO: Once this is better exercised by tests, it should be merged with
  4020. // the normal path for stores to prevent future divergence.
  4021. SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
  4022. DAG.setRoot(S);
  4023. return;
  4024. }
  4025. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4026. Ptr, Val, MMO);
  4027. DAG.setRoot(OutChain);
  4028. }
  4029. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4030. /// node.
  4031. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4032. unsigned Intrinsic) {
  4033. // Ignore the callsite's attributes. A specific call site may be marked with
  4034. // readnone, but the lowering code will expect the chain based on the
  4035. // definition.
  4036. const Function *F = I.getCalledFunction();
  4037. bool HasChain = !F->doesNotAccessMemory();
  4038. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4039. // Build the operand list.
  4040. SmallVector<SDValue, 8> Ops;
  4041. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4042. if (OnlyLoad) {
  4043. // We don't need to serialize loads against other loads.
  4044. Ops.push_back(DAG.getRoot());
  4045. } else {
  4046. Ops.push_back(getRoot());
  4047. }
  4048. }
  4049. // Info is set by getTgtMemInstrinsic
  4050. TargetLowering::IntrinsicInfo Info;
  4051. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4052. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4053. DAG.getMachineFunction(),
  4054. Intrinsic);
  4055. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4056. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4057. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4058. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4059. TLI.getPointerTy(DAG.getDataLayout())));
  4060. // Add all operands of the call to the operand list.
  4061. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4062. const Value *Arg = I.getArgOperand(i);
  4063. if (!I.paramHasAttr(i, Attribute::ImmArg)) {
  4064. Ops.push_back(getValue(Arg));
  4065. continue;
  4066. }
  4067. // Use TargetConstant instead of a regular constant for immarg.
  4068. EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
  4069. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
  4070. assert(CI->getBitWidth() <= 64 &&
  4071. "large intrinsic immediates not handled");
  4072. Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
  4073. } else {
  4074. Ops.push_back(
  4075. DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
  4076. }
  4077. }
  4078. SmallVector<EVT, 4> ValueVTs;
  4079. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4080. if (HasChain)
  4081. ValueVTs.push_back(MVT::Other);
  4082. SDVTList VTs = DAG.getVTList(ValueVTs);
  4083. // Create the node.
  4084. SDValue Result;
  4085. if (IsTgtIntrinsic) {
  4086. // This is target intrinsic that touches memory
  4087. AAMDNodes AAInfo;
  4088. I.getAAMetadata(AAInfo);
  4089. Result =
  4090. DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4091. MachinePointerInfo(Info.ptrVal, Info.offset),
  4092. Info.align, Info.flags, Info.size, AAInfo);
  4093. } else if (!HasChain) {
  4094. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4095. } else if (!I.getType()->isVoidTy()) {
  4096. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4097. } else {
  4098. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4099. }
  4100. if (HasChain) {
  4101. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4102. if (OnlyLoad)
  4103. PendingLoads.push_back(Chain);
  4104. else
  4105. DAG.setRoot(Chain);
  4106. }
  4107. if (!I.getType()->isVoidTy()) {
  4108. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4109. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4110. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4111. } else
  4112. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4113. MaybeAlign Alignment = I.getRetAlign();
  4114. if (!Alignment)
  4115. Alignment = F->getAttributes().getRetAlignment();
  4116. // Insert `assertalign` node if there's an alignment.
  4117. if (InsertAssertAlign && Alignment) {
  4118. Result =
  4119. DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
  4120. }
  4121. setValue(&I, Result);
  4122. }
  4123. }
  4124. /// GetSignificand - Get the significand and build it into a floating-point
  4125. /// number with exponent of 1:
  4126. ///
  4127. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4128. ///
  4129. /// where Op is the hexadecimal representation of floating point value.
  4130. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4131. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4132. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4133. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4134. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4135. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4136. }
  4137. /// GetExponent - Get the exponent:
  4138. ///
  4139. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4140. ///
  4141. /// where Op is the hexadecimal representation of floating point value.
  4142. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4143. const TargetLowering &TLI, const SDLoc &dl) {
  4144. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4145. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4146. SDValue t1 = DAG.getNode(
  4147. ISD::SRL, dl, MVT::i32, t0,
  4148. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4149. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4150. DAG.getConstant(127, dl, MVT::i32));
  4151. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4152. }
  4153. /// getF32Constant - Get 32-bit floating point constant.
  4154. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4155. const SDLoc &dl) {
  4156. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4157. MVT::f32);
  4158. }
  4159. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4160. SelectionDAG &DAG) {
  4161. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4162. // IntegerPartOfX = ((int32_t)(t0);
  4163. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4164. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4165. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4166. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4167. // IntegerPartOfX <<= 23;
  4168. IntegerPartOfX = DAG.getNode(
  4169. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4170. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4171. DAG.getDataLayout())));
  4172. SDValue TwoToFractionalPartOfX;
  4173. if (LimitFloatPrecision <= 6) {
  4174. // For floating-point precision of 6:
  4175. //
  4176. // TwoToFractionalPartOfX =
  4177. // 0.997535578f +
  4178. // (0.735607626f + 0.252464424f * x) * x;
  4179. //
  4180. // error 0.0144103317, which is 6 bits
  4181. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4182. getF32Constant(DAG, 0x3e814304, dl));
  4183. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4184. getF32Constant(DAG, 0x3f3c50c8, dl));
  4185. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4186. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4187. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4188. } else if (LimitFloatPrecision <= 12) {
  4189. // For floating-point precision of 12:
  4190. //
  4191. // TwoToFractionalPartOfX =
  4192. // 0.999892986f +
  4193. // (0.696457318f +
  4194. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4195. //
  4196. // error 0.000107046256, which is 13 to 14 bits
  4197. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4198. getF32Constant(DAG, 0x3da235e3, dl));
  4199. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4200. getF32Constant(DAG, 0x3e65b8f3, dl));
  4201. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4202. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4203. getF32Constant(DAG, 0x3f324b07, dl));
  4204. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4205. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4206. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4207. } else { // LimitFloatPrecision <= 18
  4208. // For floating-point precision of 18:
  4209. //
  4210. // TwoToFractionalPartOfX =
  4211. // 0.999999982f +
  4212. // (0.693148872f +
  4213. // (0.240227044f +
  4214. // (0.554906021e-1f +
  4215. // (0.961591928e-2f +
  4216. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4217. // error 2.47208000*10^(-7), which is better than 18 bits
  4218. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4219. getF32Constant(DAG, 0x3924b03e, dl));
  4220. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4221. getF32Constant(DAG, 0x3ab24b87, dl));
  4222. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4223. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4224. getF32Constant(DAG, 0x3c1d8c17, dl));
  4225. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4226. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4227. getF32Constant(DAG, 0x3d634a1d, dl));
  4228. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4229. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4230. getF32Constant(DAG, 0x3e75fe14, dl));
  4231. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4232. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4233. getF32Constant(DAG, 0x3f317234, dl));
  4234. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4235. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4236. getF32Constant(DAG, 0x3f800000, dl));
  4237. }
  4238. // Add the exponent into the result in integer domain.
  4239. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4240. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4241. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4242. }
  4243. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4244. /// limited-precision mode.
  4245. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4246. const TargetLowering &TLI, SDNodeFlags Flags) {
  4247. if (Op.getValueType() == MVT::f32 &&
  4248. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4249. // Put the exponent in the right bit position for later addition to the
  4250. // final result:
  4251. //
  4252. // t0 = Op * log2(e)
  4253. // TODO: What fast-math-flags should be set here?
  4254. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4255. DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
  4256. return getLimitedPrecisionExp2(t0, dl, DAG);
  4257. }
  4258. // No special expansion.
  4259. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
  4260. }
  4261. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4262. /// limited-precision mode.
  4263. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4264. const TargetLowering &TLI, SDNodeFlags Flags) {
  4265. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4266. if (Op.getValueType() == MVT::f32 &&
  4267. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4268. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4269. // Scale the exponent by log(2).
  4270. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4271. SDValue LogOfExponent =
  4272. DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4273. DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
  4274. // Get the significand and build it into a floating-point number with
  4275. // exponent of 1.
  4276. SDValue X = GetSignificand(DAG, Op1, dl);
  4277. SDValue LogOfMantissa;
  4278. if (LimitFloatPrecision <= 6) {
  4279. // For floating-point precision of 6:
  4280. //
  4281. // LogofMantissa =
  4282. // -1.1609546f +
  4283. // (1.4034025f - 0.23903021f * x) * x;
  4284. //
  4285. // error 0.0034276066, which is better than 8 bits
  4286. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4287. getF32Constant(DAG, 0xbe74c456, dl));
  4288. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4289. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4290. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4291. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4292. getF32Constant(DAG, 0x3f949a29, dl));
  4293. } else if (LimitFloatPrecision <= 12) {
  4294. // For floating-point precision of 12:
  4295. //
  4296. // LogOfMantissa =
  4297. // -1.7417939f +
  4298. // (2.8212026f +
  4299. // (-1.4699568f +
  4300. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4301. //
  4302. // error 0.000061011436, which is 14 bits
  4303. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4304. getF32Constant(DAG, 0xbd67b6d6, dl));
  4305. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4306. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4307. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4308. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4309. getF32Constant(DAG, 0x3fbc278b, dl));
  4310. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4311. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4312. getF32Constant(DAG, 0x40348e95, dl));
  4313. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4314. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4315. getF32Constant(DAG, 0x3fdef31a, dl));
  4316. } else { // LimitFloatPrecision <= 18
  4317. // For floating-point precision of 18:
  4318. //
  4319. // LogOfMantissa =
  4320. // -2.1072184f +
  4321. // (4.2372794f +
  4322. // (-3.7029485f +
  4323. // (2.2781945f +
  4324. // (-0.87823314f +
  4325. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4326. //
  4327. // error 0.0000023660568, which is better than 18 bits
  4328. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4329. getF32Constant(DAG, 0xbc91e5ac, dl));
  4330. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4331. getF32Constant(DAG, 0x3e4350aa, dl));
  4332. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4333. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4334. getF32Constant(DAG, 0x3f60d3e3, dl));
  4335. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4336. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4337. getF32Constant(DAG, 0x4011cdf0, dl));
  4338. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4339. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4340. getF32Constant(DAG, 0x406cfd1c, dl));
  4341. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4342. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4343. getF32Constant(DAG, 0x408797cb, dl));
  4344. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4345. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4346. getF32Constant(DAG, 0x4006dcab, dl));
  4347. }
  4348. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4349. }
  4350. // No special expansion.
  4351. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
  4352. }
  4353. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4354. /// limited-precision mode.
  4355. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4356. const TargetLowering &TLI, SDNodeFlags Flags) {
  4357. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4358. if (Op.getValueType() == MVT::f32 &&
  4359. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4360. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4361. // Get the exponent.
  4362. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4363. // Get the significand and build it into a floating-point number with
  4364. // exponent of 1.
  4365. SDValue X = GetSignificand(DAG, Op1, dl);
  4366. // Different possible minimax approximations of significand in
  4367. // floating-point for various degrees of accuracy over [1,2].
  4368. SDValue Log2ofMantissa;
  4369. if (LimitFloatPrecision <= 6) {
  4370. // For floating-point precision of 6:
  4371. //
  4372. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4373. //
  4374. // error 0.0049451742, which is more than 7 bits
  4375. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4376. getF32Constant(DAG, 0xbeb08fe0, dl));
  4377. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4378. getF32Constant(DAG, 0x40019463, dl));
  4379. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4380. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4381. getF32Constant(DAG, 0x3fd6633d, dl));
  4382. } else if (LimitFloatPrecision <= 12) {
  4383. // For floating-point precision of 12:
  4384. //
  4385. // Log2ofMantissa =
  4386. // -2.51285454f +
  4387. // (4.07009056f +
  4388. // (-2.12067489f +
  4389. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4390. //
  4391. // error 0.0000876136000, which is better than 13 bits
  4392. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4393. getF32Constant(DAG, 0xbda7262e, dl));
  4394. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4395. getF32Constant(DAG, 0x3f25280b, dl));
  4396. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4397. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4398. getF32Constant(DAG, 0x4007b923, dl));
  4399. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4400. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4401. getF32Constant(DAG, 0x40823e2f, dl));
  4402. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4403. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4404. getF32Constant(DAG, 0x4020d29c, dl));
  4405. } else { // LimitFloatPrecision <= 18
  4406. // For floating-point precision of 18:
  4407. //
  4408. // Log2ofMantissa =
  4409. // -3.0400495f +
  4410. // (6.1129976f +
  4411. // (-5.3420409f +
  4412. // (3.2865683f +
  4413. // (-1.2669343f +
  4414. // (0.27515199f -
  4415. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4416. //
  4417. // error 0.0000018516, which is better than 18 bits
  4418. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4419. getF32Constant(DAG, 0xbcd2769e, dl));
  4420. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4421. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4422. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4423. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4424. getF32Constant(DAG, 0x3fa22ae7, dl));
  4425. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4426. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4427. getF32Constant(DAG, 0x40525723, dl));
  4428. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4429. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4430. getF32Constant(DAG, 0x40aaf200, dl));
  4431. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4432. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4433. getF32Constant(DAG, 0x40c39dad, dl));
  4434. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4435. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4436. getF32Constant(DAG, 0x4042902c, dl));
  4437. }
  4438. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4439. }
  4440. // No special expansion.
  4441. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
  4442. }
  4443. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4444. /// limited-precision mode.
  4445. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4446. const TargetLowering &TLI, SDNodeFlags Flags) {
  4447. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4448. if (Op.getValueType() == MVT::f32 &&
  4449. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4450. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4451. // Scale the exponent by log10(2) [0.30102999f].
  4452. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4453. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4454. getF32Constant(DAG, 0x3e9a209a, dl));
  4455. // Get the significand and build it into a floating-point number with
  4456. // exponent of 1.
  4457. SDValue X = GetSignificand(DAG, Op1, dl);
  4458. SDValue Log10ofMantissa;
  4459. if (LimitFloatPrecision <= 6) {
  4460. // For floating-point precision of 6:
  4461. //
  4462. // Log10ofMantissa =
  4463. // -0.50419619f +
  4464. // (0.60948995f - 0.10380950f * x) * x;
  4465. //
  4466. // error 0.0014886165, which is 6 bits
  4467. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4468. getF32Constant(DAG, 0xbdd49a13, dl));
  4469. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4470. getF32Constant(DAG, 0x3f1c0789, dl));
  4471. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4472. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4473. getF32Constant(DAG, 0x3f011300, dl));
  4474. } else if (LimitFloatPrecision <= 12) {
  4475. // For floating-point precision of 12:
  4476. //
  4477. // Log10ofMantissa =
  4478. // -0.64831180f +
  4479. // (0.91751397f +
  4480. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4481. //
  4482. // error 0.00019228036, which is better than 12 bits
  4483. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4484. getF32Constant(DAG, 0x3d431f31, dl));
  4485. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4486. getF32Constant(DAG, 0x3ea21fb2, dl));
  4487. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4488. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4489. getF32Constant(DAG, 0x3f6ae232, dl));
  4490. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4491. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4492. getF32Constant(DAG, 0x3f25f7c3, dl));
  4493. } else { // LimitFloatPrecision <= 18
  4494. // For floating-point precision of 18:
  4495. //
  4496. // Log10ofMantissa =
  4497. // -0.84299375f +
  4498. // (1.5327582f +
  4499. // (-1.0688956f +
  4500. // (0.49102474f +
  4501. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4502. //
  4503. // error 0.0000037995730, which is better than 18 bits
  4504. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4505. getF32Constant(DAG, 0x3c5d51ce, dl));
  4506. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4507. getF32Constant(DAG, 0x3e00685a, dl));
  4508. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4509. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4510. getF32Constant(DAG, 0x3efb6798, dl));
  4511. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4512. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4513. getF32Constant(DAG, 0x3f88d192, dl));
  4514. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4515. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4516. getF32Constant(DAG, 0x3fc4316c, dl));
  4517. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4518. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4519. getF32Constant(DAG, 0x3f57ce70, dl));
  4520. }
  4521. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4522. }
  4523. // No special expansion.
  4524. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
  4525. }
  4526. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4527. /// limited-precision mode.
  4528. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4529. const TargetLowering &TLI, SDNodeFlags Flags) {
  4530. if (Op.getValueType() == MVT::f32 &&
  4531. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4532. return getLimitedPrecisionExp2(Op, dl, DAG);
  4533. // No special expansion.
  4534. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
  4535. }
  4536. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4537. /// limited-precision mode with x == 10.0f.
  4538. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4539. SelectionDAG &DAG, const TargetLowering &TLI,
  4540. SDNodeFlags Flags) {
  4541. bool IsExp10 = false;
  4542. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4543. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4544. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4545. APFloat Ten(10.0f);
  4546. IsExp10 = LHSC->isExactlyValue(Ten);
  4547. }
  4548. }
  4549. // TODO: What fast-math-flags should be set on the FMUL node?
  4550. if (IsExp10) {
  4551. // Put the exponent in the right bit position for later addition to the
  4552. // final result:
  4553. //
  4554. // #define LOG2OF10 3.3219281f
  4555. // t0 = Op * LOG2OF10;
  4556. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4557. getF32Constant(DAG, 0x40549a78, dl));
  4558. return getLimitedPrecisionExp2(t0, dl, DAG);
  4559. }
  4560. // No special expansion.
  4561. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
  4562. }
  4563. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4564. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4565. SelectionDAG &DAG) {
  4566. // If RHS is a constant, we can expand this out to a multiplication tree,
  4567. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4568. // optimizing for size, we only want to do this if the expansion would produce
  4569. // a small number of multiplies, otherwise we do the full expansion.
  4570. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4571. // Get the exponent as a positive value.
  4572. unsigned Val = RHSC->getSExtValue();
  4573. if ((int)Val < 0) Val = -Val;
  4574. // powi(x, 0) -> 1.0
  4575. if (Val == 0)
  4576. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4577. bool OptForSize = DAG.shouldOptForSize();
  4578. if (!OptForSize ||
  4579. // If optimizing for size, don't insert too many multiplies.
  4580. // This inserts up to 5 multiplies.
  4581. countPopulation(Val) + Log2_32(Val) < 7) {
  4582. // We use the simple binary decomposition method to generate the multiply
  4583. // sequence. There are more optimal ways to do this (for example,
  4584. // powi(x,15) generates one more multiply than it should), but this has
  4585. // the benefit of being both really simple and much better than a libcall.
  4586. SDValue Res; // Logically starts equal to 1.0
  4587. SDValue CurSquare = LHS;
  4588. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4589. // nodes.
  4590. while (Val) {
  4591. if (Val & 1) {
  4592. if (Res.getNode())
  4593. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4594. else
  4595. Res = CurSquare; // 1.0*CurSquare.
  4596. }
  4597. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4598. CurSquare, CurSquare);
  4599. Val >>= 1;
  4600. }
  4601. // If the original was negative, invert the result, producing 1/(x*x*x).
  4602. if (RHSC->getSExtValue() < 0)
  4603. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4604. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4605. return Res;
  4606. }
  4607. }
  4608. // Otherwise, expand to a libcall.
  4609. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4610. }
  4611. static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
  4612. SDValue LHS, SDValue RHS, SDValue Scale,
  4613. SelectionDAG &DAG, const TargetLowering &TLI) {
  4614. EVT VT = LHS.getValueType();
  4615. bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
  4616. bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
  4617. LLVMContext &Ctx = *DAG.getContext();
  4618. // If the type is legal but the operation isn't, this node might survive all
  4619. // the way to operation legalization. If we end up there and we do not have
  4620. // the ability to widen the type (if VT*2 is not legal), we cannot expand the
  4621. // node.
  4622. // Coax the legalizer into expanding the node during type legalization instead
  4623. // by bumping the size by one bit. This will force it to Promote, enabling the
  4624. // early expansion and avoiding the need to expand later.
  4625. // We don't have to do this if Scale is 0; that can always be expanded, unless
  4626. // it's a saturating signed operation. Those can experience true integer
  4627. // division overflow, a case which we must avoid.
  4628. // FIXME: We wouldn't have to do this (or any of the early
  4629. // expansion/promotion) if it was possible to expand a libcall of an
  4630. // illegal type during operation legalization. But it's not, so things
  4631. // get a bit hacky.
  4632. unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
  4633. if ((ScaleInt > 0 || (Saturating && Signed)) &&
  4634. (TLI.isTypeLegal(VT) ||
  4635. (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
  4636. TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
  4637. Opcode, VT, ScaleInt);
  4638. if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
  4639. EVT PromVT;
  4640. if (VT.isScalarInteger())
  4641. PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
  4642. else if (VT.isVector()) {
  4643. PromVT = VT.getVectorElementType();
  4644. PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
  4645. PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
  4646. } else
  4647. llvm_unreachable("Wrong VT for DIVFIX?");
  4648. if (Signed) {
  4649. LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
  4650. RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
  4651. } else {
  4652. LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
  4653. RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
  4654. }
  4655. EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
  4656. // For saturating operations, we need to shift up the LHS to get the
  4657. // proper saturation width, and then shift down again afterwards.
  4658. if (Saturating)
  4659. LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
  4660. DAG.getConstant(1, DL, ShiftTy));
  4661. SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
  4662. if (Saturating)
  4663. Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
  4664. DAG.getConstant(1, DL, ShiftTy));
  4665. return DAG.getZExtOrTrunc(Res, DL, VT);
  4666. }
  4667. }
  4668. return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
  4669. }
  4670. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4671. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4672. static void
  4673. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
  4674. const SDValue &N) {
  4675. switch (N.getOpcode()) {
  4676. case ISD::CopyFromReg: {
  4677. SDValue Op = N.getOperand(1);
  4678. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4679. Op.getValueType().getSizeInBits());
  4680. return;
  4681. }
  4682. case ISD::BITCAST:
  4683. case ISD::AssertZext:
  4684. case ISD::AssertSext:
  4685. case ISD::TRUNCATE:
  4686. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4687. return;
  4688. case ISD::BUILD_PAIR:
  4689. case ISD::BUILD_VECTOR:
  4690. case ISD::CONCAT_VECTORS:
  4691. for (SDValue Op : N->op_values())
  4692. getUnderlyingArgRegs(Regs, Op);
  4693. return;
  4694. default:
  4695. return;
  4696. }
  4697. }
  4698. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4699. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4700. /// instruction selection, they will be inserted to the entry BB.
  4701. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4702. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4703. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4704. const Argument *Arg = dyn_cast<Argument>(V);
  4705. if (!Arg)
  4706. return false;
  4707. if (!IsDbgDeclare) {
  4708. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4709. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4710. // the entry block.
  4711. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4712. if (!IsInEntryBlock)
  4713. return false;
  4714. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4715. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4716. // variable that also is a param.
  4717. //
  4718. // Although, if we are at the top of the entry block already, we can still
  4719. // emit using ArgDbgValue. This might catch some situations when the
  4720. // dbg.value refers to an argument that isn't used in the entry block, so
  4721. // any CopyToReg node would be optimized out and the only way to express
  4722. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4723. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4724. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4725. // current function, and the dbg.value intrinsic is found in the entry
  4726. // block.
  4727. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4728. !DL->getInlinedAt();
  4729. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4730. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4731. return false;
  4732. // Here we assume that a function argument on IR level only can be used to
  4733. // describe one input parameter on source level. If we for example have
  4734. // source code like this
  4735. //
  4736. // struct A { long x, y; };
  4737. // void foo(struct A a, long b) {
  4738. // ...
  4739. // b = a.x;
  4740. // ...
  4741. // }
  4742. //
  4743. // and IR like this
  4744. //
  4745. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4746. // entry:
  4747. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4748. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4749. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4750. // ...
  4751. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4752. // ...
  4753. //
  4754. // then the last dbg.value is describing a parameter "b" using a value that
  4755. // is an argument. But since we already has used %a1 to describe a parameter
  4756. // we should not handle that last dbg.value here (that would result in an
  4757. // incorrect hoisting of the DBG_VALUE to the function entry).
  4758. // Notice that we allow one dbg.value per IR level argument, to accommodate
  4759. // for the situation with fragments above.
  4760. if (VariableIsFunctionInputArg) {
  4761. unsigned ArgNo = Arg->getArgNo();
  4762. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4763. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4764. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4765. return false;
  4766. FuncInfo.DescribedArgs.set(ArgNo);
  4767. }
  4768. }
  4769. MachineFunction &MF = DAG.getMachineFunction();
  4770. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4771. bool IsIndirect = false;
  4772. Optional<MachineOperand> Op;
  4773. // Some arguments' frame index is recorded during argument lowering.
  4774. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4775. if (FI != std::numeric_limits<int>::max())
  4776. Op = MachineOperand::CreateFI(FI);
  4777. SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
  4778. if (!Op && N.getNode()) {
  4779. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4780. Register Reg;
  4781. if (ArgRegsAndSizes.size() == 1)
  4782. Reg = ArgRegsAndSizes.front().first;
  4783. if (Reg && Reg.isVirtual()) {
  4784. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4785. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4786. if (PR)
  4787. Reg = PR;
  4788. }
  4789. if (Reg) {
  4790. Op = MachineOperand::CreateReg(Reg, false);
  4791. IsIndirect = IsDbgDeclare;
  4792. }
  4793. }
  4794. if (!Op && N.getNode()) {
  4795. // Check if frame index is available.
  4796. SDValue LCandidate = peekThroughBitcasts(N);
  4797. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4798. if (FrameIndexSDNode *FINode =
  4799. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4800. Op = MachineOperand::CreateFI(FINode->getIndex());
  4801. }
  4802. if (!Op) {
  4803. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  4804. auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
  4805. SplitRegs) {
  4806. unsigned Offset = 0;
  4807. for (auto RegAndSize : SplitRegs) {
  4808. // If the expression is already a fragment, the current register
  4809. // offset+size might extend beyond the fragment. In this case, only
  4810. // the register bits that are inside the fragment are relevant.
  4811. int RegFragmentSizeInBits = RegAndSize.second;
  4812. if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
  4813. uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
  4814. // The register is entirely outside the expression fragment,
  4815. // so is irrelevant for debug info.
  4816. if (Offset >= ExprFragmentSizeInBits)
  4817. break;
  4818. // The register is partially outside the expression fragment, only
  4819. // the low bits within the fragment are relevant for debug info.
  4820. if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
  4821. RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
  4822. }
  4823. }
  4824. auto FragmentExpr = DIExpression::createFragmentExpression(
  4825. Expr, Offset, RegFragmentSizeInBits);
  4826. Offset += RegAndSize.second;
  4827. // If a valid fragment expression cannot be created, the variable's
  4828. // correct value cannot be determined and so it is set as Undef.
  4829. if (!FragmentExpr) {
  4830. SDDbgValue *SDV = DAG.getConstantDbgValue(
  4831. Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
  4832. DAG.AddDbgValue(SDV, nullptr, false);
  4833. continue;
  4834. }
  4835. assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
  4836. FuncInfo.ArgDbgValues.push_back(
  4837. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4838. RegAndSize.first, Variable, *FragmentExpr));
  4839. }
  4840. };
  4841. // Check if ValueMap has reg number.
  4842. DenseMap<const Value *, Register>::const_iterator
  4843. VMI = FuncInfo.ValueMap.find(V);
  4844. if (VMI != FuncInfo.ValueMap.end()) {
  4845. const auto &TLI = DAG.getTargetLoweringInfo();
  4846. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4847. V->getType(), None);
  4848. if (RFV.occupiesMultipleRegs()) {
  4849. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  4850. return true;
  4851. }
  4852. Op = MachineOperand::CreateReg(VMI->second, false);
  4853. IsIndirect = IsDbgDeclare;
  4854. } else if (ArgRegsAndSizes.size() > 1) {
  4855. // This was split due to the calling convention, and no virtual register
  4856. // mapping exists for the value.
  4857. splitMultiRegDbgValue(ArgRegsAndSizes);
  4858. return true;
  4859. }
  4860. }
  4861. if (!Op)
  4862. return false;
  4863. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4864. "Expected inlined-at fields to agree");
  4865. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4866. FuncInfo.ArgDbgValues.push_back(
  4867. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4868. *Op, Variable, Expr));
  4869. return true;
  4870. }
  4871. /// Return the appropriate SDDbgValue based on N.
  4872. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4873. DILocalVariable *Variable,
  4874. DIExpression *Expr,
  4875. const DebugLoc &dl,
  4876. unsigned DbgSDNodeOrder) {
  4877. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4878. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4879. // stack slot locations.
  4880. //
  4881. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4882. // debug values here after optimization:
  4883. //
  4884. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4885. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4886. //
  4887. // Both describe the direct values of their associated variables.
  4888. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4889. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4890. }
  4891. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4892. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4893. }
  4894. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4895. switch (Intrinsic) {
  4896. case Intrinsic::smul_fix:
  4897. return ISD::SMULFIX;
  4898. case Intrinsic::umul_fix:
  4899. return ISD::UMULFIX;
  4900. case Intrinsic::smul_fix_sat:
  4901. return ISD::SMULFIXSAT;
  4902. case Intrinsic::umul_fix_sat:
  4903. return ISD::UMULFIXSAT;
  4904. case Intrinsic::sdiv_fix:
  4905. return ISD::SDIVFIX;
  4906. case Intrinsic::udiv_fix:
  4907. return ISD::UDIVFIX;
  4908. case Intrinsic::sdiv_fix_sat:
  4909. return ISD::SDIVFIXSAT;
  4910. case Intrinsic::udiv_fix_sat:
  4911. return ISD::UDIVFIXSAT;
  4912. default:
  4913. llvm_unreachable("Unhandled fixed point intrinsic");
  4914. }
  4915. }
  4916. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4917. const char *FunctionName) {
  4918. assert(FunctionName && "FunctionName must not be nullptr");
  4919. SDValue Callee = DAG.getExternalSymbol(
  4920. FunctionName,
  4921. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4922. LowerCallTo(I, Callee, I.isTailCall());
  4923. }
  4924. /// Given a @llvm.call.preallocated.setup, return the corresponding
  4925. /// preallocated call.
  4926. static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
  4927. assert(cast<CallBase>(PreallocatedSetup)
  4928. ->getCalledFunction()
  4929. ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
  4930. "expected call_preallocated_setup Value");
  4931. for (auto *U : PreallocatedSetup->users()) {
  4932. auto *UseCall = cast<CallBase>(U);
  4933. const Function *Fn = UseCall->getCalledFunction();
  4934. if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
  4935. return UseCall;
  4936. }
  4937. }
  4938. llvm_unreachable("expected corresponding call to preallocated setup/arg");
  4939. }
  4940. /// Lower the call to the specified intrinsic function.
  4941. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4942. unsigned Intrinsic) {
  4943. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4944. SDLoc sdl = getCurSDLoc();
  4945. DebugLoc dl = getCurDebugLoc();
  4946. SDValue Res;
  4947. SDNodeFlags Flags;
  4948. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  4949. Flags.copyFMF(*FPOp);
  4950. switch (Intrinsic) {
  4951. default:
  4952. // By default, turn this into a target intrinsic node.
  4953. visitTargetIntrinsic(I, Intrinsic);
  4954. return;
  4955. case Intrinsic::vscale: {
  4956. match(&I, m_VScale(DAG.getDataLayout()));
  4957. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4958. setValue(&I,
  4959. DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
  4960. return;
  4961. }
  4962. case Intrinsic::vastart: visitVAStart(I); return;
  4963. case Intrinsic::vaend: visitVAEnd(I); return;
  4964. case Intrinsic::vacopy: visitVACopy(I); return;
  4965. case Intrinsic::returnaddress:
  4966. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4967. TLI.getPointerTy(DAG.getDataLayout()),
  4968. getValue(I.getArgOperand(0))));
  4969. return;
  4970. case Intrinsic::addressofreturnaddress:
  4971. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4972. TLI.getPointerTy(DAG.getDataLayout())));
  4973. return;
  4974. case Intrinsic::sponentry:
  4975. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4976. TLI.getFrameIndexTy(DAG.getDataLayout())));
  4977. return;
  4978. case Intrinsic::frameaddress:
  4979. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4980. TLI.getFrameIndexTy(DAG.getDataLayout()),
  4981. getValue(I.getArgOperand(0))));
  4982. return;
  4983. case Intrinsic::read_volatile_register:
  4984. case Intrinsic::read_register: {
  4985. Value *Reg = I.getArgOperand(0);
  4986. SDValue Chain = getRoot();
  4987. SDValue RegName =
  4988. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4989. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4990. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4991. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4992. setValue(&I, Res);
  4993. DAG.setRoot(Res.getValue(1));
  4994. return;
  4995. }
  4996. case Intrinsic::write_register: {
  4997. Value *Reg = I.getArgOperand(0);
  4998. Value *RegValue = I.getArgOperand(1);
  4999. SDValue Chain = getRoot();
  5000. SDValue RegName =
  5001. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  5002. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  5003. RegName, getValue(RegValue)));
  5004. return;
  5005. }
  5006. case Intrinsic::memcpy: {
  5007. const auto &MCI = cast<MemCpyInst>(I);
  5008. SDValue Op1 = getValue(I.getArgOperand(0));
  5009. SDValue Op2 = getValue(I.getArgOperand(1));
  5010. SDValue Op3 = getValue(I.getArgOperand(2));
  5011. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  5012. Align DstAlign = MCI.getDestAlign().valueOrOne();
  5013. Align SrcAlign = MCI.getSourceAlign().valueOrOne();
  5014. Align Alignment = commonAlignment(DstAlign, SrcAlign);
  5015. bool isVol = MCI.isVolatile();
  5016. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5017. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  5018. // node.
  5019. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5020. SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
  5021. /* AlwaysInline */ false, isTC,
  5022. MachinePointerInfo(I.getArgOperand(0)),
  5023. MachinePointerInfo(I.getArgOperand(1)));
  5024. updateDAGForMaybeTailCall(MC);
  5025. return;
  5026. }
  5027. case Intrinsic::memcpy_inline: {
  5028. const auto &MCI = cast<MemCpyInlineInst>(I);
  5029. SDValue Dst = getValue(I.getArgOperand(0));
  5030. SDValue Src = getValue(I.getArgOperand(1));
  5031. SDValue Size = getValue(I.getArgOperand(2));
  5032. assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
  5033. // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
  5034. Align DstAlign = MCI.getDestAlign().valueOrOne();
  5035. Align SrcAlign = MCI.getSourceAlign().valueOrOne();
  5036. Align Alignment = commonAlignment(DstAlign, SrcAlign);
  5037. bool isVol = MCI.isVolatile();
  5038. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5039. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  5040. // node.
  5041. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
  5042. /* AlwaysInline */ true, isTC,
  5043. MachinePointerInfo(I.getArgOperand(0)),
  5044. MachinePointerInfo(I.getArgOperand(1)));
  5045. updateDAGForMaybeTailCall(MC);
  5046. return;
  5047. }
  5048. case Intrinsic::memset: {
  5049. const auto &MSI = cast<MemSetInst>(I);
  5050. SDValue Op1 = getValue(I.getArgOperand(0));
  5051. SDValue Op2 = getValue(I.getArgOperand(1));
  5052. SDValue Op3 = getValue(I.getArgOperand(2));
  5053. // @llvm.memset defines 0 and 1 to both mean no alignment.
  5054. Align Alignment = MSI.getDestAlign().valueOrOne();
  5055. bool isVol = MSI.isVolatile();
  5056. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5057. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5058. SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
  5059. MachinePointerInfo(I.getArgOperand(0)));
  5060. updateDAGForMaybeTailCall(MS);
  5061. return;
  5062. }
  5063. case Intrinsic::memmove: {
  5064. const auto &MMI = cast<MemMoveInst>(I);
  5065. SDValue Op1 = getValue(I.getArgOperand(0));
  5066. SDValue Op2 = getValue(I.getArgOperand(1));
  5067. SDValue Op3 = getValue(I.getArgOperand(2));
  5068. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  5069. Align DstAlign = MMI.getDestAlign().valueOrOne();
  5070. Align SrcAlign = MMI.getSourceAlign().valueOrOne();
  5071. Align Alignment = commonAlignment(DstAlign, SrcAlign);
  5072. bool isVol = MMI.isVolatile();
  5073. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5074. // FIXME: Support passing different dest/src alignments to the memmove DAG
  5075. // node.
  5076. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5077. SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
  5078. isTC, MachinePointerInfo(I.getArgOperand(0)),
  5079. MachinePointerInfo(I.getArgOperand(1)));
  5080. updateDAGForMaybeTailCall(MM);
  5081. return;
  5082. }
  5083. case Intrinsic::memcpy_element_unordered_atomic: {
  5084. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  5085. SDValue Dst = getValue(MI.getRawDest());
  5086. SDValue Src = getValue(MI.getRawSource());
  5087. SDValue Length = getValue(MI.getLength());
  5088. unsigned DstAlign = MI.getDestAlignment();
  5089. unsigned SrcAlign = MI.getSourceAlignment();
  5090. Type *LengthTy = MI.getLength()->getType();
  5091. unsigned ElemSz = MI.getElementSizeInBytes();
  5092. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5093. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  5094. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5095. MachinePointerInfo(MI.getRawDest()),
  5096. MachinePointerInfo(MI.getRawSource()));
  5097. updateDAGForMaybeTailCall(MC);
  5098. return;
  5099. }
  5100. case Intrinsic::memmove_element_unordered_atomic: {
  5101. auto &MI = cast<AtomicMemMoveInst>(I);
  5102. SDValue Dst = getValue(MI.getRawDest());
  5103. SDValue Src = getValue(MI.getRawSource());
  5104. SDValue Length = getValue(MI.getLength());
  5105. unsigned DstAlign = MI.getDestAlignment();
  5106. unsigned SrcAlign = MI.getSourceAlignment();
  5107. Type *LengthTy = MI.getLength()->getType();
  5108. unsigned ElemSz = MI.getElementSizeInBytes();
  5109. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5110. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  5111. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5112. MachinePointerInfo(MI.getRawDest()),
  5113. MachinePointerInfo(MI.getRawSource()));
  5114. updateDAGForMaybeTailCall(MC);
  5115. return;
  5116. }
  5117. case Intrinsic::memset_element_unordered_atomic: {
  5118. auto &MI = cast<AtomicMemSetInst>(I);
  5119. SDValue Dst = getValue(MI.getRawDest());
  5120. SDValue Val = getValue(MI.getValue());
  5121. SDValue Length = getValue(MI.getLength());
  5122. unsigned DstAlign = MI.getDestAlignment();
  5123. Type *LengthTy = MI.getLength()->getType();
  5124. unsigned ElemSz = MI.getElementSizeInBytes();
  5125. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5126. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5127. LengthTy, ElemSz, isTC,
  5128. MachinePointerInfo(MI.getRawDest()));
  5129. updateDAGForMaybeTailCall(MC);
  5130. return;
  5131. }
  5132. case Intrinsic::call_preallocated_setup: {
  5133. const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
  5134. SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
  5135. SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
  5136. getRoot(), SrcValue);
  5137. setValue(&I, Res);
  5138. DAG.setRoot(Res);
  5139. return;
  5140. }
  5141. case Intrinsic::call_preallocated_arg: {
  5142. const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
  5143. SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
  5144. SDValue Ops[3];
  5145. Ops[0] = getRoot();
  5146. Ops[1] = SrcValue;
  5147. Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
  5148. MVT::i32); // arg index
  5149. SDValue Res = DAG.getNode(
  5150. ISD::PREALLOCATED_ARG, sdl,
  5151. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
  5152. setValue(&I, Res);
  5153. DAG.setRoot(Res.getValue(1));
  5154. return;
  5155. }
  5156. case Intrinsic::dbg_addr:
  5157. case Intrinsic::dbg_declare: {
  5158. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5159. DILocalVariable *Variable = DI.getVariable();
  5160. DIExpression *Expression = DI.getExpression();
  5161. dropDanglingDebugInfo(Variable, Expression);
  5162. assert(Variable && "Missing variable");
  5163. LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
  5164. << "\n");
  5165. // Check if address has undef value.
  5166. const Value *Address = DI.getVariableLocation();
  5167. if (!Address || isa<UndefValue>(Address) ||
  5168. (Address->use_empty() && !isa<Argument>(Address))) {
  5169. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
  5170. << " (bad/undef/unused-arg address)\n");
  5171. return;
  5172. }
  5173. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5174. // Check if this variable can be described by a frame index, typically
  5175. // either as a static alloca or a byval parameter.
  5176. int FI = std::numeric_limits<int>::max();
  5177. if (const auto *AI =
  5178. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5179. if (AI->isStaticAlloca()) {
  5180. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5181. if (I != FuncInfo.StaticAllocaMap.end())
  5182. FI = I->second;
  5183. }
  5184. } else if (const auto *Arg = dyn_cast<Argument>(
  5185. Address->stripInBoundsConstantOffsets())) {
  5186. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5187. }
  5188. // llvm.dbg.addr is control dependent and always generates indirect
  5189. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5190. // the MachineFunction variable table.
  5191. if (FI != std::numeric_limits<int>::max()) {
  5192. if (Intrinsic == Intrinsic::dbg_addr) {
  5193. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5194. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5195. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5196. } else {
  5197. LLVM_DEBUG(dbgs() << "Skipping " << DI
  5198. << " (variable info stashed in MF side table)\n");
  5199. }
  5200. return;
  5201. }
  5202. SDValue &N = NodeMap[Address];
  5203. if (!N.getNode() && isa<Argument>(Address))
  5204. // Check unused arguments map.
  5205. N = UnusedArgNodeMap[Address];
  5206. SDDbgValue *SDV;
  5207. if (N.getNode()) {
  5208. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5209. Address = BCI->getOperand(0);
  5210. // Parameters are handled specially.
  5211. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5212. if (isParameter && FINode) {
  5213. // Byval parameter. We have a frame index at this point.
  5214. SDV =
  5215. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5216. /*IsIndirect*/ true, dl, SDNodeOrder);
  5217. } else if (isa<Argument>(Address)) {
  5218. // Address is an argument, so try to emit its dbg value using
  5219. // virtual register info from the FuncInfo.ValueMap.
  5220. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5221. return;
  5222. } else {
  5223. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5224. true, dl, SDNodeOrder);
  5225. }
  5226. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5227. } else {
  5228. // If Address is an argument then try to emit its dbg value using
  5229. // virtual register info from the FuncInfo.ValueMap.
  5230. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5231. N)) {
  5232. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
  5233. << " (could not emit func-arg dbg_value)\n");
  5234. }
  5235. }
  5236. return;
  5237. }
  5238. case Intrinsic::dbg_label: {
  5239. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5240. DILabel *Label = DI.getLabel();
  5241. assert(Label && "Missing label");
  5242. SDDbgLabel *SDV;
  5243. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5244. DAG.AddDbgLabel(SDV);
  5245. return;
  5246. }
  5247. case Intrinsic::dbg_value: {
  5248. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5249. assert(DI.getVariable() && "Missing variable");
  5250. DILocalVariable *Variable = DI.getVariable();
  5251. DIExpression *Expression = DI.getExpression();
  5252. dropDanglingDebugInfo(Variable, Expression);
  5253. const Value *V = DI.getValue();
  5254. if (!V)
  5255. return;
  5256. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5257. SDNodeOrder))
  5258. return;
  5259. // TODO: Dangling debug info will eventually either be resolved or produce
  5260. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5261. // between the original dbg.value location and its resolved DBG_VALUE, which
  5262. // we should ideally fill with an extra Undef DBG_VALUE.
  5263. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5264. return;
  5265. }
  5266. case Intrinsic::eh_typeid_for: {
  5267. // Find the type id for the given typeinfo.
  5268. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5269. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5270. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5271. setValue(&I, Res);
  5272. return;
  5273. }
  5274. case Intrinsic::eh_return_i32:
  5275. case Intrinsic::eh_return_i64:
  5276. DAG.getMachineFunction().setCallsEHReturn(true);
  5277. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5278. MVT::Other,
  5279. getControlRoot(),
  5280. getValue(I.getArgOperand(0)),
  5281. getValue(I.getArgOperand(1))));
  5282. return;
  5283. case Intrinsic::eh_unwind_init:
  5284. DAG.getMachineFunction().setCallsUnwindInit(true);
  5285. return;
  5286. case Intrinsic::eh_dwarf_cfa:
  5287. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5288. TLI.getPointerTy(DAG.getDataLayout()),
  5289. getValue(I.getArgOperand(0))));
  5290. return;
  5291. case Intrinsic::eh_sjlj_callsite: {
  5292. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5293. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5294. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5295. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5296. MMI.setCurrentCallSite(CI->getZExtValue());
  5297. return;
  5298. }
  5299. case Intrinsic::eh_sjlj_functioncontext: {
  5300. // Get and store the index of the function context.
  5301. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5302. AllocaInst *FnCtx =
  5303. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5304. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5305. MFI.setFunctionContextIndex(FI);
  5306. return;
  5307. }
  5308. case Intrinsic::eh_sjlj_setjmp: {
  5309. SDValue Ops[2];
  5310. Ops[0] = getRoot();
  5311. Ops[1] = getValue(I.getArgOperand(0));
  5312. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5313. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5314. setValue(&I, Op.getValue(0));
  5315. DAG.setRoot(Op.getValue(1));
  5316. return;
  5317. }
  5318. case Intrinsic::eh_sjlj_longjmp:
  5319. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5320. getRoot(), getValue(I.getArgOperand(0))));
  5321. return;
  5322. case Intrinsic::eh_sjlj_setup_dispatch:
  5323. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5324. getRoot()));
  5325. return;
  5326. case Intrinsic::masked_gather:
  5327. visitMaskedGather(I);
  5328. return;
  5329. case Intrinsic::masked_load:
  5330. visitMaskedLoad(I);
  5331. return;
  5332. case Intrinsic::masked_scatter:
  5333. visitMaskedScatter(I);
  5334. return;
  5335. case Intrinsic::masked_store:
  5336. visitMaskedStore(I);
  5337. return;
  5338. case Intrinsic::masked_expandload:
  5339. visitMaskedLoad(I, true /* IsExpanding */);
  5340. return;
  5341. case Intrinsic::masked_compressstore:
  5342. visitMaskedStore(I, true /* IsCompressing */);
  5343. return;
  5344. case Intrinsic::powi:
  5345. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5346. getValue(I.getArgOperand(1)), DAG));
  5347. return;
  5348. case Intrinsic::log:
  5349. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5350. return;
  5351. case Intrinsic::log2:
  5352. setValue(&I,
  5353. expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5354. return;
  5355. case Intrinsic::log10:
  5356. setValue(&I,
  5357. expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5358. return;
  5359. case Intrinsic::exp:
  5360. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5361. return;
  5362. case Intrinsic::exp2:
  5363. setValue(&I,
  5364. expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5365. return;
  5366. case Intrinsic::pow:
  5367. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5368. getValue(I.getArgOperand(1)), DAG, TLI, Flags));
  5369. return;
  5370. case Intrinsic::sqrt:
  5371. case Intrinsic::fabs:
  5372. case Intrinsic::sin:
  5373. case Intrinsic::cos:
  5374. case Intrinsic::floor:
  5375. case Intrinsic::ceil:
  5376. case Intrinsic::trunc:
  5377. case Intrinsic::rint:
  5378. case Intrinsic::nearbyint:
  5379. case Intrinsic::round:
  5380. case Intrinsic::roundeven:
  5381. case Intrinsic::canonicalize: {
  5382. unsigned Opcode;
  5383. switch (Intrinsic) {
  5384. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5385. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5386. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5387. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5388. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5389. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5390. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5391. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5392. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5393. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5394. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5395. case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
  5396. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5397. }
  5398. setValue(&I, DAG.getNode(Opcode, sdl,
  5399. getValue(I.getArgOperand(0)).getValueType(),
  5400. getValue(I.getArgOperand(0)), Flags));
  5401. return;
  5402. }
  5403. case Intrinsic::lround:
  5404. case Intrinsic::llround:
  5405. case Intrinsic::lrint:
  5406. case Intrinsic::llrint: {
  5407. unsigned Opcode;
  5408. switch (Intrinsic) {
  5409. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5410. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5411. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5412. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5413. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5414. }
  5415. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5416. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5417. getValue(I.getArgOperand(0))));
  5418. return;
  5419. }
  5420. case Intrinsic::minnum:
  5421. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5422. getValue(I.getArgOperand(0)).getValueType(),
  5423. getValue(I.getArgOperand(0)),
  5424. getValue(I.getArgOperand(1)), Flags));
  5425. return;
  5426. case Intrinsic::maxnum:
  5427. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5428. getValue(I.getArgOperand(0)).getValueType(),
  5429. getValue(I.getArgOperand(0)),
  5430. getValue(I.getArgOperand(1)), Flags));
  5431. return;
  5432. case Intrinsic::minimum:
  5433. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5434. getValue(I.getArgOperand(0)).getValueType(),
  5435. getValue(I.getArgOperand(0)),
  5436. getValue(I.getArgOperand(1)), Flags));
  5437. return;
  5438. case Intrinsic::maximum:
  5439. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5440. getValue(I.getArgOperand(0)).getValueType(),
  5441. getValue(I.getArgOperand(0)),
  5442. getValue(I.getArgOperand(1)), Flags));
  5443. return;
  5444. case Intrinsic::copysign:
  5445. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5446. getValue(I.getArgOperand(0)).getValueType(),
  5447. getValue(I.getArgOperand(0)),
  5448. getValue(I.getArgOperand(1)), Flags));
  5449. return;
  5450. case Intrinsic::fma:
  5451. setValue(&I, DAG.getNode(
  5452. ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
  5453. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
  5454. getValue(I.getArgOperand(2)), Flags));
  5455. return;
  5456. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  5457. case Intrinsic::INTRINSIC:
  5458. #include "llvm/IR/ConstrainedOps.def"
  5459. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5460. return;
  5461. #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
  5462. #include "llvm/IR/VPIntrinsics.def"
  5463. visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
  5464. return;
  5465. case Intrinsic::fmuladd: {
  5466. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5467. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5468. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
  5469. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5470. getValue(I.getArgOperand(0)).getValueType(),
  5471. getValue(I.getArgOperand(0)),
  5472. getValue(I.getArgOperand(1)),
  5473. getValue(I.getArgOperand(2)), Flags));
  5474. } else {
  5475. // TODO: Intrinsic calls should have fast-math-flags.
  5476. SDValue Mul = DAG.getNode(
  5477. ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
  5478. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
  5479. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5480. getValue(I.getArgOperand(0)).getValueType(),
  5481. Mul, getValue(I.getArgOperand(2)), Flags);
  5482. setValue(&I, Add);
  5483. }
  5484. return;
  5485. }
  5486. case Intrinsic::convert_to_fp16:
  5487. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5488. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5489. getValue(I.getArgOperand(0)),
  5490. DAG.getTargetConstant(0, sdl,
  5491. MVT::i32))));
  5492. return;
  5493. case Intrinsic::convert_from_fp16:
  5494. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5495. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5496. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5497. getValue(I.getArgOperand(0)))));
  5498. return;
  5499. case Intrinsic::fptosi_sat: {
  5500. EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5501. SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
  5502. setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type,
  5503. getValue(I.getArgOperand(0)), SatW));
  5504. return;
  5505. }
  5506. case Intrinsic::fptoui_sat: {
  5507. EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5508. SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
  5509. setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type,
  5510. getValue(I.getArgOperand(0)), SatW));
  5511. return;
  5512. }
  5513. case Intrinsic::pcmarker: {
  5514. SDValue Tmp = getValue(I.getArgOperand(0));
  5515. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5516. return;
  5517. }
  5518. case Intrinsic::readcyclecounter: {
  5519. SDValue Op = getRoot();
  5520. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5521. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5522. setValue(&I, Res);
  5523. DAG.setRoot(Res.getValue(1));
  5524. return;
  5525. }
  5526. case Intrinsic::bitreverse:
  5527. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5528. getValue(I.getArgOperand(0)).getValueType(),
  5529. getValue(I.getArgOperand(0))));
  5530. return;
  5531. case Intrinsic::bswap:
  5532. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5533. getValue(I.getArgOperand(0)).getValueType(),
  5534. getValue(I.getArgOperand(0))));
  5535. return;
  5536. case Intrinsic::cttz: {
  5537. SDValue Arg = getValue(I.getArgOperand(0));
  5538. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5539. EVT Ty = Arg.getValueType();
  5540. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5541. sdl, Ty, Arg));
  5542. return;
  5543. }
  5544. case Intrinsic::ctlz: {
  5545. SDValue Arg = getValue(I.getArgOperand(0));
  5546. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5547. EVT Ty = Arg.getValueType();
  5548. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5549. sdl, Ty, Arg));
  5550. return;
  5551. }
  5552. case Intrinsic::ctpop: {
  5553. SDValue Arg = getValue(I.getArgOperand(0));
  5554. EVT Ty = Arg.getValueType();
  5555. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5556. return;
  5557. }
  5558. case Intrinsic::fshl:
  5559. case Intrinsic::fshr: {
  5560. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5561. SDValue X = getValue(I.getArgOperand(0));
  5562. SDValue Y = getValue(I.getArgOperand(1));
  5563. SDValue Z = getValue(I.getArgOperand(2));
  5564. EVT VT = X.getValueType();
  5565. if (X == Y) {
  5566. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5567. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5568. } else {
  5569. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5570. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5571. }
  5572. return;
  5573. }
  5574. case Intrinsic::sadd_sat: {
  5575. SDValue Op1 = getValue(I.getArgOperand(0));
  5576. SDValue Op2 = getValue(I.getArgOperand(1));
  5577. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5578. return;
  5579. }
  5580. case Intrinsic::uadd_sat: {
  5581. SDValue Op1 = getValue(I.getArgOperand(0));
  5582. SDValue Op2 = getValue(I.getArgOperand(1));
  5583. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5584. return;
  5585. }
  5586. case Intrinsic::ssub_sat: {
  5587. SDValue Op1 = getValue(I.getArgOperand(0));
  5588. SDValue Op2 = getValue(I.getArgOperand(1));
  5589. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5590. return;
  5591. }
  5592. case Intrinsic::usub_sat: {
  5593. SDValue Op1 = getValue(I.getArgOperand(0));
  5594. SDValue Op2 = getValue(I.getArgOperand(1));
  5595. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5596. return;
  5597. }
  5598. case Intrinsic::sshl_sat: {
  5599. SDValue Op1 = getValue(I.getArgOperand(0));
  5600. SDValue Op2 = getValue(I.getArgOperand(1));
  5601. setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
  5602. return;
  5603. }
  5604. case Intrinsic::ushl_sat: {
  5605. SDValue Op1 = getValue(I.getArgOperand(0));
  5606. SDValue Op2 = getValue(I.getArgOperand(1));
  5607. setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
  5608. return;
  5609. }
  5610. case Intrinsic::smul_fix:
  5611. case Intrinsic::umul_fix:
  5612. case Intrinsic::smul_fix_sat:
  5613. case Intrinsic::umul_fix_sat: {
  5614. SDValue Op1 = getValue(I.getArgOperand(0));
  5615. SDValue Op2 = getValue(I.getArgOperand(1));
  5616. SDValue Op3 = getValue(I.getArgOperand(2));
  5617. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5618. Op1.getValueType(), Op1, Op2, Op3));
  5619. return;
  5620. }
  5621. case Intrinsic::sdiv_fix:
  5622. case Intrinsic::udiv_fix:
  5623. case Intrinsic::sdiv_fix_sat:
  5624. case Intrinsic::udiv_fix_sat: {
  5625. SDValue Op1 = getValue(I.getArgOperand(0));
  5626. SDValue Op2 = getValue(I.getArgOperand(1));
  5627. SDValue Op3 = getValue(I.getArgOperand(2));
  5628. setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5629. Op1, Op2, Op3, DAG, TLI));
  5630. return;
  5631. }
  5632. case Intrinsic::smax: {
  5633. SDValue Op1 = getValue(I.getArgOperand(0));
  5634. SDValue Op2 = getValue(I.getArgOperand(1));
  5635. setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
  5636. return;
  5637. }
  5638. case Intrinsic::smin: {
  5639. SDValue Op1 = getValue(I.getArgOperand(0));
  5640. SDValue Op2 = getValue(I.getArgOperand(1));
  5641. setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
  5642. return;
  5643. }
  5644. case Intrinsic::umax: {
  5645. SDValue Op1 = getValue(I.getArgOperand(0));
  5646. SDValue Op2 = getValue(I.getArgOperand(1));
  5647. setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
  5648. return;
  5649. }
  5650. case Intrinsic::umin: {
  5651. SDValue Op1 = getValue(I.getArgOperand(0));
  5652. SDValue Op2 = getValue(I.getArgOperand(1));
  5653. setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
  5654. return;
  5655. }
  5656. case Intrinsic::abs: {
  5657. // TODO: Preserve "int min is poison" arg in SDAG?
  5658. SDValue Op1 = getValue(I.getArgOperand(0));
  5659. setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
  5660. return;
  5661. }
  5662. case Intrinsic::stacksave: {
  5663. SDValue Op = getRoot();
  5664. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5665. Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
  5666. setValue(&I, Res);
  5667. DAG.setRoot(Res.getValue(1));
  5668. return;
  5669. }
  5670. case Intrinsic::stackrestore:
  5671. Res = getValue(I.getArgOperand(0));
  5672. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5673. return;
  5674. case Intrinsic::get_dynamic_area_offset: {
  5675. SDValue Op = getRoot();
  5676. EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
  5677. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5678. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5679. // target.
  5680. if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
  5681. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5682. " intrinsic!");
  5683. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5684. Op);
  5685. DAG.setRoot(Op);
  5686. setValue(&I, Res);
  5687. return;
  5688. }
  5689. case Intrinsic::stackguard: {
  5690. MachineFunction &MF = DAG.getMachineFunction();
  5691. const Module &M = *MF.getFunction().getParent();
  5692. SDValue Chain = getRoot();
  5693. if (TLI.useLoadStackGuardNode()) {
  5694. Res = getLoadStackGuard(DAG, sdl, Chain);
  5695. } else {
  5696. EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5697. const Value *Global = TLI.getSDagStackGuard(M);
  5698. Align Align = DL->getPrefTypeAlign(Global->getType());
  5699. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5700. MachinePointerInfo(Global, 0), Align,
  5701. MachineMemOperand::MOVolatile);
  5702. }
  5703. if (TLI.useStackGuardXorFP())
  5704. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5705. DAG.setRoot(Chain);
  5706. setValue(&I, Res);
  5707. return;
  5708. }
  5709. case Intrinsic::stackprotector: {
  5710. // Emit code into the DAG to store the stack guard onto the stack.
  5711. MachineFunction &MF = DAG.getMachineFunction();
  5712. MachineFrameInfo &MFI = MF.getFrameInfo();
  5713. SDValue Src, Chain = getRoot();
  5714. if (TLI.useLoadStackGuardNode())
  5715. Src = getLoadStackGuard(DAG, sdl, Chain);
  5716. else
  5717. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5718. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5719. int FI = FuncInfo.StaticAllocaMap[Slot];
  5720. MFI.setStackProtectorIndex(FI);
  5721. EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
  5722. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5723. // Store the stack protector onto the stack.
  5724. Res = DAG.getStore(
  5725. Chain, sdl, Src, FIN,
  5726. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
  5727. MaybeAlign(), MachineMemOperand::MOVolatile);
  5728. setValue(&I, Res);
  5729. DAG.setRoot(Res);
  5730. return;
  5731. }
  5732. case Intrinsic::objectsize:
  5733. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  5734. case Intrinsic::is_constant:
  5735. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  5736. case Intrinsic::annotation:
  5737. case Intrinsic::ptr_annotation:
  5738. case Intrinsic::launder_invariant_group:
  5739. case Intrinsic::strip_invariant_group:
  5740. // Drop the intrinsic, but forward the value
  5741. setValue(&I, getValue(I.getOperand(0)));
  5742. return;
  5743. case Intrinsic::assume:
  5744. case Intrinsic::experimental_noalias_scope_decl:
  5745. case Intrinsic::var_annotation:
  5746. case Intrinsic::sideeffect:
  5747. // Discard annotate attributes, noalias scope declarations, assumptions, and
  5748. // artificial side-effects.
  5749. return;
  5750. case Intrinsic::codeview_annotation: {
  5751. // Emit a label associated with this metadata.
  5752. MachineFunction &MF = DAG.getMachineFunction();
  5753. MCSymbol *Label =
  5754. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5755. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5756. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5757. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5758. DAG.setRoot(Res);
  5759. return;
  5760. }
  5761. case Intrinsic::init_trampoline: {
  5762. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5763. SDValue Ops[6];
  5764. Ops[0] = getRoot();
  5765. Ops[1] = getValue(I.getArgOperand(0));
  5766. Ops[2] = getValue(I.getArgOperand(1));
  5767. Ops[3] = getValue(I.getArgOperand(2));
  5768. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5769. Ops[5] = DAG.getSrcValue(F);
  5770. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5771. DAG.setRoot(Res);
  5772. return;
  5773. }
  5774. case Intrinsic::adjust_trampoline:
  5775. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5776. TLI.getPointerTy(DAG.getDataLayout()),
  5777. getValue(I.getArgOperand(0))));
  5778. return;
  5779. case Intrinsic::gcroot: {
  5780. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5781. "only valid in functions with gc specified, enforced by Verifier");
  5782. assert(GFI && "implied by previous");
  5783. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5784. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5785. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5786. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5787. return;
  5788. }
  5789. case Intrinsic::gcread:
  5790. case Intrinsic::gcwrite:
  5791. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5792. case Intrinsic::flt_rounds:
  5793. Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
  5794. setValue(&I, Res);
  5795. DAG.setRoot(Res.getValue(1));
  5796. return;
  5797. case Intrinsic::expect:
  5798. // Just replace __builtin_expect(exp, c) with EXP.
  5799. setValue(&I, getValue(I.getArgOperand(0)));
  5800. return;
  5801. case Intrinsic::ubsantrap:
  5802. case Intrinsic::debugtrap:
  5803. case Intrinsic::trap: {
  5804. StringRef TrapFuncName =
  5805. I.getAttributes()
  5806. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5807. .getValueAsString();
  5808. if (TrapFuncName.empty()) {
  5809. switch (Intrinsic) {
  5810. case Intrinsic::trap:
  5811. DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
  5812. break;
  5813. case Intrinsic::debugtrap:
  5814. DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
  5815. break;
  5816. case Intrinsic::ubsantrap:
  5817. DAG.setRoot(DAG.getNode(
  5818. ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
  5819. DAG.getTargetConstant(
  5820. cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
  5821. MVT::i32)));
  5822. break;
  5823. default: llvm_unreachable("unknown trap intrinsic");
  5824. }
  5825. return;
  5826. }
  5827. TargetLowering::ArgListTy Args;
  5828. if (Intrinsic == Intrinsic::ubsantrap) {
  5829. Args.push_back(TargetLoweringBase::ArgListEntry());
  5830. Args[0].Val = I.getArgOperand(0);
  5831. Args[0].Node = getValue(Args[0].Val);
  5832. Args[0].Ty = Args[0].Val->getType();
  5833. }
  5834. TargetLowering::CallLoweringInfo CLI(DAG);
  5835. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5836. CallingConv::C, I.getType(),
  5837. DAG.getExternalSymbol(TrapFuncName.data(),
  5838. TLI.getPointerTy(DAG.getDataLayout())),
  5839. std::move(Args));
  5840. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5841. DAG.setRoot(Result.second);
  5842. return;
  5843. }
  5844. case Intrinsic::uadd_with_overflow:
  5845. case Intrinsic::sadd_with_overflow:
  5846. case Intrinsic::usub_with_overflow:
  5847. case Intrinsic::ssub_with_overflow:
  5848. case Intrinsic::umul_with_overflow:
  5849. case Intrinsic::smul_with_overflow: {
  5850. ISD::NodeType Op;
  5851. switch (Intrinsic) {
  5852. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5853. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5854. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5855. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5856. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5857. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5858. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5859. }
  5860. SDValue Op1 = getValue(I.getArgOperand(0));
  5861. SDValue Op2 = getValue(I.getArgOperand(1));
  5862. EVT ResultVT = Op1.getValueType();
  5863. EVT OverflowVT = MVT::i1;
  5864. if (ResultVT.isVector())
  5865. OverflowVT = EVT::getVectorVT(
  5866. *Context, OverflowVT, ResultVT.getVectorElementCount());
  5867. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5868. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5869. return;
  5870. }
  5871. case Intrinsic::prefetch: {
  5872. SDValue Ops[5];
  5873. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5874. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5875. Ops[0] = DAG.getRoot();
  5876. Ops[1] = getValue(I.getArgOperand(0));
  5877. Ops[2] = getValue(I.getArgOperand(1));
  5878. Ops[3] = getValue(I.getArgOperand(2));
  5879. Ops[4] = getValue(I.getArgOperand(3));
  5880. SDValue Result = DAG.getMemIntrinsicNode(
  5881. ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
  5882. EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
  5883. /* align */ None, Flags);
  5884. // Chain the prefetch in parallell with any pending loads, to stay out of
  5885. // the way of later optimizations.
  5886. PendingLoads.push_back(Result);
  5887. Result = getRoot();
  5888. DAG.setRoot(Result);
  5889. return;
  5890. }
  5891. case Intrinsic::lifetime_start:
  5892. case Intrinsic::lifetime_end: {
  5893. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5894. // Stack coloring is not enabled in O0, discard region information.
  5895. if (TM.getOptLevel() == CodeGenOpt::None)
  5896. return;
  5897. const int64_t ObjectSize =
  5898. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5899. Value *const ObjectPtr = I.getArgOperand(1);
  5900. SmallVector<const Value *, 4> Allocas;
  5901. getUnderlyingObjects(ObjectPtr, Allocas);
  5902. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5903. E = Allocas.end(); Object != E; ++Object) {
  5904. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5905. // Could not find an Alloca.
  5906. if (!LifetimeObject)
  5907. continue;
  5908. // First check that the Alloca is static, otherwise it won't have a
  5909. // valid frame index.
  5910. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5911. if (SI == FuncInfo.StaticAllocaMap.end())
  5912. return;
  5913. const int FrameIndex = SI->second;
  5914. int64_t Offset;
  5915. if (GetPointerBaseWithConstantOffset(
  5916. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5917. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5918. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5919. Offset);
  5920. DAG.setRoot(Res);
  5921. }
  5922. return;
  5923. }
  5924. case Intrinsic::pseudoprobe: {
  5925. auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
  5926. auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5927. auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  5928. Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
  5929. DAG.setRoot(Res);
  5930. return;
  5931. }
  5932. case Intrinsic::invariant_start:
  5933. // Discard region information.
  5934. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5935. return;
  5936. case Intrinsic::invariant_end:
  5937. // Discard region information.
  5938. return;
  5939. case Intrinsic::clear_cache:
  5940. /// FunctionName may be null.
  5941. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5942. lowerCallToExternalSymbol(I, FunctionName);
  5943. return;
  5944. case Intrinsic::donothing:
  5945. // ignore
  5946. return;
  5947. case Intrinsic::experimental_stackmap:
  5948. visitStackmap(I);
  5949. return;
  5950. case Intrinsic::experimental_patchpoint_void:
  5951. case Intrinsic::experimental_patchpoint_i64:
  5952. visitPatchpoint(I);
  5953. return;
  5954. case Intrinsic::experimental_gc_statepoint:
  5955. LowerStatepoint(cast<GCStatepointInst>(I));
  5956. return;
  5957. case Intrinsic::experimental_gc_result:
  5958. visitGCResult(cast<GCResultInst>(I));
  5959. return;
  5960. case Intrinsic::experimental_gc_relocate:
  5961. visitGCRelocate(cast<GCRelocateInst>(I));
  5962. return;
  5963. case Intrinsic::instrprof_increment:
  5964. llvm_unreachable("instrprof failed to lower an increment");
  5965. case Intrinsic::instrprof_value_profile:
  5966. llvm_unreachable("instrprof failed to lower a value profiling call");
  5967. case Intrinsic::localescape: {
  5968. MachineFunction &MF = DAG.getMachineFunction();
  5969. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5970. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5971. // is the same on all targets.
  5972. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5973. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5974. if (isa<ConstantPointerNull>(Arg))
  5975. continue; // Skip null pointers. They represent a hole in index space.
  5976. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5977. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5978. "can only escape static allocas");
  5979. int FI = FuncInfo.StaticAllocaMap[Slot];
  5980. MCSymbol *FrameAllocSym =
  5981. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5982. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5983. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5984. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5985. .addSym(FrameAllocSym)
  5986. .addFrameIndex(FI);
  5987. }
  5988. return;
  5989. }
  5990. case Intrinsic::localrecover: {
  5991. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5992. MachineFunction &MF = DAG.getMachineFunction();
  5993. // Get the symbol that defines the frame offset.
  5994. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5995. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5996. unsigned IdxVal =
  5997. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5998. MCSymbol *FrameAllocSym =
  5999. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  6000. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  6001. Value *FP = I.getArgOperand(1);
  6002. SDValue FPVal = getValue(FP);
  6003. EVT PtrVT = FPVal.getValueType();
  6004. // Create a MCSymbol for the label to avoid any target lowering
  6005. // that would make this PC relative.
  6006. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  6007. SDValue OffsetVal =
  6008. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  6009. // Add the offset to the FP.
  6010. SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
  6011. setValue(&I, Add);
  6012. return;
  6013. }
  6014. case Intrinsic::eh_exceptionpointer:
  6015. case Intrinsic::eh_exceptioncode: {
  6016. // Get the exception pointer vreg, copy from it, and resize it to fit.
  6017. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  6018. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  6019. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  6020. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  6021. SDValue N =
  6022. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  6023. if (Intrinsic == Intrinsic::eh_exceptioncode)
  6024. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  6025. setValue(&I, N);
  6026. return;
  6027. }
  6028. case Intrinsic::xray_customevent: {
  6029. // Here we want to make sure that the intrinsic behaves as if it has a
  6030. // specific calling convention, and only for x86_64.
  6031. // FIXME: Support other platforms later.
  6032. const auto &Triple = DAG.getTarget().getTargetTriple();
  6033. if (Triple.getArch() != Triple::x86_64)
  6034. return;
  6035. SDLoc DL = getCurSDLoc();
  6036. SmallVector<SDValue, 8> Ops;
  6037. // We want to say that we always want the arguments in registers.
  6038. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  6039. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  6040. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6041. SDValue Chain = getRoot();
  6042. Ops.push_back(LogEntryVal);
  6043. Ops.push_back(StrSizeVal);
  6044. Ops.push_back(Chain);
  6045. // We need to enforce the calling convention for the callsite, so that
  6046. // argument ordering is enforced correctly, and that register allocation can
  6047. // see that some registers may be assumed clobbered and have to preserve
  6048. // them across calls to the intrinsic.
  6049. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  6050. DL, NodeTys, Ops);
  6051. SDValue patchableNode = SDValue(MN, 0);
  6052. DAG.setRoot(patchableNode);
  6053. setValue(&I, patchableNode);
  6054. return;
  6055. }
  6056. case Intrinsic::xray_typedevent: {
  6057. // Here we want to make sure that the intrinsic behaves as if it has a
  6058. // specific calling convention, and only for x86_64.
  6059. // FIXME: Support other platforms later.
  6060. const auto &Triple = DAG.getTarget().getTargetTriple();
  6061. if (Triple.getArch() != Triple::x86_64)
  6062. return;
  6063. SDLoc DL = getCurSDLoc();
  6064. SmallVector<SDValue, 8> Ops;
  6065. // We want to say that we always want the arguments in registers.
  6066. // It's unclear to me how manipulating the selection DAG here forces callers
  6067. // to provide arguments in registers instead of on the stack.
  6068. SDValue LogTypeId = getValue(I.getArgOperand(0));
  6069. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  6070. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  6071. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6072. SDValue Chain = getRoot();
  6073. Ops.push_back(LogTypeId);
  6074. Ops.push_back(LogEntryVal);
  6075. Ops.push_back(StrSizeVal);
  6076. Ops.push_back(Chain);
  6077. // We need to enforce the calling convention for the callsite, so that
  6078. // argument ordering is enforced correctly, and that register allocation can
  6079. // see that some registers may be assumed clobbered and have to preserve
  6080. // them across calls to the intrinsic.
  6081. MachineSDNode *MN = DAG.getMachineNode(
  6082. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  6083. SDValue patchableNode = SDValue(MN, 0);
  6084. DAG.setRoot(patchableNode);
  6085. setValue(&I, patchableNode);
  6086. return;
  6087. }
  6088. case Intrinsic::experimental_deoptimize:
  6089. LowerDeoptimizeCall(&I);
  6090. return;
  6091. case Intrinsic::vector_reduce_fadd:
  6092. case Intrinsic::vector_reduce_fmul:
  6093. case Intrinsic::vector_reduce_add:
  6094. case Intrinsic::vector_reduce_mul:
  6095. case Intrinsic::vector_reduce_and:
  6096. case Intrinsic::vector_reduce_or:
  6097. case Intrinsic::vector_reduce_xor:
  6098. case Intrinsic::vector_reduce_smax:
  6099. case Intrinsic::vector_reduce_smin:
  6100. case Intrinsic::vector_reduce_umax:
  6101. case Intrinsic::vector_reduce_umin:
  6102. case Intrinsic::vector_reduce_fmax:
  6103. case Intrinsic::vector_reduce_fmin:
  6104. visitVectorReduce(I, Intrinsic);
  6105. return;
  6106. case Intrinsic::icall_branch_funnel: {
  6107. SmallVector<SDValue, 16> Ops;
  6108. Ops.push_back(getValue(I.getArgOperand(0)));
  6109. int64_t Offset;
  6110. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6111. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6112. if (!Base)
  6113. report_fatal_error(
  6114. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6115. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  6116. struct BranchFunnelTarget {
  6117. int64_t Offset;
  6118. SDValue Target;
  6119. };
  6120. SmallVector<BranchFunnelTarget, 8> Targets;
  6121. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6122. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6123. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6124. if (ElemBase != Base)
  6125. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6126. "to the same GlobalValue");
  6127. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6128. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6129. if (!GA)
  6130. report_fatal_error(
  6131. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6132. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6133. GA->getGlobal(), getCurSDLoc(),
  6134. Val.getValueType(), GA->getOffset())});
  6135. }
  6136. llvm::sort(Targets,
  6137. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6138. return T1.Offset < T2.Offset;
  6139. });
  6140. for (auto &T : Targets) {
  6141. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6142. Ops.push_back(T.Target);
  6143. }
  6144. Ops.push_back(DAG.getRoot()); // Chain
  6145. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6146. getCurSDLoc(), MVT::Other, Ops),
  6147. 0);
  6148. DAG.setRoot(N);
  6149. setValue(&I, N);
  6150. HasTailCall = true;
  6151. return;
  6152. }
  6153. case Intrinsic::wasm_landingpad_index:
  6154. // Information this intrinsic contained has been transferred to
  6155. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6156. // delete it now.
  6157. return;
  6158. case Intrinsic::aarch64_settag:
  6159. case Intrinsic::aarch64_settag_zero: {
  6160. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6161. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6162. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6163. DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
  6164. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6165. ZeroMemory);
  6166. DAG.setRoot(Val);
  6167. setValue(&I, Val);
  6168. return;
  6169. }
  6170. case Intrinsic::ptrmask: {
  6171. SDValue Ptr = getValue(I.getOperand(0));
  6172. SDValue Const = getValue(I.getOperand(1));
  6173. EVT PtrVT = Ptr.getValueType();
  6174. setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
  6175. DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
  6176. return;
  6177. }
  6178. case Intrinsic::get_active_lane_mask: {
  6179. auto DL = getCurSDLoc();
  6180. SDValue Index = getValue(I.getOperand(0));
  6181. SDValue TripCount = getValue(I.getOperand(1));
  6182. Type *ElementTy = I.getOperand(0)->getType();
  6183. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6184. unsigned VecWidth = VT.getVectorNumElements();
  6185. SmallVector<SDValue, 16> OpsTripCount;
  6186. SmallVector<SDValue, 16> OpsIndex;
  6187. SmallVector<SDValue, 16> OpsStepConstants;
  6188. for (unsigned i = 0; i < VecWidth; i++) {
  6189. OpsTripCount.push_back(TripCount);
  6190. OpsIndex.push_back(Index);
  6191. OpsStepConstants.push_back(
  6192. DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
  6193. }
  6194. EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
  6195. auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
  6196. SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
  6197. SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
  6198. SDValue VectorInduction = DAG.getNode(
  6199. ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
  6200. SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
  6201. SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
  6202. VectorTripCount, ISD::CondCode::SETULT);
  6203. setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
  6204. DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
  6205. SetCC));
  6206. return;
  6207. }
  6208. case Intrinsic::experimental_vector_insert: {
  6209. auto DL = getCurSDLoc();
  6210. SDValue Vec = getValue(I.getOperand(0));
  6211. SDValue SubVec = getValue(I.getOperand(1));
  6212. SDValue Index = getValue(I.getOperand(2));
  6213. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6214. setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
  6215. Index));
  6216. return;
  6217. }
  6218. case Intrinsic::experimental_vector_extract: {
  6219. auto DL = getCurSDLoc();
  6220. SDValue Vec = getValue(I.getOperand(0));
  6221. SDValue Index = getValue(I.getOperand(1));
  6222. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6223. setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
  6224. return;
  6225. }
  6226. }
  6227. }
  6228. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6229. const ConstrainedFPIntrinsic &FPI) {
  6230. SDLoc sdl = getCurSDLoc();
  6231. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6232. SmallVector<EVT, 4> ValueVTs;
  6233. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6234. ValueVTs.push_back(MVT::Other); // Out chain
  6235. // We do not need to serialize constrained FP intrinsics against
  6236. // each other or against (nonvolatile) loads, so they can be
  6237. // chained like loads.
  6238. SDValue Chain = DAG.getRoot();
  6239. SmallVector<SDValue, 4> Opers;
  6240. Opers.push_back(Chain);
  6241. if (FPI.isUnaryOp()) {
  6242. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6243. } else if (FPI.isTernaryOp()) {
  6244. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6245. Opers.push_back(getValue(FPI.getArgOperand(1)));
  6246. Opers.push_back(getValue(FPI.getArgOperand(2)));
  6247. } else {
  6248. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6249. Opers.push_back(getValue(FPI.getArgOperand(1)));
  6250. }
  6251. auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
  6252. assert(Result.getNode()->getNumValues() == 2);
  6253. // Push node to the appropriate list so that future instructions can be
  6254. // chained up correctly.
  6255. SDValue OutChain = Result.getValue(1);
  6256. switch (EB) {
  6257. case fp::ExceptionBehavior::ebIgnore:
  6258. // The only reason why ebIgnore nodes still need to be chained is that
  6259. // they might depend on the current rounding mode, and therefore must
  6260. // not be moved across instruction that may change that mode.
  6261. LLVM_FALLTHROUGH;
  6262. case fp::ExceptionBehavior::ebMayTrap:
  6263. // These must not be moved across calls or instructions that may change
  6264. // floating-point exception masks.
  6265. PendingConstrainedFP.push_back(OutChain);
  6266. break;
  6267. case fp::ExceptionBehavior::ebStrict:
  6268. // These must not be moved across calls or instructions that may change
  6269. // floating-point exception masks or read floating-point exception flags.
  6270. // In addition, they cannot be optimized out even if unused.
  6271. PendingConstrainedFPStrict.push_back(OutChain);
  6272. break;
  6273. }
  6274. };
  6275. SDVTList VTs = DAG.getVTList(ValueVTs);
  6276. fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
  6277. SDNodeFlags Flags;
  6278. if (EB == fp::ExceptionBehavior::ebIgnore)
  6279. Flags.setNoFPExcept(true);
  6280. if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
  6281. Flags.copyFMF(*FPOp);
  6282. unsigned Opcode;
  6283. switch (FPI.getIntrinsicID()) {
  6284. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6285. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  6286. case Intrinsic::INTRINSIC: \
  6287. Opcode = ISD::STRICT_##DAGN; \
  6288. break;
  6289. #include "llvm/IR/ConstrainedOps.def"
  6290. case Intrinsic::experimental_constrained_fmuladd: {
  6291. Opcode = ISD::STRICT_FMA;
  6292. // Break fmuladd into fmul and fadd.
  6293. if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
  6294. !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
  6295. ValueVTs[0])) {
  6296. Opers.pop_back();
  6297. SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
  6298. pushOutChain(Mul, EB);
  6299. Opcode = ISD::STRICT_FADD;
  6300. Opers.clear();
  6301. Opers.push_back(Mul.getValue(1));
  6302. Opers.push_back(Mul.getValue(0));
  6303. Opers.push_back(getValue(FPI.getArgOperand(2)));
  6304. }
  6305. break;
  6306. }
  6307. }
  6308. // A few strict DAG nodes carry additional operands that are not
  6309. // set up by the default code above.
  6310. switch (Opcode) {
  6311. default: break;
  6312. case ISD::STRICT_FP_ROUND:
  6313. Opers.push_back(
  6314. DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
  6315. break;
  6316. case ISD::STRICT_FSETCC:
  6317. case ISD::STRICT_FSETCCS: {
  6318. auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
  6319. Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
  6320. break;
  6321. }
  6322. }
  6323. SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
  6324. pushOutChain(Result, EB);
  6325. SDValue FPResult = Result.getValue(0);
  6326. setValue(&FPI, FPResult);
  6327. }
  6328. static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
  6329. Optional<unsigned> ResOPC;
  6330. switch (VPIntrin.getIntrinsicID()) {
  6331. #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
  6332. #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
  6333. #define END_REGISTER_VP_INTRINSIC(...) break;
  6334. #include "llvm/IR/VPIntrinsics.def"
  6335. }
  6336. if (!ResOPC.hasValue())
  6337. llvm_unreachable(
  6338. "Inconsistency: no SDNode available for this VPIntrinsic!");
  6339. return ResOPC.getValue();
  6340. }
  6341. void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
  6342. const VPIntrinsic &VPIntrin) {
  6343. unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
  6344. SmallVector<EVT, 4> ValueVTs;
  6345. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6346. ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
  6347. SDVTList VTs = DAG.getVTList(ValueVTs);
  6348. // Request operands.
  6349. SmallVector<SDValue, 7> OpValues;
  6350. for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
  6351. OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
  6352. SDLoc DL = getCurSDLoc();
  6353. SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
  6354. setValue(&VPIntrin, Result);
  6355. }
  6356. std::pair<SDValue, SDValue>
  6357. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6358. const BasicBlock *EHPadBB) {
  6359. MachineFunction &MF = DAG.getMachineFunction();
  6360. MachineModuleInfo &MMI = MF.getMMI();
  6361. MCSymbol *BeginLabel = nullptr;
  6362. if (EHPadBB) {
  6363. // Insert a label before the invoke call to mark the try range. This can be
  6364. // used to detect deletion of the invoke via the MachineModuleInfo.
  6365. BeginLabel = MMI.getContext().createTempSymbol();
  6366. // For SjLj, keep track of which landing pads go with which invokes
  6367. // so as to maintain the ordering of pads in the LSDA.
  6368. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6369. if (CallSiteIndex) {
  6370. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6371. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6372. // Now that the call site is handled, stop tracking it.
  6373. MMI.setCurrentCallSite(0);
  6374. }
  6375. // Both PendingLoads and PendingExports must be flushed here;
  6376. // this call might not return.
  6377. (void)getRoot();
  6378. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6379. CLI.setChain(getRoot());
  6380. }
  6381. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6382. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6383. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6384. "Non-null chain expected with non-tail call!");
  6385. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6386. "Null value expected with tail call!");
  6387. if (!Result.second.getNode()) {
  6388. // As a special case, a null chain means that a tail call has been emitted
  6389. // and the DAG root is already updated.
  6390. HasTailCall = true;
  6391. // Since there's no actual continuation from this block, nothing can be
  6392. // relying on us setting vregs for them.
  6393. PendingExports.clear();
  6394. } else {
  6395. DAG.setRoot(Result.second);
  6396. }
  6397. if (EHPadBB) {
  6398. // Insert a label at the end of the invoke call to mark the try range. This
  6399. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6400. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6401. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6402. // Inform MachineModuleInfo of range.
  6403. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6404. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6405. // actually use outlined funclets and their LSDA info style.
  6406. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6407. assert(CLI.CB);
  6408. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6409. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
  6410. } else if (!isScopedEHPersonality(Pers)) {
  6411. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6412. }
  6413. }
  6414. return Result;
  6415. }
  6416. void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
  6417. bool isTailCall,
  6418. const BasicBlock *EHPadBB) {
  6419. auto &DL = DAG.getDataLayout();
  6420. FunctionType *FTy = CB.getFunctionType();
  6421. Type *RetTy = CB.getType();
  6422. TargetLowering::ArgListTy Args;
  6423. Args.reserve(CB.arg_size());
  6424. const Value *SwiftErrorVal = nullptr;
  6425. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6426. if (isTailCall) {
  6427. // Avoid emitting tail calls in functions with the disable-tail-calls
  6428. // attribute.
  6429. auto *Caller = CB.getParent()->getParent();
  6430. if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
  6431. "true")
  6432. isTailCall = false;
  6433. // We can't tail call inside a function with a swifterror argument. Lowering
  6434. // does not support this yet. It would have to move into the swifterror
  6435. // register before the call.
  6436. if (TLI.supportSwiftError() &&
  6437. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6438. isTailCall = false;
  6439. }
  6440. for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
  6441. TargetLowering::ArgListEntry Entry;
  6442. const Value *V = *I;
  6443. // Skip empty types
  6444. if (V->getType()->isEmptyTy())
  6445. continue;
  6446. SDValue ArgNode = getValue(V);
  6447. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6448. Entry.setAttributes(&CB, I - CB.arg_begin());
  6449. // Use swifterror virtual register as input to the call.
  6450. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6451. SwiftErrorVal = V;
  6452. // We find the virtual register for the actual swifterror argument.
  6453. // Instead of using the Value, we use the virtual register instead.
  6454. Entry.Node =
  6455. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
  6456. EVT(TLI.getPointerTy(DL)));
  6457. }
  6458. Args.push_back(Entry);
  6459. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6460. // might point to function-local memory), we can't meaningfully tail-call.
  6461. if (Entry.IsSRet && isa<Instruction>(V))
  6462. isTailCall = false;
  6463. }
  6464. // If call site has a cfguardtarget operand bundle, create and add an
  6465. // additional ArgListEntry.
  6466. if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
  6467. TargetLowering::ArgListEntry Entry;
  6468. Value *V = Bundle->Inputs[0];
  6469. SDValue ArgNode = getValue(V);
  6470. Entry.Node = ArgNode;
  6471. Entry.Ty = V->getType();
  6472. Entry.IsCFGuardTarget = true;
  6473. Args.push_back(Entry);
  6474. }
  6475. // Check if target-independent constraints permit a tail call here.
  6476. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6477. if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
  6478. isTailCall = false;
  6479. // Disable tail calls if there is an swifterror argument. Targets have not
  6480. // been updated to support tail calls.
  6481. if (TLI.supportSwiftError() && SwiftErrorVal)
  6482. isTailCall = false;
  6483. TargetLowering::CallLoweringInfo CLI(DAG);
  6484. CLI.setDebugLoc(getCurSDLoc())
  6485. .setChain(getRoot())
  6486. .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
  6487. .setTailCall(isTailCall)
  6488. .setConvergent(CB.isConvergent())
  6489. .setIsPreallocated(
  6490. CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
  6491. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6492. if (Result.first.getNode()) {
  6493. Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
  6494. setValue(&CB, Result.first);
  6495. }
  6496. // The last element of CLI.InVals has the SDValue for swifterror return.
  6497. // Here we copy it to a virtual register and update SwiftErrorMap for
  6498. // book-keeping.
  6499. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6500. // Get the last element of InVals.
  6501. SDValue Src = CLI.InVals.back();
  6502. Register VReg =
  6503. SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
  6504. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6505. DAG.setRoot(CopyNode);
  6506. }
  6507. }
  6508. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6509. SelectionDAGBuilder &Builder) {
  6510. // Check to see if this load can be trivially constant folded, e.g. if the
  6511. // input is from a string literal.
  6512. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6513. // Cast pointer to the type we really want to load.
  6514. Type *LoadTy =
  6515. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6516. if (LoadVT.isVector())
  6517. LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6518. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6519. PointerType::getUnqual(LoadTy));
  6520. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6521. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6522. return Builder.getValue(LoadCst);
  6523. }
  6524. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6525. // still constant memory, the input chain can be the entry node.
  6526. SDValue Root;
  6527. bool ConstantMemory = false;
  6528. // Do not serialize (non-volatile) loads of constant memory with anything.
  6529. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6530. Root = Builder.DAG.getEntryNode();
  6531. ConstantMemory = true;
  6532. } else {
  6533. // Do not serialize non-volatile loads against each other.
  6534. Root = Builder.DAG.getRoot();
  6535. }
  6536. SDValue Ptr = Builder.getValue(PtrVal);
  6537. SDValue LoadVal =
  6538. Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
  6539. MachinePointerInfo(PtrVal), Align(1));
  6540. if (!ConstantMemory)
  6541. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6542. return LoadVal;
  6543. }
  6544. /// Record the value for an instruction that produces an integer result,
  6545. /// converting the type where necessary.
  6546. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6547. SDValue Value,
  6548. bool IsSigned) {
  6549. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6550. I.getType(), true);
  6551. if (IsSigned)
  6552. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6553. else
  6554. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6555. setValue(&I, Value);
  6556. }
  6557. /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
  6558. /// true and lower it. Otherwise return false, and it will be lowered like a
  6559. /// normal call.
  6560. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6561. /// correct prototype.
  6562. bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
  6563. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6564. const Value *Size = I.getArgOperand(2);
  6565. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6566. if (CSize && CSize->getZExtValue() == 0) {
  6567. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6568. I.getType(), true);
  6569. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6570. return true;
  6571. }
  6572. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6573. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6574. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6575. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6576. if (Res.first.getNode()) {
  6577. processIntegerCallValue(I, Res.first, true);
  6578. PendingLoads.push_back(Res.second);
  6579. return true;
  6580. }
  6581. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6582. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6583. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6584. return false;
  6585. // If the target has a fast compare for the given size, it will return a
  6586. // preferred load type for that size. Require that the load VT is legal and
  6587. // that the target supports unaligned loads of that type. Otherwise, return
  6588. // INVALID.
  6589. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6590. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6591. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6592. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6593. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6594. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6595. // TODO: Check alignment of src and dest ptrs.
  6596. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6597. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6598. if (!TLI.isTypeLegal(LVT) ||
  6599. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6600. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6601. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6602. }
  6603. return LVT;
  6604. };
  6605. // This turns into unaligned loads. We only do this if the target natively
  6606. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6607. // we'll only produce a small number of byte loads.
  6608. MVT LoadVT;
  6609. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6610. switch (NumBitsToCompare) {
  6611. default:
  6612. return false;
  6613. case 16:
  6614. LoadVT = MVT::i16;
  6615. break;
  6616. case 32:
  6617. LoadVT = MVT::i32;
  6618. break;
  6619. case 64:
  6620. case 128:
  6621. case 256:
  6622. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6623. break;
  6624. }
  6625. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6626. return false;
  6627. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6628. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6629. // Bitcast to a wide integer type if the loads are vectors.
  6630. if (LoadVT.isVector()) {
  6631. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6632. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6633. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6634. }
  6635. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6636. processIntegerCallValue(I, Cmp, false);
  6637. return true;
  6638. }
  6639. /// See if we can lower a memchr call into an optimized form. If so, return
  6640. /// true and lower it. Otherwise return false, and it will be lowered like a
  6641. /// normal call.
  6642. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6643. /// correct prototype.
  6644. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6645. const Value *Src = I.getArgOperand(0);
  6646. const Value *Char = I.getArgOperand(1);
  6647. const Value *Length = I.getArgOperand(2);
  6648. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6649. std::pair<SDValue, SDValue> Res =
  6650. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6651. getValue(Src), getValue(Char), getValue(Length),
  6652. MachinePointerInfo(Src));
  6653. if (Res.first.getNode()) {
  6654. setValue(&I, Res.first);
  6655. PendingLoads.push_back(Res.second);
  6656. return true;
  6657. }
  6658. return false;
  6659. }
  6660. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6661. /// true and lower it. Otherwise return false, and it will be lowered like a
  6662. /// normal call.
  6663. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6664. /// correct prototype.
  6665. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6666. SDValue Dst = getValue(I.getArgOperand(0));
  6667. SDValue Src = getValue(I.getArgOperand(1));
  6668. SDValue Size = getValue(I.getArgOperand(2));
  6669. Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
  6670. Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
  6671. // DAG::getMemcpy needs Alignment to be defined.
  6672. Align Alignment = std::min(DstAlign, SrcAlign);
  6673. bool isVol = false;
  6674. SDLoc sdl = getCurSDLoc();
  6675. // In the mempcpy context we need to pass in a false value for isTailCall
  6676. // because the return pointer needs to be adjusted by the size of
  6677. // the copied memory.
  6678. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  6679. SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
  6680. /*isTailCall=*/false,
  6681. MachinePointerInfo(I.getArgOperand(0)),
  6682. MachinePointerInfo(I.getArgOperand(1)));
  6683. assert(MC.getNode() != nullptr &&
  6684. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6685. DAG.setRoot(MC);
  6686. // Check if Size needs to be truncated or extended.
  6687. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6688. // Adjust return pointer to point just past the last dst byte.
  6689. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6690. Dst, Size);
  6691. setValue(&I, DstPlusSize);
  6692. return true;
  6693. }
  6694. /// See if we can lower a strcpy call into an optimized form. If so, return
  6695. /// true and lower it, otherwise return false and it will be lowered like a
  6696. /// normal call.
  6697. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6698. /// correct prototype.
  6699. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6700. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6701. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6702. std::pair<SDValue, SDValue> Res =
  6703. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6704. getValue(Arg0), getValue(Arg1),
  6705. MachinePointerInfo(Arg0),
  6706. MachinePointerInfo(Arg1), isStpcpy);
  6707. if (Res.first.getNode()) {
  6708. setValue(&I, Res.first);
  6709. DAG.setRoot(Res.second);
  6710. return true;
  6711. }
  6712. return false;
  6713. }
  6714. /// See if we can lower a strcmp call into an optimized form. If so, return
  6715. /// true and lower it, otherwise return false and it will be lowered like a
  6716. /// normal call.
  6717. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6718. /// correct prototype.
  6719. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6720. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6721. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6722. std::pair<SDValue, SDValue> Res =
  6723. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6724. getValue(Arg0), getValue(Arg1),
  6725. MachinePointerInfo(Arg0),
  6726. MachinePointerInfo(Arg1));
  6727. if (Res.first.getNode()) {
  6728. processIntegerCallValue(I, Res.first, true);
  6729. PendingLoads.push_back(Res.second);
  6730. return true;
  6731. }
  6732. return false;
  6733. }
  6734. /// See if we can lower a strlen call into an optimized form. If so, return
  6735. /// true and lower it, otherwise return false and it will be lowered like a
  6736. /// normal call.
  6737. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6738. /// correct prototype.
  6739. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6740. const Value *Arg0 = I.getArgOperand(0);
  6741. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6742. std::pair<SDValue, SDValue> Res =
  6743. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6744. getValue(Arg0), MachinePointerInfo(Arg0));
  6745. if (Res.first.getNode()) {
  6746. processIntegerCallValue(I, Res.first, false);
  6747. PendingLoads.push_back(Res.second);
  6748. return true;
  6749. }
  6750. return false;
  6751. }
  6752. /// See if we can lower a strnlen call into an optimized form. If so, return
  6753. /// true and lower it, otherwise return false and it will be lowered like a
  6754. /// normal call.
  6755. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6756. /// correct prototype.
  6757. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6758. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6759. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6760. std::pair<SDValue, SDValue> Res =
  6761. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6762. getValue(Arg0), getValue(Arg1),
  6763. MachinePointerInfo(Arg0));
  6764. if (Res.first.getNode()) {
  6765. processIntegerCallValue(I, Res.first, false);
  6766. PendingLoads.push_back(Res.second);
  6767. return true;
  6768. }
  6769. return false;
  6770. }
  6771. /// See if we can lower a unary floating-point operation into an SDNode with
  6772. /// the specified Opcode. If so, return true and lower it, otherwise return
  6773. /// false and it will be lowered like a normal call.
  6774. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6775. /// correct prototype.
  6776. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6777. unsigned Opcode) {
  6778. // We already checked this call's prototype; verify it doesn't modify errno.
  6779. if (!I.onlyReadsMemory())
  6780. return false;
  6781. SDNodeFlags Flags;
  6782. Flags.copyFMF(cast<FPMathOperator>(I));
  6783. SDValue Tmp = getValue(I.getArgOperand(0));
  6784. setValue(&I,
  6785. DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
  6786. return true;
  6787. }
  6788. /// See if we can lower a binary floating-point operation into an SDNode with
  6789. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6790. /// false, and it will be lowered like a normal call.
  6791. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6792. /// correct prototype.
  6793. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6794. unsigned Opcode) {
  6795. // We already checked this call's prototype; verify it doesn't modify errno.
  6796. if (!I.onlyReadsMemory())
  6797. return false;
  6798. SDNodeFlags Flags;
  6799. Flags.copyFMF(cast<FPMathOperator>(I));
  6800. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6801. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6802. EVT VT = Tmp0.getValueType();
  6803. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
  6804. return true;
  6805. }
  6806. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6807. // Handle inline assembly differently.
  6808. if (I.isInlineAsm()) {
  6809. visitInlineAsm(I);
  6810. return;
  6811. }
  6812. if (Function *F = I.getCalledFunction()) {
  6813. if (F->isDeclaration()) {
  6814. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6815. unsigned IID = F->getIntrinsicID();
  6816. if (!IID)
  6817. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6818. IID = II->getIntrinsicID(F);
  6819. if (IID) {
  6820. visitIntrinsicCall(I, IID);
  6821. return;
  6822. }
  6823. }
  6824. // Check for well-known libc/libm calls. If the function is internal, it
  6825. // can't be a library call. Don't do the check if marked as nobuiltin for
  6826. // some reason or the call site requires strict floating point semantics.
  6827. LibFunc Func;
  6828. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6829. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6830. LibInfo->hasOptimizedCodeGen(Func)) {
  6831. switch (Func) {
  6832. default: break;
  6833. case LibFunc_bcmp:
  6834. if (visitMemCmpBCmpCall(I))
  6835. return;
  6836. break;
  6837. case LibFunc_copysign:
  6838. case LibFunc_copysignf:
  6839. case LibFunc_copysignl:
  6840. // We already checked this call's prototype; verify it doesn't modify
  6841. // errno.
  6842. if (I.onlyReadsMemory()) {
  6843. SDValue LHS = getValue(I.getArgOperand(0));
  6844. SDValue RHS = getValue(I.getArgOperand(1));
  6845. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6846. LHS.getValueType(), LHS, RHS));
  6847. return;
  6848. }
  6849. break;
  6850. case LibFunc_fabs:
  6851. case LibFunc_fabsf:
  6852. case LibFunc_fabsl:
  6853. if (visitUnaryFloatCall(I, ISD::FABS))
  6854. return;
  6855. break;
  6856. case LibFunc_fmin:
  6857. case LibFunc_fminf:
  6858. case LibFunc_fminl:
  6859. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6860. return;
  6861. break;
  6862. case LibFunc_fmax:
  6863. case LibFunc_fmaxf:
  6864. case LibFunc_fmaxl:
  6865. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6866. return;
  6867. break;
  6868. case LibFunc_sin:
  6869. case LibFunc_sinf:
  6870. case LibFunc_sinl:
  6871. if (visitUnaryFloatCall(I, ISD::FSIN))
  6872. return;
  6873. break;
  6874. case LibFunc_cos:
  6875. case LibFunc_cosf:
  6876. case LibFunc_cosl:
  6877. if (visitUnaryFloatCall(I, ISD::FCOS))
  6878. return;
  6879. break;
  6880. case LibFunc_sqrt:
  6881. case LibFunc_sqrtf:
  6882. case LibFunc_sqrtl:
  6883. case LibFunc_sqrt_finite:
  6884. case LibFunc_sqrtf_finite:
  6885. case LibFunc_sqrtl_finite:
  6886. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6887. return;
  6888. break;
  6889. case LibFunc_floor:
  6890. case LibFunc_floorf:
  6891. case LibFunc_floorl:
  6892. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6893. return;
  6894. break;
  6895. case LibFunc_nearbyint:
  6896. case LibFunc_nearbyintf:
  6897. case LibFunc_nearbyintl:
  6898. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6899. return;
  6900. break;
  6901. case LibFunc_ceil:
  6902. case LibFunc_ceilf:
  6903. case LibFunc_ceill:
  6904. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6905. return;
  6906. break;
  6907. case LibFunc_rint:
  6908. case LibFunc_rintf:
  6909. case LibFunc_rintl:
  6910. if (visitUnaryFloatCall(I, ISD::FRINT))
  6911. return;
  6912. break;
  6913. case LibFunc_round:
  6914. case LibFunc_roundf:
  6915. case LibFunc_roundl:
  6916. if (visitUnaryFloatCall(I, ISD::FROUND))
  6917. return;
  6918. break;
  6919. case LibFunc_trunc:
  6920. case LibFunc_truncf:
  6921. case LibFunc_truncl:
  6922. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6923. return;
  6924. break;
  6925. case LibFunc_log2:
  6926. case LibFunc_log2f:
  6927. case LibFunc_log2l:
  6928. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6929. return;
  6930. break;
  6931. case LibFunc_exp2:
  6932. case LibFunc_exp2f:
  6933. case LibFunc_exp2l:
  6934. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6935. return;
  6936. break;
  6937. case LibFunc_memcmp:
  6938. if (visitMemCmpBCmpCall(I))
  6939. return;
  6940. break;
  6941. case LibFunc_mempcpy:
  6942. if (visitMemPCpyCall(I))
  6943. return;
  6944. break;
  6945. case LibFunc_memchr:
  6946. if (visitMemChrCall(I))
  6947. return;
  6948. break;
  6949. case LibFunc_strcpy:
  6950. if (visitStrCpyCall(I, false))
  6951. return;
  6952. break;
  6953. case LibFunc_stpcpy:
  6954. if (visitStrCpyCall(I, true))
  6955. return;
  6956. break;
  6957. case LibFunc_strcmp:
  6958. if (visitStrCmpCall(I))
  6959. return;
  6960. break;
  6961. case LibFunc_strlen:
  6962. if (visitStrLenCall(I))
  6963. return;
  6964. break;
  6965. case LibFunc_strnlen:
  6966. if (visitStrNLenCall(I))
  6967. return;
  6968. break;
  6969. }
  6970. }
  6971. }
  6972. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6973. // have to do anything here to lower funclet bundles.
  6974. // CFGuardTarget bundles are lowered in LowerCallTo.
  6975. assert(!I.hasOperandBundlesOtherThan(
  6976. {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
  6977. LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
  6978. "Cannot lower calls with arbitrary operand bundles!");
  6979. SDValue Callee = getValue(I.getCalledOperand());
  6980. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6981. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6982. else
  6983. // Check if we can potentially perform a tail call. More detailed checking
  6984. // is be done within LowerCallTo, after more information about the call is
  6985. // known.
  6986. LowerCallTo(I, Callee, I.isTailCall());
  6987. }
  6988. namespace {
  6989. /// AsmOperandInfo - This contains information for each constraint that we are
  6990. /// lowering.
  6991. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6992. public:
  6993. /// CallOperand - If this is the result output operand or a clobber
  6994. /// this is null, otherwise it is the incoming operand to the CallInst.
  6995. /// This gets modified as the asm is processed.
  6996. SDValue CallOperand;
  6997. /// AssignedRegs - If this is a register or register class operand, this
  6998. /// contains the set of register corresponding to the operand.
  6999. RegsForValue AssignedRegs;
  7000. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  7001. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  7002. }
  7003. /// Whether or not this operand accesses memory
  7004. bool hasMemory(const TargetLowering &TLI) const {
  7005. // Indirect operand accesses access memory.
  7006. if (isIndirect)
  7007. return true;
  7008. for (const auto &Code : Codes)
  7009. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  7010. return true;
  7011. return false;
  7012. }
  7013. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  7014. /// corresponds to. If there is no Value* for this operand, it returns
  7015. /// MVT::Other.
  7016. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  7017. const DataLayout &DL) const {
  7018. if (!CallOperandVal) return MVT::Other;
  7019. if (isa<BasicBlock>(CallOperandVal))
  7020. return TLI.getProgramPointerTy(DL);
  7021. llvm::Type *OpTy = CallOperandVal->getType();
  7022. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  7023. // If this is an indirect operand, the operand is a pointer to the
  7024. // accessed type.
  7025. if (isIndirect) {
  7026. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  7027. if (!PtrTy)
  7028. report_fatal_error("Indirect operand for inline asm not a pointer!");
  7029. OpTy = PtrTy->getElementType();
  7030. }
  7031. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  7032. if (StructType *STy = dyn_cast<StructType>(OpTy))
  7033. if (STy->getNumElements() == 1)
  7034. OpTy = STy->getElementType(0);
  7035. // If OpTy is not a single value, it may be a struct/union that we
  7036. // can tile with integers.
  7037. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  7038. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  7039. switch (BitSize) {
  7040. default: break;
  7041. case 1:
  7042. case 8:
  7043. case 16:
  7044. case 32:
  7045. case 64:
  7046. case 128:
  7047. OpTy = IntegerType::get(Context, BitSize);
  7048. break;
  7049. }
  7050. }
  7051. return TLI.getValueType(DL, OpTy, true);
  7052. }
  7053. };
  7054. } // end anonymous namespace
  7055. /// Make sure that the output operand \p OpInfo and its corresponding input
  7056. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  7057. /// out).
  7058. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  7059. SDISelAsmOperandInfo &MatchingOpInfo,
  7060. SelectionDAG &DAG) {
  7061. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  7062. return;
  7063. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  7064. const auto &TLI = DAG.getTargetLoweringInfo();
  7065. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  7066. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  7067. OpInfo.ConstraintVT);
  7068. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  7069. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  7070. MatchingOpInfo.ConstraintVT);
  7071. if ((OpInfo.ConstraintVT.isInteger() !=
  7072. MatchingOpInfo.ConstraintVT.isInteger()) ||
  7073. (MatchRC.second != InputRC.second)) {
  7074. // FIXME: error out in a more elegant fashion
  7075. report_fatal_error("Unsupported asm: input constraint"
  7076. " with a matching output constraint of"
  7077. " incompatible type!");
  7078. }
  7079. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  7080. }
  7081. /// Get a direct memory input to behave well as an indirect operand.
  7082. /// This may introduce stores, hence the need for a \p Chain.
  7083. /// \return The (possibly updated) chain.
  7084. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  7085. SDISelAsmOperandInfo &OpInfo,
  7086. SelectionDAG &DAG) {
  7087. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7088. // If we don't have an indirect input, put it in the constpool if we can,
  7089. // otherwise spill it to a stack slot.
  7090. // TODO: This isn't quite right. We need to handle these according to
  7091. // the addressing mode that the constraint wants. Also, this may take
  7092. // an additional register for the computation and we don't want that
  7093. // either.
  7094. // If the operand is a float, integer, or vector constant, spill to a
  7095. // constant pool entry to get its address.
  7096. const Value *OpVal = OpInfo.CallOperandVal;
  7097. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  7098. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  7099. OpInfo.CallOperand = DAG.getConstantPool(
  7100. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  7101. return Chain;
  7102. }
  7103. // Otherwise, create a stack slot and emit a store to it before the asm.
  7104. Type *Ty = OpVal->getType();
  7105. auto &DL = DAG.getDataLayout();
  7106. uint64_t TySize = DL.getTypeAllocSize(Ty);
  7107. MachineFunction &MF = DAG.getMachineFunction();
  7108. int SSFI = MF.getFrameInfo().CreateStackObject(
  7109. TySize, DL.getPrefTypeAlign(Ty), false);
  7110. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  7111. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  7112. MachinePointerInfo::getFixedStack(MF, SSFI),
  7113. TLI.getMemValueType(DL, Ty));
  7114. OpInfo.CallOperand = StackSlot;
  7115. return Chain;
  7116. }
  7117. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  7118. /// specified operand. We prefer to assign virtual registers, to allow the
  7119. /// register allocator to handle the assignment process. However, if the asm
  7120. /// uses features that we can't model on machineinstrs, we have SDISel do the
  7121. /// allocation. This produces generally horrible, but correct, code.
  7122. ///
  7123. /// OpInfo describes the operand
  7124. /// RefOpInfo describes the matching operand if any, the operand otherwise
  7125. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  7126. SDISelAsmOperandInfo &OpInfo,
  7127. SDISelAsmOperandInfo &RefOpInfo) {
  7128. LLVMContext &Context = *DAG.getContext();
  7129. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7130. MachineFunction &MF = DAG.getMachineFunction();
  7131. SmallVector<unsigned, 4> Regs;
  7132. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7133. // No work to do for memory operations.
  7134. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  7135. return;
  7136. // If this is a constraint for a single physreg, or a constraint for a
  7137. // register class, find it.
  7138. unsigned AssignedReg;
  7139. const TargetRegisterClass *RC;
  7140. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  7141. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  7142. // RC is unset only on failure. Return immediately.
  7143. if (!RC)
  7144. return;
  7145. // Get the actual register value type. This is important, because the user
  7146. // may have asked for (e.g.) the AX register in i32 type. We need to
  7147. // remember that AX is actually i16 to get the right extension.
  7148. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  7149. if (OpInfo.ConstraintVT != MVT::Other) {
  7150. // If this is an FP operand in an integer register (or visa versa), or more
  7151. // generally if the operand value disagrees with the register class we plan
  7152. // to stick it in, fix the operand type.
  7153. //
  7154. // If this is an input value, the bitcast to the new type is done now.
  7155. // Bitcast for output value is done at the end of visitInlineAsm().
  7156. if ((OpInfo.Type == InlineAsm::isOutput ||
  7157. OpInfo.Type == InlineAsm::isInput) &&
  7158. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  7159. // Try to convert to the first EVT that the reg class contains. If the
  7160. // types are identical size, use a bitcast to convert (e.g. two differing
  7161. // vector types). Note: output bitcast is done at the end of
  7162. // visitInlineAsm().
  7163. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  7164. // Exclude indirect inputs while they are unsupported because the code
  7165. // to perform the load is missing and thus OpInfo.CallOperand still
  7166. // refers to the input address rather than the pointed-to value.
  7167. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  7168. OpInfo.CallOperand =
  7169. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  7170. OpInfo.ConstraintVT = RegVT;
  7171. // If the operand is an FP value and we want it in integer registers,
  7172. // use the corresponding integer type. This turns an f64 value into
  7173. // i64, which can be passed with two i32 values on a 32-bit machine.
  7174. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7175. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7176. if (OpInfo.Type == InlineAsm::isInput)
  7177. OpInfo.CallOperand =
  7178. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7179. OpInfo.ConstraintVT = VT;
  7180. }
  7181. }
  7182. }
  7183. // No need to allocate a matching input constraint since the constraint it's
  7184. // matching to has already been allocated.
  7185. if (OpInfo.isMatchingInputConstraint())
  7186. return;
  7187. EVT ValueVT = OpInfo.ConstraintVT;
  7188. if (OpInfo.ConstraintVT == MVT::Other)
  7189. ValueVT = RegVT;
  7190. // Initialize NumRegs.
  7191. unsigned NumRegs = 1;
  7192. if (OpInfo.ConstraintVT != MVT::Other)
  7193. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  7194. // If this is a constraint for a specific physical register, like {r17},
  7195. // assign it now.
  7196. // If this associated to a specific register, initialize iterator to correct
  7197. // place. If virtual, make sure we have enough registers
  7198. // Initialize iterator if necessary
  7199. TargetRegisterClass::iterator I = RC->begin();
  7200. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7201. // Do not check for single registers.
  7202. if (AssignedReg) {
  7203. for (; *I != AssignedReg; ++I)
  7204. assert(I != RC->end() && "AssignedReg should be member of RC");
  7205. }
  7206. for (; NumRegs; --NumRegs, ++I) {
  7207. assert(I != RC->end() && "Ran out of registers to allocate!");
  7208. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7209. Regs.push_back(R);
  7210. }
  7211. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7212. }
  7213. static unsigned
  7214. findMatchingInlineAsmOperand(unsigned OperandNo,
  7215. const std::vector<SDValue> &AsmNodeOperands) {
  7216. // Scan until we find the definition we already emitted of this operand.
  7217. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7218. for (; OperandNo; --OperandNo) {
  7219. // Advance to the next operand.
  7220. unsigned OpFlag =
  7221. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7222. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7223. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7224. InlineAsm::isMemKind(OpFlag)) &&
  7225. "Skipped past definitions?");
  7226. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7227. }
  7228. return CurOp;
  7229. }
  7230. namespace {
  7231. class ExtraFlags {
  7232. unsigned Flags = 0;
  7233. public:
  7234. explicit ExtraFlags(const CallBase &Call) {
  7235. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  7236. if (IA->hasSideEffects())
  7237. Flags |= InlineAsm::Extra_HasSideEffects;
  7238. if (IA->isAlignStack())
  7239. Flags |= InlineAsm::Extra_IsAlignStack;
  7240. if (Call.isConvergent())
  7241. Flags |= InlineAsm::Extra_IsConvergent;
  7242. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7243. }
  7244. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7245. // Ideally, we would only check against memory constraints. However, the
  7246. // meaning of an Other constraint can be target-specific and we can't easily
  7247. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7248. // for Other constraints as well.
  7249. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7250. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7251. if (OpInfo.Type == InlineAsm::isInput)
  7252. Flags |= InlineAsm::Extra_MayLoad;
  7253. else if (OpInfo.Type == InlineAsm::isOutput)
  7254. Flags |= InlineAsm::Extra_MayStore;
  7255. else if (OpInfo.Type == InlineAsm::isClobber)
  7256. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7257. }
  7258. }
  7259. unsigned get() const { return Flags; }
  7260. };
  7261. } // end anonymous namespace
  7262. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7263. void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
  7264. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  7265. /// ConstraintOperands - Information about all of the constraints.
  7266. SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
  7267. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7268. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7269. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
  7270. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7271. // AsmDialect, MayLoad, MayStore).
  7272. bool HasSideEffect = IA->hasSideEffects();
  7273. ExtraFlags ExtraInfo(Call);
  7274. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7275. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7276. unsigned NumMatchingOps = 0;
  7277. for (auto &T : TargetConstraints) {
  7278. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7279. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7280. // Compute the value type for each operand.
  7281. if (OpInfo.Type == InlineAsm::isInput ||
  7282. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7283. OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
  7284. // Process the call argument. BasicBlocks are labels, currently appearing
  7285. // only in asm's.
  7286. if (isa<CallBrInst>(Call) &&
  7287. ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
  7288. cast<CallBrInst>(&Call)->getNumIndirectDests() -
  7289. NumMatchingOps) &&
  7290. (NumMatchingOps == 0 ||
  7291. ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
  7292. NumMatchingOps))) {
  7293. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7294. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7295. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7296. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7297. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7298. } else {
  7299. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7300. }
  7301. EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
  7302. DAG.getDataLayout());
  7303. OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
  7304. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7305. // The return value of the call is this value. As such, there is no
  7306. // corresponding argument.
  7307. assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
  7308. if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
  7309. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7310. DAG.getDataLayout(), STy->getElementType(ResNo));
  7311. } else {
  7312. assert(ResNo == 0 && "Asm only has one result!");
  7313. OpInfo.ConstraintVT =
  7314. TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
  7315. }
  7316. ++ResNo;
  7317. } else {
  7318. OpInfo.ConstraintVT = MVT::Other;
  7319. }
  7320. if (OpInfo.hasMatchingInput())
  7321. ++NumMatchingOps;
  7322. if (!HasSideEffect)
  7323. HasSideEffect = OpInfo.hasMemory(TLI);
  7324. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7325. // FIXME: Could we compute this on OpInfo rather than T?
  7326. // Compute the constraint code and ConstraintType to use.
  7327. TLI.ComputeConstraintToUse(T, SDValue());
  7328. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7329. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7330. // We've delayed emitting a diagnostic like the "n" constraint because
  7331. // inlining could cause an integer showing up.
  7332. return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
  7333. "' expects an integer constant "
  7334. "expression");
  7335. ExtraInfo.update(T);
  7336. }
  7337. // We won't need to flush pending loads if this asm doesn't touch
  7338. // memory and is nonvolatile.
  7339. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7340. bool IsCallBr = isa<CallBrInst>(Call);
  7341. if (IsCallBr) {
  7342. // If this is a callbr we need to flush pending exports since inlineasm_br
  7343. // is a terminator. We need to do this before nodes are glued to
  7344. // the inlineasm_br node.
  7345. Chain = getControlRoot();
  7346. }
  7347. // Second pass over the constraints: compute which constraint option to use.
  7348. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7349. // If this is an output operand with a matching input operand, look up the
  7350. // matching input. If their types mismatch, e.g. one is an integer, the
  7351. // other is floating point, or their sizes are different, flag it as an
  7352. // error.
  7353. if (OpInfo.hasMatchingInput()) {
  7354. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7355. patchMatchingInput(OpInfo, Input, DAG);
  7356. }
  7357. // Compute the constraint code and ConstraintType to use.
  7358. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7359. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7360. OpInfo.Type == InlineAsm::isClobber)
  7361. continue;
  7362. // If this is a memory input, and if the operand is not indirect, do what we
  7363. // need to provide an address for the memory input.
  7364. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7365. !OpInfo.isIndirect) {
  7366. assert((OpInfo.isMultipleAlternative ||
  7367. (OpInfo.Type == InlineAsm::isInput)) &&
  7368. "Can only indirectify direct input operands!");
  7369. // Memory operands really want the address of the value.
  7370. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7371. // There is no longer a Value* corresponding to this operand.
  7372. OpInfo.CallOperandVal = nullptr;
  7373. // It is now an indirect operand.
  7374. OpInfo.isIndirect = true;
  7375. }
  7376. }
  7377. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7378. std::vector<SDValue> AsmNodeOperands;
  7379. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7380. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7381. IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
  7382. // If we have a !srcloc metadata node associated with it, we want to attach
  7383. // this to the ultimately generated inline asm machineinstr. To do this, we
  7384. // pass in the third operand as this (potentially null) inline asm MDNode.
  7385. const MDNode *SrcLoc = Call.getMetadata("srcloc");
  7386. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7387. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7388. // bits as operand 3.
  7389. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7390. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7391. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7392. // this, assign virtual and physical registers for inputs and otput.
  7393. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7394. // Assign Registers.
  7395. SDISelAsmOperandInfo &RefOpInfo =
  7396. OpInfo.isMatchingInputConstraint()
  7397. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7398. : OpInfo;
  7399. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7400. auto DetectWriteToReservedRegister = [&]() {
  7401. const MachineFunction &MF = DAG.getMachineFunction();
  7402. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7403. for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
  7404. if (Register::isPhysicalRegister(Reg) &&
  7405. TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
  7406. const char *RegName = TRI.getName(Reg);
  7407. emitInlineAsmError(Call, "write to reserved register '" +
  7408. Twine(RegName) + "'");
  7409. return true;
  7410. }
  7411. }
  7412. return false;
  7413. };
  7414. switch (OpInfo.Type) {
  7415. case InlineAsm::isOutput:
  7416. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7417. unsigned ConstraintID =
  7418. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7419. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7420. "Failed to convert memory constraint code to constraint id.");
  7421. // Add information to the INLINEASM node to know about this output.
  7422. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7423. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7424. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7425. MVT::i32));
  7426. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7427. } else {
  7428. // Otherwise, this outputs to a register (directly for C_Register /
  7429. // C_RegisterClass, and a target-defined fashion for
  7430. // C_Immediate/C_Other). Find a register that we can use.
  7431. if (OpInfo.AssignedRegs.Regs.empty()) {
  7432. emitInlineAsmError(
  7433. Call, "couldn't allocate output register for constraint '" +
  7434. Twine(OpInfo.ConstraintCode) + "'");
  7435. return;
  7436. }
  7437. if (DetectWriteToReservedRegister())
  7438. return;
  7439. // Add information to the INLINEASM node to know that this register is
  7440. // set.
  7441. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7442. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7443. : InlineAsm::Kind_RegDef,
  7444. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7445. }
  7446. break;
  7447. case InlineAsm::isInput: {
  7448. SDValue InOperandVal = OpInfo.CallOperand;
  7449. if (OpInfo.isMatchingInputConstraint()) {
  7450. // If this is required to match an output register we have already set,
  7451. // just use its register.
  7452. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7453. AsmNodeOperands);
  7454. unsigned OpFlag =
  7455. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7456. if (InlineAsm::isRegDefKind(OpFlag) ||
  7457. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7458. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7459. if (OpInfo.isIndirect) {
  7460. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7461. emitInlineAsmError(Call, "inline asm not supported yet: "
  7462. "don't know how to handle tied "
  7463. "indirect register inputs");
  7464. return;
  7465. }
  7466. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7467. SmallVector<unsigned, 4> Regs;
  7468. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7469. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7470. MachineRegisterInfo &RegInfo =
  7471. DAG.getMachineFunction().getRegInfo();
  7472. for (unsigned i = 0; i != NumRegs; ++i)
  7473. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7474. } else {
  7475. emitInlineAsmError(Call,
  7476. "inline asm error: This value type register "
  7477. "class is not natively supported!");
  7478. return;
  7479. }
  7480. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7481. SDLoc dl = getCurSDLoc();
  7482. // Use the produced MatchedRegs object to
  7483. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
  7484. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7485. true, OpInfo.getMatchedOperand(), dl,
  7486. DAG, AsmNodeOperands);
  7487. break;
  7488. }
  7489. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7490. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7491. "Unexpected number of operands");
  7492. // Add information to the INLINEASM node to know about this input.
  7493. // See InlineAsm.h isUseOperandTiedToDef.
  7494. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7495. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7496. OpInfo.getMatchedOperand());
  7497. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7498. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7499. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7500. break;
  7501. }
  7502. // Treat indirect 'X' constraint as memory.
  7503. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7504. OpInfo.isIndirect)
  7505. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7506. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7507. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7508. std::vector<SDValue> Ops;
  7509. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7510. Ops, DAG);
  7511. if (Ops.empty()) {
  7512. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  7513. if (isa<ConstantSDNode>(InOperandVal)) {
  7514. emitInlineAsmError(Call, "value out of range for constraint '" +
  7515. Twine(OpInfo.ConstraintCode) + "'");
  7516. return;
  7517. }
  7518. emitInlineAsmError(Call,
  7519. "invalid operand for inline asm constraint '" +
  7520. Twine(OpInfo.ConstraintCode) + "'");
  7521. return;
  7522. }
  7523. // Add information to the INLINEASM node to know about this input.
  7524. unsigned ResOpType =
  7525. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7526. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7527. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7528. llvm::append_range(AsmNodeOperands, Ops);
  7529. break;
  7530. }
  7531. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7532. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7533. assert(InOperandVal.getValueType() ==
  7534. TLI.getPointerTy(DAG.getDataLayout()) &&
  7535. "Memory operands expect pointer values");
  7536. unsigned ConstraintID =
  7537. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7538. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7539. "Failed to convert memory constraint code to constraint id.");
  7540. // Add information to the INLINEASM node to know about this input.
  7541. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7542. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7543. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7544. getCurSDLoc(),
  7545. MVT::i32));
  7546. AsmNodeOperands.push_back(InOperandVal);
  7547. break;
  7548. }
  7549. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7550. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7551. "Unknown constraint type!");
  7552. // TODO: Support this.
  7553. if (OpInfo.isIndirect) {
  7554. emitInlineAsmError(
  7555. Call, "Don't know how to handle indirect register inputs yet "
  7556. "for constraint '" +
  7557. Twine(OpInfo.ConstraintCode) + "'");
  7558. return;
  7559. }
  7560. // Copy the input into the appropriate registers.
  7561. if (OpInfo.AssignedRegs.Regs.empty()) {
  7562. emitInlineAsmError(Call,
  7563. "couldn't allocate input reg for constraint '" +
  7564. Twine(OpInfo.ConstraintCode) + "'");
  7565. return;
  7566. }
  7567. if (DetectWriteToReservedRegister())
  7568. return;
  7569. SDLoc dl = getCurSDLoc();
  7570. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7571. &Call);
  7572. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7573. dl, DAG, AsmNodeOperands);
  7574. break;
  7575. }
  7576. case InlineAsm::isClobber:
  7577. // Add the clobbered value to the operand list, so that the register
  7578. // allocator is aware that the physreg got clobbered.
  7579. if (!OpInfo.AssignedRegs.Regs.empty())
  7580. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7581. false, 0, getCurSDLoc(), DAG,
  7582. AsmNodeOperands);
  7583. break;
  7584. }
  7585. }
  7586. // Finish up input operands. Set the input chain and add the flag last.
  7587. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7588. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7589. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7590. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7591. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7592. Flag = Chain.getValue(1);
  7593. // Do additional work to generate outputs.
  7594. SmallVector<EVT, 1> ResultVTs;
  7595. SmallVector<SDValue, 1> ResultValues;
  7596. SmallVector<SDValue, 8> OutChains;
  7597. llvm::Type *CallResultType = Call.getType();
  7598. ArrayRef<Type *> ResultTypes;
  7599. if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
  7600. ResultTypes = StructResult->elements();
  7601. else if (!CallResultType->isVoidTy())
  7602. ResultTypes = makeArrayRef(CallResultType);
  7603. auto CurResultType = ResultTypes.begin();
  7604. auto handleRegAssign = [&](SDValue V) {
  7605. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7606. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7607. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7608. ++CurResultType;
  7609. // If the type of the inline asm call site return value is different but has
  7610. // same size as the type of the asm output bitcast it. One example of this
  7611. // is for vectors with different width / number of elements. This can
  7612. // happen for register classes that can contain multiple different value
  7613. // types. The preg or vreg allocated may not have the same VT as was
  7614. // expected.
  7615. //
  7616. // This can also happen for a return value that disagrees with the register
  7617. // class it is put in, eg. a double in a general-purpose register on a
  7618. // 32-bit machine.
  7619. if (ResultVT != V.getValueType() &&
  7620. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7621. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7622. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7623. V.getValueType().isInteger()) {
  7624. // If a result value was tied to an input value, the computed result
  7625. // may have a wider width than the expected result. Extract the
  7626. // relevant portion.
  7627. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7628. }
  7629. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7630. ResultVTs.push_back(ResultVT);
  7631. ResultValues.push_back(V);
  7632. };
  7633. // Deal with output operands.
  7634. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7635. if (OpInfo.Type == InlineAsm::isOutput) {
  7636. SDValue Val;
  7637. // Skip trivial output operands.
  7638. if (OpInfo.AssignedRegs.Regs.empty())
  7639. continue;
  7640. switch (OpInfo.ConstraintType) {
  7641. case TargetLowering::C_Register:
  7642. case TargetLowering::C_RegisterClass:
  7643. Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  7644. Chain, &Flag, &Call);
  7645. break;
  7646. case TargetLowering::C_Immediate:
  7647. case TargetLowering::C_Other:
  7648. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7649. OpInfo, DAG);
  7650. break;
  7651. case TargetLowering::C_Memory:
  7652. break; // Already handled.
  7653. case TargetLowering::C_Unknown:
  7654. assert(false && "Unexpected unknown constraint");
  7655. }
  7656. // Indirect output manifest as stores. Record output chains.
  7657. if (OpInfo.isIndirect) {
  7658. const Value *Ptr = OpInfo.CallOperandVal;
  7659. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7660. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7661. MachinePointerInfo(Ptr));
  7662. OutChains.push_back(Store);
  7663. } else {
  7664. // generate CopyFromRegs to associated registers.
  7665. assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
  7666. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7667. for (const SDValue &V : Val->op_values())
  7668. handleRegAssign(V);
  7669. } else
  7670. handleRegAssign(Val);
  7671. }
  7672. }
  7673. }
  7674. // Set results.
  7675. if (!ResultValues.empty()) {
  7676. assert(CurResultType == ResultTypes.end() &&
  7677. "Mismatch in number of ResultTypes");
  7678. assert(ResultValues.size() == ResultTypes.size() &&
  7679. "Mismatch in number of output operands in asm result");
  7680. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7681. DAG.getVTList(ResultVTs), ResultValues);
  7682. setValue(&Call, V);
  7683. }
  7684. // Collect store chains.
  7685. if (!OutChains.empty())
  7686. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7687. // Only Update Root if inline assembly has a memory effect.
  7688. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7689. DAG.setRoot(Chain);
  7690. }
  7691. void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
  7692. const Twine &Message) {
  7693. LLVMContext &Ctx = *DAG.getContext();
  7694. Ctx.emitError(&Call, Message);
  7695. // Make sure we leave the DAG in a valid state
  7696. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7697. SmallVector<EVT, 1> ValueVTs;
  7698. ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
  7699. if (ValueVTs.empty())
  7700. return;
  7701. SmallVector<SDValue, 1> Ops;
  7702. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7703. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7704. setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
  7705. }
  7706. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7707. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7708. MVT::Other, getRoot(),
  7709. getValue(I.getArgOperand(0)),
  7710. DAG.getSrcValue(I.getArgOperand(0))));
  7711. }
  7712. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7713. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7714. const DataLayout &DL = DAG.getDataLayout();
  7715. SDValue V = DAG.getVAArg(
  7716. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7717. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7718. DL.getABITypeAlign(I.getType()).value());
  7719. DAG.setRoot(V.getValue(1));
  7720. if (I.getType()->isPointerTy())
  7721. V = DAG.getPtrExtOrTrunc(
  7722. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7723. setValue(&I, V);
  7724. }
  7725. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7726. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7727. MVT::Other, getRoot(),
  7728. getValue(I.getArgOperand(0)),
  7729. DAG.getSrcValue(I.getArgOperand(0))));
  7730. }
  7731. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7732. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7733. MVT::Other, getRoot(),
  7734. getValue(I.getArgOperand(0)),
  7735. getValue(I.getArgOperand(1)),
  7736. DAG.getSrcValue(I.getArgOperand(0)),
  7737. DAG.getSrcValue(I.getArgOperand(1))));
  7738. }
  7739. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7740. const Instruction &I,
  7741. SDValue Op) {
  7742. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7743. if (!Range)
  7744. return Op;
  7745. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7746. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7747. return Op;
  7748. APInt Lo = CR.getUnsignedMin();
  7749. if (!Lo.isMinValue())
  7750. return Op;
  7751. APInt Hi = CR.getUnsignedMax();
  7752. unsigned Bits = std::max(Hi.getActiveBits(),
  7753. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7754. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7755. SDLoc SL = getCurSDLoc();
  7756. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7757. DAG.getValueType(SmallVT));
  7758. unsigned NumVals = Op.getNode()->getNumValues();
  7759. if (NumVals == 1)
  7760. return ZExt;
  7761. SmallVector<SDValue, 4> Ops;
  7762. Ops.push_back(ZExt);
  7763. for (unsigned I = 1; I != NumVals; ++I)
  7764. Ops.push_back(Op.getValue(I));
  7765. return DAG.getMergeValues(Ops, SL);
  7766. }
  7767. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7768. /// the call being lowered.
  7769. ///
  7770. /// This is a helper for lowering intrinsics that follow a target calling
  7771. /// convention or require stack pointer adjustment. Only a subset of the
  7772. /// intrinsic's operands need to participate in the calling convention.
  7773. void SelectionDAGBuilder::populateCallLoweringInfo(
  7774. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7775. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7776. bool IsPatchPoint) {
  7777. TargetLowering::ArgListTy Args;
  7778. Args.reserve(NumArgs);
  7779. // Populate the argument list.
  7780. // Attributes for args start at offset 1, after the return attribute.
  7781. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7782. ArgI != ArgE; ++ArgI) {
  7783. const Value *V = Call->getOperand(ArgI);
  7784. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7785. TargetLowering::ArgListEntry Entry;
  7786. Entry.Node = getValue(V);
  7787. Entry.Ty = V->getType();
  7788. Entry.setAttributes(Call, ArgI);
  7789. Args.push_back(Entry);
  7790. }
  7791. CLI.setDebugLoc(getCurSDLoc())
  7792. .setChain(getRoot())
  7793. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7794. .setDiscardResult(Call->use_empty())
  7795. .setIsPatchPoint(IsPatchPoint)
  7796. .setIsPreallocated(
  7797. Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
  7798. }
  7799. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7800. /// or patchpoint target node's operand list.
  7801. ///
  7802. /// Constants are converted to TargetConstants purely as an optimization to
  7803. /// avoid constant materialization and register allocation.
  7804. ///
  7805. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7806. /// generate addess computation nodes, and so FinalizeISel can convert the
  7807. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7808. /// address materialization and register allocation, but may also be required
  7809. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7810. /// alloca in the entry block, then the runtime may assume that the alloca's
  7811. /// StackMap location can be read immediately after compilation and that the
  7812. /// location is valid at any point during execution (this is similar to the
  7813. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7814. /// only available in a register, then the runtime would need to trap when
  7815. /// execution reaches the StackMap in order to read the alloca's location.
  7816. static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
  7817. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7818. SelectionDAGBuilder &Builder) {
  7819. for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
  7820. SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
  7821. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7822. Ops.push_back(
  7823. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7824. Ops.push_back(
  7825. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7826. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7827. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7828. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7829. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7830. } else
  7831. Ops.push_back(OpVal);
  7832. }
  7833. }
  7834. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7835. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7836. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7837. // [live variables...])
  7838. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7839. SDValue Chain, InFlag, Callee, NullPtr;
  7840. SmallVector<SDValue, 32> Ops;
  7841. SDLoc DL = getCurSDLoc();
  7842. Callee = getValue(CI.getCalledOperand());
  7843. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7844. // The stackmap intrinsic only records the live variables (the arguments
  7845. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7846. // intrinsic, this won't be lowered to a function call. This means we don't
  7847. // have to worry about calling conventions and target specific lowering code.
  7848. // Instead we perform the call lowering right here.
  7849. //
  7850. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7851. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7852. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7853. //
  7854. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7855. InFlag = Chain.getValue(1);
  7856. // Add the <id> and <numBytes> constants.
  7857. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7858. Ops.push_back(DAG.getTargetConstant(
  7859. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7860. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7861. Ops.push_back(DAG.getTargetConstant(
  7862. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7863. MVT::i32));
  7864. // Push live variables for the stack map.
  7865. addStackMapLiveVars(CI, 2, DL, Ops, *this);
  7866. // We are not pushing any register mask info here on the operands list,
  7867. // because the stackmap doesn't clobber anything.
  7868. // Push the chain and the glue flag.
  7869. Ops.push_back(Chain);
  7870. Ops.push_back(InFlag);
  7871. // Create the STACKMAP node.
  7872. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7873. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7874. Chain = SDValue(SM, 0);
  7875. InFlag = Chain.getValue(1);
  7876. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7877. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7878. // Set the root to the target-lowered call chain.
  7879. DAG.setRoot(Chain);
  7880. // Inform the Frame Information that we have a stackmap in this function.
  7881. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7882. }
  7883. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7884. void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
  7885. const BasicBlock *EHPadBB) {
  7886. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7887. // i32 <numBytes>,
  7888. // i8* <target>,
  7889. // i32 <numArgs>,
  7890. // [Args...],
  7891. // [live variables...])
  7892. CallingConv::ID CC = CB.getCallingConv();
  7893. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7894. bool HasDef = !CB.getType()->isVoidTy();
  7895. SDLoc dl = getCurSDLoc();
  7896. SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
  7897. // Handle immediate and symbolic callees.
  7898. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7899. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7900. /*isTarget=*/true);
  7901. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7902. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7903. SDLoc(SymbolicCallee),
  7904. SymbolicCallee->getValueType(0));
  7905. // Get the real number of arguments participating in the call <numArgs>
  7906. SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
  7907. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7908. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7909. // Intrinsics include all meta-operands up to but not including CC.
  7910. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7911. assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
  7912. "Not enough arguments provided to the patchpoint intrinsic");
  7913. // For AnyRegCC the arguments are lowered later on manually.
  7914. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7915. Type *ReturnTy =
  7916. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
  7917. TargetLowering::CallLoweringInfo CLI(DAG);
  7918. populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
  7919. ReturnTy, true);
  7920. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7921. SDNode *CallEnd = Result.second.getNode();
  7922. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7923. CallEnd = CallEnd->getOperand(0).getNode();
  7924. /// Get a call instruction from the call sequence chain.
  7925. /// Tail calls are not allowed.
  7926. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7927. "Expected a callseq node.");
  7928. SDNode *Call = CallEnd->getOperand(0).getNode();
  7929. bool HasGlue = Call->getGluedNode();
  7930. // Replace the target specific call node with the patchable intrinsic.
  7931. SmallVector<SDValue, 8> Ops;
  7932. // Add the <id> and <numBytes> constants.
  7933. SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
  7934. Ops.push_back(DAG.getTargetConstant(
  7935. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7936. SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
  7937. Ops.push_back(DAG.getTargetConstant(
  7938. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7939. MVT::i32));
  7940. // Add the callee.
  7941. Ops.push_back(Callee);
  7942. // Adjust <numArgs> to account for any arguments that have been passed on the
  7943. // stack instead.
  7944. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7945. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7946. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7947. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7948. // Add the calling convention
  7949. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7950. // Add the arguments we omitted previously. The register allocator should
  7951. // place these in any free register.
  7952. if (IsAnyRegCC)
  7953. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7954. Ops.push_back(getValue(CB.getArgOperand(i)));
  7955. // Push the arguments from the call instruction up to the register mask.
  7956. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7957. Ops.append(Call->op_begin() + 2, e);
  7958. // Push live variables for the stack map.
  7959. addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
  7960. // Push the register mask info.
  7961. if (HasGlue)
  7962. Ops.push_back(*(Call->op_end()-2));
  7963. else
  7964. Ops.push_back(*(Call->op_end()-1));
  7965. // Push the chain (this is originally the first operand of the call, but
  7966. // becomes now the last or second to last operand).
  7967. Ops.push_back(*(Call->op_begin()));
  7968. // Push the glue flag (last operand).
  7969. if (HasGlue)
  7970. Ops.push_back(*(Call->op_end()-1));
  7971. SDVTList NodeTys;
  7972. if (IsAnyRegCC && HasDef) {
  7973. // Create the return types based on the intrinsic definition
  7974. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7975. SmallVector<EVT, 3> ValueVTs;
  7976. ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
  7977. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7978. // There is always a chain and a glue type at the end
  7979. ValueVTs.push_back(MVT::Other);
  7980. ValueVTs.push_back(MVT::Glue);
  7981. NodeTys = DAG.getVTList(ValueVTs);
  7982. } else
  7983. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7984. // Replace the target specific call node with a PATCHPOINT node.
  7985. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7986. dl, NodeTys, Ops);
  7987. // Update the NodeMap.
  7988. if (HasDef) {
  7989. if (IsAnyRegCC)
  7990. setValue(&CB, SDValue(MN, 0));
  7991. else
  7992. setValue(&CB, Result.first);
  7993. }
  7994. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7995. // call sequence. Furthermore the location of the chain and glue can change
  7996. // when the AnyReg calling convention is used and the intrinsic returns a
  7997. // value.
  7998. if (IsAnyRegCC && HasDef) {
  7999. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  8000. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  8001. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  8002. } else
  8003. DAG.ReplaceAllUsesWith(Call, MN);
  8004. DAG.DeleteNode(Call);
  8005. // Inform the Frame Information that we have a patchpoint in this function.
  8006. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  8007. }
  8008. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  8009. unsigned Intrinsic) {
  8010. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8011. SDValue Op1 = getValue(I.getArgOperand(0));
  8012. SDValue Op2;
  8013. if (I.getNumArgOperands() > 1)
  8014. Op2 = getValue(I.getArgOperand(1));
  8015. SDLoc dl = getCurSDLoc();
  8016. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  8017. SDValue Res;
  8018. SDNodeFlags SDFlags;
  8019. if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
  8020. SDFlags.copyFMF(*FPMO);
  8021. switch (Intrinsic) {
  8022. case Intrinsic::vector_reduce_fadd:
  8023. if (SDFlags.hasAllowReassociation())
  8024. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  8025. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
  8026. SDFlags);
  8027. else
  8028. Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
  8029. break;
  8030. case Intrinsic::vector_reduce_fmul:
  8031. if (SDFlags.hasAllowReassociation())
  8032. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  8033. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
  8034. SDFlags);
  8035. else
  8036. Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
  8037. break;
  8038. case Intrinsic::vector_reduce_add:
  8039. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  8040. break;
  8041. case Intrinsic::vector_reduce_mul:
  8042. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  8043. break;
  8044. case Intrinsic::vector_reduce_and:
  8045. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  8046. break;
  8047. case Intrinsic::vector_reduce_or:
  8048. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  8049. break;
  8050. case Intrinsic::vector_reduce_xor:
  8051. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  8052. break;
  8053. case Intrinsic::vector_reduce_smax:
  8054. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  8055. break;
  8056. case Intrinsic::vector_reduce_smin:
  8057. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  8058. break;
  8059. case Intrinsic::vector_reduce_umax:
  8060. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  8061. break;
  8062. case Intrinsic::vector_reduce_umin:
  8063. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  8064. break;
  8065. case Intrinsic::vector_reduce_fmax:
  8066. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
  8067. break;
  8068. case Intrinsic::vector_reduce_fmin:
  8069. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
  8070. break;
  8071. default:
  8072. llvm_unreachable("Unhandled vector reduce intrinsic");
  8073. }
  8074. setValue(&I, Res);
  8075. }
  8076. /// Returns an AttributeList representing the attributes applied to the return
  8077. /// value of the given call.
  8078. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  8079. SmallVector<Attribute::AttrKind, 2> Attrs;
  8080. if (CLI.RetSExt)
  8081. Attrs.push_back(Attribute::SExt);
  8082. if (CLI.RetZExt)
  8083. Attrs.push_back(Attribute::ZExt);
  8084. if (CLI.IsInReg)
  8085. Attrs.push_back(Attribute::InReg);
  8086. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  8087. Attrs);
  8088. }
  8089. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  8090. /// implementation, which just calls LowerCall.
  8091. /// FIXME: When all targets are
  8092. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  8093. std::pair<SDValue, SDValue>
  8094. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  8095. // Handle the incoming return values from the call.
  8096. CLI.Ins.clear();
  8097. Type *OrigRetTy = CLI.RetTy;
  8098. SmallVector<EVT, 4> RetTys;
  8099. SmallVector<uint64_t, 4> Offsets;
  8100. auto &DL = CLI.DAG.getDataLayout();
  8101. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  8102. if (CLI.IsPostTypeLegalization) {
  8103. // If we are lowering a libcall after legalization, split the return type.
  8104. SmallVector<EVT, 4> OldRetTys;
  8105. SmallVector<uint64_t, 4> OldOffsets;
  8106. RetTys.swap(OldRetTys);
  8107. Offsets.swap(OldOffsets);
  8108. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  8109. EVT RetVT = OldRetTys[i];
  8110. uint64_t Offset = OldOffsets[i];
  8111. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  8112. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  8113. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  8114. RetTys.append(NumRegs, RegisterVT);
  8115. for (unsigned j = 0; j != NumRegs; ++j)
  8116. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  8117. }
  8118. }
  8119. SmallVector<ISD::OutputArg, 4> Outs;
  8120. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  8121. bool CanLowerReturn =
  8122. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  8123. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  8124. SDValue DemoteStackSlot;
  8125. int DemoteStackIdx = -100;
  8126. if (!CanLowerReturn) {
  8127. // FIXME: equivalent assert?
  8128. // assert(!CS.hasInAllocaArgument() &&
  8129. // "sret demotion is incompatible with inalloca");
  8130. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  8131. Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
  8132. MachineFunction &MF = CLI.DAG.getMachineFunction();
  8133. DemoteStackIdx =
  8134. MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
  8135. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  8136. DL.getAllocaAddrSpace());
  8137. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  8138. ArgListEntry Entry;
  8139. Entry.Node = DemoteStackSlot;
  8140. Entry.Ty = StackSlotPtrType;
  8141. Entry.IsSExt = false;
  8142. Entry.IsZExt = false;
  8143. Entry.IsInReg = false;
  8144. Entry.IsSRet = true;
  8145. Entry.IsNest = false;
  8146. Entry.IsByVal = false;
  8147. Entry.IsByRef = false;
  8148. Entry.IsReturned = false;
  8149. Entry.IsSwiftSelf = false;
  8150. Entry.IsSwiftError = false;
  8151. Entry.IsCFGuardTarget = false;
  8152. Entry.Alignment = Alignment;
  8153. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  8154. CLI.NumFixedArgs += 1;
  8155. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  8156. // sret demotion isn't compatible with tail-calls, since the sret argument
  8157. // points into the callers stack frame.
  8158. CLI.IsTailCall = false;
  8159. } else {
  8160. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8161. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  8162. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8163. ISD::ArgFlagsTy Flags;
  8164. if (NeedsRegBlock) {
  8165. Flags.setInConsecutiveRegs();
  8166. if (I == RetTys.size() - 1)
  8167. Flags.setInConsecutiveRegsLast();
  8168. }
  8169. EVT VT = RetTys[I];
  8170. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8171. CLI.CallConv, VT);
  8172. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8173. CLI.CallConv, VT);
  8174. for (unsigned i = 0; i != NumRegs; ++i) {
  8175. ISD::InputArg MyFlags;
  8176. MyFlags.Flags = Flags;
  8177. MyFlags.VT = RegisterVT;
  8178. MyFlags.ArgVT = VT;
  8179. MyFlags.Used = CLI.IsReturnValueUsed;
  8180. if (CLI.RetTy->isPointerTy()) {
  8181. MyFlags.Flags.setPointer();
  8182. MyFlags.Flags.setPointerAddrSpace(
  8183. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  8184. }
  8185. if (CLI.RetSExt)
  8186. MyFlags.Flags.setSExt();
  8187. if (CLI.RetZExt)
  8188. MyFlags.Flags.setZExt();
  8189. if (CLI.IsInReg)
  8190. MyFlags.Flags.setInReg();
  8191. CLI.Ins.push_back(MyFlags);
  8192. }
  8193. }
  8194. }
  8195. // We push in swifterror return as the last element of CLI.Ins.
  8196. ArgListTy &Args = CLI.getArgs();
  8197. if (supportSwiftError()) {
  8198. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8199. if (Args[i].IsSwiftError) {
  8200. ISD::InputArg MyFlags;
  8201. MyFlags.VT = getPointerTy(DL);
  8202. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8203. MyFlags.Flags.setSwiftError();
  8204. CLI.Ins.push_back(MyFlags);
  8205. }
  8206. }
  8207. }
  8208. // Handle all of the outgoing arguments.
  8209. CLI.Outs.clear();
  8210. CLI.OutVals.clear();
  8211. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8212. SmallVector<EVT, 4> ValueVTs;
  8213. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8214. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8215. Type *FinalType = Args[i].Ty;
  8216. if (Args[i].IsByVal)
  8217. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  8218. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8219. FinalType, CLI.CallConv, CLI.IsVarArg);
  8220. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8221. ++Value) {
  8222. EVT VT = ValueVTs[Value];
  8223. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8224. SDValue Op = SDValue(Args[i].Node.getNode(),
  8225. Args[i].Node.getResNo() + Value);
  8226. ISD::ArgFlagsTy Flags;
  8227. // Certain targets (such as MIPS), may have a different ABI alignment
  8228. // for a type depending on the context. Give the target a chance to
  8229. // specify the alignment it wants.
  8230. const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
  8231. if (Args[i].Ty->isPointerTy()) {
  8232. Flags.setPointer();
  8233. Flags.setPointerAddrSpace(
  8234. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8235. }
  8236. if (Args[i].IsZExt)
  8237. Flags.setZExt();
  8238. if (Args[i].IsSExt)
  8239. Flags.setSExt();
  8240. if (Args[i].IsInReg) {
  8241. // If we are using vectorcall calling convention, a structure that is
  8242. // passed InReg - is surely an HVA
  8243. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8244. isa<StructType>(FinalType)) {
  8245. // The first value of a structure is marked
  8246. if (0 == Value)
  8247. Flags.setHvaStart();
  8248. Flags.setHva();
  8249. }
  8250. // Set InReg Flag
  8251. Flags.setInReg();
  8252. }
  8253. if (Args[i].IsSRet)
  8254. Flags.setSRet();
  8255. if (Args[i].IsSwiftSelf)
  8256. Flags.setSwiftSelf();
  8257. if (Args[i].IsSwiftError)
  8258. Flags.setSwiftError();
  8259. if (Args[i].IsCFGuardTarget)
  8260. Flags.setCFGuardTarget();
  8261. if (Args[i].IsByVal)
  8262. Flags.setByVal();
  8263. if (Args[i].IsByRef)
  8264. Flags.setByRef();
  8265. if (Args[i].IsPreallocated) {
  8266. Flags.setPreallocated();
  8267. // Set the byval flag for CCAssignFn callbacks that don't know about
  8268. // preallocated. This way we can know how many bytes we should've
  8269. // allocated and how many bytes a callee cleanup function will pop. If
  8270. // we port preallocated to more targets, we'll have to add custom
  8271. // preallocated handling in the various CC lowering callbacks.
  8272. Flags.setByVal();
  8273. }
  8274. if (Args[i].IsInAlloca) {
  8275. Flags.setInAlloca();
  8276. // Set the byval flag for CCAssignFn callbacks that don't know about
  8277. // inalloca. This way we can know how many bytes we should've allocated
  8278. // and how many bytes a callee cleanup function will pop. If we port
  8279. // inalloca to more targets, we'll have to add custom inalloca handling
  8280. // in the various CC lowering callbacks.
  8281. Flags.setByVal();
  8282. }
  8283. if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
  8284. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8285. Type *ElementTy = Ty->getElementType();
  8286. unsigned FrameSize = DL.getTypeAllocSize(
  8287. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8288. Flags.setByValSize(FrameSize);
  8289. // info is not there but there are cases it cannot get right.
  8290. Align FrameAlign;
  8291. if (auto MA = Args[i].Alignment)
  8292. FrameAlign = *MA;
  8293. else
  8294. FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
  8295. Flags.setByValAlign(FrameAlign);
  8296. }
  8297. if (Args[i].IsNest)
  8298. Flags.setNest();
  8299. if (NeedsRegBlock)
  8300. Flags.setInConsecutiveRegs();
  8301. Flags.setOrigAlign(OriginalAlignment);
  8302. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8303. CLI.CallConv, VT);
  8304. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8305. CLI.CallConv, VT);
  8306. SmallVector<SDValue, 4> Parts(NumParts);
  8307. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8308. if (Args[i].IsSExt)
  8309. ExtendKind = ISD::SIGN_EXTEND;
  8310. else if (Args[i].IsZExt)
  8311. ExtendKind = ISD::ZERO_EXTEND;
  8312. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8313. // for now.
  8314. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8315. CanLowerReturn) {
  8316. assert((CLI.RetTy == Args[i].Ty ||
  8317. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8318. CLI.RetTy->getPointerAddressSpace() ==
  8319. Args[i].Ty->getPointerAddressSpace())) &&
  8320. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8321. // Before passing 'returned' to the target lowering code, ensure that
  8322. // either the register MVT and the actual EVT are the same size or that
  8323. // the return value and argument are extended in the same way; in these
  8324. // cases it's safe to pass the argument register value unchanged as the
  8325. // return register value (although it's at the target's option whether
  8326. // to do so)
  8327. // TODO: allow code generation to take advantage of partially preserved
  8328. // registers rather than clobbering the entire register when the
  8329. // parameter extension method is not compatible with the return
  8330. // extension method
  8331. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8332. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8333. CLI.RetZExt == Args[i].IsZExt))
  8334. Flags.setReturned();
  8335. }
  8336. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
  8337. CLI.CallConv, ExtendKind);
  8338. for (unsigned j = 0; j != NumParts; ++j) {
  8339. // if it isn't first piece, alignment must be 1
  8340. // For scalable vectors the scalable part is currently handled
  8341. // by individual targets, so we just use the known minimum size here.
  8342. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8343. i < CLI.NumFixedArgs, i,
  8344. j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
  8345. if (NumParts > 1 && j == 0)
  8346. MyFlags.Flags.setSplit();
  8347. else if (j != 0) {
  8348. MyFlags.Flags.setOrigAlign(Align(1));
  8349. if (j == NumParts - 1)
  8350. MyFlags.Flags.setSplitEnd();
  8351. }
  8352. CLI.Outs.push_back(MyFlags);
  8353. CLI.OutVals.push_back(Parts[j]);
  8354. }
  8355. if (NeedsRegBlock && Value == NumValues - 1)
  8356. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8357. }
  8358. }
  8359. SmallVector<SDValue, 4> InVals;
  8360. CLI.Chain = LowerCall(CLI, InVals);
  8361. // Update CLI.InVals to use outside of this function.
  8362. CLI.InVals = InVals;
  8363. // Verify that the target's LowerCall behaved as expected.
  8364. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8365. "LowerCall didn't return a valid chain!");
  8366. assert((!CLI.IsTailCall || InVals.empty()) &&
  8367. "LowerCall emitted a return value for a tail call!");
  8368. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8369. "LowerCall didn't emit the correct number of values!");
  8370. // For a tail call, the return value is merely live-out and there aren't
  8371. // any nodes in the DAG representing it. Return a special value to
  8372. // indicate that a tail call has been emitted and no more Instructions
  8373. // should be processed in the current block.
  8374. if (CLI.IsTailCall) {
  8375. CLI.DAG.setRoot(CLI.Chain);
  8376. return std::make_pair(SDValue(), SDValue());
  8377. }
  8378. #ifndef NDEBUG
  8379. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8380. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8381. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8382. "LowerCall emitted a value with the wrong type!");
  8383. }
  8384. #endif
  8385. SmallVector<SDValue, 4> ReturnValues;
  8386. if (!CanLowerReturn) {
  8387. // The instruction result is the result of loading from the
  8388. // hidden sret parameter.
  8389. SmallVector<EVT, 1> PVTs;
  8390. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8391. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8392. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8393. EVT PtrVT = PVTs[0];
  8394. unsigned NumValues = RetTys.size();
  8395. ReturnValues.resize(NumValues);
  8396. SmallVector<SDValue, 4> Chains(NumValues);
  8397. // An aggregate return value cannot wrap around the address space, so
  8398. // offsets to its parts don't wrap either.
  8399. SDNodeFlags Flags;
  8400. Flags.setNoUnsignedWrap(true);
  8401. MachineFunction &MF = CLI.DAG.getMachineFunction();
  8402. Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
  8403. for (unsigned i = 0; i < NumValues; ++i) {
  8404. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8405. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8406. PtrVT), Flags);
  8407. SDValue L = CLI.DAG.getLoad(
  8408. RetTys[i], CLI.DL, CLI.Chain, Add,
  8409. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8410. DemoteStackIdx, Offsets[i]),
  8411. HiddenSRetAlign);
  8412. ReturnValues[i] = L;
  8413. Chains[i] = L.getValue(1);
  8414. }
  8415. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8416. } else {
  8417. // Collect the legal value parts into potentially illegal values
  8418. // that correspond to the original function's return values.
  8419. Optional<ISD::NodeType> AssertOp;
  8420. if (CLI.RetSExt)
  8421. AssertOp = ISD::AssertSext;
  8422. else if (CLI.RetZExt)
  8423. AssertOp = ISD::AssertZext;
  8424. unsigned CurReg = 0;
  8425. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8426. EVT VT = RetTys[I];
  8427. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8428. CLI.CallConv, VT);
  8429. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8430. CLI.CallConv, VT);
  8431. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8432. NumRegs, RegisterVT, VT, nullptr,
  8433. CLI.CallConv, AssertOp));
  8434. CurReg += NumRegs;
  8435. }
  8436. // For a function returning void, there is no return value. We can't create
  8437. // such a node, so we just return a null return value in that case. In
  8438. // that case, nothing will actually look at the value.
  8439. if (ReturnValues.empty())
  8440. return std::make_pair(SDValue(), CLI.Chain);
  8441. }
  8442. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8443. CLI.DAG.getVTList(RetTys), ReturnValues);
  8444. return std::make_pair(Res, CLI.Chain);
  8445. }
  8446. /// Places new result values for the node in Results (their number
  8447. /// and types must exactly match those of the original return values of
  8448. /// the node), or leaves Results empty, which indicates that the node is not
  8449. /// to be custom lowered after all.
  8450. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8451. SmallVectorImpl<SDValue> &Results,
  8452. SelectionDAG &DAG) const {
  8453. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  8454. if (!Res.getNode())
  8455. return;
  8456. // If the original node has one result, take the return value from
  8457. // LowerOperation as is. It might not be result number 0.
  8458. if (N->getNumValues() == 1) {
  8459. Results.push_back(Res);
  8460. return;
  8461. }
  8462. // If the original node has multiple results, then the return node should
  8463. // have the same number of results.
  8464. assert((N->getNumValues() == Res->getNumValues()) &&
  8465. "Lowering returned the wrong number of results!");
  8466. // Places new result values base on N result number.
  8467. for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
  8468. Results.push_back(Res.getValue(I));
  8469. }
  8470. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8471. llvm_unreachable("LowerOperation not implemented for this target!");
  8472. }
  8473. void
  8474. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8475. SDValue Op = getNonRegisterValue(V);
  8476. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8477. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8478. "Copy from a reg to the same reg!");
  8479. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  8480. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8481. // If this is an InlineAsm we have to match the registers required, not the
  8482. // notional registers required by the type.
  8483. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8484. None); // This is not an ABI copy.
  8485. SDValue Chain = DAG.getEntryNode();
  8486. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8487. FuncInfo.PreferredExtendType.end())
  8488. ? ISD::ANY_EXTEND
  8489. : FuncInfo.PreferredExtendType[V];
  8490. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8491. PendingExports.push_back(Chain);
  8492. }
  8493. #include "llvm/CodeGen/SelectionDAGISel.h"
  8494. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8495. /// entry block, return true. This includes arguments used by switches, since
  8496. /// the switch may expand into multiple basic blocks.
  8497. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8498. // With FastISel active, we may be splitting blocks, so force creation
  8499. // of virtual registers for all non-dead arguments.
  8500. if (FastISel)
  8501. return A->use_empty();
  8502. const BasicBlock &Entry = A->getParent()->front();
  8503. for (const User *U : A->users())
  8504. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8505. return false; // Use not in entry block.
  8506. return true;
  8507. }
  8508. using ArgCopyElisionMapTy =
  8509. DenseMap<const Argument *,
  8510. std::pair<const AllocaInst *, const StoreInst *>>;
  8511. /// Scan the entry block of the function in FuncInfo for arguments that look
  8512. /// like copies into a local alloca. Record any copied arguments in
  8513. /// ArgCopyElisionCandidates.
  8514. static void
  8515. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8516. FunctionLoweringInfo *FuncInfo,
  8517. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8518. // Record the state of every static alloca used in the entry block. Argument
  8519. // allocas are all used in the entry block, so we need approximately as many
  8520. // entries as we have arguments.
  8521. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8522. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8523. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8524. StaticAllocas.reserve(NumArgs * 2);
  8525. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8526. if (!V)
  8527. return nullptr;
  8528. V = V->stripPointerCasts();
  8529. const auto *AI = dyn_cast<AllocaInst>(V);
  8530. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8531. return nullptr;
  8532. auto Iter = StaticAllocas.insert({AI, Unknown});
  8533. return &Iter.first->second;
  8534. };
  8535. // Look for stores of arguments to static allocas. Look through bitcasts and
  8536. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8537. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8538. // unanalyzed store might write it.
  8539. // FIXME: Handle structs initialized with multiple stores.
  8540. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8541. // Look for stores, and handle non-store uses conservatively.
  8542. const auto *SI = dyn_cast<StoreInst>(&I);
  8543. if (!SI) {
  8544. // We will look through cast uses, so ignore them completely.
  8545. if (I.isCast())
  8546. continue;
  8547. // Ignore debug info and pseudo op intrinsics, they don't escape or store
  8548. // to allocas.
  8549. if (I.isDebugOrPseudoInst())
  8550. continue;
  8551. // This is an unknown instruction. Assume it escapes or writes to all
  8552. // static alloca operands.
  8553. for (const Use &U : I.operands()) {
  8554. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8555. *Info = StaticAllocaInfo::Clobbered;
  8556. }
  8557. continue;
  8558. }
  8559. // If the stored value is a static alloca, mark it as escaped.
  8560. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8561. *Info = StaticAllocaInfo::Clobbered;
  8562. // Check if the destination is a static alloca.
  8563. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8564. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8565. if (!Info)
  8566. continue;
  8567. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8568. // Skip allocas that have been initialized or clobbered.
  8569. if (*Info != StaticAllocaInfo::Unknown)
  8570. continue;
  8571. // Check if the stored value is an argument, and that this store fully
  8572. // initializes the alloca. Don't elide copies from the same argument twice.
  8573. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8574. const auto *Arg = dyn_cast<Argument>(Val);
  8575. if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
  8576. Arg->getType()->isEmptyTy() ||
  8577. DL.getTypeStoreSize(Arg->getType()) !=
  8578. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8579. ArgCopyElisionCandidates.count(Arg)) {
  8580. *Info = StaticAllocaInfo::Clobbered;
  8581. continue;
  8582. }
  8583. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8584. << '\n');
  8585. // Mark this alloca and store for argument copy elision.
  8586. *Info = StaticAllocaInfo::Elidable;
  8587. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8588. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8589. // builds, which is useful, because -O0 builds have large entry blocks and
  8590. // many allocas.
  8591. if (ArgCopyElisionCandidates.size() == NumArgs)
  8592. break;
  8593. }
  8594. }
  8595. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8596. /// ArgVal is a load from a suitable fixed stack object.
  8597. static void tryToElideArgumentCopy(
  8598. FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8599. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8600. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8601. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8602. SDValue ArgVal, bool &ArgHasUses) {
  8603. // Check if this is a load from a fixed stack object.
  8604. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8605. if (!LNode)
  8606. return;
  8607. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8608. if (!FINode)
  8609. return;
  8610. // Check that the fixed stack object is the right size and alignment.
  8611. // Look at the alignment that the user wrote on the alloca instead of looking
  8612. // at the stack object.
  8613. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8614. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8615. const AllocaInst *AI = ArgCopyIter->second.first;
  8616. int FixedIndex = FINode->getIndex();
  8617. int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
  8618. int OldIndex = AllocaIndex;
  8619. MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
  8620. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8621. LLVM_DEBUG(
  8622. dbgs() << " argument copy elision failed due to bad fixed stack "
  8623. "object size\n");
  8624. return;
  8625. }
  8626. Align RequiredAlignment = AI->getAlign();
  8627. if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
  8628. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8629. "greater than stack argument alignment ("
  8630. << DebugStr(RequiredAlignment) << " vs "
  8631. << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
  8632. return;
  8633. }
  8634. // Perform the elision. Delete the old stack object and replace its only use
  8635. // in the variable info map. Mark the stack object as mutable.
  8636. LLVM_DEBUG({
  8637. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8638. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8639. << '\n';
  8640. });
  8641. MFI.RemoveStackObject(OldIndex);
  8642. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8643. AllocaIndex = FixedIndex;
  8644. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8645. Chains.push_back(ArgVal.getValue(1));
  8646. // Avoid emitting code for the store implementing the copy.
  8647. const StoreInst *SI = ArgCopyIter->second.second;
  8648. ElidedArgCopyInstrs.insert(SI);
  8649. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8650. // if it is't used by anything other than the store.
  8651. for (const Value *U : Arg.users()) {
  8652. if (U != SI) {
  8653. ArgHasUses = true;
  8654. break;
  8655. }
  8656. }
  8657. }
  8658. void SelectionDAGISel::LowerArguments(const Function &F) {
  8659. SelectionDAG &DAG = SDB->DAG;
  8660. SDLoc dl = SDB->getCurSDLoc();
  8661. const DataLayout &DL = DAG.getDataLayout();
  8662. SmallVector<ISD::InputArg, 16> Ins;
  8663. // In Naked functions we aren't going to save any registers.
  8664. if (F.hasFnAttribute(Attribute::Naked))
  8665. return;
  8666. if (!FuncInfo->CanLowerReturn) {
  8667. // Put in an sret pointer parameter before all the other parameters.
  8668. SmallVector<EVT, 1> ValueVTs;
  8669. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8670. F.getReturnType()->getPointerTo(
  8671. DAG.getDataLayout().getAllocaAddrSpace()),
  8672. ValueVTs);
  8673. // NOTE: Assuming that a pointer will never break down to more than one VT
  8674. // or one register.
  8675. ISD::ArgFlagsTy Flags;
  8676. Flags.setSRet();
  8677. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8678. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8679. ISD::InputArg::NoArgIndex, 0);
  8680. Ins.push_back(RetArg);
  8681. }
  8682. // Look for stores of arguments to static allocas. Mark such arguments with a
  8683. // flag to ask the target to give us the memory location of that argument if
  8684. // available.
  8685. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8686. findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
  8687. ArgCopyElisionCandidates);
  8688. // Set up the incoming argument description vector.
  8689. for (const Argument &Arg : F.args()) {
  8690. unsigned ArgNo = Arg.getArgNo();
  8691. SmallVector<EVT, 4> ValueVTs;
  8692. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8693. bool isArgValueUsed = !Arg.use_empty();
  8694. unsigned PartBase = 0;
  8695. Type *FinalType = Arg.getType();
  8696. if (Arg.hasAttribute(Attribute::ByVal))
  8697. FinalType = Arg.getParamByValType();
  8698. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8699. FinalType, F.getCallingConv(), F.isVarArg());
  8700. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8701. Value != NumValues; ++Value) {
  8702. EVT VT = ValueVTs[Value];
  8703. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8704. ISD::ArgFlagsTy Flags;
  8705. // Certain targets (such as MIPS), may have a different ABI alignment
  8706. // for a type depending on the context. Give the target a chance to
  8707. // specify the alignment it wants.
  8708. const Align OriginalAlignment(
  8709. TLI->getABIAlignmentForCallingConv(ArgTy, DL));
  8710. if (Arg.getType()->isPointerTy()) {
  8711. Flags.setPointer();
  8712. Flags.setPointerAddrSpace(
  8713. cast<PointerType>(Arg.getType())->getAddressSpace());
  8714. }
  8715. if (Arg.hasAttribute(Attribute::ZExt))
  8716. Flags.setZExt();
  8717. if (Arg.hasAttribute(Attribute::SExt))
  8718. Flags.setSExt();
  8719. if (Arg.hasAttribute(Attribute::InReg)) {
  8720. // If we are using vectorcall calling convention, a structure that is
  8721. // passed InReg - is surely an HVA
  8722. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8723. isa<StructType>(Arg.getType())) {
  8724. // The first value of a structure is marked
  8725. if (0 == Value)
  8726. Flags.setHvaStart();
  8727. Flags.setHva();
  8728. }
  8729. // Set InReg Flag
  8730. Flags.setInReg();
  8731. }
  8732. if (Arg.hasAttribute(Attribute::StructRet))
  8733. Flags.setSRet();
  8734. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8735. Flags.setSwiftSelf();
  8736. if (Arg.hasAttribute(Attribute::SwiftError))
  8737. Flags.setSwiftError();
  8738. if (Arg.hasAttribute(Attribute::ByVal))
  8739. Flags.setByVal();
  8740. if (Arg.hasAttribute(Attribute::ByRef))
  8741. Flags.setByRef();
  8742. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8743. Flags.setInAlloca();
  8744. // Set the byval flag for CCAssignFn callbacks that don't know about
  8745. // inalloca. This way we can know how many bytes we should've allocated
  8746. // and how many bytes a callee cleanup function will pop. If we port
  8747. // inalloca to more targets, we'll have to add custom inalloca handling
  8748. // in the various CC lowering callbacks.
  8749. Flags.setByVal();
  8750. }
  8751. if (Arg.hasAttribute(Attribute::Preallocated)) {
  8752. Flags.setPreallocated();
  8753. // Set the byval flag for CCAssignFn callbacks that don't know about
  8754. // preallocated. This way we can know how many bytes we should've
  8755. // allocated and how many bytes a callee cleanup function will pop. If
  8756. // we port preallocated to more targets, we'll have to add custom
  8757. // preallocated handling in the various CC lowering callbacks.
  8758. Flags.setByVal();
  8759. }
  8760. Type *ArgMemTy = nullptr;
  8761. if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
  8762. Flags.isByRef()) {
  8763. if (!ArgMemTy)
  8764. ArgMemTy = Arg.getPointeeInMemoryValueType();
  8765. uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
  8766. // For in-memory arguments, size and alignment should be passed from FE.
  8767. // BE will guess if this info is not there but there are cases it cannot
  8768. // get right.
  8769. MaybeAlign MemAlign = Arg.getParamAlign();
  8770. if (!MemAlign)
  8771. MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
  8772. if (Flags.isByRef()) {
  8773. Flags.setByRefSize(MemSize);
  8774. Flags.setByRefAlign(*MemAlign);
  8775. } else {
  8776. Flags.setByValSize(MemSize);
  8777. Flags.setByValAlign(*MemAlign);
  8778. }
  8779. }
  8780. if (Arg.hasAttribute(Attribute::Nest))
  8781. Flags.setNest();
  8782. if (NeedsRegBlock)
  8783. Flags.setInConsecutiveRegs();
  8784. Flags.setOrigAlign(OriginalAlignment);
  8785. if (ArgCopyElisionCandidates.count(&Arg))
  8786. Flags.setCopyElisionCandidate();
  8787. if (Arg.hasAttribute(Attribute::Returned))
  8788. Flags.setReturned();
  8789. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8790. *CurDAG->getContext(), F.getCallingConv(), VT);
  8791. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8792. *CurDAG->getContext(), F.getCallingConv(), VT);
  8793. for (unsigned i = 0; i != NumRegs; ++i) {
  8794. // For scalable vectors, use the minimum size; individual targets
  8795. // are responsible for handling scalable vector arguments and
  8796. // return values.
  8797. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8798. ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
  8799. if (NumRegs > 1 && i == 0)
  8800. MyFlags.Flags.setSplit();
  8801. // if it isn't first piece, alignment must be 1
  8802. else if (i > 0) {
  8803. MyFlags.Flags.setOrigAlign(Align(1));
  8804. if (i == NumRegs - 1)
  8805. MyFlags.Flags.setSplitEnd();
  8806. }
  8807. Ins.push_back(MyFlags);
  8808. }
  8809. if (NeedsRegBlock && Value == NumValues - 1)
  8810. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8811. PartBase += VT.getStoreSize().getKnownMinSize();
  8812. }
  8813. }
  8814. // Call the target to set up the argument values.
  8815. SmallVector<SDValue, 8> InVals;
  8816. SDValue NewRoot = TLI->LowerFormalArguments(
  8817. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8818. // Verify that the target's LowerFormalArguments behaved as expected.
  8819. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8820. "LowerFormalArguments didn't return a valid chain!");
  8821. assert(InVals.size() == Ins.size() &&
  8822. "LowerFormalArguments didn't emit the correct number of values!");
  8823. LLVM_DEBUG({
  8824. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8825. assert(InVals[i].getNode() &&
  8826. "LowerFormalArguments emitted a null value!");
  8827. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8828. "LowerFormalArguments emitted a value with the wrong type!");
  8829. }
  8830. });
  8831. // Update the DAG with the new chain value resulting from argument lowering.
  8832. DAG.setRoot(NewRoot);
  8833. // Set up the argument values.
  8834. unsigned i = 0;
  8835. if (!FuncInfo->CanLowerReturn) {
  8836. // Create a virtual register for the sret pointer, and put in a copy
  8837. // from the sret argument into it.
  8838. SmallVector<EVT, 1> ValueVTs;
  8839. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8840. F.getReturnType()->getPointerTo(
  8841. DAG.getDataLayout().getAllocaAddrSpace()),
  8842. ValueVTs);
  8843. MVT VT = ValueVTs[0].getSimpleVT();
  8844. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8845. Optional<ISD::NodeType> AssertOp = None;
  8846. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8847. nullptr, F.getCallingConv(), AssertOp);
  8848. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8849. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8850. Register SRetReg =
  8851. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8852. FuncInfo->DemoteRegister = SRetReg;
  8853. NewRoot =
  8854. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8855. DAG.setRoot(NewRoot);
  8856. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8857. ++i;
  8858. }
  8859. SmallVector<SDValue, 4> Chains;
  8860. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8861. for (const Argument &Arg : F.args()) {
  8862. SmallVector<SDValue, 4> ArgValues;
  8863. SmallVector<EVT, 4> ValueVTs;
  8864. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8865. unsigned NumValues = ValueVTs.size();
  8866. if (NumValues == 0)
  8867. continue;
  8868. bool ArgHasUses = !Arg.use_empty();
  8869. // Elide the copying store if the target loaded this argument from a
  8870. // suitable fixed stack object.
  8871. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8872. tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8873. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8874. InVals[i], ArgHasUses);
  8875. }
  8876. // If this argument is unused then remember its value. It is used to generate
  8877. // debugging information.
  8878. bool isSwiftErrorArg =
  8879. TLI->supportSwiftError() &&
  8880. Arg.hasAttribute(Attribute::SwiftError);
  8881. if (!ArgHasUses && !isSwiftErrorArg) {
  8882. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8883. // Also remember any frame index for use in FastISel.
  8884. if (FrameIndexSDNode *FI =
  8885. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8886. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8887. }
  8888. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8889. EVT VT = ValueVTs[Val];
  8890. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8891. F.getCallingConv(), VT);
  8892. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8893. *CurDAG->getContext(), F.getCallingConv(), VT);
  8894. // Even an apparent 'unused' swifterror argument needs to be returned. So
  8895. // we do generate a copy for it that can be used on return from the
  8896. // function.
  8897. if (ArgHasUses || isSwiftErrorArg) {
  8898. Optional<ISD::NodeType> AssertOp;
  8899. if (Arg.hasAttribute(Attribute::SExt))
  8900. AssertOp = ISD::AssertSext;
  8901. else if (Arg.hasAttribute(Attribute::ZExt))
  8902. AssertOp = ISD::AssertZext;
  8903. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8904. PartVT, VT, nullptr,
  8905. F.getCallingConv(), AssertOp));
  8906. }
  8907. i += NumParts;
  8908. }
  8909. // We don't need to do anything else for unused arguments.
  8910. if (ArgValues.empty())
  8911. continue;
  8912. // Note down frame index.
  8913. if (FrameIndexSDNode *FI =
  8914. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8915. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8916. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8917. SDB->getCurSDLoc());
  8918. SDB->setValue(&Arg, Res);
  8919. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8920. // We want to associate the argument with the frame index, among
  8921. // involved operands, that correspond to the lowest address. The
  8922. // getCopyFromParts function, called earlier, is swapping the order of
  8923. // the operands to BUILD_PAIR depending on endianness. The result of
  8924. // that swapping is that the least significant bits of the argument will
  8925. // be in the first operand of the BUILD_PAIR node, and the most
  8926. // significant bits will be in the second operand.
  8927. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8928. if (LoadSDNode *LNode =
  8929. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8930. if (FrameIndexSDNode *FI =
  8931. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8932. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8933. }
  8934. // Analyses past this point are naive and don't expect an assertion.
  8935. if (Res.getOpcode() == ISD::AssertZext)
  8936. Res = Res.getOperand(0);
  8937. // Update the SwiftErrorVRegDefMap.
  8938. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8939. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8940. if (Register::isVirtualRegister(Reg))
  8941. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8942. Reg);
  8943. }
  8944. // If this argument is live outside of the entry block, insert a copy from
  8945. // wherever we got it to the vreg that other BB's will reference it as.
  8946. if (Res.getOpcode() == ISD::CopyFromReg) {
  8947. // If we can, though, try to skip creating an unnecessary vreg.
  8948. // FIXME: This isn't very clean... it would be nice to make this more
  8949. // general.
  8950. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8951. if (Register::isVirtualRegister(Reg)) {
  8952. FuncInfo->ValueMap[&Arg] = Reg;
  8953. continue;
  8954. }
  8955. }
  8956. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8957. FuncInfo->InitializeRegForValue(&Arg);
  8958. SDB->CopyToExportRegsIfNeeded(&Arg);
  8959. }
  8960. }
  8961. if (!Chains.empty()) {
  8962. Chains.push_back(NewRoot);
  8963. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8964. }
  8965. DAG.setRoot(NewRoot);
  8966. assert(i == InVals.size() && "Argument register count mismatch!");
  8967. // If any argument copy elisions occurred and we have debug info, update the
  8968. // stale frame indices used in the dbg.declare variable info table.
  8969. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8970. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8971. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8972. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8973. if (I != ArgCopyElisionFrameIndexMap.end())
  8974. VI.Slot = I->second;
  8975. }
  8976. }
  8977. // Finally, if the target has anything special to do, allow it to do so.
  8978. emitFunctionEntryCode();
  8979. }
  8980. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8981. /// ensure constants are generated when needed. Remember the virtual registers
  8982. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8983. /// directly add them, because expansion might result in multiple MBB's for one
  8984. /// BB. As such, the start of the BB might correspond to a different MBB than
  8985. /// the end.
  8986. void
  8987. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8988. const Instruction *TI = LLVMBB->getTerminator();
  8989. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8990. // Check PHI nodes in successors that expect a value to be available from this
  8991. // block.
  8992. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8993. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8994. if (!isa<PHINode>(SuccBB->begin())) continue;
  8995. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8996. // If this terminator has multiple identical successors (common for
  8997. // switches), only handle each succ once.
  8998. if (!SuccsHandled.insert(SuccMBB).second)
  8999. continue;
  9000. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  9001. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  9002. // nodes and Machine PHI nodes, but the incoming operands have not been
  9003. // emitted yet.
  9004. for (const PHINode &PN : SuccBB->phis()) {
  9005. // Ignore dead phi's.
  9006. if (PN.use_empty())
  9007. continue;
  9008. // Skip empty types
  9009. if (PN.getType()->isEmptyTy())
  9010. continue;
  9011. unsigned Reg;
  9012. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  9013. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  9014. unsigned &RegOut = ConstantsOut[C];
  9015. if (RegOut == 0) {
  9016. RegOut = FuncInfo.CreateRegs(C);
  9017. CopyValueToVirtualRegister(C, RegOut);
  9018. }
  9019. Reg = RegOut;
  9020. } else {
  9021. DenseMap<const Value *, Register>::iterator I =
  9022. FuncInfo.ValueMap.find(PHIOp);
  9023. if (I != FuncInfo.ValueMap.end())
  9024. Reg = I->second;
  9025. else {
  9026. assert(isa<AllocaInst>(PHIOp) &&
  9027. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  9028. "Didn't codegen value into a register!??");
  9029. Reg = FuncInfo.CreateRegs(PHIOp);
  9030. CopyValueToVirtualRegister(PHIOp, Reg);
  9031. }
  9032. }
  9033. // Remember that this register needs to added to the machine PHI node as
  9034. // the input for this MBB.
  9035. SmallVector<EVT, 4> ValueVTs;
  9036. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9037. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  9038. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  9039. EVT VT = ValueVTs[vti];
  9040. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  9041. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  9042. FuncInfo.PHINodesToUpdate.push_back(
  9043. std::make_pair(&*MBBI++, Reg + i));
  9044. Reg += NumRegisters;
  9045. }
  9046. }
  9047. }
  9048. ConstantsOut.clear();
  9049. }
  9050. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  9051. /// is 0.
  9052. MachineBasicBlock *
  9053. SelectionDAGBuilder::StackProtectorDescriptor::
  9054. AddSuccessorMBB(const BasicBlock *BB,
  9055. MachineBasicBlock *ParentMBB,
  9056. bool IsLikely,
  9057. MachineBasicBlock *SuccMBB) {
  9058. // If SuccBB has not been created yet, create it.
  9059. if (!SuccMBB) {
  9060. MachineFunction *MF = ParentMBB->getParent();
  9061. MachineFunction::iterator BBI(ParentMBB);
  9062. SuccMBB = MF->CreateMachineBasicBlock(BB);
  9063. MF->insert(++BBI, SuccMBB);
  9064. }
  9065. // Add it as a successor of ParentMBB.
  9066. ParentMBB->addSuccessor(
  9067. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  9068. return SuccMBB;
  9069. }
  9070. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  9071. MachineFunction::iterator I(MBB);
  9072. if (++I == FuncInfo.MF->end())
  9073. return nullptr;
  9074. return &*I;
  9075. }
  9076. /// During lowering new call nodes can be created (such as memset, etc.).
  9077. /// Those will become new roots of the current DAG, but complications arise
  9078. /// when they are tail calls. In such cases, the call lowering will update
  9079. /// the root, but the builder still needs to know that a tail call has been
  9080. /// lowered in order to avoid generating an additional return.
  9081. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  9082. // If the node is null, we do have a tail call.
  9083. if (MaybeTC.getNode() != nullptr)
  9084. DAG.setRoot(MaybeTC);
  9085. else
  9086. HasTailCall = true;
  9087. }
  9088. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  9089. MachineBasicBlock *SwitchMBB,
  9090. MachineBasicBlock *DefaultMBB) {
  9091. MachineFunction *CurMF = FuncInfo.MF;
  9092. MachineBasicBlock *NextMBB = nullptr;
  9093. MachineFunction::iterator BBI(W.MBB);
  9094. if (++BBI != FuncInfo.MF->end())
  9095. NextMBB = &*BBI;
  9096. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  9097. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9098. if (Size == 2 && W.MBB == SwitchMBB) {
  9099. // If any two of the cases has the same destination, and if one value
  9100. // is the same as the other, but has one bit unset that the other has set,
  9101. // use bit manipulation to do two compares at once. For example:
  9102. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  9103. // TODO: This could be extended to merge any 2 cases in switches with 3
  9104. // cases.
  9105. // TODO: Handle cases where W.CaseBB != SwitchBB.
  9106. CaseCluster &Small = *W.FirstCluster;
  9107. CaseCluster &Big = *W.LastCluster;
  9108. if (Small.Low == Small.High && Big.Low == Big.High &&
  9109. Small.MBB == Big.MBB) {
  9110. const APInt &SmallValue = Small.Low->getValue();
  9111. const APInt &BigValue = Big.Low->getValue();
  9112. // Check that there is only one bit different.
  9113. APInt CommonBit = BigValue ^ SmallValue;
  9114. if (CommonBit.isPowerOf2()) {
  9115. SDValue CondLHS = getValue(Cond);
  9116. EVT VT = CondLHS.getValueType();
  9117. SDLoc DL = getCurSDLoc();
  9118. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  9119. DAG.getConstant(CommonBit, DL, VT));
  9120. SDValue Cond = DAG.getSetCC(
  9121. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  9122. ISD::SETEQ);
  9123. // Update successor info.
  9124. // Both Small and Big will jump to Small.BB, so we sum up the
  9125. // probabilities.
  9126. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  9127. if (BPI)
  9128. addSuccessorWithProb(
  9129. SwitchMBB, DefaultMBB,
  9130. // The default destination is the first successor in IR.
  9131. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  9132. else
  9133. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  9134. // Insert the true branch.
  9135. SDValue BrCond =
  9136. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  9137. DAG.getBasicBlock(Small.MBB));
  9138. // Insert the false branch.
  9139. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  9140. DAG.getBasicBlock(DefaultMBB));
  9141. DAG.setRoot(BrCond);
  9142. return;
  9143. }
  9144. }
  9145. }
  9146. if (TM.getOptLevel() != CodeGenOpt::None) {
  9147. // Here, we order cases by probability so the most likely case will be
  9148. // checked first. However, two clusters can have the same probability in
  9149. // which case their relative ordering is non-deterministic. So we use Low
  9150. // as a tie-breaker as clusters are guaranteed to never overlap.
  9151. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  9152. [](const CaseCluster &a, const CaseCluster &b) {
  9153. return a.Prob != b.Prob ?
  9154. a.Prob > b.Prob :
  9155. a.Low->getValue().slt(b.Low->getValue());
  9156. });
  9157. // Rearrange the case blocks so that the last one falls through if possible
  9158. // without changing the order of probabilities.
  9159. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  9160. --I;
  9161. if (I->Prob > W.LastCluster->Prob)
  9162. break;
  9163. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  9164. std::swap(*I, *W.LastCluster);
  9165. break;
  9166. }
  9167. }
  9168. }
  9169. // Compute total probability.
  9170. BranchProbability DefaultProb = W.DefaultProb;
  9171. BranchProbability UnhandledProbs = DefaultProb;
  9172. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  9173. UnhandledProbs += I->Prob;
  9174. MachineBasicBlock *CurMBB = W.MBB;
  9175. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  9176. bool FallthroughUnreachable = false;
  9177. MachineBasicBlock *Fallthrough;
  9178. if (I == W.LastCluster) {
  9179. // For the last cluster, fall through to the default destination.
  9180. Fallthrough = DefaultMBB;
  9181. FallthroughUnreachable = isa<UnreachableInst>(
  9182. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  9183. } else {
  9184. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  9185. CurMF->insert(BBI, Fallthrough);
  9186. // Put Cond in a virtual register to make it available from the new blocks.
  9187. ExportFromCurrentBlock(Cond);
  9188. }
  9189. UnhandledProbs -= I->Prob;
  9190. switch (I->Kind) {
  9191. case CC_JumpTable: {
  9192. // FIXME: Optimize away range check based on pivot comparisons.
  9193. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  9194. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  9195. // The jump block hasn't been inserted yet; insert it here.
  9196. MachineBasicBlock *JumpMBB = JT->MBB;
  9197. CurMF->insert(BBI, JumpMBB);
  9198. auto JumpProb = I->Prob;
  9199. auto FallthroughProb = UnhandledProbs;
  9200. // If the default statement is a target of the jump table, we evenly
  9201. // distribute the default probability to successors of CurMBB. Also
  9202. // update the probability on the edge from JumpMBB to Fallthrough.
  9203. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  9204. SE = JumpMBB->succ_end();
  9205. SI != SE; ++SI) {
  9206. if (*SI == DefaultMBB) {
  9207. JumpProb += DefaultProb / 2;
  9208. FallthroughProb -= DefaultProb / 2;
  9209. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  9210. JumpMBB->normalizeSuccProbs();
  9211. break;
  9212. }
  9213. }
  9214. if (FallthroughUnreachable) {
  9215. // Skip the range check if the fallthrough block is unreachable.
  9216. JTH->OmitRangeCheck = true;
  9217. }
  9218. if (!JTH->OmitRangeCheck)
  9219. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  9220. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  9221. CurMBB->normalizeSuccProbs();
  9222. // The jump table header will be inserted in our current block, do the
  9223. // range check, and fall through to our fallthrough block.
  9224. JTH->HeaderBB = CurMBB;
  9225. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  9226. // If we're in the right place, emit the jump table header right now.
  9227. if (CurMBB == SwitchMBB) {
  9228. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9229. JTH->Emitted = true;
  9230. }
  9231. break;
  9232. }
  9233. case CC_BitTests: {
  9234. // FIXME: Optimize away range check based on pivot comparisons.
  9235. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  9236. // The bit test blocks haven't been inserted yet; insert them here.
  9237. for (BitTestCase &BTC : BTB->Cases)
  9238. CurMF->insert(BBI, BTC.ThisBB);
  9239. // Fill in fields of the BitTestBlock.
  9240. BTB->Parent = CurMBB;
  9241. BTB->Default = Fallthrough;
  9242. BTB->DefaultProb = UnhandledProbs;
  9243. // If the cases in bit test don't form a contiguous range, we evenly
  9244. // distribute the probability on the edge to Fallthrough to two
  9245. // successors of CurMBB.
  9246. if (!BTB->ContiguousRange) {
  9247. BTB->Prob += DefaultProb / 2;
  9248. BTB->DefaultProb -= DefaultProb / 2;
  9249. }
  9250. if (FallthroughUnreachable) {
  9251. // Skip the range check if the fallthrough block is unreachable.
  9252. BTB->OmitRangeCheck = true;
  9253. }
  9254. // If we're in the right place, emit the bit test header right now.
  9255. if (CurMBB == SwitchMBB) {
  9256. visitBitTestHeader(*BTB, SwitchMBB);
  9257. BTB->Emitted = true;
  9258. }
  9259. break;
  9260. }
  9261. case CC_Range: {
  9262. const Value *RHS, *LHS, *MHS;
  9263. ISD::CondCode CC;
  9264. if (I->Low == I->High) {
  9265. // Check Cond == I->Low.
  9266. CC = ISD::SETEQ;
  9267. LHS = Cond;
  9268. RHS=I->Low;
  9269. MHS = nullptr;
  9270. } else {
  9271. // Check I->Low <= Cond <= I->High.
  9272. CC = ISD::SETLE;
  9273. LHS = I->Low;
  9274. MHS = Cond;
  9275. RHS = I->High;
  9276. }
  9277. // If Fallthrough is unreachable, fold away the comparison.
  9278. if (FallthroughUnreachable)
  9279. CC = ISD::SETTRUE;
  9280. // The false probability is the sum of all unhandled cases.
  9281. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9282. getCurSDLoc(), I->Prob, UnhandledProbs);
  9283. if (CurMBB == SwitchMBB)
  9284. visitSwitchCase(CB, SwitchMBB);
  9285. else
  9286. SL->SwitchCases.push_back(CB);
  9287. break;
  9288. }
  9289. }
  9290. CurMBB = Fallthrough;
  9291. }
  9292. }
  9293. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9294. CaseClusterIt First,
  9295. CaseClusterIt Last) {
  9296. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9297. if (X.Prob != CC.Prob)
  9298. return X.Prob > CC.Prob;
  9299. // Ties are broken by comparing the case value.
  9300. return X.Low->getValue().slt(CC.Low->getValue());
  9301. });
  9302. }
  9303. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9304. const SwitchWorkListItem &W,
  9305. Value *Cond,
  9306. MachineBasicBlock *SwitchMBB) {
  9307. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9308. "Clusters not sorted?");
  9309. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9310. // Balance the tree based on branch probabilities to create a near-optimal (in
  9311. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9312. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9313. CaseClusterIt LastLeft = W.FirstCluster;
  9314. CaseClusterIt FirstRight = W.LastCluster;
  9315. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9316. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9317. // Move LastLeft and FirstRight towards each other from opposite directions to
  9318. // find a partitioning of the clusters which balances the probability on both
  9319. // sides. If LeftProb and RightProb are equal, alternate which side is
  9320. // taken to ensure 0-probability nodes are distributed evenly.
  9321. unsigned I = 0;
  9322. while (LastLeft + 1 < FirstRight) {
  9323. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9324. LeftProb += (++LastLeft)->Prob;
  9325. else
  9326. RightProb += (--FirstRight)->Prob;
  9327. I++;
  9328. }
  9329. while (true) {
  9330. // Our binary search tree differs from a typical BST in that ours can have up
  9331. // to three values in each leaf. The pivot selection above doesn't take that
  9332. // into account, which means the tree might require more nodes and be less
  9333. // efficient. We compensate for this here.
  9334. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9335. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9336. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9337. // If one side has less than 3 clusters, and the other has more than 3,
  9338. // consider taking a cluster from the other side.
  9339. if (NumLeft < NumRight) {
  9340. // Consider moving the first cluster on the right to the left side.
  9341. CaseCluster &CC = *FirstRight;
  9342. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9343. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9344. if (LeftSideRank <= RightSideRank) {
  9345. // Moving the cluster to the left does not demote it.
  9346. ++LastLeft;
  9347. ++FirstRight;
  9348. continue;
  9349. }
  9350. } else {
  9351. assert(NumRight < NumLeft);
  9352. // Consider moving the last element on the left to the right side.
  9353. CaseCluster &CC = *LastLeft;
  9354. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9355. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9356. if (RightSideRank <= LeftSideRank) {
  9357. // Moving the cluster to the right does not demot it.
  9358. --LastLeft;
  9359. --FirstRight;
  9360. continue;
  9361. }
  9362. }
  9363. }
  9364. break;
  9365. }
  9366. assert(LastLeft + 1 == FirstRight);
  9367. assert(LastLeft >= W.FirstCluster);
  9368. assert(FirstRight <= W.LastCluster);
  9369. // Use the first element on the right as pivot since we will make less-than
  9370. // comparisons against it.
  9371. CaseClusterIt PivotCluster = FirstRight;
  9372. assert(PivotCluster > W.FirstCluster);
  9373. assert(PivotCluster <= W.LastCluster);
  9374. CaseClusterIt FirstLeft = W.FirstCluster;
  9375. CaseClusterIt LastRight = W.LastCluster;
  9376. const ConstantInt *Pivot = PivotCluster->Low;
  9377. // New blocks will be inserted immediately after the current one.
  9378. MachineFunction::iterator BBI(W.MBB);
  9379. ++BBI;
  9380. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9381. // we can branch to its destination directly if it's squeezed exactly in
  9382. // between the known lower bound and Pivot - 1.
  9383. MachineBasicBlock *LeftMBB;
  9384. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9385. FirstLeft->Low == W.GE &&
  9386. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9387. LeftMBB = FirstLeft->MBB;
  9388. } else {
  9389. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9390. FuncInfo.MF->insert(BBI, LeftMBB);
  9391. WorkList.push_back(
  9392. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9393. // Put Cond in a virtual register to make it available from the new blocks.
  9394. ExportFromCurrentBlock(Cond);
  9395. }
  9396. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9397. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9398. // directly if RHS.High equals the current upper bound.
  9399. MachineBasicBlock *RightMBB;
  9400. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9401. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9402. RightMBB = FirstRight->MBB;
  9403. } else {
  9404. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9405. FuncInfo.MF->insert(BBI, RightMBB);
  9406. WorkList.push_back(
  9407. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9408. // Put Cond in a virtual register to make it available from the new blocks.
  9409. ExportFromCurrentBlock(Cond);
  9410. }
  9411. // Create the CaseBlock record that will be used to lower the branch.
  9412. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9413. getCurSDLoc(), LeftProb, RightProb);
  9414. if (W.MBB == SwitchMBB)
  9415. visitSwitchCase(CB, SwitchMBB);
  9416. else
  9417. SL->SwitchCases.push_back(CB);
  9418. }
  9419. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9420. // from the swith statement.
  9421. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9422. BranchProbability PeeledCaseProb) {
  9423. if (PeeledCaseProb == BranchProbability::getOne())
  9424. return BranchProbability::getZero();
  9425. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9426. uint32_t Numerator = CaseProb.getNumerator();
  9427. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9428. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9429. }
  9430. // Try to peel the top probability case if it exceeds the threshold.
  9431. // Return current MachineBasicBlock for the switch statement if the peeling
  9432. // does not occur.
  9433. // If the peeling is performed, return the newly created MachineBasicBlock
  9434. // for the peeled switch statement. Also update Clusters to remove the peeled
  9435. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9436. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9437. const SwitchInst &SI, CaseClusterVector &Clusters,
  9438. BranchProbability &PeeledCaseProb) {
  9439. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9440. // Don't perform if there is only one cluster or optimizing for size.
  9441. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9442. TM.getOptLevel() == CodeGenOpt::None ||
  9443. SwitchMBB->getParent()->getFunction().hasMinSize())
  9444. return SwitchMBB;
  9445. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9446. unsigned PeeledCaseIndex = 0;
  9447. bool SwitchPeeled = false;
  9448. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9449. CaseCluster &CC = Clusters[Index];
  9450. if (CC.Prob < TopCaseProb)
  9451. continue;
  9452. TopCaseProb = CC.Prob;
  9453. PeeledCaseIndex = Index;
  9454. SwitchPeeled = true;
  9455. }
  9456. if (!SwitchPeeled)
  9457. return SwitchMBB;
  9458. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9459. << TopCaseProb << "\n");
  9460. // Record the MBB for the peeled switch statement.
  9461. MachineFunction::iterator BBI(SwitchMBB);
  9462. ++BBI;
  9463. MachineBasicBlock *PeeledSwitchMBB =
  9464. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9465. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9466. ExportFromCurrentBlock(SI.getCondition());
  9467. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9468. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9469. nullptr, nullptr, TopCaseProb.getCompl()};
  9470. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9471. Clusters.erase(PeeledCaseIt);
  9472. for (CaseCluster &CC : Clusters) {
  9473. LLVM_DEBUG(
  9474. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9475. << CC.Prob << "\n");
  9476. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9477. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9478. }
  9479. PeeledCaseProb = TopCaseProb;
  9480. return PeeledSwitchMBB;
  9481. }
  9482. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9483. // Extract cases from the switch.
  9484. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9485. CaseClusterVector Clusters;
  9486. Clusters.reserve(SI.getNumCases());
  9487. for (auto I : SI.cases()) {
  9488. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9489. const ConstantInt *CaseVal = I.getCaseValue();
  9490. BranchProbability Prob =
  9491. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9492. : BranchProbability(1, SI.getNumCases() + 1);
  9493. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9494. }
  9495. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9496. // Cluster adjacent cases with the same destination. We do this at all
  9497. // optimization levels because it's cheap to do and will make codegen faster
  9498. // if there are many clusters.
  9499. sortAndRangeify(Clusters);
  9500. // The branch probablity of the peeled case.
  9501. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9502. MachineBasicBlock *PeeledSwitchMBB =
  9503. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9504. // If there is only the default destination, jump there directly.
  9505. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9506. if (Clusters.empty()) {
  9507. assert(PeeledSwitchMBB == SwitchMBB);
  9508. SwitchMBB->addSuccessor(DefaultMBB);
  9509. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9510. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9511. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9512. }
  9513. return;
  9514. }
  9515. SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
  9516. SL->findBitTestClusters(Clusters, &SI);
  9517. LLVM_DEBUG({
  9518. dbgs() << "Case clusters: ";
  9519. for (const CaseCluster &C : Clusters) {
  9520. if (C.Kind == CC_JumpTable)
  9521. dbgs() << "JT:";
  9522. if (C.Kind == CC_BitTests)
  9523. dbgs() << "BT:";
  9524. C.Low->getValue().print(dbgs(), true);
  9525. if (C.Low != C.High) {
  9526. dbgs() << '-';
  9527. C.High->getValue().print(dbgs(), true);
  9528. }
  9529. dbgs() << ' ';
  9530. }
  9531. dbgs() << '\n';
  9532. });
  9533. assert(!Clusters.empty());
  9534. SwitchWorkList WorkList;
  9535. CaseClusterIt First = Clusters.begin();
  9536. CaseClusterIt Last = Clusters.end() - 1;
  9537. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9538. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9539. // DefaultMBB is not replaced.
  9540. if (PeeledCaseProb != BranchProbability::getZero() &&
  9541. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9542. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9543. WorkList.push_back(
  9544. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9545. while (!WorkList.empty()) {
  9546. SwitchWorkListItem W = WorkList.pop_back_val();
  9547. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9548. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9549. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9550. // For optimized builds, lower large range as a balanced binary tree.
  9551. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9552. continue;
  9553. }
  9554. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9555. }
  9556. }
  9557. void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
  9558. SmallVector<EVT, 4> ValueVTs;
  9559. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  9560. ValueVTs);
  9561. unsigned NumValues = ValueVTs.size();
  9562. if (NumValues == 0) return;
  9563. SmallVector<SDValue, 4> Values(NumValues);
  9564. SDValue Op = getValue(I.getOperand(0));
  9565. for (unsigned i = 0; i != NumValues; ++i)
  9566. Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
  9567. SDValue(Op.getNode(), Op.getResNo() + i));
  9568. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  9569. DAG.getVTList(ValueVTs), Values));
  9570. }