SelectionDAGBuilder.cpp 318 KB

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