SelectionDAGBuilder.cpp 304 KB

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